47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"codeberg.org/nextgo/dbots/internal/db"
|
|
"codeberg.org/nextgo/dbots/internal/errorutil"
|
|
"github.com/go-chi/render"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const userKey contextKey = "user"
|
|
|
|
// AuthMiddleware is a middleware to set the user as context value.
|
|
// this middleware does not prevents the user from accessing the route
|
|
// if not authorized.
|
|
func AuthMiddleware(q *db.Queries) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// ctx := context.WithValue(r.Context(), userKey, user) // mocked
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
// AuthGuardMiddleware is a middleware that prevents the user
|
|
// from accessing the route if they are NOT authorized.
|
|
func AuthGuardMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_, ok := r.Context().Value(userKey).(*db.User)
|
|
if !ok {
|
|
render.Render(w, r, errorutil.ErrUnauthorized)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func GetUser(ctx context.Context) *db.User {
|
|
user, ok := ctx.Value(userKey).(*db.User)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
return user
|
|
}
|