feat: initpage com sync Go + auth + frontend em web/
This commit is contained in:
45
internal/middleware/auth.go
Normal file
45
internal/middleware/auth.go
Normal file
@@ -0,0 +1,45 @@
|
||||
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 ""
|
||||
}
|
||||
Reference in New Issue
Block a user