57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package internals
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func checkCreds(username, password string) bool {
|
|
if username != appCreds.Username {
|
|
return false
|
|
}
|
|
got := hashPassword(password, appCreds.Salt)
|
|
return hmac.Equal([]byte(got), []byte(appCreds.Hash))
|
|
}
|
|
|
|
func initAuthSecret() {
|
|
authSecret = make([]byte, 32)
|
|
rand.Read(authSecret)
|
|
}
|
|
|
|
func makeAuthToken() string {
|
|
ts := fmt.Sprintf("%d", time.Now().Unix())
|
|
mac := hmac.New(sha256.New, authSecret)
|
|
mac.Write([]byte(ts))
|
|
return ts + "." + hex.EncodeToString(mac.Sum(nil))
|
|
}
|
|
|
|
func validAuthToken(token string) bool {
|
|
dot := strings.LastIndex(token, ".")
|
|
if dot < 0 {
|
|
return false
|
|
}
|
|
ts, sig := token[:dot], token[dot+1:]
|
|
mac := hmac.New(sha256.New, authSecret)
|
|
mac.Write([]byte(ts))
|
|
if !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) {
|
|
return false
|
|
}
|
|
var t int64
|
|
fmt.Sscanf(ts, "%d", &t)
|
|
return time.Since(time.Unix(t, 0)) < authTokenTTL
|
|
}
|
|
|
|
func isAuthed(r *http.Request) bool {
|
|
if nopwMode {
|
|
return true
|
|
}
|
|
c, err := r.Cookie(authCookieName)
|
|
return err == nil && validAuthToken(c.Value)
|
|
}
|