feat: Implement role-based authentication and authorization

- Add AdminMiddleware for protecting sensitive operations
- Update JWT generation to include user role and details
- Modify login/registration to use enhanced JWT claims
- Update main.go to set admin-protected routes
- Add user role to JWT context for downstream handlers
This commit is contained in:
2026-01-26 16:55:32 -05:00
parent 0b126202c8
commit f5bfac996d
2 changed files with 77 additions and 13 deletions
+46 -10
View File
@@ -53,6 +53,7 @@ type UserProfile struct {
Username string `json:"username"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Role string `json:"role"`
}
type UpdateProfileRequest struct {
@@ -138,8 +139,13 @@ func (h *AuthHandler) Register(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
// Generate JWT
token, err := h.generateJWT(uuid.UUID(user.ID.Bytes).String())
// Generate JWT with user details
token, err := h.generateJWTWithAllClaims(
uuid.UUID(user.ID.Bytes).String(),
user.Role,
user.Email,
user.Username,
)
if err != nil {
if c.Request().Header.Get("HX-Request") == "true" {
return c.HTML(http.StatusInternalServerError, `<div class="text-red-500">Failed to generate token</div>`)
@@ -155,7 +161,7 @@ func (h *AuthHandler) Register(c echo.Context) error {
localStorage.setItem('token', '%s');
localStorage.setItem('user', JSON.stringify(%s));
document.cookie = 'token=%s; path=/; max-age=86400';
window.location.href = '/';
window.location.href = '/api/dashboard';
</script>`, token, fmt.Sprintf(`{"id":"%s","email":"%s","username":"%s"}`, uuid.UUID(user.ID.Bytes).String(), user.Email, user.Username), token)
return c.HTML(http.StatusCreated, html)
}
@@ -166,6 +172,7 @@ window.location.href = '/';
ID: uuid.UUID(user.ID.Bytes).String(),
Email: user.Email,
Username: user.Username,
Role: user.Role,
},
})
}
@@ -229,8 +236,13 @@ func (h *AuthHandler) Login(c echo.Context) error {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "invalid credentials"})
}
// Generate JWT
token, err := h.generateJWT(uuid.UUID(user.ID.Bytes).String())
// Generate JWT with user details
token, err := h.generateJWTWithAllClaims(
uuid.UUID(user.ID.Bytes).String(),
user.Role,
user.Email,
user.Username,
)
if err != nil {
if c.Request().Header.Get("HX-Request") == "true" {
return c.HTML(http.StatusInternalServerError, `<div class="text-red-500">Failed to generate token</div>`)
@@ -246,7 +258,7 @@ func (h *AuthHandler) Login(c echo.Context) error {
localStorage.setItem('token', '%s');
localStorage.setItem('user', JSON.stringify(%s));
document.cookie = 'token=%s; path=/; max-age=86400';
window.location.href = '/';
window.location.href = '/api/dashboard';
</script>`, token, fmt.Sprintf(`{"id":"%s","email":"%s","username":"%s","first_name":"%s","last_name":"%s"}`, uuid.UUID(user.ID.Bytes).String(), user.Email, user.Username, user.FirstName.String, user.LastName.String), token)
return c.HTML(http.StatusOK, html)
}
@@ -267,6 +279,7 @@ window.location.href = '/';
Username: user.Username,
FirstName: firstName,
LastName: lastName,
Role: user.Role,
},
})
}
@@ -301,6 +314,7 @@ func (h *AuthHandler) GetProfile(c echo.Context) error {
Username: user.Username,
FirstName: firstName,
LastName: lastName,
Role: user.Role,
})
}
@@ -760,12 +774,34 @@ func (h *AuthHandler) GetScanSettings(c echo.Context) error {
})
}
func (h *AuthHandler) generateJWT(userID string) (string, error) {
// AdminMiddleware checks if the user has admin role
func AdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
userRole, exists := c.Get("user_role").(string)
if !exists || userRole != "admin" {
return c.JSON(http.StatusForbidden, map[string]string{"error": "admin access required"})
}
return next(c)
}
}
func (h *AuthHandler) generateJWTWithAllClaims(userID, userRole, userEmail, userUsername string) (string, error) {
claims := jwt.MapClaims{
"user_id": userID,
"exp": time.Now().Add(24 * time.Hour).Unix(),
"iat": time.Now().Unix(),
"user_id": userID,
"user_role": userRole,
"user_email": userEmail,
"user_username": userUsername,
"exp": time.Now().Add(24 * time.Hour).Unix(),
"iat": time.Now().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(h.jwtKey)
}
func (h *AuthHandler) generateJWTWithRole(userID, userRole string) (string, error) {
return h.generateJWTWithAllClaims(userID, userRole, "", "")
}
func (h *AuthHandler) generateJWT(userID string) (string, error) {
return h.generateJWTWithRole(userID, "user")
}