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
+31 -3
View File
@@ -60,6 +60,9 @@ func main() {
token := c.Get("user").(*jwt.Token)
claims := token.Claims.(jwt.MapClaims)
c.Set("user_id", claims["user_id"])
c.Set("user_role", claims["user_role"])
c.Set("user_email", claims["user_email"])
c.Set("user_username", claims["user_username"])
},
})
@@ -68,9 +71,12 @@ func main() {
protected.GET("/auth/profile", authHandler.GetProfile)
protected.PUT("/auth/profile", authHandler.UpdateProfile)
protected.GET("/auth/users", authHandler.ListUsers)
protected.POST("/auth/ebook-folders", authHandler.AddEbookFolder)
protected.GET("/auth/ebook-folders", authHandler.GetEbookFolders)
protected.DELETE("/auth/ebook-folders", authHandler.DeleteEbookFolder)
// Admin-only routes for folder management
admin := protected.Group("/auth", handlers.AdminMiddleware)
admin.POST("/ebook-folders", authHandler.AddEbookFolder)
admin.GET("/ebook-folders", authHandler.GetEbookFolders)
admin.DELETE("/ebook-folders", authHandler.DeleteEbookFolder)
protected.DELETE("/auth/account", authHandler.DeleteAccount)
protected.PUT("/library/scan-settings", authHandler.UpdateScanSettings)
@@ -90,6 +96,28 @@ func main() {
// Routes
handlers.SetupRoutes(protected, queries)
// Dashboard route (protected)
protected.GET("/dashboard", func(c echo.Context) error {
userID := c.Get("user_id").(string)
userEmail := c.Get("user_email").(string)
userUsername := c.Get("user_username").(string)
userRole := c.Get("user_role").(string)
user := templates.User{
ID: userID,
Email: userEmail,
Username: userUsername,
Role: userRole,
}
var buf bytes.Buffer
err := templates.Dashboard(user).Render(c.Request().Context(), &buf)
if err != nil {
return err
}
return c.HTML(http.StatusOK, buf.String())
})
dummyUser := templates.User{ID: "", Username: "Admin", Email: "admin@example.com"}
// Routes