Compare commits

...

3 Commits

Author SHA1 Message Date
ac26a981b2 swag fmt 2025-12-21 22:21:58 +02:00
e9d8877fbf fully implement acl backend and interface 2025-12-21 22:18:29 +02:00
85f8ac60e7 some changes 2025-12-21 00:00:03 +02:00
20 changed files with 2072 additions and 1476 deletions

View File

@@ -1,5 +1,11 @@
package api_acladmin
import (
"encoding/json"
"log/slog"
"net/http"
)
const (
ErrorInvalidRequestBody = "INVALID_REQUEST_BODY"
ErrorInternalServerError = "INTERNAL_SERVER_ERROR"
@@ -26,3 +32,28 @@ const (
const (
ErrorACLServiceNotInitialized = "ACL service is not initialized"
)
// RFC-7807 (Problem Details)
type ProblemDetails struct {
Type string `json:"type" example:"https://api.triggerssmith.com/errors/role-not-found"`
Title string `json:"title" example:"Role not found"`
Status int `json:"status" example:"404"`
Detail string `json:"detail" example:"No role with ID 42"`
Instance string `json:"instance" example:"/api/acl/roles/42"`
}
var typeDomain = "https://api.triggerssmith.com"
func writeProblem(w http.ResponseWriter, status int, typ, title, detail string, r *http.Request) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
prob := ProblemDetails{
Type: typeDomain + typ,
Title: title,
Status: status,
Detail: detail,
Instance: r.URL.Path,
}
slog.Warn("new problem", "type", typ, "title", title, "detail", detail, "instance", r.URL.Path, "status", status)
_ = json.NewEncoder(w).Encode(prob)
}

View File

@@ -51,19 +51,28 @@ func MustRoute(config *config.Config, aclService *acl.Service, authService *auth
// DELETE /roles/{roleId}/resources/{resId} — убрать ресурс
return func(r chi.Router) {
// Roles
r.Get("/roles", h.getRoles) // list all roles
r.Post("/roles", h.createRole) // create a new role
r.Get("/roles/{roleId}", h.getRole) // get a role by ID
r.Patch("/roles/{roleId}", h.updateRole) // update a role by ID
r.Delete("/roles/{roleId}", h.deleteRole) // delete a role by ID
r.Get("/roles", h.getRoles) // list all roles
r.Post("/roles", h.createRole) // create a new role
r.Get("/roles/{roleId}", h.getRole) // get a role by ID
r.Get("/roles/{roleId}/users", h.getRoleUsers) // get all assigned users to a role
r.Get("/roles/{roleId}/resources", h.getRoleResources) // get all resources assigned to a role
r.Patch("/roles/{roleId}", h.updateRole) // update a role by ID
r.Delete("/roles/{roleId}", h.deleteRole) // delete a role by ID
r.Post("/roles/{roleId}/resources", h.assignResourceToRole) // assign a resource to a role
r.Delete("/roles/{roleId}/resources/{resId}", h.removeResourceFromRole) // remove a resource from a role
// // Resources
// Resources
r.Get("/resources", h.getResources) // list all resources
r.Post("/resources", h.createResource) // create a new resource
r.Get("/resources/{resourceId}", h.getResource) // get a resource by ID
r.Patch("/resources/{resourceId}", h.updateResource) // update a resource by ID
r.Delete("/resources/{resourceId}", h.deleteResource) // delete a resource by ID
// Users
r.Get("/users/{userId}/roles", h.getUserRoles) // get all roles for a user
r.Post("/users/{userId}/roles", h.assignRoleToUser) // assign a role to a user
r.Delete("/users/{userId}/roles/{roleId}", h.removeRoleFromUser) // remove a role from a user
// Users
// r.Get("/users/{userId}/roles", h.getUserRoles) // get all roles for a user
// r.Post("/users/{userId}/roles", h.assignRoleToUser) // assign a role to a user

View File

@@ -11,67 +11,55 @@ import (
)
// @Summary Get all resources
// @Tags resources
// @Tags acl/resources
// @Produce json
// @Success 200 {object} getResourcesResponse
// @Failure 500 {object} errorInternalServerError
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/resources [get]
func (h *aclAdminHandler) getResources(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resources, err := h.a.GetResources()
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get resources",
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
_ = json.NewEncoder(w).Encode(func() getResourcesResponse {
resp := make(getResourcesResponse, 0, len(resources))
for _, res := range resources {
resp = append(resp, struct {
ID uint `json:"id" example:"1"`
Key string `json:"key" example:"html.view"`
}{
ID: res.ID,
Key: res.Key,
})
}
return resp
}())
type R struct {
ID uint `json:"id" example:"1"`
Key string `json:"key" example:"html.view"`
}
resp := make([]R, 0, len(resources))
for _, res := range resources {
resp = append(resp, R{ID: res.ID, Key: res.Key})
}
_ = json.NewEncoder(w).Encode(resp)
}
// @Summary Get resource by ID
// @Tags resources
// @Tags acl/resources
// @Produce json
// @Param resourceId path int true "Resource ID" example(1)
// @Success 200 {object} getResourceResponse
// @Failure 400 {object} getResourceErrorInvalidResourceID
// @Failure 404 {object} getResourceErrorResourceNotFound
// @Failure 500 {object} errorInternalServerError
// @Success 200 {object} getResourceResponse
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/resources/{resourceId} [get]
func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resourceIDStr := chi.URLParam(r, "resourceId")
resourceID, err := strconv.Atoi(resourceIDStr)
if err != nil || resourceID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(getResourceErrorInvalidResourceID{
Error: ErrorInvalidResourceID,
Details: "Resource ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
return
}
@@ -79,27 +67,14 @@ func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(getResourceErrorResourceNotFound{
Error: ErrorResourceNotFound,
Details: "No resource with ID " + resourceIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get resource with ID " + resourceIDStr,
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
_ = json.NewEncoder(w).Encode(getResourceResponse{
@@ -109,61 +84,40 @@ func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
}
// @Summary Create resource
// @Tags resources
// @Tags acl/resources
// @Accept json
// @Produce json
// @Param request body createResourceRequest true "Resource"
// @Success 201 {object} createResourceResponse
// @Failure 400 {object} errorInvalidRequestBody
// @Failure 400 {object} createResourceErrorInvalidResourceKey
// @Failure 409 {object} createResourceErrorResourceAlreadyExists
// @Failure 500 {object} errorInternalServerError
// @Failure 400 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/resources [post]
func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req createResourceRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
Error: ErrorInvalidRequestBody,
Details: "Request body is not valid JSON",
})
writeProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
return
}
resourceID, err := h.a.CreateResource(req.Key)
if err != nil {
slog.Error("Failed to create resource", "error", err.Error())
slog.Error("Failed to create resource", "error", err)
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
case acl.ErrInvalidResourceKey:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(createResourceErrorInvalidResourceKey{
Error: ErrorFailedToCreateResource,
Details: "Resource key must be non-empty",
})
return
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-key", "Invalid resource key", "Resource key must be non-empty", r)
case acl.ErrResourceAlreadyExists:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(createResourceErrorResourceAlreadyExists{
Error: ErrorFailedToCreateResource,
Details: "Resource with key '" + req.Key + "' already exists",
})
return
writeProblem(w, http.StatusConflict, "/errors/acl/resource-already-exists", "Resource already exists", "Resource '"+req.Key+"' already exists", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to create resource with key '" + req.Key + "'",
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusCreated)
@@ -174,85 +128,53 @@ func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request)
}
// @Summary Update resource
// @Tags resources
// @Tags acl/resources
// @Accept json
// @Produce json
// @Param resourceId path int true "Resource ID" example(1)
// @Param request body updateResourceRequest true "Resource"
// @Success 200 {object} updateResourceResponse
// @Failure 400 {object} errorInvalidRequestBody
// @Failure 400 {object} updateResourceErrorInvalidResourceID
// @Failure 400 {object} updateResourceErrorInvalidResourceKey
// @Failure 404 {object} updateResourceErrorResourceNotFound
// @Failure 409 {object} updateResourceErrorResourceKeyAlreadyExists
// @Failure 500 {object} errorInternalServerError
// @Param request body updateResourceRequest true "Resource"
// @Success 200 {object} updateResourceResponse
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/resources/{resourceId} [patch]
func (h *aclAdminHandler) updateResource(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req updateResourceRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
Error: ErrorInvalidRequestBody,
Details: "Request body is not valid JSON",
})
writeProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
return
}
resourceIDStr := chi.URLParam(r, "resourceId")
resourceID, err := strconv.Atoi(resourceIDStr)
if err != nil || resourceID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateResourceErrorInvalidResourceID{
Error: ErrorInvalidResourceID,
Details: "Resource ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
return
}
err = h.a.UpdateResource(uint(resourceID), req.Key)
if err != nil {
slog.Error("Failed to update resource", "error", err.Error())
slog.Error("Failed to update resource", "error", err)
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
case acl.ErrInvalidResourceKey:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateResourceErrorInvalidResourceKey{
Error: ErrorFailedToUpdateResource,
Details: "Invalid resource key",
})
return
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-key", "Invalid resource key", "Resource key must be non-empty", r)
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceNotFound{
Error: ErrorFailedToUpdateResource,
Details: "No resource with ID " + resourceIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
case acl.ErrSameResourceKey:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceKeyAlreadyExists{
Error: ErrorFailedToUpdateResource,
Details: "Resource with key '" + req.Key + "' already exists",
})
return
writeProblem(w, http.StatusConflict, "/errors/acl/resource-key-already-exists", "Resource key already exists", "Resource key '"+req.Key+"' already exists", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to update resource with key '" + req.Key + "'",
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(updateResourceResponse{
ID: uint(resourceID),
Key: req.Key,
@@ -260,61 +182,41 @@ func (h *aclAdminHandler) updateResource(w http.ResponseWriter, r *http.Request)
}
// @Summary Delete resource
// @Tags resources
// @Tags acl/resources
// @Produce json
// @Param resourceId path int true "Resource ID" example(1)
// @Param resourceId path int true "Resource ID" example(1)
// @Success 200
// @Failure 400 {object} deleteResourceErrorInvalidResourceID
// @Failure 404 {object} deleteResourceErrorResourceNotFound
// @Failure 409 {object} deleteResourceErrorResourceInUse
// @Failure 500 {object} errorInternalServerError
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/resources/{resourceId} [delete]
func (h *aclAdminHandler) deleteResource(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resourceIDStr := chi.URLParam(r, "resourceId")
resourceID, err := strconv.Atoi(resourceIDStr)
if err != nil || resourceID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(deleteResourceErrorInvalidResourceID{
Error: ErrorInvalidResourceID,
Details: "Resource ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
return
}
err = h.a.DeleteResource(uint(resourceID))
if err != nil {
slog.Error("Failed to delete resource", "error", err.Error())
slog.Error("Failed to delete resource", "error", err)
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(deleteResourceErrorResourceNotFound{
Error: ErrorFailedToDeleteResource,
Details: "No resource with ID " + resourceIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
case acl.ErrResourceInUse:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(deleteResourceErrorResourceInUse{
Error: ErrorFailedToDeleteResource,
Details: "Resource with ID " + resourceIDStr + " is used and cannot be deleted",
})
return
writeProblem(w, http.StatusConflict, "/errors/acl/resource-in-use", "Resource in use", "Resource "+resourceIDStr+" is in use", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to delete resource with ID '" + resourceIDStr + "'",
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusOK)

View File

@@ -7,6 +7,8 @@ type getResourcesResponse []struct {
Key string `json:"key" example:"html.view"`
}
var _ getResourcesResponse // for documentation
/*******************************************************************/
// used in getResource()
type getResourceResponse struct {
@@ -14,16 +16,6 @@ type getResourceResponse struct {
Key string `json:"key" example:"html.view"`
}
type getResourceErrorInvalidResourceID struct {
Error string `json:"error" example:"INVALID_RESOURCE_ID"`
Details string `json:"details" example:"Resource ID must be positive integer"`
}
type getResourceErrorResourceNotFound struct {
Error string `json:"error" example:"RESOURCE_NOT_FOUND"`
Details string `json:"details" example:"No resource with ID 123"`
}
/*******************************************************************/
// used in createResource()
type createResourceRequest struct {
@@ -35,16 +27,6 @@ type createResourceResponse struct {
Key string `json:"key" example:"html.view"`
}
type createResourceErrorResourceAlreadyExists struct {
Error string `json:"error" example:"FAILED_TO_CREATE_RESOURCE"`
Details string `json:"details" example:"Resource with key 'html.view' already exists"`
}
type createResourceErrorInvalidResourceKey struct {
Error string `json:"error" example:"FAILED_TO_CREATE_RESOURCE"`
Details string `json:"details" example:"Invalid resource key"`
}
/*******************************************************************/
// used in updateResource()
type updateResourceRequest struct {
@@ -55,40 +37,3 @@ type updateResourceResponse struct {
ID uint `json:"id" example:"1"`
Key string `json:"key" example:"html.view"`
}
type updateResourceErrorResourceNotFound struct {
Error string `json:"error" example:"RESOURCE_NOT_FOUND"`
Details string `json:"details" example:"No resource with ID 123"`
}
type updateResourceErrorInvalidResourceID struct {
Error string `json:"error" example:"INVALID_RESOURCE_ID"`
Details string `json:"details" example:"Resource ID must be positive integer"`
}
type updateResourceErrorInvalidResourceKey struct {
Error string `json:"error" example:"FAILED_TO_UPDATE_RESOURCE"`
Details string `json:"details" example:"Invalid resource key"`
}
type updateResourceErrorResourceKeyAlreadyExists struct {
Error string `json:"error" example:"FAILED_TO_UPDATE_RESOURCE"`
Details string `json:"details" example:"Resource with key 'html.view' already exists"`
}
/*******************************************************************/
// used in deleteResource()
type deleteResourceErrorResourceNotFound struct {
Error string `json:"error" example:"RESOURCE_NOT_FOUND"`
Details string `json:"details" example:"No resource with ID 123"`
}
type deleteResourceErrorInvalidResourceID struct {
Error string `json:"error" example:"INVALID_RESOURCE_ID"`
Details string `json:"details" example:"Resource ID must be positive integer"`
}
type deleteResourceErrorResourceInUse struct {
Error string `json:"error" example:"FAILED_TO_DELETE_RESOURCE"`
Details string `json:"details" example:"Resource with ID 123 is used and cannot be deleted"`
}

View File

@@ -11,10 +11,10 @@ import (
)
// @Summary Get all roles
// @Tags roles
// @Tags acl/roles
// @Produce json
// @Success 200 {object} getRolesResponse
// @Failure 500 {object} errorInternalServerError
// @Success 200 {array} getRolesResponse
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles [get]
func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
@@ -22,146 +22,190 @@ func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get roles",
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
_ = json.NewEncoder(w).Encode(func() getRolesResponse {
// Transform acl.Role to getRolesResponse
resp := make(getRolesResponse, 0, len(roles))
for _, role := range roles {
resp = append(resp, struct {
ID uint `json:"id" example:"1"`
Name string `json:"name" example:"admin"`
}{
ID: role.ID,
Name: role.Name,
})
}
return resp
}())
type R struct {
ID uint `json:"id" example:"1"`
Name string `json:"name" example:"admin"`
}
resp := make([]R, 0, len(roles))
for _, role := range roles {
resp = append(resp, R{ID: role.ID, Name: role.Name})
}
_ = json.NewEncoder(w).Encode(resp)
}
// @Summary Get role by ID
// @Tags roles
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Success 200 {object} getRoleResponse
// @Failure 400 {object} getRoleErrorInvalidRoleID
// @Failure 404 {object} getRoleErrorRoleNotFound
// @Failure 500 {object} errorInternalServerError
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId} [get]
func (h *aclAdminHandler) getRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(getRoleErrorInvalidRoleID{
Error: ErrorInvalidRoleID,
Details: "Role ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
role, err := h.a.GetRoleByID(uint(roleID))
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(getRoleErrorRoleNotFound{
Error: ErrorRoleNotFound,
Details: "No role with ID " + roleIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get role with ID " + roleIDStr,
})
return
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
_ = json.NewEncoder(w).Encode(getRoleResponse{
ID: role.ID,
Name: role.Name,
})
}
// @Summary Get role users
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Success 200 {array} getRoleUsersResponse
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId}/users [get]
func (h *aclAdminHandler) getRoleUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
role, err := h.a.GetRoleByID(uint(roleID))
if err != nil {
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
default:
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
if len(role.Users) == 0 {
writeProblem(w, http.StatusNotFound, "/errors/acl/role-has-no-users", "Role has no users", "Role has no users", r)
return
}
var respUsers getRoleUsersResponse
for _, user := range role.Users {
respUsers = append(respUsers, getRoleUser{
ID: user.ID,
Name: user.Username,
Email: user.Email,
})
}
_ = json.NewEncoder(w).Encode(respUsers)
}
// @Summary Get role resources
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Success 200 {array} getRoleResourcesResponse
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId}/resources [get]
func (h *aclAdminHandler) getRoleResources(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
role, err := h.a.GetRoleByID(uint(roleID))
if err != nil {
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
default:
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
if len(role.Resources) == 0 {
writeProblem(w, http.StatusNotFound, "/errors/acl/role-has-no-users", "Role has no users", "Role has no users", r)
return
}
var respResources getRoleResourcesResponse
for _, user := range role.Resources {
respResources = append(respResources, getRoleResource{
ID: user.ID,
Name: user.Key,
})
}
_ = json.NewEncoder(w).Encode(respResources)
}
// @Summary Create role
// @Tags roles
// @Tags acl/roles
// @Accept json
// @Produce json
// @Param request body createRoleRequest true "Role"
// @Success 201 {object} createRoleResponse
// @Failure 400 {object} errorInvalidRequestBody
// @Failure 401 {object} createRoleErrorInvalidRoleName
// @Failure 409 {object} createRoleErrorRoleAlreadyExists
// @Failure 500 {object} errorInternalServerError
// @Failure 400 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles [post]
func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req createRoleRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
Error: ErrorInvalidRequestBody,
Details: "Request body is not valid JSON",
})
writeProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
return
}
roleID, err := h.a.CreateRole(req.Name)
if err != nil {
slog.Error("Failed to create role", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
case acl.ErrRoleAlreadyExists:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(createRoleErrorRoleAlreadyExists{
Error: ErrorFailedToCreateRole,
Details: "Role with name '" + req.Name + "' already exists",
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrInvalidRoleName:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(createRoleErrorInvalidRoleName{
Error: ErrorFailedToCreateRole,
Details: "Role name must be non-empty string",
})
return
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-name", "Invalid role name", "Role name must be non-empty", r)
case acl.ErrRoleAlreadyExists:
writeProblem(w, http.StatusConflict, "/errors/acl/role-already-exists", "Role already exists", "Role '"+req.Name+"' already exists", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to create role with name '" + req.Name + "'",
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(createRoleResponse{
ID: roleID,
@@ -170,83 +214,51 @@ func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
}
// @Summary Update role
// @Tags roles
// @Tags acl/roles
// @Accept json
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Param request body updateRoleRequest true "Role"
// @Success 200 {object} updateRoleResponse
// @Failure 400 {object} errorInvalidRequestBody
// @Failure 400 {object} updateRoleErrorInvalidRoleID
// @Failure 400 {object} updateRoleErrorInvalidRoleName
// @Failure 404 {object} updateRoleErrorRoleNotFound
// @Failure 409 {object} updateRoleErrorRoleNameAlreadyExists
// @Failure 500 {object} errorInternalServerError
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId} [patch]
func (h *aclAdminHandler) updateRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req updateRoleRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
Error: ErrorInvalidRequestBody,
Details: "Request body is not valid JSON",
})
writeProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
return
}
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateRoleErrorInvalidRoleID{
Error: ErrorInvalidRoleID,
Details: "Role ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
err = h.a.UpdateRole(uint(roleID), req.Name)
// TODO: make error handling more specific in acl service
if err != nil {
slog.Error("Failed to update role", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrInvalidRoleName:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateRoleErrorInvalidRoleName{
Error: ErrorFailedToUpdateRole,
Details: "Invalid role name",
})
return
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-name", "Invalid role name", "Role name must be non-empty", r)
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNotFound{
Error: ErrorFailedToUpdateRole,
Details: "No role with ID " + roleIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
case acl.ErrSameRoleName:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNameAlreadyExists{
Error: ErrorFailedToUpdateRole,
Details: "Role with name '" + req.Name + "' already exists",
})
return
writeProblem(w, http.StatusConflict, "/errors/acl/role-name-already-exists", "Role name already exists", "Role '"+req.Name+"' already exists", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to update role with name '" + req.Name + "'",
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(updateRoleResponse{
ID: uint(roleID),
Name: req.Name,
@@ -254,61 +266,125 @@ func (h *aclAdminHandler) updateRole(w http.ResponseWriter, r *http.Request) {
}
// @Summary Delete role
// @Tags roles
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Success 200
// @Failure 400 {object} deleteRoleErrorInvalidRoleID
// @Failure 404 {object} deleteRoleErrorRoleNotFound
// @Failure 409 {object} deleteRoleErrorRoleInUse
// @Failure 500 {object} errorInternalServerError
// @Param roleId path int true "Role ID" example(1)
// @Success 204
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId} [delete]
func (h *aclAdminHandler) deleteRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(deleteRoleErrorInvalidRoleID{
Error: ErrorInvalidRoleID,
Details: "Role ID must be positive integer",
})
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
err = h.a.DeleteRole(uint(roleID))
// TODO: make error handling more specific in acl service
if err != nil {
slog.Error("Failed to delete role", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(deleteRoleErrorRoleNotFound{
Error: ErrorFailedToDeleteRole,
Details: "No role with ID " + roleIDStr,
})
return
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
case acl.ErrRoleInUse:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(deleteRoleErrorRoleInUse{
Error: ErrorFailedToDeleteRole,
Details: "Role with ID " + roleIDStr + " is assigned to users and cannot be deleted",
})
return
writeProblem(w, http.StatusConflict, "/errors/acl/role-in-use", "Role in use", "Role "+roleIDStr+" is assigned to at least one user and cannot be deleted", r)
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to delete role with ID '" + roleIDStr + "'",
})
return
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusOK)
w.WriteHeader(http.StatusNoContent)
}
// @Summary Assign resource to role
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Param request body assignResourceToRoleRequest true "Resource"
// @Success 201
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId}/resources [post]
func (h *aclAdminHandler) assignResourceToRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
var req assignResourceToRoleRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-request-body", "Invalid request body", "Invalid JSON body", r)
return
}
if err := h.a.AssignResourceToRole(uint(roleID), req.ResourceID); err != nil {
slog.Error("Failed to assign resource to role", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
case acl.ErrResourceNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+strconv.Itoa(int(req.ResourceID)), r)
case acl.ErrResourceAlreadyAssigned:
writeProblem(w, http.StatusConflict, "/errors/acl/resource-already-assigned", "Resource already assigned", "Resource with ID "+strconv.Itoa(int(req.ResourceID))+" is already assigned to role with ID "+roleIDStr, r)
default:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusCreated)
}
// @Summary Remove resource from role
// @Tags acl/roles
// @Produce json
// @Param roleId path int true "Role ID" example(1)
// @Param resId path int true "Resource ID" example(1)
// @Success 204
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/roles/{roleId}/resources/{resId} [delete]
func (h *aclAdminHandler) removeResourceFromRole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
resourceIDStr := chi.URLParam(r, "resId")
resourceID, err := strconv.Atoi(resourceIDStr)
if err != nil || resourceID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
return
}
if err := h.a.RemoveResourceFromRole(uint(roleID), uint(resourceID)); err != nil {
slog.Error("Failed to remove resource from role", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
case acl.ErrResourceNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+strconv.Itoa(int(resourceID)), r)
case acl.ErrRoleResourceNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/role-resource-not-found", "Role resource not found", "No role-resource pair with role ID "+roleIDStr+" and resource ID "+strconv.Itoa(int(resourceID)), r)
default:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -7,6 +7,8 @@ type getRolesResponse []struct {
Name string `json:"name" example:"admin"`
}
var _ getRolesResponse
/*******************************************************************/
// used in getRole()
type getRoleResponse struct {
@@ -14,15 +16,22 @@ type getRoleResponse struct {
Name string `json:"name" example:"admin"`
}
type getRoleErrorInvalidRoleID struct {
Error string `json:"error" example:"INVALID_ROLE_ID"`
Details string `json:"details" example:"Role ID must be positive integer"`
/*******************************************************************/
// used in getRoleUsers()
type getRoleUser struct {
ID uint `json:"id" example:"1"`
Name string `json:"username" example:"admin"`
Email string `json:"email" example:"admin@triggerssmith.com"`
}
type getRoleUsersResponse []getRoleUser
type getRoleErrorRoleNotFound struct {
Error string `json:"error" example:"ROLE_NOT_FOUND"`
Details string `json:"details" example:"No role with ID 123"`
/*******************************************************************/
// used in getRoleResources()
type getRoleResource struct {
ID uint `json:"id" example:"1"`
Name string `json:"name" example:"*"`
}
type getRoleResourcesResponse []getRoleResource
/*******************************************************************/
// used in createRole()
@@ -35,16 +44,6 @@ type createRoleResponse struct {
Name string `json:"name" example:"admin"`
}
type createRoleErrorRoleAlreadyExists struct {
Error string `json:"error" example:"FAILED_TO_CREATE_ROLE"`
Details string `json:"details" example:"Role with name 'admin' already exists"`
}
type createRoleErrorInvalidRoleName struct {
Error string `json:"error" example:"FAILED_TO_CREATE_ROLE"`
Details string `json:"details" example:"Invalid role name"`
}
/*******************************************************************/
// used in updateRole()
type updateRoleRequest struct {
@@ -56,39 +55,8 @@ type updateRoleResponse struct {
Name string `json:"name" example:"admin"`
}
type updateRoleErrorRoleNotFound struct {
Error string `json:"error" example:"ROLE_NOT_FOUND"`
Details string `json:"details" example:"No role with ID 123"`
}
type updateRoleErrorInvalidRoleID struct {
Error string `json:"error" example:"INVALID_ROLE_ID"`
Details string `json:"details" example:"Role ID must be positive integer"`
}
type updateRoleErrorInvalidRoleName struct {
Error string `json:"error" example:"FAILED_TO_UPDATE_ROLE"`
Details string `json:"details" example:"Invalid role name"`
}
type updateRoleErrorRoleNameAlreadyExists struct {
Error string `json:"error" example:"FAILED_TO_UPDATE_ROLE"`
Details string `json:"details" example:"Role with name 'admin' already exists"`
}
/*******************************************************************/
// used in deleteRole()
type deleteRoleErrorRoleNotFound struct {
Error string `json:"error" example:"ROLE_NOT_FOUND"`
Details string `json:"details" example:"No role with ID 123"`
}
type deleteRoleErrorInvalidRoleID struct {
Error string `json:"error" example:"INVALID_ROLE_ID"`
Details string `json:"details" example:"Role ID must be positive integer"`
}
type deleteRoleErrorRoleInUse struct {
Error string `json:"error" example:"FAILED_TO_DELETE_ROLE"`
Details string `json:"details" example:"Role with ID 123 is assigned to users and cannot be deleted"`
// used in assignResourceToRole()
type assignResourceToRoleRequest struct {
ResourceID uint `json:"resourceId" example:"1"`
}

136
api/acl_admin/users.go Normal file
View File

@@ -0,0 +1,136 @@
package api_acladmin
import (
"encoding/json"
"log/slog"
"net/http"
"strconv"
"git.oblat.lv/alex/triggerssmith/internal/acl"
"github.com/go-chi/chi/v5"
)
// @Summary Get user roles by user ID
// @Tags acl/users
// @Produce json
// @Param userId path int true "User ID" example(1)
// @Success 200 {object} getUserRolesResponse
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/users/{userId}/roles [get]
func (h *aclAdminHandler) getUserRoles(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
userIDStr := chi.URLParam(r, "userId")
userID, err := strconv.Atoi(userIDStr)
if err != nil {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
return
}
roles, err := h.a.GetUserRoles(uint(userID))
if err != nil {
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrUserNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
default:
slog.Error("unexpected server error", "error", err.Error())
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
resp := make(getUserRolesResponse, 0, len(roles))
for _, role := range roles {
resp = append(resp, getUserRole{ID: role.ID, Name: role.Name})
}
_ = json.NewEncoder(w).Encode(resp)
}
// @Summary Assign role to user
// @Tags acl/users
// @Produce json
// @Param userId path int true "User ID" example(1)
// @Param body body assignRoleToUserRequest true "Role ID"
// @Success 201
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 409 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/users/{userId}/roles [post]
func (h *aclAdminHandler) assignRoleToUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
userIDStr := chi.URLParam(r, "userId")
userID, err := strconv.Atoi(userIDStr)
if err != nil || userID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
return
}
var req assignRoleToUserRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-request-body", "Invalid request body", "Invalid JSON body", r)
return
}
if err := h.a.AssignRoleToUser(req.RoleID, uint(userID)); err != nil {
slog.Error("Failed to assign role to user", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrUserNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
case acl.ErrRoleAlreadyAssigned:
writeProblem(w, http.StatusConflict, "/errors/acl/role-already-assigned", "Role already assigned", "Role with ID "+strconv.Itoa(int(req.RoleID))+" is already assigned to user "+strconv.Itoa(userID), r)
default:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
return
}
w.WriteHeader(http.StatusCreated)
}
// @Summary Remove role from user
// @Tags acl/users
// @Produce json
// @Param userId path int true "User ID" example(1)
// @Param roleId path int true "Role ID" example(1)
// @Success 204
// @Failure 400 {object} ProblemDetails
// @Failure 404 {object} ProblemDetails
// @Failure 500 {object} ProblemDetails
// @Router /api/acl/users/{userId}/roles/{roleId} [delete]
func (h *aclAdminHandler) removeRoleFromUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
userIDStr := chi.URLParam(r, "userId")
userID, err := strconv.Atoi(userIDStr)
if err != nil || userID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
return
}
roleIDStr := chi.URLParam(r, "roleId")
roleID, err := strconv.Atoi(roleIDStr)
if err != nil || roleID < 0 {
writeProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
return
}
err = h.a.RemoveRoleFromUser(uint(roleID), uint(userID))
if err != nil {
slog.Error("Failed to remove role from user", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
case acl.ErrUserNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
case acl.ErrRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
case acl.ErrUserRoleNotFound:
writeProblem(w, http.StatusNotFound, "/errors/acl/user-role-not-found", "User role not found", "User "+strconv.Itoa(userID)+" does not have role "+strconv.Itoa(roleID), r)
default:
writeProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
}
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -0,0 +1,16 @@
package api_acladmin
/*******************************************************************/
// used in getUserRoles()
type getUserRole struct {
ID uint `json:"id" example:"1"`
Name string `json:"name" example:"*"`
}
type getUserRolesResponse []getUserRole
/*******************************************************************/
// used in assignRoleToUser()
type assignRoleToUserRequest struct {
RoleID uint `json:"roleId" example:"1"`
}

View File

@@ -5,6 +5,7 @@ package api_auth
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"time"
@@ -79,6 +80,7 @@ func (h *authHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
user, err := h.a.Register(req.Username, req.Email, req.Password)
if err != nil {
slog.Error("Failed to register user", "error", err)
http.Error(w, "Registration failed", http.StatusInternalServerError)
return
}

View File

@@ -90,7 +90,7 @@ func (r *Router) MustRoute() chi.Router {
api.Route("/block", api_block.MustRoute(r.cfg))
authRoute := api_auth.MustRoute(r.cfg, r.authService)
api.Route("/auth", authRoute)
api.Route("/users", authRoute) // legacy support
//api.Route("/users", authRoute) // legacy support
aclAdminRoute := api_acladmin.MustRoute(r.cfg, r.aclService, r.authService)
api.Route("/acl", aclAdminRoute)
api.Route("/acl-admin", aclAdminRoute) // legacy support

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,21 +1,33 @@
definitions:
api_acladmin.createResourceErrorInvalidResourceKey:
api_acladmin.ProblemDetails:
properties:
details:
example: Invalid resource key
detail:
example: No role with ID 42
type: string
error:
example: FAILED_TO_CREATE_RESOURCE
instance:
example: /api/acl/roles/42
type: string
status:
example: 404
type: integer
title:
example: Role not found
type: string
type:
example: https://api.triggerssmith.com/errors/role-not-found
type: string
type: object
api_acladmin.createResourceErrorResourceAlreadyExists:
api_acladmin.assignResourceToRoleRequest:
properties:
details:
example: Resource with key 'html.view' already exists
type: string
error:
example: FAILED_TO_CREATE_RESOURCE
type: string
resourceId:
example: 1
type: integer
type: object
api_acladmin.assignRoleToUserRequest:
properties:
roleId:
example: 1
type: integer
type: object
api_acladmin.createResourceRequest:
properties:
@@ -32,24 +44,6 @@ definitions:
example: html.view
type: string
type: object
api_acladmin.createRoleErrorInvalidRoleName:
properties:
details:
example: Invalid role name
type: string
error:
example: FAILED_TO_CREATE_ROLE
type: string
type: object
api_acladmin.createRoleErrorRoleAlreadyExists:
properties:
details:
example: Role with name 'admin' already exists
type: string
error:
example: FAILED_TO_CREATE_ROLE
type: string
type: object
api_acladmin.createRoleRequest:
properties:
name:
@@ -65,94 +59,6 @@ definitions:
example: admin
type: string
type: object
api_acladmin.deleteResourceErrorInvalidResourceID:
properties:
details:
example: Resource ID must be positive integer
type: string
error:
example: INVALID_RESOURCE_ID
type: string
type: object
api_acladmin.deleteResourceErrorResourceInUse:
properties:
details:
example: Resource with ID 123 is used and cannot be deleted
type: string
error:
example: FAILED_TO_DELETE_RESOURCE
type: string
type: object
api_acladmin.deleteResourceErrorResourceNotFound:
properties:
details:
example: No resource with ID 123
type: string
error:
example: RESOURCE_NOT_FOUND
type: string
type: object
api_acladmin.deleteRoleErrorInvalidRoleID:
properties:
details:
example: Role ID must be positive integer
type: string
error:
example: INVALID_ROLE_ID
type: string
type: object
api_acladmin.deleteRoleErrorRoleInUse:
properties:
details:
example: Role with ID 123 is assigned to users and cannot be deleted
type: string
error:
example: FAILED_TO_DELETE_ROLE
type: string
type: object
api_acladmin.deleteRoleErrorRoleNotFound:
properties:
details:
example: No role with ID 123
type: string
error:
example: ROLE_NOT_FOUND
type: string
type: object
api_acladmin.errorInternalServerError:
properties:
details:
type: string
error:
type: string
type: object
api_acladmin.errorInvalidRequestBody:
properties:
details:
example: Request body is not valid JSON
type: string
error:
example: INVALID_REQUEST_BODY
type: string
type: object
api_acladmin.getResourceErrorInvalidResourceID:
properties:
details:
example: Resource ID must be positive integer
type: string
error:
example: INVALID_RESOURCE_ID
type: string
type: object
api_acladmin.getResourceErrorResourceNotFound:
properties:
details:
example: No resource with ID 123
type: string
error:
example: RESOURCE_NOT_FOUND
type: string
type: object
api_acladmin.getResourceResponse:
properties:
id:
@@ -162,22 +68,13 @@ definitions:
example: html.view
type: string
type: object
api_acladmin.getRoleErrorInvalidRoleID:
api_acladmin.getRoleResource:
properties:
details:
example: Role ID must be positive integer
type: string
error:
example: INVALID_ROLE_ID
type: string
type: object
api_acladmin.getRoleErrorRoleNotFound:
properties:
details:
example: No role with ID 123
type: string
error:
example: ROLE_NOT_FOUND
id:
example: 1
type: integer
name:
example: '*'
type: string
type: object
api_acladmin.getRoleResponse:
@@ -189,40 +86,25 @@ definitions:
example: admin
type: string
type: object
api_acladmin.updateResourceErrorInvalidResourceID:
api_acladmin.getRoleUser:
properties:
details:
example: Resource ID must be positive integer
email:
example: admin@triggerssmith.com
type: string
error:
example: INVALID_RESOURCE_ID
id:
example: 1
type: integer
username:
example: admin
type: string
type: object
api_acladmin.updateResourceErrorInvalidResourceKey:
api_acladmin.getUserRole:
properties:
details:
example: Invalid resource key
type: string
error:
example: FAILED_TO_UPDATE_RESOURCE
type: string
type: object
api_acladmin.updateResourceErrorResourceKeyAlreadyExists:
properties:
details:
example: Resource with key 'html.view' already exists
type: string
error:
example: FAILED_TO_UPDATE_RESOURCE
type: string
type: object
api_acladmin.updateResourceErrorResourceNotFound:
properties:
details:
example: No resource with ID 123
type: string
error:
example: RESOURCE_NOT_FOUND
id:
example: 1
type: integer
name:
example: '*'
type: string
type: object
api_acladmin.updateResourceRequest:
@@ -240,42 +122,6 @@ definitions:
example: html.view
type: string
type: object
api_acladmin.updateRoleErrorInvalidRoleID:
properties:
details:
example: Role ID must be positive integer
type: string
error:
example: INVALID_ROLE_ID
type: string
type: object
api_acladmin.updateRoleErrorInvalidRoleName:
properties:
details:
example: Invalid role name
type: string
error:
example: FAILED_TO_UPDATE_ROLE
type: string
type: object
api_acladmin.updateRoleErrorRoleNameAlreadyExists:
properties:
details:
example: Role with name 'admin' already exists
type: string
error:
example: FAILED_TO_UPDATE_ROLE
type: string
type: object
api_acladmin.updateRoleErrorRoleNotFound:
properties:
details:
example: No role with ID 123
type: string
error:
example: ROLE_NOT_FOUND
type: string
type: object
api_acladmin.updateRoleRequest:
properties:
name:
@@ -315,10 +161,10 @@ paths:
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get all resources
tags:
- resources
- acl/resources
post:
consumes:
- application/json
@@ -339,18 +185,18 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.createResourceErrorInvalidResourceKey'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.createResourceErrorResourceAlreadyExists'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Create resource
tags:
- resources
- acl/resources
/api/acl/resources/{resourceId}:
delete:
parameters:
@@ -368,22 +214,22 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorInvalidResourceID'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorResourceNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorResourceInUse'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Delete resource
tags:
- resources
- acl/resources
get:
parameters:
- description: Resource ID
@@ -402,18 +248,18 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.getResourceErrorInvalidResourceID'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.getResourceErrorResourceNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get resource by ID
tags:
- resources
- acl/resources
patch:
consumes:
- application/json
@@ -440,22 +286,22 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorInvalidResourceKey'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorResourceNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorResourceKeyAlreadyExists'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Update resource
tags:
- resources
- acl/resources
/api/acl/roles:
get:
produces:
@@ -465,22 +311,24 @@ paths:
description: OK
schema:
items:
properties:
id:
example: 1
type: integer
name:
example: admin
type: string
type: object
items:
properties:
id:
example: 1
type: integer
name:
example: admin
type: string
type: object
type: array
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get all roles
tags:
- roles
- acl/roles
post:
consumes:
- application/json
@@ -501,22 +349,18 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.errorInvalidRequestBody'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/api_acladmin.createRoleErrorInvalidRoleName'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.createRoleErrorRoleAlreadyExists'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Create role
tags:
- roles
- acl/roles
/api/acl/roles/{roleId}:
delete:
parameters:
@@ -529,27 +373,27 @@ paths:
produces:
- application/json
responses:
"200":
description: OK
"204":
description: No Content
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorInvalidRoleID'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorRoleNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorRoleInUse'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Delete role
tags:
- roles
- acl/roles
get:
parameters:
- description: Role ID
@@ -568,18 +412,18 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.getRoleErrorInvalidRoleID'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.getRoleErrorRoleNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get role by ID
tags:
- roles
- acl/roles
patch:
consumes:
- application/json
@@ -606,20 +450,269 @@ paths:
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorInvalidRoleName'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorRoleNotFound'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorRoleNameAlreadyExists'
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Update role
tags:
- roles
- acl/roles
/api/acl/roles/{roleId}/resources:
get:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
items:
$ref: '#/definitions/api_acladmin.getRoleResource'
type: array
type: array
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get role resources
tags:
- acl/roles
post:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
- description: Resource
in: body
name: request
required: true
schema:
$ref: '#/definitions/api_acladmin.assignResourceToRoleRequest'
produces:
- application/json
responses:
"201":
description: Created
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Assign resource to role
tags:
- acl/roles
/api/acl/roles/{roleId}/resources/{resId}:
delete:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
- description: Resource ID
example: 1
in: path
name: resId
required: true
type: integer
produces:
- application/json
responses:
"204":
description: No Content
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Remove resource from role
tags:
- acl/roles
/api/acl/roles/{roleId}/users:
get:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
items:
$ref: '#/definitions/api_acladmin.getRoleUser'
type: array
type: array
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get role users
tags:
- acl/roles
/api/acl/users/{userId}/roles:
get:
parameters:
- description: User ID
example: 1
in: path
name: userId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/api_acladmin.getUserRole'
type: array
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Get user roles by user ID
tags:
- acl/users
post:
parameters:
- description: User ID
example: 1
in: path
name: userId
required: true
type: integer
- description: Role ID
in: body
name: body
required: true
schema:
$ref: '#/definitions/api_acladmin.assignRoleToUserRequest'
produces:
- application/json
responses:
"201":
description: Created
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Assign role to user
tags:
- acl/users
/api/acl/users/{userId}/roles/{roleId}:
delete:
parameters:
- description: User ID
example: 1
in: path
name: userId
required: true
type: integer
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
produces:
- application/json
responses:
"204":
description: No Content
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.ProblemDetails'
summary: Remove role from user
tags:
- acl/users
swagger: "2.0"

View File

@@ -7,15 +7,21 @@ import "fmt"
var (
ErrNotInitialized = fmt.Errorf("acl service is not initialized")
ErrRoleNotFound = fmt.Errorf("role not found")
ErrRoleAlreadyExists = fmt.Errorf("role already exists")
ErrInvalidRoleName = fmt.Errorf("role name is invalid")
ErrSameRoleName = fmt.Errorf("role name is the same as another role")
ErrRoleInUse = fmt.Errorf("role is in use")
ErrRoleNotFound = fmt.Errorf("role not found")
ErrRoleAlreadyExists = fmt.Errorf("role already exists")
ErrInvalidRoleName = fmt.Errorf("role name is invalid")
ErrSameRoleName = fmt.Errorf("role name is the same as another role")
ErrRoleInUse = fmt.Errorf("role is in use")
ErrRoleAlreadyAssigned = fmt.Errorf("role is already assigned to user")
ErrResourceNotFound = fmt.Errorf("resource not found")
ErrResourceAlreadyExists = fmt.Errorf("resource already exists")
ErrInvalidResourceKey = fmt.Errorf("invalid resource key")
ErrResourceInUse = fmt.Errorf("resource is in use")
ErrSameResourceKey = fmt.Errorf("resource key is the same as another resource")
ErrResourceNotFound = fmt.Errorf("resource not found")
ErrResourceAlreadyExists = fmt.Errorf("resource already exists")
ErrInvalidResourceKey = fmt.Errorf("invalid resource key")
ErrResourceInUse = fmt.Errorf("resource is in use")
ErrSameResourceKey = fmt.Errorf("resource key is the same as another resource")
ErrResourceAlreadyAssigned = fmt.Errorf("resource is already assigned to role")
ErrRoleResourceNotFound = fmt.Errorf("assigned resource to role is not found")
ErrUserNotFound = fmt.Errorf("user not found")
ErrUserRoleNotFound = fmt.Errorf("user role not found")
)

View File

@@ -1,11 +1,13 @@
package acl
import "git.oblat.lv/alex/triggerssmith/internal/user"
type UserRole struct {
UserID uint `gorm:"index;not null;uniqueIndex:ux_user_role"`
RoleID uint `gorm:"index;not null;uniqueIndex:ux_user_role"`
Role Role `gorm:"constraint:OnDelete:CASCADE;foreignKey:RoleID;references:ID" json:"role"`
//User user.User `gorm:"constraint:OnDelete:CASCADE;foreignKey:UserID;references:ID"`
Role Role `gorm:"constraint:OnDelete:CASCADE;foreignKey:RoleID;references:ID" json:"role"`
User user.User `gorm:"constraint:OnDelete:CASCADE;foreignKey:UserID;references:ID"`
}
type Resource struct {
@@ -17,8 +19,8 @@ type Role struct {
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
Name string `gorm:"unique;not null" json:"name"`
Resources []Resource `gorm:"many2many:role_resources" json:"resources"`
//Users []user.User `gorm:"many2many:user_roles"`
Resources []Resource `gorm:"many2many:role_resources" json:"resources"`
Users []user.User `gorm:"many2many:user_roles"`
}
type RoleResource struct {

View File

@@ -6,6 +6,7 @@ import (
"strings"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// GetResources returns all resources.
@@ -138,3 +139,82 @@ func (s *Service) DeleteResource(resourceID uint) error {
return nil
}
// AssignResourceToRole assigns a resource to a role
// May return [ErrNotInitialized], [ErrRoleNotFound], [ErrResourceNotFound], [ErrAlreadyAssigned] or db error.
func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
// check role exists
var r Role
if err := s.db.First(&r, roleID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return fmt.Errorf("failed to fetch role: %w", err)
}
// check resource exists
var res Resource
if err := s.db.First(&res, resourceID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrResourceNotFound
}
return fmt.Errorf("failed to fetch resource: %w", err)
}
rr := RoleResource{
RoleID: roleID,
ResourceID: resourceID,
}
tx := s.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rr)
if tx.Error != nil {
return fmt.Errorf("failed to assign resource to role: %w", tx.Error)
}
// if nothing inserted — already assigned
if tx.RowsAffected == 0 {
return ErrResourceAlreadyAssigned
}
return nil
}
// RemoveResourceFromRole removes a resource from a role
// May return [ErrNotInitialized], [ErrRoleNotFound], [ErrResourceNotFound], [ErrRoleResourceNotFound] or db error.
func (s *Service) RemoveResourceFromRole(roleID, resourceID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
// check role exists
var r Role
if err := s.db.First(&r, roleID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return fmt.Errorf("failed to fetch role: %w", err)
}
// check resource exists
var res Resource
if err := s.db.First(&res, resourceID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrResourceNotFound
}
return fmt.Errorf("failed to fetch resource: %w", err)
}
tx := s.db.Where("role_id = ? AND resource_id = ?", roleID, resourceID).Delete(&RoleResource{})
if tx.Error != nil {
return fmt.Errorf("failed to remove resource from role: %w", tx.Error)
}
if tx.RowsAffected == 0 {
return ErrRoleResourceNotFound
}
return nil
}

View File

@@ -5,7 +5,9 @@ import (
"fmt"
"strings"
"git.oblat.lv/alex/triggerssmith/internal/user"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// GetRoles returns all roles.
@@ -16,7 +18,7 @@ func (s *Service) GetRoles() ([]Role, error) {
}
var roles []Role
if err := s.db.Preload("Resources").Order("id").Find(&roles).Error; err != nil {
if err := s.db.Preload("Resources").Preload("Users").Order("id").Find(&roles).Error; err != nil {
return nil, fmt.Errorf("db error: %w", err)
}
@@ -60,7 +62,7 @@ func (s *Service) GetRoleByID(roleID uint) (*Role, error) {
return nil, ErrNotInitialized
}
var role Role
err := s.db.Preload("Resources").First(&role, roleID).Error
err := s.db.Preload("Resources").Preload("Users").First(&role, roleID).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrRoleNotFound
@@ -134,3 +136,105 @@ func (s *Service) DeleteRole(roleID uint) error {
return nil
}
// GetUserRoles returns all roles for a given user.
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound] or db error.
func (s *Service) GetUserRoles(userID uint) ([]Role, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var user user.User
if err := s.db.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotFound
}
return nil, fmt.Errorf("failed to fetch user: %w", err)
}
var roles []Role
err := s.db.
Joins("JOIN user_roles ur ON ur.role_id = roles.id").
Where("ur.user_id = ?", userID).
Find(&roles).Error
if err != nil {
return nil, fmt.Errorf("failed to get user roles: %w", err)
}
if len(roles) == 0 {
return nil, ErrRoleNotFound
}
return roles, nil
}
// AssignRoleToUser assigns a role to a user.
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound], [ErrRoleAlreadyAssigned] or db error.
func (s *Service) AssignRoleToUser(roleID, userID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
var user user.User
if err := s.db.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return fmt.Errorf("failed to fetch user: %w", err)
}
var r Role
if err := s.db.First(&r, roleID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return fmt.Errorf("failed to fetch role: %w", err)
}
ur := UserRole{
UserID: userID,
RoleID: roleID,
}
tx := s.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&ur)
if tx.Error != nil {
return fmt.Errorf("failed to assign resource to role: %w", tx.Error)
}
if tx.RowsAffected == 0 {
return ErrRoleAlreadyAssigned
}
return nil
}
// RemoveRoleFromUser removes a role from a user.
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound], [ErrUserRoleNotFound] or db error.
func (s *Service) RemoveRoleFromUser(roleID, userID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
var user user.User
if err := s.db.First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return fmt.Errorf("failed to fetch user: %w", err)
}
var r Role
if err := s.db.First(&r, roleID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return fmt.Errorf("failed to fetch role: %w", err)
}
tx := s.db.Where("role_id = ? AND user_id = ?", roleID, userID).Delete(&UserRole{})
if tx.Error != nil {
return fmt.Errorf("failed to remove role from user: %w", tx.Error)
}
if tx.RowsAffected == 0 {
return ErrUserRoleNotFound
}
return nil
}

View File

@@ -1,7 +1,6 @@
package acl
import (
"errors"
"fmt"
"gorm.io/gorm"
@@ -40,75 +39,3 @@ func (s *Service) Init() error {
s.initialized = true
return nil
}
// Admin crud functions //
// Resources
// AssignResourceToRole assigns a resource to a role
func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
rr := RoleResource{
RoleID: roleID,
ResourceID: resourceID,
}
return s.db.FirstOrCreate(&rr, RoleResource{RoleID: roleID, ResourceID: resourceID}).Error
}
// AssignRoleToUser assigns a role to a user
func (s *Service) AssignRoleToUser(roleID, userID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
ur := UserRole{
UserID: userID,
RoleID: roleID,
}
if err := s.db.Create(&ur).Error; err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
return fmt.Errorf("role already assigned to user")
}
return err
}
return nil
}
// RemoveResourceFromRole removes a resource from a role
func (s *Service) RemoveResourceFromRole(roleID, resourceID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
return s.db.Where("role_id = ? AND resource_id = ?", roleID, resourceID).Delete(&RoleResource{}).Error
}
// RemoveRoleFromUser removes a role from a user
func (s *Service) RemoveRoleFromUser(roleID, userID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
return s.db.Where("role_id = ? AND user_id = ?", roleID, userID).Delete(&UserRole{}).Error
}
// GetRoleResources returns all resources for a given role
func (s *Service) GetRoleResources(roleID uint) ([]Resource, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var resources []Resource
err := s.db.Joins("JOIN role_resources rr ON rr.resource_id = resources.id").
Where("rr.role_id = ?", roleID).Find(&resources).Error
return resources, err
}
// GetUserRoles returns all roles for a given user
func (s *Service) GetUserRoles(userID uint) ([]Role, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var roles []Role
err := s.db.Joins("JOIN user_roles ur ON ur.role_id = roles.id").
Where("ur.user_id = ?", userID).Find(&roles).Error
return roles, err
}

7
internal/user/errors.go Normal file
View File

@@ -0,0 +1,7 @@
package user
import "fmt"
var (
ErrUserNotFound = fmt.Errorf("user not found")
)

View File

@@ -1,7 +1,6 @@
package user
import (
"git.oblat.lv/alex/triggerssmith/internal/acl"
"gorm.io/gorm"
)
@@ -10,6 +9,5 @@ type User struct {
Username string `gorm:"uniqueIndex;not null"`
Email string `gorm:"uniqueIndex;not null"`
Password string `gorm:"not null"`
Roles []acl.Role `gorm:"many2many:user_roles"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}