diff --git a/auth.go b/auth.go index e655bfd..6e7da52 100644 --- a/auth.go +++ b/auth.go @@ -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 diff --git a/middleware.go b/middleware.go index f658e12..31b5ff0 100644 --- a/middleware.go +++ b/middleware.go @@ -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 +}