add initial auth0 module
This commit is contained in:
42
auth/auth0/middleware.go
Normal file
42
auth/auth0/middleware.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package auth0
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type userContextKey struct{}
|
||||
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
func authenticatedMiddleware(deps *deps, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionUser := deps.sessions.Get(r.Context(), "user")
|
||||
if sessionUser == nil {
|
||||
state, err := generateRandomState()
|
||||
if err != nil {
|
||||
deps.log.Error("unable to generate random state", "error", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err = deps.sessions.Put(r.Context(), StateKey, state); err != nil {
|
||||
deps.log.Error("unable to store state in session", "error", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
loginURL := deps.auth.AuthCodeURL(state)
|
||||
http.Redirect(w, r, loginURL, http.StatusFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, sessionUser)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func CurrentUser(r *http.Request) any {
|
||||
return r.Context().Value(userContextKey{})
|
||||
}
|
||||
Reference in New Issue
Block a user