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
|
package main
|
||||||
|
|
||||||
import "net/http"
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
type ApiHandler struct {
|
type ApiHandler struct {
|
||||||
|
db *Database
|
||||||
|
authToken *string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewApiHandler() *ApiHandler {
|
const authTokenCookieName = "auth-token"
|
||||||
// TODO
|
const isAuthorizedContextKey = "is-authorized"
|
||||||
return &ApiHandler{}
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
func (api *ApiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
if !isAuthorized && required {
|
||||||
// TODO
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user