Add octoprint proxy stub

This commit is contained in:
Kelvin Ly 2024-08-25 02:11:47 -04:00
parent 5150f78230
commit 95a63133de
1 changed files with 58 additions and 1 deletions

59
main.go
View File

@ -5,6 +5,7 @@ import (
"context"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
@ -140,8 +141,32 @@ func main() {
log.Println("server terminated")
}
type auth struct {
username, password []byte
}
func readAuth() []auth {
ret := make([]auth, 0)
b, err := os.ReadFile("auth_secret")
if err != nil {
log.Printf("[ERR] auth keys not found, authentication will not work!")
return ret
}
lines := bytes.Split(b, []byte("\n"))
for _, l := range lines {
parts := bytes.Split(l, []byte(","))
if len(parts) == 2 {
user := sha256.Sum256(parts[0])
password := sha256.Sum256(parts[1])
ret = append(ret, auth{user[:], password[:]})
}
}
return ret
}
func readWebhookKey() []byte {
b, err := ioutil.ReadFile("webhook_secret")
b, err := os.ReadFile("webhook_secret")
if err != nil {
log.Printf("[ERR] webhook key not found, webhook updates will not work!")
return nil
@ -186,6 +211,38 @@ func startServer(srv *http.Server) {
}
serveMux.Handle("shrooms."+DOMAIN_NAME+"/", httputil.NewSingleHostReverseProxy(shroomsUrl))
octoUrl, err := url.Parse("http://localhost:9000")
if err != nil {
log.Fatalf("unable to parse reverse proxy path: %v", err)
return
}
auths := readAuth()
octoProxy := httputil.NewSingleHostReverseProxy(octoUrl)
serveMux.HandleFunc("octo."+DOMAIN_NAME+"/", func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
userHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
match := false
for _, a := range auths {
userMatch := bytes.Compare(userHash[:], a.username)
passwordMatch := bytes.Compare(passwordHash[:], a.password)
if userMatch == 0 && passwordMatch == 0 {
match = true
}
}
if match {
octoProxy.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
serveMux.HandleFunc("/", rootHandler)
//serveMux.Handle("/certbot/", http.StripPrefix("/certbot/", http.FileServer(http.Dir("./certbot-tmp"))))
serveMux.Handle("/gfm/", http.StripPrefix("/gfm", http.FileServer(gfmstyle.Assets)))