@@ -3,8 +3,9 @@ package middleware
3
3
import (
4
4
"context"
5
5
"net/http"
6
-
6
+ "fmt"
7
7
"github.com/golang-jwt/jwt/v5"
8
+ "github.com/krishkumar84/bdcoe-golang-portal/pkg/types"
8
9
"github.com/krishkumar84/bdcoe-golang-portal/pkg/utils/response"
9
10
)
10
11
@@ -13,6 +14,7 @@ type contextKey string
13
14
const (
14
15
UserIDKey contextKey = "user_id"
15
16
StudentIDKey contextKey = "student_id"
17
+ RoleKey contextKey = "role"
16
18
)
17
19
18
20
type AuthMiddleware struct {
@@ -48,6 +50,18 @@ func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler {
48
50
// Update the context values to use the custom keys
49
51
ctx := context .WithValue (r .Context (), UserIDKey , claims ["user_id" ])
50
52
ctx = context .WithValue (ctx , StudentIDKey , claims ["student_id" ])
53
+ ctx = context .WithValue (ctx , RoleKey , claims ["role" ])
51
54
next .ServeHTTP (w , r .WithContext (ctx ))
52
55
})
53
56
}
57
+
58
+ func (m * AuthMiddleware ) RequireAdmin (next http.Handler ) http.Handler {
59
+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
60
+ role := r .Context ().Value (RoleKey )
61
+ if role != string (types .RoleAdmin ) {
62
+ response .WriteJson (w , http .StatusForbidden , response .GeneralError (fmt .Errorf ("admin access required" )))
63
+ return
64
+ }
65
+ next .ServeHTTP (w , r )
66
+ })
67
+ }
0 commit comments