Files
initpage/internal/middleware/auth.go

46 lines
1.0 KiB
Go

package middleware
import (
"context"
"net/http"
"github.com/alexedwards/scs/v2"
)
type ctxKey string
const UserIDKey ctxKey = "user_id"
func AuthRequired(sm *scs.SessionManager) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !sm.Exists(r.Context(), "user_id") {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"não autenticado"}`))
return
}
next.ServeHTTP(w, r)
})
}
}
func LoadUserID(sm *scs.SessionManager) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uid, ok := sm.Get(r.Context(), "user_id").(string)
if ok {
r = r.WithContext(context.WithValue(r.Context(), UserIDKey, uid))
}
next.ServeHTTP(w, r)
})
}
}
func GetUserID(ctx context.Context) string {
v := ctx.Value(UserIDKey)
if s, ok := v.(string); ok {
return s
}
return ""
}