local-server/cmd/dkl-local-server/auth.go
2023-05-18 19:55:52 +02:00

46 lines
947 B
Go

package main
import (
"log"
"net/http"
)
var adminToken string
func authorizeAdmin(r *http.Request) bool {
return authorizeToken(r, adminToken)
}
func authorizeToken(r *http.Request, token string) bool {
if token == "" {
// access is open
return true
}
reqToken := r.Header.Get("Authorization")
if reqToken != "" {
return reqToken == "Bearer "+token
}
return r.URL.Query().Get("token") == token
}
func forbidden(w http.ResponseWriter, r *http.Request) {
log.Printf("denied access to %s from %s", r.RequestURI, r.RemoteAddr)
http.Error(w, "Forbidden", http.StatusForbidden)
}
func requireToken(token string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if !authorizeToken(req, token) {
forbidden(w, req)
return
}
handler.ServeHTTP(w, req)
})
}
func requireAdmin(handler http.Handler) http.Handler {
return requireToken(adminToken, handler)
}