Skip to content

Commit

Permalink
updating the admin guard
Browse files Browse the repository at this point in the history
  • Loading branch information
makhlouf1102 committed Jan 9, 2025
1 parent d03d908 commit 3654db5
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
Binary file modified database/database-test.db
Binary file not shown.
1 change: 1 addition & 0 deletions logs.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
invalid login : sql: no rows in result set
20 changes: 11 additions & 9 deletions middlewares/roleGuard/adminGuard.go
Original file line number Diff line number Diff line change
@@ -1,41 +1,43 @@
package logger_middleware

import (
commonerrors "lets-go/libs/commonErrors"
localconstants "lets-go/libs/localConstants"
"net/http"
"slices"
)

type AdminGuar struct {
type AdminGuard struct {
handler http.Handler
}

func (a *AdminGuar) ServeHTTP(w http.ResponseWriter, r *http.Request) {
protectedData, ok := r.Context().Value("protected_data").(map[string]interface{})
func (a *AdminGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
protectedData, ok := r.Context().Value(localconstants.PROTECTED_DATA_KEY).(map[string]interface{})
if !ok {
http.Error(w, "server error: invalid protected data type", http.StatusInternalServerError)
commonerrors.HttpErrorWithMessage(w, nil, http.StatusInternalServerError, "invalid protected data type")
return
}

userRoles, exists := protectedData["userRoles"]
if !exists {
http.Error(w, "server error: userRoles key missing", http.StatusInternalServerError)
commonerrors.HttpErrorWithMessage(w, nil, http.StatusInternalServerError, "userRoles key missing")
return
}

roles, ok := userRoles.([]string)
if !ok {
http.Error(w, "server error: userRoles has invalid type", http.StatusInternalServerError)
commonerrors.HttpErrorWithMessage(w, nil, http.StatusInternalServerError, "userRoles has invalid type")
return
}

if !slices.Contains(roles, "Admin") {
http.Error(w, "server error: You are not allowed use this feature", http.StatusForbidden)
commonerrors.HttpErrorWithMessage(w, nil, http.StatusForbidden, "You are not allowed use this feature")
return
}
a.handler.ServeHTTP(w, r)
}

// NewLogger constructs a new Logger middleware handler
func NewLogger(handlerToWrap http.Handler) *AdminGuar {
return &AdminGuar{handlerToWrap}
func NewAdminGuard(handlerToWrap http.Handler) *AdminGuard {
return &AdminGuard{handlerToWrap}
}

0 comments on commit 3654db5

Please sign in to comment.