Compare commits

..

5 Commits

Author SHA1 Message Date
904f446447 basicly implement acl crud ops with roles and resources 2025-12-20 17:38:15 +02:00
c188b46519 gitignore add data dir 2025-12-20 17:37:34 +02:00
8e31a84b0e get some modules 2025-12-20 17:36:52 +02:00
bd06d071b2 add swagger 2025-12-20 17:36:36 +02:00
f0d7d79e0f add swagger 2025-12-20 17:36:24 +02:00
26 changed files with 4214 additions and 338 deletions

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@ config.yaml
panic.log
testdata/
secret/
data/

View File

@@ -20,7 +20,7 @@ imports-tools:
go install golang.org/x/tools/cmd/goimports@latest; \
fi
.PHONY: all build run test lint fmt imports
.PHONY: all swag build run test lint fmt imports
all: build
@@ -30,6 +30,12 @@ run: build
BUILD_PARAMS = -trimpath -ldflags "-X git.oblat.lv/alex/triggerssmith/internal/vars.Version=$(VERSION)"
build-with-swag: swag build
swag:
@echo "-- generating swagger docs"
@swag init -g cmd/serve.go
build:
@echo "-- building $(NAME)"
@go build $(BUILD_PARAMS) -o $(BINARY) $(ENTRY)

View File

@@ -0,0 +1,11 @@
package api_acladmin
type errorInvalidRequestBody struct {
Error string `json:"error" example:"INVALID_REQUEST_BODY"`
Details string `json:"details" example:"Request body is not valid JSON"`
}
type errorInternalServerError struct {
Error string `json:"error"`
Details string `json:"details"`
}

28
api/acl_admin/errors.go Normal file
View File

@@ -0,0 +1,28 @@
package api_acladmin
const (
ErrorInvalidRequestBody = "INVALID_REQUEST_BODY"
ErrorInternalServerError = "INTERNAL_SERVER_ERROR"
// Roles
ErrorFailedToCreateRole = "FAILED_TO_CREATE_ROLE"
ErrorFailedToGetRole = "FAILED_TO_GET_ROLE"
ErrorFailedToUpdateRole = "FAILED_TO_UPDATE_ROLE"
ErrorFailedToDeleteRole = "FAILED_TO_DELETE_ROLE"
ErrorInvalidRoleID = "INVALID_ROLE_ID"
ErrorRoleNotFound = "ROLE_NOT_FOUND"
// Resources
ErrorFailedToCreateResource = "FAILED_TO_CREATE_RESOURCE"
ErrorFailedToGetResource = "FAILED_TO_GET_RESOURCE"
ErrorFailedToUpdateResource = "FAILED_TO_UPDATE_RESOURCE"
ErrorFailedToDeleteResource = "FAILED_TO_DELETE_RESOURCE"
ErrorInvalidResourceID = "INVALID_RESOURCE_ID"
ErrorResourceNotFound = "RESOURCE_NOT_FOUND"
)
const (
ErrorACLServiceNotInitialized = "ACL service is not initialized"
)

View File

