auth
sophuwu sophie@skisiel.com
Thu, 11 Jan 2024 15:43:05 +0100
2 files changed,
70 insertions(+),
0 deletions(-)
A
httpauth.go
@@ -0,0 +1,26 @@
+package main + +import ( + "crypto/sha512" + "crypto/subtle" + "encoding/hex" + "net/http" +) + +var userpass map[string]string + +func handleAuth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, authOK := r.BasicAuth() + checksum := sha512.New().Sum([]byte(pass)) + pass = hex.EncodeToString(checksum) + expectedPass, lookupOK := userpass[user] + + if !authOK || !lookupOK || subtle.ConstantTimeCompare([]byte(expectedPass), []byte(pass)) != 1 { + w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) + http.Error(w, "Unauthorized.", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +}
A
sophex/sophex.go
@@ -0,0 +1,44 @@
+package sophex + +const sopHexSet string = "SOPHIE+MAL1VN=<3" + +func Encode(b []byte) string { + var s string + for i := 0; i < len(b); i++ { + if i%16 == 0 { + s += "\n" + } + s += string(sopHexSet[(b[i]>>4)&15]) + string(sopHexSet[b[i]&15]) + } +} + +func newErr(text string) error { + Error := func() string { return text }() + return interface{}(Error).(error) +} + +func Decode(s string) ([]byte, error) { + var b []byte + var n int + for i, v := range s { + n = index(v) + if n == -1 { + return nil, newErr("invalid character in decode string") + } + if i%2 == 0 { + b = append(b, byte(n<<4)) + } else { + b[len(b)-1] |= byte(n) + } + } + return b, nil +} + +func index(c rune) (j int) { + for j, v := range sopHexSet { + if v == c { + return j + } + } + return -1 +}