llist/submit.go -rw-r--r-- 1.4 KiB View raw
                                                                                
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
package main

import (
	"crypto/sha256"
	"fmt"
	"net/http"
	"strings"
)

func checkPasswd(name, pass string) bool {
	loadUsers()
	hash := fmt.Sprintf("%x", sha256.Sum256([]byte(name+":"+pass)))
	_, found := users[name]
	return found && users[name].passwd == hash
}

func submit(rw http.ResponseWriter, req *http.Request) {
	if req.Method != http.MethodPost {
		tags, err := queryTags()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}
		err = tmpl.ExecuteTemplate(rw, "submit.gtml", tags)
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
		}

	} else {
		err := req.ParseForm()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		name, pass, ok := req.BasicAuth()
		if !ok || !checkPasswd(name, pass) {
			rw.Header().Set("WWW-Authenticate", "Basic realm=\"Credentials\"")
			http.Error(rw, "Invalid password", http.StatusUnauthorized)
			return
		}

		if req.FormValue("title") == "" || req.FormValue("url") == "" {
			http.Error(rw, "Either no title or no URL specified", http.StatusBadRequest)
			return
		}

		err = Link{
			Title: req.FormValue("title"),
			Url:   req.FormValue("url"),
			Tags:  strings.Split(req.FormValue("tags"), " "),
			Name:  name,
		}.addLink()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		http.Redirect(rw, req, "..", http.StatusFound)
	}
}