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

45 lines
929 B
Go
Raw Normal View History

2019-01-23 22:40:23 +00:00
package main
import (
"log"
"net/http"
)
2023-05-18 17:55:52 +00:00
var adminToken string
2019-01-23 22:40:23 +00:00
func authorizeAdmin(r *http.Request) bool {
2023-05-18 17:55:52 +00:00
return authorizeToken(r, adminToken)
2019-01-23 22:40:23 +00:00
}
func authorizeToken(r *http.Request, token string) bool {
if token == "" {
2024-02-26 10:21:29 +00:00
return false
2019-01-23 22:40:23 +00:00
}
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) {
2023-09-10 14:47:54 +00:00
log.Printf("denied access to %s from %s", r.URL.Path, r.RemoteAddr)
2019-01-23 22:40:23 +00:00
http.Error(w, "Forbidden", http.StatusForbidden)
}
2023-02-07 20:29:19 +00:00
2024-02-26 10:21:29 +00:00
func requireToken(token *string, handler http.Handler) http.Handler {
2023-02-07 20:29:19 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
2024-02-26 10:21:29 +00:00
if !authorizeToken(req, *token) {
2023-02-07 20:29:19 +00:00
forbidden(w, req)
return
}
handler.ServeHTTP(w, req)
})
}
func requireAdmin(handler http.Handler) http.Handler {
2024-02-26 10:21:29 +00:00
return requireToken(&adminToken, handler)
2023-02-07 20:29:19 +00:00
}