aboutsummaryrefslogtreecommitdiff
path: root/backend/api/routes.go
blob: 26c932fb791d79b38dd7681d113834126de9a8d8 (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
105
106
package api

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

	"github.com/jackyzha0/ctrl-v/security"

	"github.com/gorilla/mux"
	"github.com/jackyzha0/ctrl-v/cache"
	"github.com/jackyzha0/ctrl-v/db"
)

func healthCheckFunc(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "status ok")
}

func insertFunc(w http.ResponseWriter, r *http.Request) {

	// Allow CORS
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// get content
	_ = r.ParseMultipartForm(0)
	expiry := r.FormValue("expiry")
	content := r.FormValue("content")
	title := r.FormValue("title")
	password := r.FormValue("password")

	// get ip
	ip := getIP(r)

	// insert content
	hash, err := db.New(ip, content, expiry, title, password)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "%s", err.Error())
		return
	}

	// if successful return paste hash
	w.Header().Set("Content-Type", "application/json")
	pasteMap := map[string]interface{}{
		"hash": hash,
	}

	jsonData, _ := json.Marshal(pasteMap)
	fmt.Fprintf(w, "%+v", string(jsonData))
}

func getPasteFunc(w http.ResponseWriter, r *http.Request) {
	// no password given for get
	handleGetPaste(w, r, "")
}

func getPasteWithPasswordFunc(w http.ResponseWriter, r *http.Request) {
	// get password from form
	_ = r.ParseMultipartForm(0)
	parsedPassword := r.FormValue("password")

	handleGetPaste(w, r, parsedPassword)

}

func handleGetPaste(w http.ResponseWriter, r *http.Request, parsedPassword string) {
	// Allow CORS
	w.Header().Set("Access-Control-Allow-Origin", "*")

	hash := mux.Vars(r)["hash"]
	paste, err := cache.C.Get(hash, parsedPassword)

	// if hash was not found
	if err == cache.PasteNotFound {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "%s", err)
		return
	}

	// if paste is password protected
	if err == cache.UserUnauthorized {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "%s", err)
		return
	}

	// if internal error with encryption
	if err == security.EncryptionError {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "%s", err)
		return
	}

	// otherwise, return paste content, title, and current time
	w.Header().Set("Content-Type", "application/json")
	pasteMap := map[string]interface{}{
		"timestamp": time.Now(),
		"title":     paste.Title,
		"content":   paste.Content,
		"expiry":    paste.Expiry,
	}

	jsonData, _ := json.Marshal(pasteMap)
	fmt.Fprintf(w, "%+v", string(jsonData))
}