mirror of
https://github.com/gabehf/Koito.git
synced 2026-04-22 20:11:50 -07:00
add admin-only routes and authorization middleware tests
This commit is contained in:
parent
64236c99c9
commit
4cbdf6a261
3 changed files with 106 additions and 7 deletions
28
engine/middleware/authorize.go
Normal file
28
engine/middleware/authorize.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gabehf/koito/internal/logger"
|
||||
"github.com/gabehf/koito/internal/models"
|
||||
"github.com/gabehf/koito/internal/utils"
|
||||
)
|
||||
|
||||
// ensures the authenticated user has admin role
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
l := logger.FromContext(r.Context())
|
||||
user := GetUserFromContext(r.Context())
|
||||
if user == nil {
|
||||
l.Debug().Msg("RequireAdmin: Unauthorized access (no user)")
|
||||
utils.WriteError(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if user.Role != models.UserRoleAdmin {
|
||||
l.Debug().Msgf("RequireAdmin: Forbidden - user %d is not admin", user.ID)
|
||||
utils.WriteError(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue