47 lines
1.0 KiB
Go
47 lines
1.0 KiB
Go
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
|
|
}
|