13cdbe249b
Signed-off-by: Tobias Erbshäußer <tobias@tesoft.dev>
37 lines
937 B
Go
37 lines
937 B
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
type ApiHandler struct {
|
|
db *Database
|
|
authToken *string
|
|
}
|
|
|
|
const authTokenCookieName = "auth-token"
|
|
const isAuthorizedContextKey = "is-authorized"
|
|
|
|
func (h *ApiHandler) ProcessAuth(next http.Handler, required bool) http.Handler {
|
|
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
|
isAuthorized := false
|
|
cookie, _ := request.Cookie(authTokenCookieName)
|
|
if cookie != nil {
|
|
isAuthorized = h.authToken != nil && *h.authToken == cookie.Value
|
|
}
|
|
|
|
if !isAuthorized && required {
|
|
http.Error(writer, "authentication required", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(writer, request.WithContext(context.WithValue(request.Context(), isAuthorizedContextKey, isAuthorized)))
|
|
})
|
|
}
|
|
|
|
func IsAuthorized(request *http.Request) bool {
|
|
value := request.Context().Value(isAuthorizedContextKey)
|
|
return value != nil && value.(bool)
|
|
}
|