83 lines
2.1 KiB
Go
83 lines
2.1 KiB
Go
package admin
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
|
|
"gitea.local/admin/hspguard/internal/repository"
|
|
"gitea.local/admin/hspguard/internal/web"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
func (h *AdminHandler) GetAllPermissions(w http.ResponseWriter, r *http.Request) {
|
|
rows, err := h.repo.GetGroupedPermissions(r.Context())
|
|
if err != nil {
|
|
log.Println("ERR: Failed to list permissions from db:", err)
|
|
web.Error(w, "failed to get all permissions", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
type RowDTO struct {
|
|
Scope string `json:"scope"`
|
|
Permissions []repository.Permission `json:"permissions"`
|
|
}
|
|
|
|
if len(rows) == 0 {
|
|
rows = make([]repository.GetGroupedPermissionsRow, 0)
|
|
}
|
|
|
|
var mapped []RowDTO
|
|
|
|
for _, row := range rows {
|
|
var permissions []repository.Permission
|
|
|
|
if err := json.Unmarshal(row.Permissions, &permissions); err != nil {
|
|
log.Println("ERR: Failed to extract permissions from byte array:", err)
|
|
web.Error(w, "failed to get permissions", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
mapped = append(mapped, RowDTO{
|
|
Scope: row.Scope,
|
|
Permissions: permissions,
|
|
})
|
|
}
|
|
|
|
if len(mapped) == 0 {
|
|
mapped = make([]RowDTO, 0)
|
|
}
|
|
|
|
encoder := json.NewEncoder(w)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
if err := encoder.Encode(mapped); err != nil {
|
|
web.Error(w, "failed to encode response", http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func (h *AdminHandler) GetUserPermissions(w http.ResponseWriter, r *http.Request) {
|
|
userId := chi.URLParam(r, "user_id")
|
|
|
|
permissions, err := h.repo.GetUserPermissions(r.Context(), uuid.MustParse(userId))
|
|
if err != nil {
|
|
log.Println("ERR: Failed to list permissions from db:", err)
|
|
web.Error(w, "failed to get user permissions", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if len(permissions) == 0 {
|
|
permissions = make([]repository.Permission, 0)
|
|
}
|
|
|
|
encoder := json.NewEncoder(w)
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
if err := encoder.Encode(permissions); err != nil {
|
|
web.Error(w, "failed to encode response", http.StatusInternalServerError)
|
|
}
|
|
}
|