Gestion des permissions

This commit is contained in:
William Bouzourène 2025-01-03 16:13:41 +01:00
parent 9d25ca20df
commit 1705ac7353
6 changed files with 211 additions and 2 deletions

View file

@ -61,9 +61,15 @@ func UserShow(c *fiber.Ctx) error {
user.Name,
)
var userRoles []models.UserRole
db.Joins("Role").Joins("Section").Order("Section__name collate nocase asc").Find(
&userRoles, "user_id = ?", id,
)
return c.Render("user", fiber.Map{
"PageTitle": title,
"User": user,
"UserRoles": userRoles,
})
}
@ -231,6 +237,97 @@ func UserEdit(c *fiber.Ctx) error {
})
}
func UserPermissions(c *fiber.Ctx) error {
id := c.Params("id")
db, err := helpers.GetDatabase()
if err != nil {
return err
}
var user models.User
result := db.Find(&user, "id = ?", id)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return fiber.NewError(fiber.StatusNotFound, "Not found")
}
if result.Error != nil {
return result.Error
}
title := fmt.Sprintf(
"%s | Permissions utilisateur",
user.Name,
)
var roles []models.Role
db.Order("name collate nocase asc").Find(&roles)
var sections []models.Section
db.Order("name collate nocase asc").Find(&sections)
var errors []string
if c.Method() == "POST" {
var newUserRoles []models.UserRole
for _, section := range sections {
key := fmt.Sprintf("section-%d", section.ID)
value := c.FormValue(key, "0")
valueInt, err := strconv.ParseUint(value, 10, 0)
if err == nil && valueInt > 0 {
roleID := uint(valueInt)
roleFound := false
for _, role := range roles {
if role.ID == roleID {
roleFound = true
break
}
}
if roleFound {
newUserRoles = append(newUserRoles, models.UserRole{
UserID: user.ID,
RoleID: roleID,
SectionID: section.ID,
})
}
}
}
db.Delete(&models.UserRole{}, "user_id = ?", id)
for _, newUserRole := range newUserRoles {
db.Create(&newUserRole)
}
if len(errors) == 0 {
result2 := db.Save(&user)
if result2.Error != nil {
return result2.Error
} else {
c.Redirect(fmt.Sprintf(
"/admin/users/%d",
user.ID,
))
}
}
}
var userRoles []models.UserRole
db.Find(&userRoles, "user_id = ?", id)
return c.Render("user_permissions", fiber.Map{
"PageTitle": title,
"User": user,
"Roles": roles,
"Sections": sections,
"UserRoles": userRoles,
"Errors": errors,
})
}
func UserDelete(c *fiber.Ctx) error {
id := c.Params("id")