@@ -1,13 +1,11 @@
package api_acladmin
import (
"encoding/json"
"net/http"
"git.oblat.lv/alex/triggerssmith/internal/acl"
"git.oblat.lv/alex/triggerssmith/internal/auth"
"git.oblat.lv/alex/triggerssmith/internal/config"
"git.oblat.lv/alex/triggerssmith/internal/server"
//"git.oblat.lv/alex/triggerssmith/internal/server"
"github.com/go-chi/chi/v5"
)
@@ -32,91 +30,221 @@ func MustRoute(config *config.Config, aclService *acl.Service, authService *auth
a: aclService,
auth: authService,
}
// GET /roles — список ролей
// POST /roles — создать роль
// GET /roles/{roleId} — получить роль
// PATCH /roles/{roleId} — обновить роль (если нужно)
// DELETE /roles/{roleId} — удалить роль
// GET /resources — список ресурсов
// POST /resources — создать ресурс
// GET /resources/{resId} — получить ресурс
// PATCH /resources/{resId} — обновить ресурс
// DELETE /resources/{resId} — удалить ресурс
// GET /users/{userId}/roles — роли пользователя
// POST /users/{userId}/roles — назначить роль пользователю
// DELETE /users/{userId}/roles/{roleId} — снять роль
// GET /roles/{roleId}/resources — ресурсы роли
// POST /roles/{roleId}/resources — назначить ресурс роли
// DELETE /roles/{roleId}/resources/{resId} — убрать ресурс
return func(r chi.Router) {
r.Get("/roles", h.getRoles)
r.Post("/create-role", h.createRole)
r.Post("/assign-role", h.assignRoleToUser)
r.Get("/user-roles", h.getUserRoles)
r.Post("/remove-role", h.removeRoleFromUser)
// 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("/resources", h.getResources)
r.Post("/create-resource", h.createResource)
r.Post("/assign-resource", h.assignResourceToRole)
r.Get("/role-resources", h.getRoleResources)
r.Post("/remove-resource", h.removeResourceFromRole)
// // 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
r.Get("/permissions", h.getResources) // legacy support
r.Post("/create-permissions", h.createResource) // legacy support
r.Post("/assign-permissions", h.assignResourceToRole) // legacy support
r.Get("/role-permissions", h.getRoleResources) // legacy support
r.Post("/remove-permissions", h.removeResourceFromRole) // legacy support
// 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
// r.Get("/roles", h.getRoles)
// r.Post("/create-role", h.createRole)
// r.Post("/assign-role", h.assignRoleToUser)
// r.Get("/user-roles", h.getUserRoles)
// r.Post("/remove-role", h.removeRoleFromUser)
// r.Get("/resources", h.getResources)
// r.Post("/create-resource", h.createResource)
// r.Post("/assign-resource", h.assignResourceToRole)
// r.Get("/role-resources", h.getRoleResources)
// r.Post("/remove-resource", h.removeResourceFromRole)
// r.Get("/permissions", h.getResources) // legacy support
// r.Post("/create-permissions", h.createResource) // legacy support
// r.Post("/assign-permissions", h.assignResourceToRole) // legacy support
// r.Get("/role-permissions", h.getRoleResources) // legacy support
// r.Post("/remove-permissions", h.removeResourceFromRole) // legacy support
}
}
type rolesResponse []struct {
ID uint `json:"id"`
Name string `json:"name"`
}
// type assignRoleRequest struct {
// UserID int `json:"userId"`
// RoleID int `json:"roleId"`
// }
func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
roles, err := h.a.GetRoles()
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(func() rolesResponse {
// Transform acl.Role to rolesResponse
resp := make(rolesResponse, 0, len(roles))
for _, role := range roles {
resp = append(resp, struct {
ID uint `json:"id"`
Name string `json:"name"`
}{
ID: role.ID,
Name: role.Name,
})
}
return resp
}())
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
// func (h *aclAdminHandler) assignRoleToUser(w http.ResponseWriter, r *http.Request) {
// var req assignRoleRequest
// if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// http.Error(w, "Invalid request body", http.StatusBadRequest)
// return
// }
// if req.UserID < 0 || req.RoleID < 0 {
// http.Error(w, "Invalid user or role ID", http.StatusBadRequest)
// return
// }
// if err := h.a.AssignRoleToUser(uint(req.RoleID), uint(req.UserID)); err != nil {
// http.Error(w, "Failed to assign role to user", http.StatusConflict)
// return
// }
// w.WriteHeader(http.StatusCreated)
// }
func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// type getUserRolesResponse getRolesResponse
func (h *aclAdminHandler) assignRoleToUser(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// func (h *aclAdminHandler) getUserRoles(w http.ResponseWriter, r *http.Request) {
// uidStr := r.URL.Query().Get("userId")
// if uidStr == "" {
// http.Error(w, "Missing userId parameter", http.StatusBadRequest)
// return
// }
// userID, err := strconv.Atoi(uidStr)
// if err != nil || userID < 0 {
// http.Error(w, "Invalid userId parameter", http.StatusBadRequest)
// return
// }
// roles, err := h.a.GetUserRoles(uint(userID))
// if err != nil {
// http.Error(w, "Internal server error", http.StatusInternalServerError)
// return
// }
// w.Header().Set("Content-Type", "application/json")
// err = json.NewEncoder(w).Encode(func() getUserRolesResponse {
// // Transform acl.Role to getUserRolesResponse
// resp := make(getUserRolesResponse, 0, len(roles))
// for _, role := range roles {
// resp = append(resp, struct {
// ID uint `json:"id"`
// Name string `json:"name"`
// }{
// ID: role.ID,
// Name: role.Name,
// })
// }
// return resp
// }())
// if err != nil {
// http.Error(w, "Failed to encode response", http.StatusInternalServerError)
// return
// }
// }
func (h *aclAdminHandler) getUserRoles(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// type removeRoleRequest struct {
// UserID int `json:"userId"`
// RoleID int `json:"roleId"`
// }
func (h *aclAdminHandler) removeRoleFromUser(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// func (h *aclAdminHandler) removeRoleFromUser(w http.ResponseWriter, r *http.Request) {
// var req removeRoleRequest
// if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// http.Error(w, "Invalid request body", http.StatusBadRequest)
// return
// }
// if req.UserID < 0 || req.RoleID < 0 {
// http.Error(w, "Invalid user or role ID", http.StatusBadRequest)
// return
// }
// if err := h.a.RemoveRoleFromUser(uint(req.RoleID), uint(req.UserID)); err != nil {
// http.Error(w, "Failed to remove role from user", http.StatusConflict)
// return
// }
// w.WriteHeader(http.StatusNoContent)
// }
func (h *aclAdminHandler) getResources(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// type getResourcesResponse getRolesResponse
func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// func (h *aclAdminHandler) getResources(w http.ResponseWriter, r *http.Request) {
// resources, err := h.a.GetResources()
// if err != nil {
// http.Error(w, "Internal server error", http.StatusInternalServerError)
// return
// }
// w.Header().Set("Content-Type", "application/json")
// err = json.NewEncoder(w).Encode(func() getResourcesResponse {
// // Transform acl.Resource to getResourcesResponse
// resp := make(getResourcesResponse, 0, len(resources))
// for _, res := range resources {
// resp = append(resp, struct {
// ID uint `json:"id"`
// Name string `json:"name"`
// }{
// ID: res.ID,
// Name: res.Key,
// })
// }
// return resp
// }())
// if err != nil {
// http.Error(w, "Failed to encode response", http.StatusInternalServerError)
// return
// }
// }
func (h *aclAdminHandler) assignResourceToRole(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// type createResourceRequest struct {
// Name string `json:"name"`
// }
func (h *aclAdminHandler) getRoleResources(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// type createResourceResponse struct {
// ID uint `json:"id"`
// Name string `json:"name"`
// }
func (h *aclAdminHandler) removeResourceFromRole(w http.ResponseWriter, r *http.Request) {
server.NotImplemented(w)
}
// func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request) {
// var req createResourceRequest
// if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// http.Error(w, "Invalid request body", http.StatusBadRequest)
// return
// }
// if req.Name == "" {
// http.Error(w, "Name is required", http.StatusBadRequest)
// return
// }
// id, err := h.a.CreateResource(req.Name)
// if err != nil {
// http.Error(w, "Failed to create resource", http.StatusConflict)
// return
// }
// w.WriteHeader(http.StatusCreated)
// w.Header().Set("Content-Type", "application/json")
// err = json.NewEncoder(w).Encode(createResourceResponse{
// ID: id,
// Name: req.Name,
// })
// if err != nil {
// http.Error(w, "Failed to encode response", http.StatusInternalServerError)
// return
// }
// }
// func (h *aclAdminHandler) assignResourceToRole(w http.ResponseWriter, r *http.Request) {
// server.NotImplemented(w)
// }
// func (h *aclAdminHandler) getRoleResources(w http.ResponseWriter, r *http.Request) {
// server.NotImplemented(w)
// }
// func (h *aclAdminHandler) removeResourceFromRole(w http.ResponseWriter, r *http.Request) {
// server.NotImplemented(w)
// }

321
api/acl_admin/resources.go Normal file
View File

@@ -0,0 +1,321 @@
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 all resources
// @Tags resources
// @Produce json
// @Success 200 {object} getResourcesResponse
// @Failure 500 {object} errorInternalServerError
// @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
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get resources",
})
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
}())
}
// @Summary Get resource by ID
// @Tags 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
// @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",
})
return
}
resource, err := h.a.GetResourceByID(uint(resourceID))
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(getResourceErrorResourceNotFound{
Error: ErrorResourceNotFound,
Details: "No resource with ID " + resourceIDStr,
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get resource with ID " + resourceIDStr,
})
return
}
}
_ = json.NewEncoder(w).Encode(getResourceResponse{
ID: resource.ID,
Key: resource.Key,
})
}
// @Summary Create resource
// @Tags 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
// @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",
})
return
}
resourceID, err := h.a.CreateResource(req.Key)
if err != nil {
slog.Error("Failed to create resource", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
case acl.ErrInvalidResourceKey:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(createResourceErrorInvalidResourceKey{
Error: ErrorFailedToCreateResource,
Details: "Resource key must be non-empty",
})
return
case acl.ErrResourceAlreadyExists:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(createResourceErrorResourceAlreadyExists{
Error: ErrorFailedToCreateResource,
Details: "Resource with key '" + req.Key + "' already exists",
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to create resource with key '" + req.Key + "'",
})
return
}
}
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(createResourceResponse{
ID: resourceID,
Key: req.Key,
})
}
// @Summary Update resource
// @Tags 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
// @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",
})
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",
})
return
}
err = h.a.UpdateResource(uint(resourceID), req.Key)
if err != nil {
slog.Error("Failed to update resource", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
case acl.ErrInvalidResourceKey:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateResourceErrorInvalidResourceKey{
Error: ErrorFailedToUpdateResource,
Details: "Invalid resource key",
})
return
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceNotFound{
Error: ErrorFailedToUpdateResource,
Details: "No resource with ID " + resourceIDStr,
})
return
case acl.ErrSameResourceKey:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceKeyAlreadyExists{
Error: ErrorFailedToUpdateResource,
Details: "Resource with key '" + req.Key + "' already exists",
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to update resource with key '" + req.Key + "'",
})
return
}
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(updateResourceResponse{
ID: uint(resourceID),
Key: req.Key,
})
}
// @Summary Delete resource
// @Tags resources
// @Produce json
// @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
// @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",
})
return
}
err = h.a.DeleteResource(uint(resourceID))
if err != nil {
slog.Error("Failed to delete resource", "error", err.Error())
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
case acl.ErrResourceNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(deleteResourceErrorResourceNotFound{
Error: ErrorFailedToDeleteResource,
Details: "No resource with ID " + resourceIDStr,
})
return
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
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to delete resource with ID '" + resourceIDStr + "'",
})
return
}
}
w.WriteHeader(http.StatusOK)
}

View File

