feat: Enhance notifications and pagination functionality

- Implemented pagination for user notifications, allowing users to navigate through their notifications more efficiently.
- Updated the notifications page to display the total count of notifications and provide controls for adjusting the number of notifications shown per page.
- Added backend support for fetching paginated notifications and counting total notifications for users.
- Improved the user interface for notifications, including a new layout and additional help sections to guide users on managing their notifications.
This commit is contained in:
StarFleetCPTN
2025-03-23 09:54:06 -07:00
parent db6259f8a3
commit 3140d9e143
11 changed files with 1187 additions and 895 deletions
+14
View File
@@ -38,6 +38,20 @@ func (db *DB) GetUserNotifications(userID uint, limit int) ([]UserNotification,
return notifications, result.Error
}
// GetUserNotificationCount returns the total count of notifications for a user
func (db *DB) GetUserNotificationCount(userID uint) (int64, error) {
var count int64
result := db.Model(&UserNotification{}).Where("user_id = ?", userID).Count(&count)
return count, result.Error
}
// GetPaginatedUserNotifications returns paginated notifications for a user
func (db *DB) GetPaginatedUserNotifications(userID uint, offset, limit int) ([]UserNotification, error) {
var notifications []UserNotification
result := db.Where("user_id = ?", userID).Order("created_at DESC").Offset(offset).Limit(limit).Find(&notifications)
return notifications, result.Error
}
// GetUnreadNotificationCount returns the count of unread notifications for a user
func (db *DB) GetUnreadNotificationCount(userID uint) (int64, error) {
var count int64
+315 -126
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -74,30 +75,25 @@ func (h *Handlers) GetBackupFiles() ([]components.BackupFile, error) {
// HandleBackupDatabase creates a backup of the current database
func (h *Handlers) HandleBackupDatabase(c *gin.Context) {
// Close the existing database connection to ensure a clean backup
h.DB.Close()
// Instead of closing the database connection, get a new connection to the database
// This will use the underlying connection pool - just checking connection availability
_, err := h.DB.DB.DB()
if err != nil {
h.HandleError(c, http.StatusInternalServerError, "Database Error", "Failed to access database", err)
return
}
// Generate a backup filename with timestamp
timestamp := time.Now().Format("2006-01-02-150405")
backupName := fmt.Sprintf("backup-%s.db", timestamp)
backupPath := filepath.Join(h.BackupDir, backupName)
// Copy the database file
err := copyFile(h.DBPath, backupPath)
if err != nil {
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
return
}
// Copy the database file without closing the main connection
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+create+backup&details="+err.Error())
return
}
// Reopen the database connection and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup") {
return
}
c.Redirect(http.StatusSeeOther, "/admin/database?status=Backup+created+successfully")
}
@@ -130,36 +126,74 @@ func (h *Handlers) HandleRestoreDatabase(c *gin.Context) {
return
}
// Close the database connection
h.DB.Close()
// Create a backup of the current database before restoring
currentBackupName := fmt.Sprintf("pre-restore-%s.db", time.Now().Format("2006-01-02-150405"))
currentBackupPath := filepath.Join(h.BackupDir, currentBackupName)
if err := copyFile(h.DBPath, currentBackupPath); err != nil {
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+pre-restore+backup+attempt") {
return
}
if err := backupDatabaseFile(h.DBPath, currentBackupPath); err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+current+database&details="+err.Error())
return
}
// Store auth info from context
userID, userExists := c.Get("userID")
email, emailExists := c.Get("email")
username, usernameExists := c.Get("username")
isAdmin, adminExists := c.Get("isAdmin")
// Close current connections before restore
sqlDB, err := h.DB.DB.DB()
if err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+access+database&details="+err.Error())
return
}
// Close the current connection pool
if err := sqlDB.Close(); err != nil {
fmt.Printf("Warning: Error closing database connection: %v\n", err)
}
// Wait for connections to fully close
time.Sleep(1 * time.Second)
// Restore the database by copying the backup file
if err := copyFile(backupPath, h.DBPath); err != nil {
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+restore+attempt") {
// Need to reopen the database
newDB, reopenErr := db.ReopenWithoutMigrations(h.DBPath)
if reopenErr != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Critical+error:+Database+restore+failed+and+reconnection+failed&details="+reopenErr.Error())
return
}
h.DB = newDB
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+restore+database&details="+err.Error())
return
}
// Reopen the database connection with the restored database and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+restore") {
// Reopen the database connection with the restored database
newDB, err := db.ReopenWithoutMigrations(h.DBPath)
if err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+reconnect+to+database+after+restore&details="+err.Error())
return
}
// Update the handler's database connection
h.DB = newDB
// Restore auth context
if userExists {
c.Set("userID", userID)
}
if emailExists {
c.Set("email", email)
}
if usernameExists {
c.Set("username", username)
}
if adminExists {
c.Set("isAdmin", isAdmin)
}
// Clean up temp file if it was an upload
if strings.HasPrefix(filename, "temp-") {
os.Remove(backupPath)
@@ -255,23 +289,12 @@ func (h *Handlers) HandleVacuumDatabase(c *gin.Context) {
backupName := fmt.Sprintf("pre-vacuum-%s.db", timestamp)
backupPath := filepath.Join(h.BackupDir, backupName)
// Close DB connection to make a clean backup
h.DB.Close()
if err := copyFile(h.DBPath, backupPath); err != nil {
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
return
}
// Make a backup without closing the DB
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+before+vacuum&details="+err.Error())
return
}
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup") {
return
}
// Run vacuum command
result := h.DB.Exec("VACUUM")
if result.Error != nil {
@@ -282,80 +305,6 @@ func (h *Handlers) HandleVacuumDatabase(c *gin.Context) {
c.Redirect(http.StatusSeeOther, "/admin/database?status=Database+optimized+successfully")
}
// reopenDatabaseWithAuth safely closes and reopens the database while preserving user authentication
func (h *Handlers) reopenDatabaseWithAuth(c *gin.Context, reason string) (success bool) {
// Store auth info from context
userID, userExists := c.Get("userID")
email, emailExists := c.Get("email")
username, usernameExists := c.Get("username")
isAdmin, adminExists := c.Get("isAdmin")
// First close the existing connection if it exists
if h.DB != nil {
h.DB.Close()
// Set to nil to avoid using a closed connection
h.DB = nil
}
// Make sure we wait a moment to ensure the file is released
time.Sleep(100 * time.Millisecond)
// Reopen database WITHOUT running migrations
newDB, err := db.ReopenWithoutMigrations(h.DBPath)
if err != nil {
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Failed+to+reconnect+to+database+%s&details=%s", reason, err.Error()))
return false
}
// Verify the connection works by executing a simple query
var count int64
if err := newDB.Raw("SELECT 1").Scan(&count).Error; err != nil {
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Database+connection+test+failed+%s&details=%s", reason, err.Error()))
return false
}
// Only after validation, assign the new database connection
h.DB = newDB
// Restore auth context
if userExists {
c.Set("userID", userID)
}
if emailExists {
c.Set("email", email)
}
if usernameExists {
c.Set("username", username)
}
if adminExists {
c.Set("isAdmin", isAdmin)
}
// If we had a user, attempt to reload their info
if userExists && h.DB != nil {
var user db.User
userIDValue, ok := userID.(uint)
if !ok {
// Try to convert from float64 (the JWT parser returns numbers as float64)
if userIDFloat, ok := userID.(float64); ok {
userIDValue = uint(userIDFloat)
}
}
if userIDValue > 0 {
result := h.DB.Preload("Roles").First(&user, userIDValue)
if result.Error == nil {
c.Set("user", &user)
} else {
// Log the error but continue - we still have basic user info from JWT
fmt.Printf("Error loading user roles after DB reconnect: %v\n", result.Error)
}
}
}
return true
}
// HandleClearJobHistory clears job history records
func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
// Check if DB is nil
@@ -376,23 +325,12 @@ func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
backupName := fmt.Sprintf("pre-clear-history-%s.db", timestamp)
backupPath := filepath.Join(h.BackupDir, backupName)
// Close DB connection to make a clean backup
h.DB.Close()
if err := copyFile(h.DBPath, backupPath); err != nil {
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup+attempt") {
return
}
// Make a backup without closing the DB
if err := backupDatabaseFile(h.DBPath, backupPath); err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+backup+before+clearing+history&details="+err.Error())
return
}
// Reopen DB and preserve auth
if !h.reopenDatabaseWithAuth(c, "after+backup") {
return
}
// Make sure we have a valid connection before executing the DELETE
var testCount int64
if err := h.DB.Raw("SELECT COUNT(*) FROM job_histories").Scan(&testCount).Error; err != nil {
@@ -430,6 +368,159 @@ func (h *Handlers) HandleClearJobHistory(c *gin.Context) {
c.Redirect(http.StatusSeeOther, "/admin/database?status=Job+history+cleared+successfully+"+logMessage)
}
// backupDatabaseFile creates a copy of the database file without closing the connection
func backupDatabaseFile(srcPath, destPath string) error {
// Copy the database using the WAL mode safe approach
srcFile, err := os.Open(srcPath)
if err != nil {
return fmt.Errorf("failed to open source database: %v", err)
}
defer srcFile.Close()
destFile, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("failed to create destination file: %v", err)
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return fmt.Errorf("failed to copy database: %v", err)
}
// Also copy the WAL files if they exist
walPath := srcPath + "-wal"
if _, err := os.Stat(walPath); err == nil {
if err := copyFile(walPath, destPath+"-wal"); err != nil {
fmt.Printf("Warning: failed to copy WAL file: %v\n", err)
}
}
shmPath := srcPath + "-shm"
if _, err := os.Stat(shmPath); err == nil {
if err := copyFile(shmPath, destPath+"-shm"); err != nil {
fmt.Printf("Warning: failed to copy SHM file: %v\n", err)
}
}
return destFile.Sync()
}
// reopenDatabaseWithAuth safely closes and reopens the database while preserving user authentication
// This is now only used as a fallback when necessary, not as the primary approach
func (h *Handlers) reopenDatabaseWithAuth(c *gin.Context, reason string) (success bool) {
// Store auth info from context
userID, userExists := c.Get("userID")
email, emailExists := c.Get("email")
username, usernameExists := c.Get("username")
isAdmin, adminExists := c.Get("isAdmin")
// First close the existing connection if it exists
if h.DB != nil {
// Close the database connection properly
if err := h.DB.Close(); err != nil {
fmt.Printf("Warning: Error closing database connection: %v\n", err)
}
// Set to nil to avoid using a closed connection
h.DB = nil
}
// Make sure we wait longer to ensure the file is completely released
// Different OSes might need different times for file handles to be released
time.Sleep(1000 * time.Millisecond)
// Define max retry attempts and backoff times
maxRetries := 5
var err error
// Attempt to reopen the database with retries
for attempt := 0; attempt < maxRetries; attempt++ {
// Reopen database WITHOUT running migrations
h.DB, err = db.ReopenWithoutMigrations(h.DBPath)
if err == nil {
// Verify the connection works by executing a simple query
var count int64
if verifyErr := h.DB.Raw("SELECT 1").Scan(&count).Error; verifyErr == nil {
break // Successfully reopened and verified
} else {
// Close this failed connection
h.DB.Close()
h.DB = nil
err = verifyErr
fmt.Printf("Database verification failed on attempt %d: %v\n", attempt+1, verifyErr)
}
} else {
fmt.Printf("Database reopen failed on attempt %d: %v\n", attempt+1, err)
}
// Wait before retrying, with increasing backoff
waitTime := time.Duration(1000*(attempt+1)) * time.Millisecond
fmt.Printf("Waiting %v before retry #%d\n", waitTime, attempt+1)
time.Sleep(waitTime)
}
// If all retries failed, redirect with error
if err != nil {
c.Redirect(http.StatusSeeOther, fmt.Sprintf("/admin/database?error=Failed+to+reconnect+to+database+%s&details=%s", reason, err.Error()))
return false
}
// Restore auth context
if userExists {
c.Set("userID", userID)
}
if emailExists {
c.Set("email", email)
}
if usernameExists {
c.Set("username", username)
}
if adminExists {
c.Set("isAdmin", isAdmin)
}
// If we had a user, attempt to reload their info
if userExists && h.DB != nil {
var user db.User
userIDValue, ok := userID.(uint)
if !ok {
// Try to convert from float64 (the JWT parser returns numbers as float64)
if userIDFloat, ok := userID.(float64); ok {
userIDValue = uint(userIDFloat)
} else {
// Try string conversion as a last resort
if userIDStr, ok := userID.(string); ok {
if parsed, err := strconv.ParseUint(userIDStr, 10, 32); err == nil {
userIDValue = uint(parsed)
}
}
}
}
if userIDValue > 0 {
// Try to load the user with their roles
result := h.DB.Preload("Roles").First(&user, userIDValue)
if result.Error == nil {
c.Set("user", &user)
} else {
// Log the error but continue - we still have basic user info from JWT
fmt.Printf("Error loading user roles after DB reconnect: %v\n", result.Error)
// Try a simpler query as fallback
simpleResult := h.DB.First(&user, userIDValue)
if simpleResult.Error == nil {
c.Set("user", &user)
fmt.Println("Loaded user without roles after DB reconnect")
}
}
}
}
fmt.Printf("Database successfully reopened after %s\n", reason)
return true
}
// Helper function to copy a file
func copyFile(src, dst string) error {
sourceFile, err := os.Open(src)
@@ -465,3 +556,101 @@ func formatFileSize(size int64) string {
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}
// HandleExportConfigs exports system configurations as JSON
func (h *Handlers) HandleExportConfigs(c *gin.Context) {
// Check if DB is nil
if h.DB == nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Database+connection+is+not+available")
return
}
// Check if user is authenticated and is admin
_, exists := c.Get("userID")
if !exists {
c.Redirect(http.StatusSeeOther, "/login")
return
}
isAdmin, adminExists := c.Get("isAdmin")
if !adminExists || isAdmin != true {
h.HandleError(c, http.StatusForbidden, "Permission Denied", "You do not have permission to export configurations", nil)
return
}
// Query all system configurations
var configs []db.TransferConfig
if err := h.DB.Find(&configs).Error; err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+export+configurations&details="+err.Error())
return
}
// Generate filename with timestamp
timestamp := time.Now().Format("2006-01-02-150405")
filename := fmt.Sprintf("gomft-configs-%s.json", timestamp)
// Set headers for file download
c.Header("Content-Description", "File Transfer")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
c.Header("Content-Type", "application/json")
// Write the JSON to response
c.JSON(http.StatusOK, configs)
}
// HandleExportJobs exports jobs as JSON
func (h *Handlers) HandleExportJobs(c *gin.Context) {
// Check if DB is nil
if h.DB == nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Database+connection+is+not+available")
return
}
// Check if user is authenticated and is admin
_, exists := c.Get("userID")
if !exists {
c.Redirect(http.StatusSeeOther, "/login")
return
}
isAdmin, adminExists := c.Get("isAdmin")
if !adminExists || isAdmin != true {
h.HandleError(c, http.StatusForbidden, "Permission Denied", "You do not have permission to export jobs", nil)
return
}
// Query all jobs with all possible relationships
var jobs []db.Job
query := h.DB.Model(&db.Job{})
// Check if each relation exists before trying to preload
// This makes the export more robust against schema changes
// Try to preload steps if they exist
if h.DB.Migrator().HasTable("job_steps") {
query = query.Preload("Steps")
}
// Try to preload schedules if they exist
if h.DB.Migrator().HasTable("job_schedules") {
query = query.Preload("Schedule")
}
// Get the jobs with appropriate preloads
if err := query.Find(&jobs).Error; err != nil {
c.Redirect(http.StatusSeeOther, "/admin/database?error=Failed+to+export+jobs&details="+err.Error())
return
}
// Generate filename with timestamp
timestamp := time.Now().Format("2006-01-02-150405")
filename := fmt.Sprintf("gomft-jobs-%s.json", timestamp)
// Set headers for file download
c.Header("Content-Description", "File Transfer")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
c.Header("Content-Type", "application/json")
// Write the JSON to response
c.JSON(http.StatusOK, jobs)
}
@@ -1,6 +1,7 @@
package handlers
import (
"math"
"net/http"
"strconv"
@@ -12,8 +13,56 @@ import (
func (h *Handlers) HandleNotifications(c *gin.Context) {
userID := c.GetUint("userID")
// Get notifications for the user
notifications, err := h.DB.GetUserNotifications(userID, 50) // Get more for the full page
// Get pagination parameters from query
pageStr := c.DefaultQuery("page", "1")
perPageStr := c.DefaultQuery("perPage", "10")
page, err := strconv.Atoi(pageStr)
if err != nil || page < 1 {
page = 1
}
perPage, err := strconv.Atoi(perPageStr)
if err != nil {
perPage = 10
}
// Ensure perPage is one of the allowed values
validPerPage := []int{10, 25, 50, 100}
isValid := false
for _, v := range validPerPage {
if v == perPage {
isValid = true
break
}
}
if !isValid {
perPage = 10
}
// Get total count for pagination
totalCount, err := h.DB.GetUserNotificationCount(userID)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to count notifications")
return
}
// Calculate total pages
totalPages := int(math.Ceil(float64(totalCount) / float64(perPage)))
if totalPages < 1 {
totalPages = 1
}
// Ensure page is within range
if page > totalPages {
page = totalPages
}
// Calculate offset for database query
offset := (page - 1) * perPage
// Get paginated notifications for the user
notifications, err := h.DB.GetPaginatedUserNotifications(userID, offset, perPage)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to load notifications")
return
@@ -29,6 +78,10 @@ func (h *Handlers) HandleNotifications(c *gin.Context) {
data := components.NotificationsData{
Notifications: notifications,
UnreadCount: unreadCount,
CurrentPage: page,
TotalPages: totalPages,
TotalCount: int(totalCount),
PerPage: perPage,
}
// Render the notifications page
+8 -6
View File
@@ -118,12 +118,12 @@ func (h *Handlers) RegisterRoutes(router *gin.Engine) {
adminRoles := admin.Group("/roles")
adminRoles.Use(h.PermissionMiddleware("roles.admin"))
{
adminRoles.GET("", h.AdminRoles)
adminRoles.GET("/new", h.AdminNewRolePage)
adminRoles.GET("/:id/edit", h.AdminEditRolePage)
adminRoles.POST("", h.AdminCreateRole)
adminRoles.PUT("/:id", h.AdminUpdateRole)
adminRoles.DELETE("/:id", h.AdminDeleteRole)
adminRoles.GET("", h.HandleRoles)
adminRoles.GET("/new", h.HandleNewRole)
adminRoles.GET("/:id/edit", h.HandleRoles)
adminRoles.POST("", h.HandleCreateRole)
adminRoles.PUT("/:id", h.HandleEditRole)
adminRoles.DELETE("/:id", h.HandleDeleteRole)
}
// Audit log routes
@@ -159,6 +159,8 @@ func (h *Handlers) RegisterRoutes(router *gin.Engine) {
dbGroup.GET("/refresh-backups", h.HandleRefreshBackups)
dbGroup.POST("/vacuum-database", h.HandleVacuumDatabase)
dbGroup.POST("/clear-job-history", h.HandleClearJobHistory)
dbGroup.GET("/export-configs", h.PermissionMiddleware("system.export"), h.HandleExportConfigs)
dbGroup.GET("/export-jobs", h.PermissionMiddleware("system.export"), h.HandleExportJobs)
}
}
+252 -258
View File
@@ -7,7 +7,6 @@ import (
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -571,317 +570,312 @@ func (h *Handlers) AdminDeleteUser(c *gin.Context) {
}
// AdminRoles handles the GET /admin/roles route
func (h *Handlers) AdminRoles(c *gin.Context) {
var dbRoles []db.Role
if err := h.DB.Find(&dbRoles).Error; err != nil {
c.String(http.StatusInternalServerError, "Error fetching roles")
return
}
// func (h *Handlers) AdminRoles(c *gin.Context) {
// var dbRoles []db.Role
// if err := h.DB.Find(&dbRoles).Error; err != nil {
// c.String(http.StatusInternalServerError, "Error fetching roles")
// return
// }
// Convert db.Role to components.Role
var roles []components.Role
for _, dbRole := range dbRoles {
role := components.Role{
ID: dbRole.ID,
Name: dbRole.Name,
Description: dbRole.Description,
Permissions: dbRole.Permissions,
}
roles = append(roles, role)
}
// // Convert db.Role to components.Role
// var roles []components.Role
// for _, dbRole := range dbRoles {
// role := components.Role{
// ID: dbRole.ID,
// Name: dbRole.Name,
// Description: dbRole.Description,
// Permissions: dbRole.Permissions,
// }
// roles = append(roles, role)
// }
// Use components instead of HTML templates
data := components.RolesData{
Roles: roles,
}
// // Use components instead of HTML templates
// data := components.RolesData{
// Roles: roles,
// }
ctx := h.CreateTemplateContext(c)
components.AdminRoles(ctx, data).Render(ctx, c.Writer)
}
// ctx := h.CreateTemplateContext(c)
// components.AdminRoles(ctx, data).Render(ctx, c.Writer)
// }
// AdminNewRolePage handles the GET /admin/roles/new route
func (h *Handlers) AdminNewRolePage(c *gin.Context) {
// Create an empty role for the form
role := &components.Role{
ID: 0,
Name: "",
Description: "",
Permissions: []string{},
}
// func (h *Handlers) AdminNewRolePage(c *gin.Context) {
// // Create an empty role for the form
// role := &components.Role{
// ID: 0,
// Name: "",
// Description: "",
// Permissions: []string{},
// }
// All available permissions
allPermissions := []string{
"users.view", "users.create", "users.edit", "users.delete",
"roles.view", "roles.create", "roles.edit", "roles.delete",
"transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
"audit.view",
}
// // All available permissions
// allPermissions := []string{
// "users.view", "users.create", "users.edit", "users.delete",
// "roles.view", "roles.create", "roles.edit", "roles.delete",
// "transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
// "audit.view",
// }
// Use components instead of HTML templates
data := components.RoleFormData{
Role: role,
IsNew: true,
AllPermissions: allPermissions,
}
// // Use components instead of HTML templates
// data := components.RoleFormData{
// Role: role,
// IsNew: true,
// AllPermissions: allPermissions,
// }
ctx := h.CreateTemplateContext(c)
components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
}
// ctx := h.CreateTemplateContext(c)
// components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
// }
// AdminCreateRole handles the POST /admin/roles route
func (h *Handlers) AdminCreateRole(c *gin.Context) {
var role db.Role
if err := c.ShouldBind(&role); err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("Invalid form data: %v", err))
return
}
// func (h *Handlers) AdminCreateRole(c *gin.Context) {
// name := c.PostForm("name")
// description := c.PostForm("description")
// permissions := c.PostFormArray("permissions[]")
// Process permissions
permissionsStr := c.PostForm("permissions")
if permissionsStr != "" {
permissions := strings.Split(permissionsStr, ",")
for i, p := range permissions {
permissions[i] = strings.TrimSpace(p)
}
role.Permissions = db.Permissions(permissions)
}
// // Create role
// role := &db.Role{
// Name: name,
// Description: description,
// }
// role.SetPermissions(permissions)
// Start a transaction
tx := h.DB.Begin()
if tx.Error != nil {
c.String(http.StatusInternalServerError, "Failed to begin transaction")
return
}
// // Validate role
// if err := role.Validate(); err != nil {
// ctx := components.CreateTemplateContext(c)
// data := components.RoleFormData{
// Role: &components.Role{Name: name, Description: description, Permissions: permissions},
// IsNew: true,
// ErrorMessage: err.Error(),
// AllPermissions: GetAllPermissions(),
// }
// _ = components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
// return
// }
// Save the role
if err := tx.Create(&role).Error; err != nil {
tx.Rollback()
c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to create role: %v", err))
return
}
// // Start transaction
// tx := h.DB.Begin()
// if err := tx.Error; err != nil {
// handleRoleError(c, role, true, "Failed to begin transaction: "+err.Error())
// return
// }
// Create audit log for role creation
adminID := c.GetUint("userID")
auditDetails := map[string]interface{}{
"name": role.Name,
"description": role.Description,
"permissions": role.Permissions,
}
// // Create role in database
// if err := tx.Create(role).Error; err != nil {
// tx.Rollback()
// handleRoleError(c, role, true, "Failed to create role: "+err.Error())
// return
// }
auditLog := db.AuditLog{
Action: "create",
EntityType: "role",
EntityID: role.ID,
UserID: adminID,
Details: auditDetails,
Timestamp: time.Now(),
}
// // Create audit log
// userID := getUserID(c) // Implement this helper to get current user ID
// if err := role.AuditLog(tx, "create", userID); err != nil {
// tx.Rollback()
// handleRoleError(c, role, true, "Failed to create audit log: "+err.Error())
// return
// }
if err := tx.Create(&auditLog).Error; err != nil {
tx.Rollback()
c.String(http.StatusInternalServerError, "Failed to create audit log")
return
}
// // Commit transaction
// if err := tx.Commit().Error; err != nil {
// handleRoleError(c, role, true, "Failed to commit transaction: "+err.Error())
// return
// }
// Commit the transaction
if err := tx.Commit().Error; err != nil {
c.String(http.StatusInternalServerError, "Failed to commit transaction")
return
}
c.Redirect(http.StatusFound, "/admin/roles")
}
// c.Redirect(http.StatusFound, "/admin/roles")
// }
// AdminEditRolePage handles the GET /admin/roles/:id/edit route
func (h *Handlers) AdminEditRolePage(c *gin.Context) {
id := c.Param("id")
// func (h *Handlers) AdminEditRolePage(c *gin.Context) {
// id := c.Param("id")
var dbRole db.Role
if err := h.DB.First(&dbRole, id).Error; err != nil {
c.Redirect(http.StatusFound, "/admin/roles")
return
}
// var dbRole db.Role
// if err := h.DB.First(&dbRole, id).Error; err != nil {
// c.Redirect(http.StatusFound, "/admin/roles")
// return
// }
// Convert db.Role to components.Role
role := &components.Role{
ID: dbRole.ID,
Name: dbRole.Name,
Description: dbRole.Description,
Permissions: dbRole.Permissions,
}
// // Convert db.Role to components.Role
// role := &components.Role{
// ID: dbRole.ID,
// Name: dbRole.Name,
// Description: dbRole.Description,
// Permissions: dbRole.Permissions,
// }
// All available permissions
allPermissions := []string{
"users.view", "users.create", "users.edit", "users.delete",
"roles.view", "roles.create", "roles.edit", "roles.delete",
"transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
"audit.view",
}
// // All available permissions
// allPermissions := []string{
// "users.view", "users.create", "users.edit", "users.delete",
// "roles.view", "roles.create", "roles.edit", "roles.delete",
// "transfers.view", "transfers.create", "transfers.edit", "transfers.delete",
// "audit.view",
// }
// Use components instead of HTML templates
data := components.RoleFormData{
Role: role,
IsNew: false,
AllPermissions: allPermissions,
}
// // Use components instead of HTML templates
// data := components.RoleFormData{
// Role: role,
// IsNew: false,
// AllPermissions: allPermissions,
// }
ctx := h.CreateTemplateContext(c)
components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
}
// ctx := h.CreateTemplateContext(c)
// components.AdminRoleForm(ctx, data).Render(ctx, c.Writer)
// }
// AdminUpdateRole handles the PUT /admin/roles/:id route
func (h *Handlers) AdminUpdateRole(c *gin.Context) {
id := c.Param("id")
// func (h *Handlers) AdminUpdateRole(c *gin.Context) {
// id := c.Param("id")
var role db.Role
if err := h.DB.First(&role, id).Error; err != nil {
c.String(http.StatusNotFound, "Role not found")
return
}
// var role db.Role
// if err := h.DB.First(&role, id).Error; err != nil {
// c.String(http.StatusNotFound, "Role not found")
// return
// }
// Store original role state for audit log
oldRole := role
// // Store original role state for audit log
// oldRole := role
// Update role with form data
name := c.PostForm("name")
if name != "" {
role.Name = name
}
// // Update role with form data
// name := c.PostForm("name")
// if name != "" {
// role.Name = name
// }
description := c.PostForm("description")
if description != "" {
role.Description = description
}
// description := c.PostForm("description")
// if description != "" {
// role.Description = description
// }
// Process permissions
permissionsStr := c.PostForm("permissions")
if permissionsStr != "" {
permissions := strings.Split(permissionsStr, ",")
for i, p := range permissions {
permissions[i] = strings.TrimSpace(p)
}
role.Permissions = db.Permissions(permissions)
}
// // Process permissions
// permissionsStr := c.PostForm("permissions")
// if permissionsStr != "" {
// permissions := strings.Split(permissionsStr, ",")
// for i, p := range permissions {
// permissions[i] = strings.TrimSpace(p)
// }
// role.Permissions = db.Permissions(permissions)
// }
// Start a transaction
tx := h.DB.Begin()
if tx.Error != nil {
c.String(http.StatusInternalServerError, "Failed to begin transaction")
return
}
// // Start a transaction
// tx := h.DB.Begin()
// if tx.Error != nil {
// c.String(http.StatusInternalServerError, "Failed to begin transaction")
// return
// }
// Save the role
if err := tx.Save(&role).Error; err != nil {
tx.Rollback()
c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to update role: %v", err))
return
}
// // Save the role
// if err := tx.Save(&role).Error; err != nil {
// tx.Rollback()
// c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to update role: %v", err))
// return
// }
// Create audit log entry
adminID := c.GetUint("userID")
auditDetails := map[string]interface{}{
"name": role.Name,
"description": role.Description,
"permissions": role.Permissions,
"previous_state": map[string]interface{}{
"name": oldRole.Name,
"description": oldRole.Description,
"permissions": oldRole.Permissions,
},
}
// // Create audit log entry
// adminID := c.GetUint("userID")
// auditDetails := map[string]interface{}{
// "name": role.Name,
// "description": role.Description,
// "permissions": role.Permissions,
// "previous_state": map[string]interface{}{
// "name": oldRole.Name,
// "description": oldRole.Description,
// "permissions": oldRole.Permissions,
// },
// }
auditLog := db.AuditLog{
Action: "update",
EntityType: "role",
EntityID: role.ID,
UserID: adminID,
Details: auditDetails,
Timestamp: time.Now(),
}
// auditLog := db.AuditLog{
// Action: "update",
// EntityType: "role",
// EntityID: role.ID,
// UserID: adminID,
// Details: auditDetails,
// Timestamp: time.Now(),
// }
if err := tx.Create(&auditLog).Error; err != nil {
tx.Rollback()
c.String(http.StatusInternalServerError, "Failed to create audit log")
return
}
// if err := tx.Create(&auditLog).Error; err != nil {
// tx.Rollback()
// c.String(http.StatusInternalServerError, "Failed to create audit log")
// return
// }
// Commit the transaction
if err := tx.Commit().Error; err != nil {
c.String(http.StatusInternalServerError, "Failed to commit transaction")
return
}
// // Commit the transaction
// if err := tx.Commit().Error; err != nil {
// c.String(http.StatusInternalServerError, "Failed to commit transaction")
// return
// }
c.Redirect(http.StatusFound, "/admin/roles")
}
// c.Redirect(http.StatusFound, "/admin/roles")
// }
// AdminDeleteRole handles the DELETE /admin/roles/:id route
func (h *Handlers) AdminDeleteRole(c *gin.Context) {
id := c.Param("id")
adminID := c.GetUint("userID")
// func (h *Handlers) AdminDeleteRole(c *gin.Context) {
// id := c.Param("id")
// adminID := c.GetUint("userID")
var role db.Role
if err := h.DB.First(&role, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Role not found"})
return
}
// var role db.Role
// if err := h.DB.First(&role, id).Error; err != nil {
// c.JSON(http.StatusNotFound, gin.H{"error": "Role not found"})
// return
// }
// Check if role is in use
var count int64
h.DB.Table("user_roles").Where("role_id = ?", role.ID).Count(&count)
if count > 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Role is assigned to users and cannot be deleted"})
return
}
// // Check if role is in use
// var count int64
// h.DB.Table("user_roles").Where("role_id = ?", role.ID).Count(&count)
// if count > 0 {
// c.JSON(http.StatusBadRequest, gin.H{"error": "Role is assigned to users and cannot be deleted"})
// return
// }
// Start a transaction
tx := h.DB.Begin()
if tx.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to begin transaction"})
return
}
// // Start a transaction
// tx := h.DB.Begin()
// if tx.Error != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to begin transaction"})
// return
// }
// Create audit log before deletion
auditDetails := map[string]interface{}{
"name": role.Name,
"description": role.Description,
"permissions": role.Permissions,
}
// // Create audit log before deletion
// auditDetails := map[string]interface{}{
// "name": role.Name,
// "description": role.Description,
// "permissions": role.Permissions,
// }
auditLog := db.AuditLog{
Action: "delete",
EntityType: "role",
EntityID: role.ID,
UserID: adminID,
Details: auditDetails,
Timestamp: time.Now(),
}
// auditLog := db.AuditLog{
// Action: "delete",
// EntityType: "role",
// EntityID: role.ID,
// UserID: adminID,
// Details: auditDetails,
// Timestamp: time.Now(),
// }
if err := tx.Create(&auditLog).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create audit log"})
return
}
// if err := tx.Create(&auditLog).Error; err != nil {
// tx.Rollback()
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create audit log"})
// return
// }
// Delete the role
if err := tx.Delete(&role).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to delete role: %v", err)})
return
}
// // Delete the role
// if err := tx.Delete(&role).Error; err != nil {
// tx.Rollback()
// c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to delete role: %v", err)})
// return
// }
// Commit the transaction
if err := tx.Commit().Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
return
}
// // Commit the transaction
// if err := tx.Commit().Error; err != nil {
// c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
// return
// }
c.JSON(http.StatusOK, gin.H{"message": "Role deleted successfully"})
}
// c.JSON(http.StatusOK, gin.H{"message": "Role deleted successfully"})
// }
// AdminUserRoles handles the GET /admin/users/:id/roles route
func (h *Handlers) AdminUserRoles(c *gin.Context) {
id := c.Param("id")
fmt.Println("AdminUserRoles")
var user db.User
if err := h.DB.First(&user, id).Error; err != nil {
c.Redirect(http.StatusFound, "/admin/users")