From 790cc439495ac1803f958f736499f95978bf8869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Thu, 20 Jan 2022 01:11:40 +0100 Subject: [PATCH] Add authlevel to middleware --- auth.go | 8 ++++++++ middleware.go | 14 ++++++++++++++ 2 files changed, 22 insertions(+) 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 +}