@@ -0,0 +1,94 @@
package api_acladmin
/*******************************************************************/
// used in getResources()
type getResourcesResponse []struct {
ID uint `json:"id" example:"1"`
Key string `json:"key" example:"html.view"`
}
/*******************************************************************/
// used in getResource()
type getResourceResponse struct {
ID uint `json:"id" example:"1"`
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 {
Key string `json:"key" example:"html.view"`
}
type createResourceResponse struct {
ID uint `json:"id" example:"1"`
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 {
Key string `json:"key" example:"html.view"`
}
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"`
}

314
api/acl_admin/roles.go Normal file
View File

@@ -0,0 +1,314 @@
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 all roles
// @Tags roles
// @Produce json
// @Success 200 {object} getRolesResponse
// @Failure 500 {object} errorInternalServerError
// @Router /api/acl/roles [get]
func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roles, err := h.a.GetRoles()
if err != nil {
switch err {
case acl.ErrNotInitialized:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: ErrorACLServiceNotInitialized,
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get roles",
})
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
}())
}
// @Summary Get role by ID
// @Tags 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
// @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",
})
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
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(getRoleErrorRoleNotFound{
Error: ErrorRoleNotFound,
Details: "No role with ID " + roleIDStr,
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to get role with ID " + roleIDStr,
})
return
}
}
_ = json.NewEncoder(w).Encode(getRoleResponse{
ID: role.ID,
Name: role.Name,
})
}
// @Summary Create role
// @Tags 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
// @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",
})
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
case acl.ErrInvalidRoleName:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(createRoleErrorInvalidRoleName{
Error: ErrorFailedToCreateRole,
Details: "Role name must be non-empty string",
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to create role with name '" + req.Name + "'",
})
return
}
}
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(createRoleResponse{
ID: roleID,
Name: req.Name,
})
}
// @Summary Update role
// @Tags 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
// @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",
})
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",
})
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
case acl.ErrInvalidRoleName:
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(updateRoleErrorInvalidRoleName{
Error: ErrorFailedToUpdateRole,
Details: "Invalid role name",
})
return
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNotFound{
Error: ErrorFailedToUpdateRole,
Details: "No role with ID " + roleIDStr,
})
return
case acl.ErrSameRoleName:
w.WriteHeader(http.StatusConflict)
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNameAlreadyExists{
Error: ErrorFailedToUpdateRole,
Details: "Role with name '" + req.Name + "' already exists",
})
return
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to update role with name '" + req.Name + "'",
})
return
}
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(updateRoleResponse{
ID: uint(roleID),
Name: req.Name,
})
}
// @Summary Delete role
// @Tags 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
// @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",
})
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
case acl.ErrRoleNotFound:
w.WriteHeader(http.StatusNotFound)
_ = json.NewEncoder(w).Encode(deleteRoleErrorRoleNotFound{
Error: ErrorFailedToDeleteRole,
Details: "No role with ID " + roleIDStr,
})
return
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
default:
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(errorInternalServerError{
Error: ErrorInternalServerError,
Details: "Failed to delete role with ID '" + roleIDStr + "'",
})
return
}
}
w.WriteHeader(http.StatusOK)
}

View File

