aboutsummaryrefslogtreecommitdiffstats
path: root/api/http/git_file_upload_handler.go
blob: 2f02baf10af7c4e7e866005e4b42c2ec1937aab0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package http

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/gorilla/mux"

	"github.com/MichaelMure/git-bug/api/auth"
	"github.com/MichaelMure/git-bug/cache"
)

// implement a http.Handler that will accept and store content into git blob.
//
// Expected gorilla/mux parameters:
//   - "repo" : the ref of the repo or "" for the default one
type gitUploadFileHandler struct {
	mrc *cache.MultiRepoCache
}

func NewGitUploadFileHandler(mrc *cache.MultiRepoCache) http.Handler {
	return &gitUploadFileHandler{mrc: mrc}
}

func (gufh *gitUploadFileHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	var repo *cache.RepoCache
	var err error

	repoVar := mux.Vars(r)["repo"]
	switch repoVar {
	case "":
		repo, err = gufh.mrc.DefaultRepo()
	default:
		repo, err = gufh.mrc.ResolveRepo(repoVar)
	}

	if err != nil {
		http.Error(rw, "invalid repo reference", http.StatusBadRequest)
		return
	}

	_, err = auth.UserFromCtx(r.Context(), repo)
	if err == auth.ErrNotAuthenticated {
		http.Error(rw, "read-only mode or not logged in", http.StatusForbidden)
		return
	} else if err != nil {
		http.Error(rw, fmt.Sprintf("loading identity: %v", err), http.StatusInternalServerError)
		return
	}

	// 100MB (github limit)
	var maxUploadSize int64 = 100 * 1000 * 1000
	r.Body = http.MaxBytesReader(rw, r.Body, maxUploadSize)
	if err := r.ParseMultipartForm(maxUploadSize); err != nil {
		http.Error(rw, "file too big (100MB max)", http.StatusBadRequest)
		return
	}

	file, _, err := r.FormFile("uploadfile")
	if err != nil {
		http.Error(rw, "invalid file", http.StatusBadRequest)
		return
	}
	defer file.Close()
	fileBytes, err := io.ReadAll(file)
	if err != nil {
		http.Error(rw, "invalid file", http.StatusBadRequest)
		return
	}

	filetype := http.DetectContentType(fileBytes)
	if filetype != "image/jpeg" && filetype != "image/jpg" &&
		filetype != "image/gif" && filetype != "image/png" {
		http.Error(rw, "invalid file type", http.StatusBadRequest)
		return
	}

	hash, err := repo.StoreData(fileBytes)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	type response struct {
		Hash string `json:"hash"`
	}

	resp := response{Hash: string(hash)}

	js, err := json.Marshal(resp)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}

	rw.Header().Set("Content-Type", "application/json")
	_, err = rw.Write(js)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
}