Skip to content

Commit e51e43b

Browse files
committed
authrization added in login and middleware
1 parent af31532 commit e51e43b

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

pkg/http/handler/auth/login.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ func Login(storage storage.Storage, secretKey string) http.HandlerFunc {
4242
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
4343
"user_id": user.ID,
4444
"student_id": user.StudentId,
45+
"role": string(user.Role),
4546
"exp": time.Now().Add(time.Hour * 24).Unix(), // Token expires in 24 hours
4647
})
4748

pkg/middleware/auth.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ package middleware
33
import (
44
"context"
55
"net/http"
6-
6+
"fmt"
77
"github.com/golang-jwt/jwt/v5"
8+
"github.com/krishkumar84/bdcoe-golang-portal/pkg/types"
89
"github.com/krishkumar84/bdcoe-golang-portal/pkg/utils/response"
910
)
1011

@@ -13,6 +14,7 @@ type contextKey string
1314
const (
1415
UserIDKey contextKey = "user_id"
1516
StudentIDKey contextKey = "student_id"
17+
RoleKey contextKey = "role"
1618
)
1719

1820
type AuthMiddleware struct {
@@ -48,6 +50,18 @@ func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler {
4850
// Update the context values to use the custom keys
4951
ctx := context.WithValue(r.Context(), UserIDKey, claims["user_id"])
5052
ctx = context.WithValue(ctx, StudentIDKey, claims["student_id"])
53+
ctx = context.WithValue(ctx, RoleKey, claims["role"])
5154
next.ServeHTTP(w, r.WithContext(ctx))
5255
})
5356
}
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

Comments
 (0)