@@ -0,0 +1,94 @@
package api_acladmin
/*******************************************************************/
// used in getRoles()
type getRolesResponse []struct {
ID uint `json:"id" example:"1"`
Name string `json:"name" example:"admin"`
}
/*******************************************************************/
// used in getRole()
type getRoleResponse struct {
ID uint `json:"id" example:"1"`
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"`
}
type getRoleErrorRoleNotFound struct {
Error string `json:"error" example:"ROLE_NOT_FOUND"`
Details string `json:"details" example:"No role with ID 123"`
}
/*******************************************************************/
// used in createRole()
type createRoleRequest struct {
Name string `json:"name" example:"admin"`
}
type createRoleResponse struct {
ID uint `json:"id" example:"1"`
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 {
Name string `json:"name" example:"admin"`
}
type updateRoleResponse struct {
ID uint `json:"id" example:"1"`
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"`
}

View File

@@ -65,7 +65,7 @@ type registerRequest struct {
}
type registerResponse struct {
UserID int64 `json:"id"`
UserID uint `json:"id"`
Username string `json:"username"`
}
@@ -92,6 +92,7 @@ func (h *authHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
type loginRequest struct {
@@ -152,7 +153,7 @@ func (h *authHandler) handleLogout(w http.ResponseWriter, r *http.Request) {
}
type meResponse struct {
UserID int64 `json:"id"`
UserID uint `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}

View File

@@ -11,12 +11,14 @@ import (
api_acladmin "git.oblat.lv/alex/triggerssmith/api/acl_admin"
api_auth "git.oblat.lv/alex/triggerssmith/api/auth"
api_block "git.oblat.lv/alex/triggerssmith/api/block"
_ "git.oblat.lv/alex/triggerssmith/docs"
"git.oblat.lv/alex/triggerssmith/internal/acl"
"git.oblat.lv/alex/triggerssmith/internal/auth"
"git.oblat.lv/alex/triggerssmith/internal/config"
"git.oblat.lv/alex/triggerssmith/internal/vars"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
httpSwagger "github.com/swaggo/http-swagger"
)
type Router struct {
@@ -66,7 +68,7 @@ func (r *Router) MustRoute() chi.Router {
slog.String("dir", r.cfg.Server.StaticConfig.Dir),
slog.String("index_file", r.cfg.Server.StaticConfig.IndexFile),
)
r.r.Get("/", func(w http.ResponseWriter, req *http.Request) {
r.r.Get("/*", func(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, filepath.Join(r.cfg.Server.StaticConfig.Dir, r.cfg.Server.StaticConfig.IndexFile))
})
fs := http.FileServer(http.Dir(r.cfg.Server.StaticConfig.Dir))
@@ -82,6 +84,9 @@ func (r *Router) MustRoute() chi.Router {
}
r.r.Route("/api", func(api chi.Router) {
api.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("/api/swagger/doc.json"),
))
api.Route("/block", api_block.MustRoute(r.cfg))
authRoute := api_auth.MustRoute(r.cfg, r.authService)
api.Route("/auth", authRoute)

View File

@@ -202,7 +202,7 @@ var serveCmd = &cobra.Command{
}
// also acl !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
userData, err := gorm.Open(sqlite.Open(filepath.Join(cfg.Data.DataPath, "user_data.sqlite3")), &gorm.Config{})
userData, err := gorm.Open(sqlite.Open(filepath.Join(cfg.Data.DataPath, "user_data.sqlite3")+"?_foreign_keys=on"), &gorm.Config{})
if err != nil {
slog.Error("Failed to open user database", slog.String("error", err.Error()))
return

959
docs/docs.go Normal file
View File

@@ -0,0 +1,959 @@
// Package docs Code generated by swaggo/swag. DO NOT EDIT
package docs
import "github.com/swaggo/swag"
const docTemplate = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{escape .Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/api/acl/resources": {
"get": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Get all resources",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Create resource",
"parameters": [
{
"description": "Resource",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceRequest"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceErrorInvalidResourceKey"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceErrorResourceAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/resources/{resourceId}": {
"get": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Get resource by ID",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceErrorInvalidResourceID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceErrorResourceNotFound"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"delete": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Delete resource",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorInvalidResourceID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorResourceNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorResourceInUse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Update resource",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
},
{
"description": "Resource",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorInvalidResourceKey"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorResourceNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorResourceKeyAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/roles": {
"get": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Get all roles",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Create role",
"parameters": [
{
"description": "Role",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleRequest"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInvalidRequestBody"
}
},
"401": {
"description": "Unauthorized",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleErrorInvalidRoleName"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleErrorRoleAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/roles/{roleId}": {
"get": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Get role by ID",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleErrorInvalidRoleID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleErrorRoleNotFound"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"delete": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Delete role",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorInvalidRoleID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorRoleNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorRoleInUse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Update role",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
},
{
"description": "Role",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorInvalidRoleName"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorRoleNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorRoleNameAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
}
},
"definitions": {
"api_acladmin.createResourceErrorInvalidResourceKey": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid resource key"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_RESOURCE"
}
}
},
"api_acladmin.createResourceErrorResourceAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with key 'html.view' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_RESOURCE"
}
}
},
"api_acladmin.createResourceRequest": {
"type": "object",
"properties": {
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.createResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.createRoleErrorInvalidRoleName": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid role name"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_ROLE"
}
}
},
"api_acladmin.createRoleErrorRoleAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with name 'admin' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_ROLE"
}
}
},
"api_acladmin.createRoleRequest": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.createRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.deleteResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.deleteResourceErrorResourceInUse": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with ID 123 is used and cannot be deleted"
},
"error": {
"type": "string",
"example": "FAILED_TO_DELETE_RESOURCE"
}
}
},
"api_acladmin.deleteResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.deleteRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.deleteRoleErrorRoleInUse": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with ID 123 is assigned to users and cannot be deleted"
},
"error": {
"type": "string",
"example": "FAILED_TO_DELETE_ROLE"
}
}
},
"api_acladmin.deleteRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.errorInternalServerError": {
"type": "object",
"properties": {
"details": {
"type": "string"
},
"error": {
"type": "string"
}
}
},
"api_acladmin.errorInvalidRequestBody": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Request body is not valid JSON"
},
"error": {
"type": "string",
"example": "INVALID_REQUEST_BODY"
}
}
},
"api_acladmin.getResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.getResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.getResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.getRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.getRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.getRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.updateResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.updateResourceErrorInvalidResourceKey": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid resource key"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_RESOURCE"
}
}
},
"api_acladmin.updateResourceErrorResourceKeyAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with key 'html.view' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_RESOURCE"
}
}
},
"api_acladmin.updateResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.updateResourceRequest": {
"type": "object",
"properties": {
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.updateResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.updateRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.updateRoleErrorInvalidRoleName": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid role name"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_ROLE"
}
}
},
"api_acladmin.updateRoleErrorRoleNameAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with name 'admin' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_ROLE"
}
}
},
"api_acladmin.updateRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.updateRoleRequest": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.updateRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = &swag.Spec{
Version: "",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "",
Description: "",
InfoInstanceName: "swagger",
SwaggerTemplate: docTemplate,
LeftDelim: "{{",
RightDelim: "}}",
}
func init() {
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
}

930
docs/swagger.json Normal file
View File

@@ -0,0 +1,930 @@
{
"swagger": "2.0",
"info": {
"contact": {}
},
"paths": {
"/api/acl/resources": {
"get": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Get all resources",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Create resource",
"parameters": [
{
"description": "Resource",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceRequest"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceErrorInvalidResourceKey"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.createResourceErrorResourceAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/resources/{resourceId}": {
"get": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Get resource by ID",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceErrorInvalidResourceID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.getResourceErrorResourceNotFound"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"delete": {
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Delete resource",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorInvalidResourceID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorResourceNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteResourceErrorResourceInUse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"resources"
],
"summary": "Update resource",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Resource ID",
"name": "resourceId",
"in": "path",
"required": true
},
{
"description": "Resource",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorInvalidResourceKey"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorResourceNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.updateResourceErrorResourceKeyAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/roles": {
"get": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Get all roles",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
}
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Create role",
"parameters": [
{
"description": "Role",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleRequest"
}
}
],
"responses": {
"201": {
"description": "Created",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInvalidRequestBody"
}
},
"401": {
"description": "Unauthorized",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleErrorInvalidRoleName"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.createRoleErrorRoleAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
},
"/api/acl/roles/{roleId}": {
"get": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Get role by ID",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleErrorInvalidRoleID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.getRoleErrorRoleNotFound"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"delete": {
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Delete role",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK"
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorInvalidRoleID"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorRoleNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.deleteRoleErrorRoleInUse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
},
"patch": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"roles"
],
"summary": "Update role",
"parameters": [
{
"type": "integer",
"example": 1,
"description": "Role ID",
"name": "roleId",
"in": "path",
"required": true
},
{
"description": "Role",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorInvalidRoleName"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorRoleNotFound"
}
},
"409": {
"description": "Conflict",
"schema": {
"$ref": "#/definitions/api_acladmin.updateRoleErrorRoleNameAlreadyExists"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/api_acladmin.errorInternalServerError"
}
}
}
}
}
},
"definitions": {
"api_acladmin.createResourceErrorInvalidResourceKey": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid resource key"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_RESOURCE"
}
}
},
"api_acladmin.createResourceErrorResourceAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with key 'html.view' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_RESOURCE"
}
}
},
"api_acladmin.createResourceRequest": {
"type": "object",
"properties": {
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.createResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.createRoleErrorInvalidRoleName": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid role name"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_ROLE"
}
}
},
"api_acladmin.createRoleErrorRoleAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with name 'admin' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_CREATE_ROLE"
}
}
},
"api_acladmin.createRoleRequest": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.createRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.deleteResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.deleteResourceErrorResourceInUse": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with ID 123 is used and cannot be deleted"
},
"error": {
"type": "string",
"example": "FAILED_TO_DELETE_RESOURCE"
}
}
},
"api_acladmin.deleteResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.deleteRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.deleteRoleErrorRoleInUse": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with ID 123 is assigned to users and cannot be deleted"
},
"error": {
"type": "string",
"example": "FAILED_TO_DELETE_ROLE"
}
}
},
"api_acladmin.deleteRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.errorInternalServerError": {
"type": "object",
"properties": {
"details": {
"type": "string"
},
"error": {
"type": "string"
}
}
},
"api_acladmin.errorInvalidRequestBody": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Request body is not valid JSON"
},
"error": {
"type": "string",
"example": "INVALID_REQUEST_BODY"
}
}
},
"api_acladmin.getResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.getResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.getResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.getRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.getRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.getRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.updateResourceErrorInvalidResourceID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_RESOURCE_ID"
}
}
},
"api_acladmin.updateResourceErrorInvalidResourceKey": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid resource key"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_RESOURCE"
}
}
},
"api_acladmin.updateResourceErrorResourceKeyAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Resource with key 'html.view' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_RESOURCE"
}
}
},
"api_acladmin.updateResourceErrorResourceNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No resource with ID 123"
},
"error": {
"type": "string",
"example": "RESOURCE_NOT_FOUND"
}
}
},
"api_acladmin.updateResourceRequest": {
"type": "object",
"properties": {
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.updateResourceResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"key": {
"type": "string",
"example": "html.view"
}
}
},
"api_acladmin.updateRoleErrorInvalidRoleID": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role ID must be positive integer"
},
"error": {
"type": "string",
"example": "INVALID_ROLE_ID"
}
}
},
"api_acladmin.updateRoleErrorInvalidRoleName": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Invalid role name"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_ROLE"
}
}
},
"api_acladmin.updateRoleErrorRoleNameAlreadyExists": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "Role with name 'admin' already exists"
},
"error": {
"type": "string",
"example": "FAILED_TO_UPDATE_ROLE"
}
}
},
"api_acladmin.updateRoleErrorRoleNotFound": {
"type": "object",
"properties": {
"details": {
"type": "string",
"example": "No role with ID 123"
},
"error": {
"type": "string",
"example": "ROLE_NOT_FOUND"
}
}
},
"api_acladmin.updateRoleRequest": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "admin"
}
}
},
"api_acladmin.updateRoleResponse": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"name": {
"type": "string",
"example": "admin"
}
}
}
}
}

625
docs/swagger.yaml Normal file
View File

@@ -0,0 +1,625 @@
definitions:
api_acladmin.createResourceErrorInvalidResourceKey:
properties:
details:
example: Invalid resource key
type: string
error:
example: FAILED_TO_CREATE_RESOURCE
type: string
type: object
api_acladmin.createResourceErrorResourceAlreadyExists:
properties:
details:
example: Resource with key 'html.view' already exists
type: string
error:
example: FAILED_TO_CREATE_RESOURCE
type: string
type: object
api_acladmin.createResourceRequest:
properties:
key:
example: html.view
type: string
type: object
api_acladmin.createResourceResponse:
properties:
id:
example: 1
type: integer
key:
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:
example: admin
type: string
type: object
api_acladmin.createRoleResponse:
properties:
id:
example: 1
type: integer
name:
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:
example: 1
type: integer
key:
example: html.view
type: string
type: object
api_acladmin.getRoleErrorInvalidRoleID:
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
type: string
type: object
api_acladmin.getRoleResponse:
properties:
id:
example: 1
type: integer
name:
example: admin
type: string
type: object
api_acladmin.updateResourceErrorInvalidResourceID:
properties:
details:
example: Resource ID must be positive integer
type: string
error:
example: INVALID_RESOURCE_ID
type: string
type: object
api_acladmin.updateResourceErrorInvalidResourceKey:
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
type: string
type: object
api_acladmin.updateResourceRequest:
properties:
key:
example: html.view
type: string
type: object
api_acladmin.updateResourceResponse:
properties:
id:
example: 1
type: integer
key:
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:
example: admin
type: string
type: object
api_acladmin.updateRoleResponse:
properties:
id:
example: 1
type: integer
name:
example: admin
type: string
type: object
info:
contact: {}
paths:
/api/acl/resources:
get:
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
properties:
id:
example: 1
type: integer
key:
example: html.view
type: string
type: object
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Get all resources
tags:
- resources
post:
consumes:
- application/json
parameters:
- description: Resource
in: body
name: request
required: true
schema:
$ref: '#/definitions/api_acladmin.createResourceRequest'
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/api_acladmin.createResourceResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.createResourceErrorInvalidResourceKey'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.createResourceErrorResourceAlreadyExists'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Create resource
tags:
- resources
/api/acl/resources/{resourceId}:
delete:
parameters:
- description: Resource ID
example: 1
in: path
name: resourceId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorInvalidResourceID'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorResourceNotFound'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.deleteResourceErrorResourceInUse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Delete resource
tags:
- resources
get:
parameters:
- description: Resource ID
example: 1
in: path
name: resourceId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/api_acladmin.getResourceResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.getResourceErrorInvalidResourceID'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.getResourceErrorResourceNotFound'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Get resource by ID
tags:
- resources
patch:
consumes:
- application/json
parameters:
- description: Resource ID
example: 1
in: path
name: resourceId
required: true
type: integer
- description: Resource
in: body
name: request
required: true
schema:
$ref: '#/definitions/api_acladmin.updateResourceRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/api_acladmin.updateResourceResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorInvalidResourceKey'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorResourceNotFound'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.updateResourceErrorResourceKeyAlreadyExists'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Update resource
tags:
- resources
/api/acl/roles:
get:
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
properties:
id:
example: 1
type: integer
name:
example: admin
type: string
type: object
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Get all roles
tags:
- roles
post:
consumes:
- application/json
parameters:
- description: Role
in: body
name: request
required: true
schema:
$ref: '#/definitions/api_acladmin.createRoleRequest'
produces:
- application/json
responses:
"201":
description: Created
schema:
$ref: '#/definitions/api_acladmin.createRoleResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.errorInvalidRequestBody'
"401":
description: Unauthorized
schema:
$ref: '#/definitions/api_acladmin.createRoleErrorInvalidRoleName'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.createRoleErrorRoleAlreadyExists'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Create role
tags:
- roles
/api/acl/roles/{roleId}:
delete:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorInvalidRoleID'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorRoleNotFound'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.deleteRoleErrorRoleInUse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Delete role
tags:
- roles
get:
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/api_acladmin.getRoleResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.getRoleErrorInvalidRoleID'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.getRoleErrorRoleNotFound'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Get role by ID
tags:
- roles
patch:
consumes:
- application/json
parameters:
- description: Role ID
example: 1
in: path
name: roleId
required: true
type: integer
- description: Role
in: body
name: request
required: true
schema:
$ref: '#/definitions/api_acladmin.updateRoleRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/api_acladmin.updateRoleResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorInvalidRoleName'
"404":
description: Not Found
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorRoleNotFound'
"409":
description: Conflict
schema:
$ref: '#/definitions/api_acladmin.updateRoleErrorRoleNameAlreadyExists'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/api_acladmin.errorInternalServerError'
summary: Update role
tags:
- roles
swagger: "2.0"

27
go.mod
View File

@@ -5,15 +5,32 @@ go 1.24.9
require (
github.com/akyaiy/GSfass/core v0.0.0-20251115194535-2b7489bfc204
github.com/spf13/cobra v1.10.1
github.com/swaggo/http-swagger v1.3.4
github.com/swaggo/swag v1.16.6
golang.org/x/crypto v0.46.0
)
require golang.org/x/crypto v0.46.0 // indirect
require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.6 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe // indirect
golang.org/x/mod v0.30.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/tools v0.39.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-chi/chi/v5 v5.2.3 // indirect
github.com/go-chi/chi/v5 v5.2.3
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/google/uuid v1.6.0
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
@@ -30,6 +47,6 @@ require (
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
gorm.io/driver/sqlite v1.6.0 // indirect
gorm.io/gorm v1.31.1 // indirect
gorm.io/driver/sqlite v1.6.0
gorm.io/gorm v1.31.1
)

62
go.sum
View File

@@ -1,6 +1,10 @@
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
github.com/akyaiy/GSfass/core v0.0.0-20251115194535-2b7489bfc204 h1:tvG9DIB1e58sWfDbYLdgOcXRdyZxSYy/wk2VHJHgzec=
github.com/akyaiy/GSfass/core v0.0.0-20251115194535-2b7489bfc204/go.mod h1:Sk61563skjfIIYbmTUTJSWqGwBp9ODiBMjza8F5+UFY=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -9,6 +13,16 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA=
github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo=
github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ=
github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
@@ -23,12 +37,23 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -51,25 +76,50 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe h1:K8pHPVoTgxFJt1lXuIzzOX7zZhZFldJQK/CgKx9BFIc=
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w=
github.com/swaggo/http-swagger v1.3.4 h1:q7t/XLx0n15H1Q9/tk3Y9L4n210XzJF5WtnDX64a5ww=
github.com/swaggo/http-swagger v1.3.4/go.mod h1:9dAh0unqMBAlbp1uE2Uc2mQTxNMU/ha4UbucIg1MFkQ=
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=

21
internal/acl/errors.go Normal file
View File

@@ -0,0 +1,21 @@
package acl
// TODO: add more specific errors
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")
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")
)

View File

@@ -1,8 +1,8 @@
package acl
type UserRole struct {
UserID uint `gorm:"primaryKey" json:"userId"`
RoleID uint `gorm:"primaryKey" json:"roleId"`
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"`

140
internal/acl/resources.go Normal file
View File

@@ -0,0 +1,140 @@
package acl
import (
"errors"
"fmt"
"strings"
"gorm.io/gorm"
)
// GetResources returns all resources.
// May return [ErrNotInitialized] or db error.
func (s *Service) GetResources() ([]Resource, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var resources []Resource
if err := s.db.Order("id").Find(&resources).Error; err != nil {
return nil, fmt.Errorf("db error: %w", err)
}
return resources, nil
}
// CreateResource creates a new resource with the given key or returns existing one.
// Returns ID of created resource.
// May return [ErrNotInitialized], [ErrInvalidResourceKey], [ErrResourceAlreadyExists] or db error.
func (s *Service) CreateResource(key string) (uint, error) {
if !s.isInitialized() {
return 0, ErrNotInitialized
}
key = strings.TrimSpace(key)
if key == "" {
return 0, ErrInvalidResourceKey
}
var res Resource
if err := s.db.Where("key = ?", key).First(&res).Error; err == nil {
// already exists
return res.ID, ErrResourceAlreadyExists
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
// other db error
return 0, fmt.Errorf("db error: %w", err)
}
res = Resource{Key: key}
if err := s.db.Create(&res).Error; err != nil {
return 0, fmt.Errorf("db error: %w", err)
}
return res.ID, nil
}
// GetResourceByID returns the resource with the given ID.
// May return [ErrNotInitialized], [ErrResourceNotFound] or db error.
func (s *Service) GetResourceByID(resourceID uint) (*Resource, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var res Resource
if err := s.db.First(&res, resourceID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrResourceNotFound
}
return nil, fmt.Errorf("db error: %w", err)
}
return &res, nil
}
// UpdateResource updates the key of a resource.
// May return [ErrNotInitialized], [ErrInvalidResourceKey], [ErrResourceNotFound], [ErrSameResourceKey] or db error.
func (s *Service) UpdateResource(resourceID uint, newKey string) error {
if !s.isInitialized() {
return ErrNotInitialized
}
newKey = strings.TrimSpace(newKey)
if newKey == "" {
return ErrInvalidResourceKey
}
var res Resource
if err := s.db.First(&res, resourceID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrResourceNotFound
}
return fmt.Errorf("db error: %w", err)
}
// same key?
if res.Key == newKey {
return ErrSameResourceKey
}
// check if key used by another resource
var count int64
if err := s.db.Model(&Resource{}).
Where("key = ? AND id != ?", newKey, resourceID).
Count(&count).Error; err != nil {
return fmt.Errorf("db error: %w", err)
}
if count > 0 {
return ErrSameResourceKey
}
res.Key = newKey
if err := s.db.Save(&res).Error; err != nil {
return fmt.Errorf("failed to update resource: %w", err)
}
return nil
}
// DeleteResource deletes a resource.
// May return [ErrNotInitialized], [ErrResourceNotFound], [ErrResourceInUse] or db error.
func (s *Service) DeleteResource(resourceID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
result := s.db.Delete(&Resource{}, resourceID)
if err := result.Error; err != nil {
if strings.Contains(err.Error(), "FOREIGN KEY constraint failed") {
return ErrResourceInUse
}
return fmt.Errorf("db error: %w", err)
}
if result.RowsAffected == 0 {
return ErrResourceNotFound
}
return nil
}

136
internal/acl/roles.go Normal file
View File

@@ -0,0 +1,136 @@
package acl
import (
"errors"
"fmt"
"strings"
"gorm.io/gorm"
)
// GetRoles returns all roles.
// May return [ErrNotInitialized] or db error.
func (s *Service) GetRoles() ([]Role, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var roles []Role
if err := s.db.Preload("Resources").Order("id").Find(&roles).Error; err != nil {
return nil, fmt.Errorf("db error: %w", err)
}
return roles, nil
}
// CreateRole creates a new role with the given name or returns existing one.
// Returns the ID of the created role.
// May return [ErrNotInitialized], [ErrInvalidRoleName], [ErrRoleAlreadyExists] or db error.
func (s *Service) CreateRole(name string) (uint, error) {
if !s.isInitialized() {
return 0, ErrNotInitialized
}
name = strings.TrimSpace(name)
if name == "" {
return 0, ErrInvalidRoleName
}
var role Role
if err := s.db.Where("name = ?", name).First(&role).Error; err == nil {
// already exists
return role.ID, ErrRoleAlreadyExists
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
// other database error
return 0, fmt.Errorf("db error: %w", err)
}
role = Role{Name: name}
if err := s.db.Create(&role).Error; err != nil {
return 0, fmt.Errorf("db error: %w", err)
}
return role.ID, nil
}
// GetRoleByID returns the role with the given ID or an error.
// May return [ErrNotInitialized], [ErrRoleNotFound] or db error.
func (s *Service) GetRoleByID(roleID uint) (*Role, error) {
if !s.isInitialized() {
return nil, ErrNotInitialized
}
var role Role
err := s.db.Preload("Resources").First(&role, roleID).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrRoleNotFound
}
return nil, fmt.Errorf("db error: %w", err)
}
return &role, nil
}
// UpdateRole updates the name of a role.
// May return [ErrNotInitialized], [ErrInvalidRoleName], [ErrRoleNotFound], [ErrSameRoleName], or db error.
func (s *Service) UpdateRole(roleID uint, newName string) error {
if !s.isInitialized() {
return ErrNotInitialized
}
newName = strings.TrimSpace(newName)
if newName == "" {
return ErrInvalidRoleName
}
var role Role
err := s.db.First(&role, roleID).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return fmt.Errorf("db error: %w", err)
}
// check for name conflicts
if role.Name == newName {
return ErrSameRoleName
}
var count int64
err = s.db.Model(&Role{}).Where("name = ? AND id != ?", newName, roleID).Count(&count).Error
if err != nil {
return fmt.Errorf("db error: %w", err)
}
if count > 0 {
return ErrSameRoleName
}
role.Name = newName
if err := s.db.Save(&role).Error; err != nil {
return fmt.Errorf("failed to update role: %w", err)
}
return nil
}
// DeleteRole deletes a role.
// May return [ErrNotInitialized], [ErrRoleNotFound], [ErrRoleInUse] or db error.
func (s *Service) DeleteRole(roleID uint) error {
if !s.isInitialized() {
return ErrNotInitialized
}
result := s.db.Delete(&Role{}, roleID)
if err := result.Error; err != nil {
if strings.Contains(err.Error(), "FOREIGN KEY constraint failed") {
return ErrRoleInUse
}
return fmt.Errorf("db error: %w", err)
}
if result.RowsAffected == 0 {
return ErrRoleNotFound
}
return nil
}

