Add authlevel to middleware
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
Torjus Håkestad 2022-01-20 01:11:40 +01:00
parent a8a64d118c
commit 790cc43949
2 changed files with 22 additions and 0 deletions

View File

@ -8,6 +8,14 @@ import (
"github.com/google/uuid"
)
type AuthLevel int
const (
AuthLevelUnset AuthLevel = iota
AuthLevelUser
AuthLevelAdmin
)
type AuthService struct {
users UserStore
hmacSecret []byte

View File

@ -14,6 +14,7 @@ type authCtxKey int
const (
authCtxUsername authCtxKey = iota
authCtxAuthLevel
)
func (s *HTTPServer) MiddlewareAccessLogger(next http.Handler) http.Handler {
@ -64,6 +65,7 @@ func (s *HTTPServer) MiddlewareAuthentication(next http.Handler) http.Handler {
}
ctx := context.WithValue(r.Context(), authCtxUsername, claims.Subject)
ctx = context.WithValue(ctx, authCtxAuthLevel, AuthLevelUser)
withCtx := r.WithContext(ctx)
s.Logger.Debugw("Request is authenticated.", "req_id", reqID, "username", claims.Subject)
@ -85,3 +87,15 @@ func UsernameFromRequest(r *http.Request) (string, error) {
}
return username, nil
}
func AuthLevelFromRequest(r *http.Request) (AuthLevel, error) {
rawLevel := r.Context().Value(authCtxAuthLevel)
if rawLevel == nil {
return AuthLevelUnset, fmt.Errorf("no username")
}
level, ok := rawLevel.(AuthLevel)
if !ok {
return AuthLevelUnset, fmt.Errorf("no username")
}
return level, nil
}