adding validated services? patching forcad_local.py
This commit is contained in:
46
OmCTF-2025/services/block_game/backend/auth/auth.go
Normal file
46
OmCTF-2025/services/block_game/backend/auth/auth.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"omctf.ru/block-game-backend/auth/session"
|
||||
"omctf.ru/block-game-backend/codegen/ent"
|
||||
"omctf.ru/block-game-backend/utils"
|
||||
)
|
||||
|
||||
type ctxUserKeyT struct{}
|
||||
|
||||
var ctxUserKey = ctxUserKeyT{}
|
||||
|
||||
func Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := session.GetSessionUser(r)
|
||||
if session.IsNotLoggedIn(err) {
|
||||
http.Error(w, "Not logged in", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if session.IsInvalidSession(err) {
|
||||
http.Error(w, "Invalid session, reset cookies", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err != nil || user == nil {
|
||||
utils.BailInternalServerError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), ctxUserKey, user)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func GetUser(ctx context.Context) (*ent.User, error) {
|
||||
user, ok := ctx.Value(ctxUserKey).(*ent.User)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("context is invalid: expected user")
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
Reference in New Issue
Block a user