View File

@@ -1,6 +1,7 @@
package acl
import (
"errors"
"fmt"
"gorm.io/gorm"
@@ -40,30 +41,14 @@ func (s *Service) Init() error {
return nil
}
// Admin crud functions
// Admin crud functions //
// CreateRole creates a new role with the given name
func (s *Service) CreateRole(name string) error {
if !s.isInitialized() {
return fmt.Errorf("acl service is not initialized")
}
role := Role{Name: name}
return s.db.FirstOrCreate(&role, &Role{Name: name}).Error
}
// CreateResource creates a new resource with the given key
func (s *Service) CreateResource(key string) error {
if !s.isInitialized() {
return fmt.Errorf("acl service is not initialized")
}
res := Resource{Key: key}
return s.db.FirstOrCreate(&res, &Resource{Key: key}).Error
}
// Resources
// AssignResourceToRole assigns a resource to a role
func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
if !s.isInitialized() {
return fmt.Errorf("acl service is not initialized")
return ErrNotInitialized
}
rr := RoleResource{
RoleID: roleID,
@@ -75,19 +60,25 @@ func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
// AssignRoleToUser assigns a role to a user
func (s *Service) AssignRoleToUser(roleID, userID uint) error {
if !s.isInitialized() {
return fmt.Errorf("acl service is not initialized")
return ErrNotInitialized
}
ur := UserRole{
UserID: userID,
RoleID: roleID,
}
return s.db.FirstOrCreate(&ur, UserRole{UserID: userID, RoleID: roleID}).Error
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 fmt.Errorf("acl service is not initialized")
return ErrNotInitialized
}
return s.db.Where("role_id = ? AND resource_id = ?", roleID, resourceID).Delete(&RoleResource{}).Error
}
@@ -95,35 +86,15 @@ func (s *Service) RemoveResourceFromRole(roleID, resourceID uint) error {
// RemoveRoleFromUser removes a role from a user
func (s *Service) RemoveRoleFromUser(roleID, userID uint) error {
if !s.isInitialized() {
return fmt.Errorf("acl service is not initialized")
return ErrNotInitialized
}
return s.db.Where("role_id = ? AND user_id = ?", roleID, userID).Delete(&UserRole{}).Error
}
// GetRoles returns all roles
func (s *Service) GetRoles() ([]Role, error) {
if !s.isInitialized() {
return nil, fmt.Errorf("acl service is not initialized")
}
var roles []Role
err := s.db.Preload("Resources").Order("id").Find(&roles).Error
return roles, err
}
// GetPermissions returns all permissions
func (s *Service) GetPermissions() ([]Resource, error) {
if !s.isInitialized() {
return nil, fmt.Errorf("acl service is not initialized")
}
var resources []Resource
err := s.db.Order("id").Find(&resources).Error
return resources, err
}
// GetRoleResources returns all resources for a given role
func (s *Service) GetRoleResources(roleID uint) ([]Resource, error) {
if !s.isInitialized() {
return nil, fmt.Errorf("acl service is not initialized")
return nil, ErrNotInitialized
}
var resources []Resource
err := s.db.Joins("JOIN role_resources rr ON rr.resource_id = resources.id").
@@ -134,7 +105,7 @@ func (s *Service) GetRoleResources(roleID uint) ([]Resource, error) {
// GetUserRoles returns all roles for a given user
func (s *Service) GetUserRoles(userID uint) ([]Role, error) {
if !s.isInitialized() {
return nil, fmt.Errorf("acl service is not initialized")
return nil, ErrNotInitialized
}
var roles []Role
err := s.db.Joins("JOIN user_roles ur ON ur.role_id = roles.id").

View File

@@ -1,156 +1,158 @@
package acl_test
import (
"os"
"path/filepath"
"testing"
// DEPRECATED TEST FILE
"git.oblat.lv/alex/triggerssmith/internal/acl"
"git.oblat.lv/alex/triggerssmith/internal/user"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// import (
// "os"
// "path/filepath"
// "testing"
func openTestDB(t *testing.T) *gorm.DB {
t.Helper()
// "git.oblat.lv/alex/triggerssmith/internal/acl"
// "git.oblat.lv/alex/triggerssmith/internal/user"
// "gorm.io/driver/sqlite"
// "gorm.io/gorm"
// )
// Путь к файлу базы
dbPath := filepath.Join("testdata", "test.db")
// func openTestDB(t *testing.T) *gorm.DB {
// t.Helper()
// Удаляем старую базу, если есть
os.Remove(dbPath)
// // Путь к файлу базы
// dbPath := filepath.Join("testdata", "test.db")
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
t.Fatalf("failed to open test db: %v", err)
}
// // Удаляем старую базу, если есть
// os.Remove(dbPath)
// Миграция таблицы User для связи с ACL
if err := db.AutoMigrate(&user.User{}); err != nil {
t.Fatalf("failed to migrate User: %v", err)
}
// db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
// if err != nil {
// t.Fatalf("failed to open test db: %v", err)
// }
return db
}
// // Миграция таблицы User для связи с ACL
// if err := db.AutoMigrate(&user.User{}); err != nil {
// t.Fatalf("failed to migrate User: %v", err)
// }
func TestACLService_CRUD(t *testing.T) {
db := openTestDB(t)
// return db
// }
// Создаём сервис ACL
svc, err := acl.NewService(db)
if err != nil {
t.Fatalf("failed to create ACL service: %v", err)
}
// func TestACLService_CRUD(t *testing.T) {
// db := openTestDB(t)
if err := svc.Init(); err != nil {
t.Fatalf("failed to init ACL service: %v", err)
}
// // Создаём сервис ACL
// svc, err := acl.NewService(db)
// if err != nil {
// t.Fatalf("failed to create ACL service: %v", err)
// }
// Создаём роли
if err := svc.CreateRole("admin"); err != nil {
t.Fatalf("CreateRole failed: %v", err)
}
if err := svc.CreateRole("guest"); err != nil {
t.Fatalf("CreateRole failed: %v", err)
}
// if err := svc.Init(); err != nil {
// t.Fatalf("failed to init ACL service: %v", err)
// }
roles, err := svc.GetRoles()
if err != nil {
t.Fatalf("GetRoles failed: %v", err)
}
if len(roles) != 2 {
t.Fatalf("expected 2 roles, got %d", len(roles))
}
// // Создаём роли
// if err := svc.CreateRole("admin"); err != nil {
// t.Fatalf("CreateRole failed: %v", err)
// }
// if err := svc.CreateRole("guest"); err != nil {
// t.Fatalf("CreateRole failed: %v", err)
// }
// Создаём ресурсы
if err := svc.CreateResource("*"); err != nil {
t.Fatalf("CreateResource failed: %v", err)
}
if err := svc.CreateResource("html.view.*"); err != nil {
t.Fatalf("CreateResource failed: %v", err)
}
// roles, err := svc.GetRoles()
// if err != nil {
// t.Fatalf("GetRoles failed: %v", err)
// }
// if len(roles) != 2 {
// t.Fatalf("expected 2 roles, got %d", len(roles))
// }
resources, err := svc.GetPermissions()
if err != nil {
t.Fatalf("GetPermissions failed: %v", err)
}
if len(resources) != 2 {
t.Fatalf("expected 2 resources, got %d", len(resources))
}
// // Создаём ресурсы
// if err := svc.CreateResource("*"); err != nil {
// t.Fatalf("CreateResource failed: %v", err)
// }
// if err := svc.CreateResource("html.view.*"); err != nil {
// t.Fatalf("CreateResource failed: %v", err)
// }
// 1. Создаём сервис user
store, err := user.NewGormUserStore(db)
if err != nil {
t.Fatalf("failed to create user store: %v", err)
}
userSvc, err := user.NewService(store)
if err != nil {
t.Fatalf("failed to create user service: %v", err)
}
// resources, err := svc.GetPermissions()
// if err != nil {
// t.Fatalf("GetPermissions failed: %v", err)
// }
// if len(resources) != 2 {
// t.Fatalf("expected 2 resources, got %d", len(resources))
// }
// 2. Инициализируем
if err := userSvc.Init(); err != nil {
t.Fatalf("failed to init user service: %v", err)
}
// // 1. Создаём сервис user
// store, err := user.NewGormUserStore(db)
// if err != nil {
// t.Fatalf("failed to create user store: %v", err)
// }
// userSvc, err := user.NewService(store)
// if err != nil {
// t.Fatalf("failed to create user service: %v", err)
// }
user := &user.User{
Username: "testuser",
Email: "testuser@example.com",
Password: "secret",
}
// // 2. Инициализируем
// if err := userSvc.Init(); err != nil {
// t.Fatalf("failed to init user service: %v", err)
// }
u := user
// user := &user.User{
// Username: "testuser",
// Email: "testuser@example.com",
// Password: "secret",
// }
// 3. Создаём пользователя через сервис
err = userSvc.Create(user)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// u := user
// Привязываем роль к пользователю
adminRoleID := roles[0].ID
if err := svc.AssignRoleToUser(adminRoleID, uint(u.ID)); err != nil {
t.Fatalf("AssignRoleToUser failed: %v", err)
}
// // 3. Создаём пользователя через сервис
// err = userSvc.Create(user)
// if err != nil {
// t.Fatalf("failed to create user: %v", err)
// }
userRoles, err := svc.GetUserRoles(uint(u.ID))
if err != nil {
t.Fatalf("GetUserRoles failed: %v", err)
}
if len(userRoles) != 1 || userRoles[0].ID != adminRoleID {
t.Fatalf("expected user to have admin role")
}
// // Привязываем роль к пользователю
// adminRoleID := roles[0].ID
// if err := svc.AssignRoleToUser(adminRoleID, uint(u.ID)); err != nil {
// t.Fatalf("AssignRoleToUser failed: %v", err)
// }
// Привязываем ресурсы к роли
for _, res := range resources {
if err := svc.AssignResourceToRole(adminRoleID, res.ID); err != nil {
t.Fatalf("AssignResourceToRole failed: %v", err)
}
}
// userRoles, err := svc.GetUserRoles(uint(u.ID))
// if err != nil {
// t.Fatalf("GetUserRoles failed: %v", err)
// }
// if len(userRoles) != 1 || userRoles[0].ID != adminRoleID {
// t.Fatalf("expected user to have admin role")
// }
roleResources, err := svc.GetRoleResources(adminRoleID)
if err != nil {
t.Fatalf("GetRoleResources failed: %v", err)
}
if len(roleResources) != 2 {
t.Fatalf("expected role to have 2 resources")
}
// // Привязываем ресурсы к роли
// for _, res := range resources {
// if err := svc.AssignResourceToRole(adminRoleID, res.ID); err != nil {
// t.Fatalf("AssignResourceToRole failed: %v", err)
// }
// }
// Удаляем ресурс из роли
if err := svc.RemoveResourceFromRole(adminRoleID, resources[0].ID); err != nil {
t.Fatalf("RemoveResourceFromRole failed: %v", err)
}
roleResources, _ = svc.GetRoleResources(adminRoleID)
if len(roleResources) != 1 {
t.Fatalf("expected 1 resource after removal")
}
// roleResources, err := svc.GetRoleResources(adminRoleID)
// if err != nil {
// t.Fatalf("GetRoleResources failed: %v", err)
// }
// if len(roleResources) != 2 {
// t.Fatalf("expected role to have 2 resources")
// }
// Удаляем роль у пользователя
if err := svc.RemoveRoleFromUser(adminRoleID, uint(u.ID)); err != nil {
t.Fatalf("RemoveRoleFromUser failed: %v", err)
}
userRoles, _ = svc.GetUserRoles(uint(u.ID))
if len(userRoles) != 0 {
t.Fatalf("expected user to have 0 roles after removal")
}
}
// // Удаляем ресурс из роли
// if err := svc.RemoveResourceFromRole(adminRoleID, resources[0].ID); err != nil {
// t.Fatalf("RemoveResourceFromRole failed: %v", err)
// }
// roleResources, _ = svc.GetRoleResources(adminRoleID)
// if len(roleResources) != 1 {
// t.Fatalf("expected 1 resource after removal")
// }
// // Удаляем роль у пользователя
// if err := svc.RemoveRoleFromUser(adminRoleID, uint(u.ID)); err != nil {
// t.Fatalf("RemoveRoleFromUser failed: %v", err)
// }
// userRoles, _ = svc.GetUserRoles(uint(u.ID))
// if len(userRoles) != 0 {
// t.Fatalf("expected user to have 0 roles after removal")
// }
// }

20
internal/server/error.go Normal file
View File

@@ -0,0 +1,20 @@
package server
import (
"encoding/json"
"net/http"
)
type ErrorResponse struct {
Error string `json:"error"`
Details string `json:"details,omitempty"`
}
func WriteError(w http.ResponseWriter, error, details string, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(ErrorResponse{
Error: error,
Details: details,
})
}

View File

@@ -6,7 +6,7 @@ import (
)
type User struct {
ID int64 `gorm:"primaryKey"`
ID uint `gorm:"primaryKey"`
Username string `gorm:"uniqueIndex;not null"`
Email string `gorm:"uniqueIndex;not null"`
Password string `gorm:"not null"`

View File

@@ -1,84 +1,86 @@
package user
import (
"os"
"path/filepath"
"testing"
// DEPRECATED TEST FILE
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// import (
// "os"
// "path/filepath"
// "testing"
func setupTestDB(t *testing.T) *gorm.DB {
t.Helper()
// "gorm.io/driver/sqlite"
// "gorm.io/gorm"
// )
dbPath := filepath.Join("testdata", "users.db")
// func setupTestDB(t *testing.T) *gorm.DB {
// t.Helper()
_ = os.Remove(dbPath)
// dbPath := filepath.Join("testdata", "users.db")
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
t.Fatalf("failed to open db: %v", err)
}
// _ = os.Remove(dbPath)
if err := db.AutoMigrate(&User{}); err != nil {
t.Fatalf("failed to migrate: %v", err)
}
// db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
// if err != nil {
// t.Fatalf("failed to open db: %v", err)
// }
return db
}
// if err := db.AutoMigrate(&User{}); err != nil {
// t.Fatalf("failed to migrate: %v", err)
// }
func TestUsersCRUD(t *testing.T) {
db := setupTestDB(t)
// return db
// }
store, err := NewGormUserStore(db)
if err != nil {
t.Fatalf("failed to create store: %v", err)
}
// func TestUsersCRUD(t *testing.T) {
// db := setupTestDB(t)
service, err := NewService(store)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// store, err := NewGormUserStore(db)
// if err != nil {
// t.Fatalf("failed to create store: %v", err)
// }
user := &User{
Username: "testuser",
Email: "test@example.com",
Password: "password123",
}
// service, err := NewService(store)
// if err != nil {
// t.Fatalf("failed to create service: %v", err)
// }
if err := service.Create(user); err != nil {
t.Fatalf("failed to create user: %v", err)
}
// retrieved, err := service.GetByID(user.ID)
// if err != nil {
// t.Fatalf("failed to get user by ID: %v", err)
// }
// if retrieved.Username != user.Username {
// t.Fatalf("expected username %s, got %s", user.Username, retrieved.Username)
// }
// user := &User{
// Username: "testuser",
// Email: "test@example.com",
// Password: "password123",
// }
// retrievedByUsername, err := service.GetByUsername(user.Username)
// if err != nil {
// t.Fatalf("failed to get user by username: %v", err)
// }
// if retrievedByUsername.Email != user.Email {
// t.Fatalf("expected email %s, got %s", user.Email, retrievedByUsername.Email)
// }
// if err := service.Create(user); err != nil {
// t.Fatalf("failed to create user: %v", err)
// }
// // retrieved, err := service.GetByID(user.ID)
// // if err != nil {
// // t.Fatalf("failed to get user by ID: %v", err)
// // }
// // if retrieved.Username != user.Username {
// // t.Fatalf("expected username %s, got %s", user.Username, retrieved.Username)
// // }
// user.Email = "newemail@example.com"
// if err := service.Update(user); err != nil {
// t.Fatalf("failed to update user: %v", err)
// }
// retrieved, err = service.GetByID(user.ID)
// if err != nil {
// t.Fatalf("failed to get user by ID: %v", err)
// }
// if retrieved.Email != user.Email {
// t.Fatalf("expected email %s, got %s", user.Email, retrieved.Email)
// }
err = service.Delete(user.ID)
if err != nil {
t.Fatalf("failed to delete user: %v", err)
}
}
// // retrievedByUsername, err := service.GetByUsername(user.Username)
// // if err != nil {
// // t.Fatalf("failed to get user by username: %v", err)
// // }
// // if retrievedByUsername.Email != user.Email {
// // t.Fatalf("expected email %s, got %s", user.Email, retrievedByUsername.Email)
// // }
// // user.Email = "newemail@example.com"
// // if err := service.Update(user); err != nil {
// // t.Fatalf("failed to update user: %v", err)
// // }
// // retrieved, err = service.GetByID(user.ID)
// // if err != nil {
// // t.Fatalf("failed to get user by ID: %v", err)
// // }
// // if retrieved.Email != user.Email {
// // t.Fatalf("expected email %s, got %s", user.Email, retrieved.Email)
// // }
// err = service.Delete(user.ID)
// if err != nil {
// t.Fatalf("failed to delete user: %v", err)
// }
// }