aboutsummaryrefslogtreecommitdiff
path: root/status.go
blob: 8ef5301a8d4299eea19fb2dd7106f50987212af9 (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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)
	})

	http.HandleFunc("/generate-hash", func(w http.ResponseWriter, r *http.Request) {
		username, password, ok := r.BasicAuth()
		if ok {
			hash, err := bcrypt.GenerateFromPassword([]byte(username+password), 0)
			if err != nil {
				http.Error(w, "Failed to generate hash", http.StatusInternalServerError)
				return
			}

			log.Print(string(hash))
			w.Write([]byte("Hash successfully generated (output to server log for some semblance of security)"))
			return
		}

		deny(w)
	})

	log.Fatal(http.ListenAndServe(":"+os.Args[1], nil))
}

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