118 lines
2 KiB
Go
118 lines
2 KiB
Go
package helpers
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.readonly.ch/bouzoure/pop-camarades/models"
|
|
)
|
|
|
|
var Permissions = []string{
|
|
// Members
|
|
"show_member",
|
|
"create_member",
|
|
"edit_member",
|
|
"show_archived_member",
|
|
"archive_member",
|
|
"restore_member",
|
|
"purge_member",
|
|
"convert_member_to_contact",
|
|
// Contacts
|
|
"show_contact",
|
|
"create_contact",
|
|
"edit_contact",
|
|
"show_archived_contact",
|
|
"archive_contact",
|
|
"restore_contact",
|
|
"purge_contact",
|
|
"convert_contact_to_member",
|
|
}
|
|
|
|
func PermissionsGetSections(userid uint, permission string) ([]uint, error) {
|
|
var sections []uint
|
|
|
|
found := false
|
|
for _, item := range Permissions {
|
|
if item == permission {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
return sections, fmt.Errorf("unknown permission")
|
|
}
|
|
|
|
db, err := GetDatabase()
|
|
if err != nil {
|
|
return sections, err
|
|
}
|
|
|
|
var user models.User
|
|
result := db.Find(&user, "id = ?", userid)
|
|
|
|
if result.RowsAffected < 1 {
|
|
return sections, nil
|
|
}
|
|
|
|
if user.IsAdmin {
|
|
var allSections []models.Section
|
|
db.Find(&allSections)
|
|
|
|
for _, s := range allSections {
|
|
sections = append(sections, s.ID)
|
|
}
|
|
|
|
return sections, nil
|
|
}
|
|
|
|
var userRoles []models.UserRole
|
|
result = db.Joins(
|
|
"Role",
|
|
).Find(
|
|
&userRoles,
|
|
fmt.Sprintf(
|
|
"user_id = ? AND Role__%s = ?",
|
|
permission,
|
|
),
|
|
userid,
|
|
true,
|
|
)
|
|
|
|
if result.RowsAffected < 1 {
|
|
return sections, nil
|
|
}
|
|
|
|
for _, userRole := range userRoles {
|
|
sections = append(sections, userRole.SectionID)
|
|
|
|
var childSections []models.Section
|
|
db.Find(
|
|
&childSections,
|
|
"parent_section_id = ?",
|
|
userRole.SectionID,
|
|
)
|
|
|
|
for _, childSection := range childSections {
|
|
sections = append(sections, childSection.ID)
|
|
}
|
|
}
|
|
|
|
return sections, nil
|
|
}
|
|
|
|
func PermissionsCheckSection(userid uint, permission string, section uint) (bool, error) {
|
|
sections, err := PermissionsGetSections(userid, permission)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
allow := false
|
|
for _, s := range sections {
|
|
if s == section {
|
|
allow = true
|
|
break
|
|
}
|
|
}
|
|
|
|
return allow, nil
|
|
}
|