add auth middleware
Signed-off-by: Tobias Erbshäußer <tobias@tesoft.dev>
This commit is contained in:
+27
-6
@@ -1,15 +1,36 @@
|
||||
package main
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ApiHandler struct {
|
||||
db *Database
|
||||
authToken *string
|
||||
}
|
||||
|
||||
func NewApiHandler() *ApiHandler {
|
||||
// TODO
|
||||
return &ApiHandler{}
|
||||
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 (api *ApiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// TODO
|
||||
func IsAuthorized(request *http.Request) bool {
|
||||
value := request.Context().Value(isAuthorizedContextKey)
|
||||
return value != nil && value.(bool)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user