local-server/cmd/dkl-local-server/auth.go

58 lines
1.3 KiB
Go
Raw Normal View History

2019-01-23 22:40:23 +00:00
package main
import (
"flag"
"log"
"net/http"
)
var (
hostsToken = flag.String("hosts-token", "", "Token to give to access /hosts (open is none)")
adminToken = flag.String("admin-token", "", "Token to give to access to admin actions (open is none)")
)
func authorizeHosts(r *http.Request) bool {
return authorizeToken(r, *hostsToken)
}
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")
2023-02-07 20:29:19 +00:00
if reqToken != "" {
return reqToken == "Bearer "+token
}
2019-01-23 22:40:23 +00:00
2023-02-07 20:29:19 +00:00
return r.URL.Query().Get("token") == token
2019-01-23 22:40:23 +00:00
}
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)
}
2023-02-07 20:29:19 +00:00
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)
}
func requireHosts(handler http.Handler) http.Handler {
return requireToken(*hostsToken, handler)
}