aboutsummaryrefslogtreecommitdiff
path: root/status.go
blob: c06c877930bb5d7434edf49783b7cc24314186d3 (plain)
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
package main

import (
	"bufio"
	"io"
	"log"
	"net/http"
	"os"
	"os/user"
	"strings"

	"golang.org/x/crypto/bcrypt"
)

func main() {
	var msg string = ""
	var adminHash []byte
	var userHash []byte

	user, err := user.Current()
	if err != nil {
		log.Fatal(err.Error())
	}

	file, err := os.Open(user.HomeDir + "/.status/auth")
	if err != nil {
		log.Fatal(err.Error())
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()

		if after, found := strings.CutPrefix(line, "admin:"); found {
			adminHash = []byte(after)
		}

		if after, found := strings.CutPrefix(line, "user:"); found {
			userHash = []byte(after)
		}
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		username, password, ok := r.BasicAuth()
		if ok {
			err := bcrypt.CompareHashAndPassword(userHash, []byte(username+password))
			if err != nil {
				deny(w)
				return
			}

			w.Write([]byte(msg))
			return
		}

		deny(w)
	})

	http.HandleFunc("/update", func(w http.ResponseWriter, r *http.Request) {
		username, password, ok := r.BasicAuth()
		if ok {
			err := bcrypt.CompareHashAndPassword(adminHash, []byte(username+password))
			if err != nil {
				deny(w)
				return
			}

			if r.Method == "POST" {
				buf, err := io.ReadAll(r.Body)
				if err != nil {
					http.Error(w, "Failed to read request body", http.StatusInternalServerError)
					return
				}

				log.Print(string(buf))
				msg = string(buf)
				w.Write([]byte("success"))
				return
			}
		}

		deny(w)
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

func deny(w http.ResponseWriter) {
	w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
	http.Error(w, "Unauthorized", http.StatusUnauthorized)
}