Compare commits
21 Commits
904f446447
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 68bce99e1d | |||
| d64645599d | |||
| 6ce7edd194 | |||
| c718db565e | |||
| af7770eb06 | |||
| 8e67bae683 | |||
| 5468c831c4 | |||
| 600cf84776 | |||
| 0485fd3bee | |||
| f2f7819f8c | |||
| 48d9c14944 | |||
| cadb42d17a | |||
| 0510103125 | |||
| e75390f673 | |||
| bf96ca1263 | |||
| ca569d25bc | |||
| 1468937589 | |||
| 9070b4138e | |||
| ac26a981b2 | |||
| e9d8877fbf | |||
| 85f8ac60e7 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -4,4 +4,5 @@ config.yaml
|
|||||||
panic.log
|
panic.log
|
||||||
testdata/
|
testdata/
|
||||||
secret/
|
secret/
|
||||||
data/
|
data/
|
||||||
|
docs/
|
||||||
@@ -51,19 +51,28 @@ func MustRoute(config *config.Config, aclService *acl.Service, authService *auth
|
|||||||
// DELETE /roles/{roleId}/resources/{resId} — убрать ресурс
|
// DELETE /roles/{roleId}/resources/{resId} — убрать ресурс
|
||||||
return func(r chi.Router) {
|
return func(r chi.Router) {
|
||||||
// Roles
|
// Roles
|
||||||
r.Get("/roles", h.getRoles) // list all roles
|
r.Get("/roles", h.getRoles) // list all roles
|
||||||
r.Post("/roles", h.createRole) // create a new role
|
r.Post("/roles", h.createRole) // create a new role
|
||||||
r.Get("/roles/{roleId}", h.getRole) // get a role by ID
|
r.Get("/roles/{roleId}", h.getRole) // get a role by ID
|
||||||
r.Patch("/roles/{roleId}", h.updateRole) // update a role by ID
|
r.Get("/roles/{roleId}/users", h.getRoleUsers) // get all assigned users to a role
|
||||||
r.Delete("/roles/{roleId}", h.deleteRole) // delete a role by ID
|
r.Get("/roles/{roleId}/resources", h.getRoleResources) // get all resources assigned to a role
|
||||||
|
r.Patch("/roles/{roleId}", h.updateRole) // update a role by ID
|
||||||
|
r.Delete("/roles/{roleId}", h.deleteRole) // delete a role by ID
|
||||||
|
r.Post("/roles/{roleId}/resources", h.assignResourceToRole) // assign a resource to a role
|
||||||
|
r.Delete("/roles/{roleId}/resources/{resId}", h.removeResourceFromRole) // remove a resource from a role
|
||||||
|
|
||||||
// // Resources
|
// Resources
|
||||||
r.Get("/resources", h.getResources) // list all resources
|
r.Get("/resources", h.getResources) // list all resources
|
||||||
r.Post("/resources", h.createResource) // create a new resource
|
r.Post("/resources", h.createResource) // create a new resource
|
||||||
r.Get("/resources/{resourceId}", h.getResource) // get a resource by ID
|
r.Get("/resources/{resourceId}", h.getResource) // get a resource by ID
|
||||||
r.Patch("/resources/{resourceId}", h.updateResource) // update 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.Delete("/resources/{resourceId}", h.deleteResource) // delete a resource by ID
|
||||||
|
|
||||||
|
// Users
|
||||||
|
r.Get("/users/{userId}/roles", h.getUserRoles) // get all roles for a user
|
||||||
|
r.Post("/users/{userId}/roles", h.assignRoleToUser) // assign a role to a user
|
||||||
|
r.Delete("/users/{userId}/roles/{roleId}", h.removeRoleFromUser) // remove a role from a user
|
||||||
|
|
||||||
// Users
|
// Users
|
||||||
// r.Get("/users/{userId}/roles", h.getUserRoles) // get all roles for a user
|
// 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.Post("/users/{userId}/roles", h.assignRoleToUser) // assign a role to a user
|
||||||
|
|||||||
@@ -7,71 +7,60 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// @Summary Get all resources
|
// @Summary Get all resources
|
||||||
// @Tags resources
|
// @Tags acl/resources
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Success 200 {object} getResourcesResponse
|
// @Success 200 {object} getResourcesResponse
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/resources [get]
|
// @Router /api/acl/resources [get]
|
||||||
func (h *aclAdminHandler) getResources(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) getResources(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
resources, err := h.a.GetResources()
|
resources, err := h.a.GetResources()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to get resources",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = json.NewEncoder(w).Encode(func() getResourcesResponse {
|
type R struct {
|
||||||
resp := make(getResourcesResponse, 0, len(resources))
|
ID uint `json:"id" example:"1"`
|
||||||
for _, res := range resources {
|
Key string `json:"key" example:"html.view"`
|
||||||
resp = append(resp, struct {
|
}
|
||||||
ID uint `json:"id" example:"1"`
|
|
||||||
Key string `json:"key" example:"html.view"`
|
resp := make([]R, 0, len(resources))
|
||||||
}{
|
for _, res := range resources {
|
||||||
ID: res.ID,
|
resp = append(resp, R{ID: res.ID, Key: res.Key})
|
||||||
Key: res.Key,
|
}
|
||||||
})
|
|
||||||
}
|
_ = json.NewEncoder(w).Encode(resp)
|
||||||
return resp
|
|
||||||
}())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Get resource by ID
|
// @Summary Get resource by ID
|
||||||
// @Tags resources
|
// @Tags acl/resources
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param resourceId path int true "Resource ID" example(1)
|
// @Param resourceId path int true "Resource ID" example(1)
|
||||||
// @Success 200 {object} getResourceResponse
|
// @Success 200 {object} getResourceResponse
|
||||||
// @Failure 400 {object} getResourceErrorInvalidResourceID
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} getResourceErrorResourceNotFound
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/resources/{resourceId} [get]
|
// @Router /api/acl/resources/{resourceId} [get]
|
||||||
func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
resourceIDStr := chi.URLParam(r, "resourceId")
|
resourceIDStr := chi.URLParam(r, "resourceId")
|
||||||
resourceID, err := strconv.Atoi(resourceIDStr)
|
resourceID, err := strconv.Atoi(resourceIDStr)
|
||||||
if err != nil || resourceID < 0 {
|
if err != nil || resourceID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(getResourceErrorInvalidResourceID{
|
|
||||||
Error: ErrorInvalidResourceID,
|
|
||||||
Details: "Resource ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,27 +68,14 @@ func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrResourceNotFound:
|
case acl.ErrResourceNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(getResourceErrorResourceNotFound{
|
|
||||||
Error: ErrorResourceNotFound,
|
|
||||||
Details: "No resource with ID " + resourceIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to get resource with ID " + resourceIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = json.NewEncoder(w).Encode(getResourceResponse{
|
_ = json.NewEncoder(w).Encode(getResourceResponse{
|
||||||
@@ -109,61 +85,40 @@ func (h *aclAdminHandler) getResource(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Create resource
|
// @Summary Create resource
|
||||||
// @Tags resources
|
// @Tags acl/resources
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param request body createResourceRequest true "Resource"
|
// @Param request body createResourceRequest true "Resource"
|
||||||
// @Success 201 {object} createResourceResponse
|
// @Success 201 {object} createResourceResponse
|
||||||
// @Failure 400 {object} errorInvalidRequestBody
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 400 {object} createResourceErrorInvalidResourceKey
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} createResourceErrorResourceAlreadyExists
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
|
||||||
// @Router /api/acl/resources [post]
|
// @Router /api/acl/resources [post]
|
||||||
func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var req createResourceRequest
|
var req createResourceRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
|
|
||||||
Error: ErrorInvalidRequestBody,
|
|
||||||
Details: "Request body is not valid JSON",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
resourceID, err := h.a.CreateResource(req.Key)
|
resourceID, err := h.a.CreateResource(req.Key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to create resource", "error", err.Error())
|
slog.Error("Failed to create resource", "error", err)
|
||||||
|
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrInvalidResourceKey:
|
case acl.ErrInvalidResourceKey:
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-key", "Invalid resource key", "Resource key must be non-empty", r)
|
||||||
_ = json.NewEncoder(w).Encode(createResourceErrorInvalidResourceKey{
|
|
||||||
Error: ErrorFailedToCreateResource,
|
|
||||||
Details: "Resource key must be non-empty",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrResourceAlreadyExists:
|
case acl.ErrResourceAlreadyExists:
|
||||||
w.WriteHeader(http.StatusConflict)
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/resource-already-exists", "Resource already exists", "Resource '"+req.Key+"' already exists", r)
|
||||||
_ = json.NewEncoder(w).Encode(createResourceErrorResourceAlreadyExists{
|
|
||||||
Error: ErrorFailedToCreateResource,
|
|
||||||
Details: "Resource with key '" + req.Key + "' already exists",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to create resource with key '" + req.Key + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
@@ -174,85 +129,53 @@ func (h *aclAdminHandler) createResource(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Update resource
|
// @Summary Update resource
|
||||||
// @Tags resources
|
// @Tags acl/resources
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param resourceId path int true "Resource ID" example(1)
|
// @Param resourceId path int true "Resource ID" example(1)
|
||||||
// @Param request body updateResourceRequest true "Resource"
|
// @Param request body updateResourceRequest true "Resource"
|
||||||
// @Success 200 {object} updateResourceResponse
|
// @Success 200 {object} updateResourceResponse
|
||||||
// @Failure 400 {object} errorInvalidRequestBody
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 400 {object} updateResourceErrorInvalidResourceID
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 400 {object} updateResourceErrorInvalidResourceKey
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} updateResourceErrorResourceNotFound
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} updateResourceErrorResourceKeyAlreadyExists
|
|
||||||
// @Failure 500 {object} errorInternalServerError
|
|
||||||
// @Router /api/acl/resources/{resourceId} [patch]
|
// @Router /api/acl/resources/{resourceId} [patch]
|
||||||
func (h *aclAdminHandler) updateResource(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) updateResource(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var req updateResourceRequest
|
var req updateResourceRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
|
|
||||||
Error: ErrorInvalidRequestBody,
|
|
||||||
Details: "Request body is not valid JSON",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
resourceIDStr := chi.URLParam(r, "resourceId")
|
resourceIDStr := chi.URLParam(r, "resourceId")
|
||||||
resourceID, err := strconv.Atoi(resourceIDStr)
|
resourceID, err := strconv.Atoi(resourceIDStr)
|
||||||
if err != nil || resourceID < 0 {
|
if err != nil || resourceID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateResourceErrorInvalidResourceID{
|
|
||||||
Error: ErrorInvalidResourceID,
|
|
||||||
Details: "Resource ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = h.a.UpdateResource(uint(resourceID), req.Key)
|
err = h.a.UpdateResource(uint(resourceID), req.Key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to update resource", "error", err.Error())
|
slog.Error("Failed to update resource", "error", err)
|
||||||
|
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrInvalidResourceKey:
|
case acl.ErrInvalidResourceKey:
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-key", "Invalid resource key", "Resource key must be non-empty", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateResourceErrorInvalidResourceKey{
|
|
||||||
Error: ErrorFailedToUpdateResource,
|
|
||||||
Details: "Invalid resource key",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrResourceNotFound:
|
case acl.ErrResourceNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceNotFound{
|
|
||||||
Error: ErrorFailedToUpdateResource,
|
|
||||||
Details: "No resource with ID " + resourceIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrSameResourceKey:
|
case acl.ErrSameResourceKey:
|
||||||
w.WriteHeader(http.StatusConflict)
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/resource-key-already-exists", "Resource key already exists", "Resource key '"+req.Key+"' already exists", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateResourceErrorResourceKeyAlreadyExists{
|
|
||||||
Error: ErrorFailedToUpdateResource,
|
|
||||||
Details: "Resource with key '" + req.Key + "' already exists",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to update resource with key '" + req.Key + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
_ = json.NewEncoder(w).Encode(updateResourceResponse{
|
_ = json.NewEncoder(w).Encode(updateResourceResponse{
|
||||||
ID: uint(resourceID),
|
ID: uint(resourceID),
|
||||||
Key: req.Key,
|
Key: req.Key,
|
||||||
@@ -260,61 +183,41 @@ func (h *aclAdminHandler) updateResource(w http.ResponseWriter, r *http.Request)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Delete resource
|
// @Summary Delete resource
|
||||||
// @Tags resources
|
// @Tags acl/resources
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param resourceId path int true "Resource ID" example(1)
|
// @Param resourceId path int true "Resource ID" example(1)
|
||||||
// @Success 200
|
// @Success 200
|
||||||
// @Failure 400 {object} deleteResourceErrorInvalidResourceID
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} deleteResourceErrorResourceNotFound
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} deleteResourceErrorResourceInUse
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/resources/{resourceId} [delete]
|
// @Router /api/acl/resources/{resourceId} [delete]
|
||||||
func (h *aclAdminHandler) deleteResource(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) deleteResource(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
resourceIDStr := chi.URLParam(r, "resourceId")
|
resourceIDStr := chi.URLParam(r, "resourceId")
|
||||||
resourceID, err := strconv.Atoi(resourceIDStr)
|
resourceID, err := strconv.Atoi(resourceIDStr)
|
||||||
if err != nil || resourceID < 0 {
|
if err != nil || resourceID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteResourceErrorInvalidResourceID{
|
|
||||||
Error: ErrorInvalidResourceID,
|
|
||||||
Details: "Resource ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = h.a.DeleteResource(uint(resourceID))
|
err = h.a.DeleteResource(uint(resourceID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to delete resource", "error", err.Error())
|
slog.Error("Failed to delete resource", "error", err)
|
||||||
|
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "acl service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrResourceNotFound:
|
case acl.ErrResourceNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+resourceIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteResourceErrorResourceNotFound{
|
|
||||||
Error: ErrorFailedToDeleteResource,
|
|
||||||
Details: "No resource with ID " + resourceIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrResourceInUse:
|
case acl.ErrResourceInUse:
|
||||||
w.WriteHeader(http.StatusConflict)
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/resource-in-use", "Resource in use", "Resource "+resourceIDStr+" is in use", r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteResourceErrorResourceInUse{
|
|
||||||
Error: ErrorFailedToDeleteResource,
|
|
||||||
Details: "Resource with ID " + resourceIDStr + " is used and cannot be deleted",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to delete resource with ID '" + resourceIDStr + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ type getResourcesResponse []struct {
|
|||||||
Key string `json:"key" example:"html.view"`
|
Key string `json:"key" example:"html.view"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ getResourcesResponse // for documentation
|
||||||
|
|
||||||
/*******************************************************************/
|
/*******************************************************************/
|
||||||
// used in getResource()
|
// used in getResource()
|
||||||
type getResourceResponse struct {
|
type getResourceResponse struct {
|
||||||
@@ -14,16 +16,6 @@ type getResourceResponse struct {
|
|||||||
Key string `json:"key" example:"html.view"`
|
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()
|
// used in createResource()
|
||||||
type createResourceRequest struct {
|
type createResourceRequest struct {
|
||||||
@@ -35,16 +27,6 @@ type createResourceResponse struct {
|
|||||||
Key string `json:"key" example:"html.view"`
|
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()
|
// used in updateResource()
|
||||||
type updateResourceRequest struct {
|
type updateResourceRequest struct {
|
||||||
@@ -55,40 +37,3 @@ type updateResourceResponse struct {
|
|||||||
ID uint `json:"id" example:"1"`
|
ID uint `json:"id" example:"1"`
|
||||||
Key string `json:"key" example:"html.view"`
|
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"`
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,14 +7,15 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// @Summary Get all roles
|
// @Summary Get all roles
|
||||||
// @Tags roles
|
// @Tags acl/roles
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Success 200 {object} getRolesResponse
|
// @Success 200 {array} getRolesResponse
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/roles [get]
|
// @Router /api/acl/roles [get]
|
||||||
func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -22,146 +23,190 @@ func (h *aclAdminHandler) getRoles(w http.ResponseWriter, r *http.Request) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to get roles",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
_ = json.NewEncoder(w).Encode(func() getRolesResponse {
|
|
||||||
// Transform acl.Role to getRolesResponse
|
type R struct {
|
||||||
resp := make(getRolesResponse, 0, len(roles))
|
ID uint `json:"id" example:"1"`
|
||||||
for _, role := range roles {
|
Name string `json:"name" example:"admin"`
|
||||||
resp = append(resp, struct {
|
}
|
||||||
ID uint `json:"id" example:"1"`
|
|
||||||
Name string `json:"name" example:"admin"`
|
resp := make([]R, 0, len(roles))
|
||||||
}{
|
for _, role := range roles {
|
||||||
ID: role.ID,
|
resp = append(resp, R{ID: role.ID, Name: role.Name})
|
||||||
Name: role.Name,
|
}
|
||||||
})
|
|
||||||
}
|
_ = json.NewEncoder(w).Encode(resp)
|
||||||
return resp
|
|
||||||
}())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Get role by ID
|
// @Summary Get role by ID
|
||||||
// @Tags roles
|
// @Tags acl/roles
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param roleId path int true "Role ID" example(1)
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
// @Success 200 {object} getRoleResponse
|
// @Success 200 {object} getRoleResponse
|
||||||
// @Failure 400 {object} getRoleErrorInvalidRoleID
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} getRoleErrorRoleNotFound
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/roles/{roleId} [get]
|
// @Router /api/acl/roles/{roleId} [get]
|
||||||
func (h *aclAdminHandler) getRole(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) getRole(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
roleIDStr := chi.URLParam(r, "roleId")
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
roleID, err := strconv.Atoi(roleIDStr)
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
if err != nil || roleID < 0 {
|
if err != nil || roleID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(getRoleErrorInvalidRoleID{
|
|
||||||
Error: ErrorInvalidRoleID,
|
|
||||||
Details: "Role ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
role, err := h.a.GetRoleByID(uint(roleID))
|
role, err := h.a.GetRoleByID(uint(roleID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrRoleNotFound:
|
case acl.ErrRoleNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(getRoleErrorRoleNotFound{
|
|
||||||
Error: ErrorRoleNotFound,
|
|
||||||
Details: "No role with ID " + roleIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to get role with ID " + roleIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = json.NewEncoder(w).Encode(getRoleResponse{
|
_ = json.NewEncoder(w).Encode(getRoleResponse{
|
||||||
ID: role.ID,
|
ID: role.ID,
|
||||||
Name: role.Name,
|
Name: role.Name,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @Summary Get role users
|
||||||
|
// @Tags acl/roles
|
||||||
|
// @Produce json
|
||||||
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
|
// @Success 200 {array} getRoleUsersResponse
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/roles/{roleId}/users [get]
|
||||||
|
func (h *aclAdminHandler) getRoleUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
|
if err != nil || roleID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
role, err := h.a.GetRoleByID(uint(roleID))
|
||||||
|
if err != nil {
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
|
default:
|
||||||
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(role.Users) == 0 {
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-has-no-users", "Role has no users", "Role has no users", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var respUsers getRoleUsersResponse
|
||||||
|
for _, user := range role.Users {
|
||||||
|
respUsers = append(respUsers, getRoleUser{
|
||||||
|
ID: user.ID,
|
||||||
|
Name: user.Username,
|
||||||
|
Email: user.Email,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(respUsers)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Get role resources
|
||||||
|
// @Tags acl/roles
|
||||||
|
// @Produce json
|
||||||
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
|
// @Success 200 {array} getRoleResourcesResponse
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/roles/{roleId}/resources [get]
|
||||||
|
func (h *aclAdminHandler) getRoleResources(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
|
if err != nil || roleID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
role, err := h.a.GetRoleByID(uint(roleID))
|
||||||
|
if err != nil {
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
|
default:
|
||||||
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(role.Resources) == 0 {
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-has-no-users", "Role has no users", "Role has no users", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var respResources getRoleResourcesResponse
|
||||||
|
for _, user := range role.Resources {
|
||||||
|
respResources = append(respResources, getRoleResource{
|
||||||
|
ID: user.ID,
|
||||||
|
Name: user.Key,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(respResources)
|
||||||
|
}
|
||||||
|
|
||||||
// @Summary Create role
|
// @Summary Create role
|
||||||
// @Tags roles
|
// @Tags acl/roles
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param request body createRoleRequest true "Role"
|
// @Param request body createRoleRequest true "Role"
|
||||||
// @Success 201 {object} createRoleResponse
|
// @Success 201 {object} createRoleResponse
|
||||||
// @Failure 400 {object} errorInvalidRequestBody
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 401 {object} createRoleErrorInvalidRoleName
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} createRoleErrorRoleAlreadyExists
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
|
||||||
// @Router /api/acl/roles [post]
|
// @Router /api/acl/roles [post]
|
||||||
func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var req createRoleRequest
|
var req createRoleRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
|
|
||||||
Error: ErrorInvalidRequestBody,
|
|
||||||
Details: "Request body is not valid JSON",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
roleID, err := h.a.CreateRole(req.Name)
|
roleID, err := h.a.CreateRole(req.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to create role", "error", err.Error())
|
slog.Error("Failed to create role", "error", err.Error())
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
_ = 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:
|
case acl.ErrInvalidRoleName:
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-name", "Invalid role name", "Role name must be non-empty", r)
|
||||||
_ = json.NewEncoder(w).Encode(createRoleErrorInvalidRoleName{
|
case acl.ErrRoleAlreadyExists:
|
||||||
Error: ErrorFailedToCreateRole,
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/role-already-exists", "Role already exists", "Role '"+req.Name+"' already exists", r)
|
||||||
Details: "Role name must be non-empty string",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to create role with name '" + req.Name + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
_ = json.NewEncoder(w).Encode(createRoleResponse{
|
_ = json.NewEncoder(w).Encode(createRoleResponse{
|
||||||
ID: roleID,
|
ID: roleID,
|
||||||
@@ -170,83 +215,51 @@ func (h *aclAdminHandler) createRole(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Update role
|
// @Summary Update role
|
||||||
// @Tags roles
|
// @Tags acl/roles
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param roleId path int true "Role ID" example(1)
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
// @Param request body updateRoleRequest true "Role"
|
// @Param request body updateRoleRequest true "Role"
|
||||||
// @Success 200 {object} updateRoleResponse
|
// @Success 200 {object} updateRoleResponse
|
||||||
// @Failure 400 {object} errorInvalidRequestBody
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 400 {object} updateRoleErrorInvalidRoleID
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 400 {object} updateRoleErrorInvalidRoleName
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} updateRoleErrorRoleNotFound
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} updateRoleErrorRoleNameAlreadyExists
|
|
||||||
// @Failure 500 {object} errorInternalServerError
|
|
||||||
// @Router /api/acl/roles/{roleId} [patch]
|
// @Router /api/acl/roles/{roleId} [patch]
|
||||||
func (h *aclAdminHandler) updateRole(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) updateRole(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
var req updateRoleRequest
|
var req updateRoleRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInvalidRequestBody{
|
|
||||||
Error: ErrorInvalidRequestBody,
|
|
||||||
Details: "Request body is not valid JSON",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
roleIDStr := chi.URLParam(r, "roleId")
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
roleID, err := strconv.Atoi(roleIDStr)
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
if err != nil || roleID < 0 {
|
if err != nil || roleID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateRoleErrorInvalidRoleID{
|
|
||||||
Error: ErrorInvalidRoleID,
|
|
||||||
Details: "Role ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = h.a.UpdateRole(uint(roleID), req.Name)
|
err = h.a.UpdateRole(uint(roleID), req.Name)
|
||||||
// TODO: make error handling more specific in acl service
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to update role", "error", err.Error())
|
slog.Error("Failed to update role", "error", err.Error())
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrInvalidRoleName:
|
case acl.ErrInvalidRoleName:
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-name", "Invalid role name", "Role name must be non-empty", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateRoleErrorInvalidRoleName{
|
|
||||||
Error: ErrorFailedToUpdateRole,
|
|
||||||
Details: "Invalid role name",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrRoleNotFound:
|
case acl.ErrRoleNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNotFound{
|
|
||||||
Error: ErrorFailedToUpdateRole,
|
|
||||||
Details: "No role with ID " + roleIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrSameRoleName:
|
case acl.ErrSameRoleName:
|
||||||
w.WriteHeader(http.StatusConflict)
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/role-name-already-exists", "Role name already exists", "Role '"+req.Name+"' already exists", r)
|
||||||
_ = json.NewEncoder(w).Encode(updateRoleErrorRoleNameAlreadyExists{
|
|
||||||
Error: ErrorFailedToUpdateRole,
|
|
||||||
Details: "Role with name '" + req.Name + "' already exists",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to update role with name '" + req.Name + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
_ = json.NewEncoder(w).Encode(updateRoleResponse{
|
_ = json.NewEncoder(w).Encode(updateRoleResponse{
|
||||||
ID: uint(roleID),
|
ID: uint(roleID),
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
@@ -254,61 +267,125 @@ func (h *aclAdminHandler) updateRole(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// @Summary Delete role
|
// @Summary Delete role
|
||||||
// @Tags roles
|
// @Tags acl/roles
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param roleId path int true "Role ID" example(1)
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
// @Success 200
|
// @Success 204
|
||||||
// @Failure 400 {object} deleteRoleErrorInvalidRoleID
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
// @Failure 404 {object} deleteRoleErrorRoleNotFound
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
// @Failure 409 {object} deleteRoleErrorRoleInUse
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
// @Failure 500 {object} errorInternalServerError
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
// @Router /api/acl/roles/{roleId} [delete]
|
// @Router /api/acl/roles/{roleId} [delete]
|
||||||
func (h *aclAdminHandler) deleteRole(w http.ResponseWriter, r *http.Request) {
|
func (h *aclAdminHandler) deleteRole(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
roleIDStr := chi.URLParam(r, "roleId")
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
roleID, err := strconv.Atoi(roleIDStr)
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
if err != nil || roleID < 0 {
|
if err != nil || roleID < 0 {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteRoleErrorInvalidRoleID{
|
|
||||||
Error: ErrorInvalidRoleID,
|
|
||||||
Details: "Role ID must be positive integer",
|
|
||||||
})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = h.a.DeleteRole(uint(roleID))
|
err = h.a.DeleteRole(uint(roleID))
|
||||||
// TODO: make error handling more specific in acl service
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to delete role", "error", err.Error())
|
slog.Error("Failed to delete role", "error", err.Error())
|
||||||
switch err {
|
switch err {
|
||||||
case acl.ErrNotInitialized:
|
case acl.ErrNotInitialized:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: ErrorACLServiceNotInitialized,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrRoleNotFound:
|
case acl.ErrRoleNotFound:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteRoleErrorRoleNotFound{
|
|
||||||
Error: ErrorFailedToDeleteRole,
|
|
||||||
Details: "No role with ID " + roleIDStr,
|
|
||||||
})
|
|
||||||
return
|
|
||||||
case acl.ErrRoleInUse:
|
case acl.ErrRoleInUse:
|
||||||
w.WriteHeader(http.StatusConflict)
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/role-in-use", "Role in use", "Role "+roleIDStr+" is assigned to at least one user and cannot be deleted", r)
|
||||||
_ = json.NewEncoder(w).Encode(deleteRoleErrorRoleInUse{
|
|
||||||
Error: ErrorFailedToDeleteRole,
|
|
||||||
Details: "Role with ID " + roleIDStr + " is assigned to users and cannot be deleted",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
_ = json.NewEncoder(w).Encode(errorInternalServerError{
|
|
||||||
Error: ErrorInternalServerError,
|
|
||||||
Details: "Failed to delete role with ID '" + roleIDStr + "'",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Assign resource to role
|
||||||
|
// @Tags acl/roles
|
||||||
|
// @Produce json
|
||||||
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
|
// @Param request body assignResourceToRoleRequest true "Resource"
|
||||||
|
// @Success 201
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/roles/{roleId}/resources [post]
|
||||||
|
func (h *aclAdminHandler) assignResourceToRole(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
|
if err != nil || roleID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req assignResourceToRoleRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-request-body", "Invalid request body", "Invalid JSON body", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.a.AssignResourceToRole(uint(roleID), req.ResourceID); err != nil {
|
||||||
|
slog.Error("Failed to assign resource to role", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
|
case acl.ErrResourceNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+strconv.Itoa(int(req.ResourceID)), r)
|
||||||
|
case acl.ErrResourceAlreadyAssigned:
|
||||||
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/resource-already-assigned", "Resource already assigned", "Resource with ID "+strconv.Itoa(int(req.ResourceID))+" is already assigned to role with ID "+roleIDStr, r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Remove resource from role
|
||||||
|
// @Tags acl/roles
|
||||||
|
// @Produce json
|
||||||
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
|
// @Param resId path int true "Resource ID" example(1)
|
||||||
|
// @Success 204
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/roles/{roleId}/resources/{resId} [delete]
|
||||||
|
func (h *aclAdminHandler) removeResourceFromRole(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
|
if err != nil || roleID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resourceIDStr := chi.URLParam(r, "resId")
|
||||||
|
resourceID, err := strconv.Atoi(resourceIDStr)
|
||||||
|
if err != nil || resourceID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-resource-id", "Invalid resource ID", "Resource ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.a.RemoveResourceFromRole(uint(roleID), uint(resourceID)); err != nil {
|
||||||
|
slog.Error("Failed to remove resource from role", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-not-found", "Role not found", "No role with ID "+roleIDStr, r)
|
||||||
|
case acl.ErrResourceNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/resource-not-found", "Resource not found", "No resource with ID "+strconv.Itoa(int(resourceID)), r)
|
||||||
|
case acl.ErrRoleResourceNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/role-resource-not-found", "Role resource not found", "No role-resource pair with role ID "+roleIDStr+" and resource ID "+strconv.Itoa(int(resourceID)), r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ type getRolesResponse []struct {
|
|||||||
Name string `json:"name" example:"admin"`
|
Name string `json:"name" example:"admin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ getRolesResponse
|
||||||
|
|
||||||
/*******************************************************************/
|
/*******************************************************************/
|
||||||
// used in getRole()
|
// used in getRole()
|
||||||
type getRoleResponse struct {
|
type getRoleResponse struct {
|
||||||
@@ -14,15 +16,22 @@ type getRoleResponse struct {
|
|||||||
Name string `json:"name" example:"admin"`
|
Name string `json:"name" example:"admin"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type getRoleErrorInvalidRoleID struct {
|
/*******************************************************************/
|
||||||
Error string `json:"error" example:"INVALID_ROLE_ID"`
|
// used in getRoleUsers()
|
||||||
Details string `json:"details" example:"Role ID must be positive integer"`
|
type getRoleUser struct {
|
||||||
|
ID uint `json:"id" example:"1"`
|
||||||
|
Name string `json:"username" example:"admin"`
|
||||||
|
Email string `json:"email" example:"admin@triggerssmith.com"`
|
||||||
}
|
}
|
||||||
|
type getRoleUsersResponse []getRoleUser
|
||||||
|
|
||||||
type getRoleErrorRoleNotFound struct {
|
/*******************************************************************/
|
||||||
Error string `json:"error" example:"ROLE_NOT_FOUND"`
|
// used in getRoleResources()
|
||||||
Details string `json:"details" example:"No role with ID 123"`
|
type getRoleResource struct {
|
||||||
|
ID uint `json:"id" example:"1"`
|
||||||
|
Name string `json:"name" example:"*"`
|
||||||
}
|
}
|
||||||
|
type getRoleResourcesResponse []getRoleResource
|
||||||
|
|
||||||
/*******************************************************************/
|
/*******************************************************************/
|
||||||
// used in createRole()
|
// used in createRole()
|
||||||
@@ -35,16 +44,6 @@ type createRoleResponse struct {
|
|||||||
Name string `json:"name" example:"admin"`
|
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()
|
// used in updateRole()
|
||||||
type updateRoleRequest struct {
|
type updateRoleRequest struct {
|
||||||
@@ -56,39 +55,8 @@ type updateRoleResponse struct {
|
|||||||
Name string `json:"name" example:"admin"`
|
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()
|
// used in assignResourceToRole()
|
||||||
type deleteRoleErrorRoleNotFound struct {
|
type assignResourceToRoleRequest struct {
|
||||||
Error string `json:"error" example:"ROLE_NOT_FOUND"`
|
ResourceID uint `json:"resourceId" example:"1"`
|
||||||
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"`
|
|
||||||
}
|
}
|
||||||
|
|||||||
137
api/acl_admin/users.go
Normal file
137
api/acl_admin/users.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package api_acladmin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary Get user roles by user ID
|
||||||
|
// @Tags acl/users
|
||||||
|
// @Produce json
|
||||||
|
// @Param userId path int true "User ID" example(1)
|
||||||
|
// @Success 200 {object} getUserRolesResponse
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/users/{userId}/roles [get]
|
||||||
|
func (h *aclAdminHandler) getUserRoles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
userIDStr := chi.URLParam(r, "userId")
|
||||||
|
userID, err := strconv.Atoi(userIDStr)
|
||||||
|
if err != nil {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
roles, err := h.a.GetUserRoles(uint(userID))
|
||||||
|
if err != nil {
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrUserNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
|
||||||
|
default:
|
||||||
|
slog.Error("unexpected server error", "error", err.Error())
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp := make(getUserRolesResponse, 0, len(roles))
|
||||||
|
for _, role := range roles {
|
||||||
|
resp = append(resp, getUserRole{ID: role.ID, Name: role.Name})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Assign role to user
|
||||||
|
// @Tags acl/users
|
||||||
|
// @Produce json
|
||||||
|
// @Param userId path int true "User ID" example(1)
|
||||||
|
// @Param body body assignRoleToUserRequest true "Role ID"
|
||||||
|
// @Success 201
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 409 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/users/{userId}/roles [post]
|
||||||
|
func (h *aclAdminHandler) assignRoleToUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
userIDStr := chi.URLParam(r, "userId")
|
||||||
|
userID, err := strconv.Atoi(userIDStr)
|
||||||
|
if err != nil || userID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var req assignRoleToUserRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-request-body", "Invalid request body", "Invalid JSON body", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.a.AssignRoleToUser(req.RoleID, uint(userID)); err != nil {
|
||||||
|
slog.Error("Failed to assign role to user", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrUserNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
|
||||||
|
case acl.ErrRoleAlreadyAssigned:
|
||||||
|
server.WriteProblem(w, http.StatusConflict, "/errors/acl/role-already-assigned", "Role already assigned", "Role with ID "+strconv.Itoa(int(req.RoleID))+" is already assigned to user "+strconv.Itoa(userID), r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Remove role from user
|
||||||
|
// @Tags acl/users
|
||||||
|
// @Produce json
|
||||||
|
// @Param userId path int true "User ID" example(1)
|
||||||
|
// @Param roleId path int true "Role ID" example(1)
|
||||||
|
// @Success 204
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/acl/users/{userId}/roles/{roleId} [delete]
|
||||||
|
func (h *aclAdminHandler) removeRoleFromUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
userIDStr := chi.URLParam(r, "userId")
|
||||||
|
userID, err := strconv.Atoi(userIDStr)
|
||||||
|
if err != nil || userID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-user-id", "Invalid user ID", "User ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
roleIDStr := chi.URLParam(r, "roleId")
|
||||||
|
roleID, err := strconv.Atoi(roleIDStr)
|
||||||
|
if err != nil || roleID < 0 {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/acl/invalid-role-id", "Invalid role ID", "Role ID must be positive integer", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = h.a.RemoveRoleFromUser(uint(roleID), uint(userID))
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to remove role from user", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case acl.ErrNotInitialized:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "ACL service is not initialized", r)
|
||||||
|
case acl.ErrUserNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/user-not-found", "User not found", "User not found", r)
|
||||||
|
case acl.ErrRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/no-role-found", "No role found", "No role found for user "+strconv.Itoa(userID), r)
|
||||||
|
case acl.ErrUserRoleNotFound:
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/acl/user-role-not-found", "User role not found", "User "+strconv.Itoa(userID)+" does not have role "+strconv.Itoa(roleID), r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
16
api/acl_admin/users_models.go
Normal file
16
api/acl_admin/users_models.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package api_acladmin
|
||||||
|
|
||||||
|
/*******************************************************************/
|
||||||
|
// used in getUserRoles()
|
||||||
|
type getUserRole struct {
|
||||||
|
ID uint `json:"id" example:"1"`
|
||||||
|
Name string `json:"name" example:"*"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type getUserRolesResponse []getUserRole
|
||||||
|
|
||||||
|
/*******************************************************************/
|
||||||
|
// used in assignRoleToUser()
|
||||||
|
type assignRoleToUserRequest struct {
|
||||||
|
RoleID uint `json:"roleId" example:"1"`
|
||||||
|
}
|
||||||
7
api/auth/errors.go
Normal file
7
api/auth/errors.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
const (
|
||||||
|
ErrorInvalidCredentials = "INVALID_CREDENTIALS"
|
||||||
|
ErrorInvalidToken = "INVALID_TOKEN"
|
||||||
|
ErrorExpiredToken = "EXPIRED_TOKEN"
|
||||||
|
)
|
||||||
35
api/auth/get_user_data.go
Normal file
35
api/auth/get_user_data.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetUserDataResponse struct {
|
||||||
|
UserID uint `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *authHandler) handleGetUserData(w http.ResponseWriter, r *http.Request) {
|
||||||
|
by := r.URL.Query().Get("by")
|
||||||
|
value := r.URL.Query().Get("value")
|
||||||
|
if value == "" {
|
||||||
|
value = r.URL.Query().Get(by)
|
||||||
|
}
|
||||||
|
user, err := h.a.Get(by, value)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to get user", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
err = json.NewEncoder(w).Encode(meResponse{
|
||||||
|
UserID: user.ID,
|
||||||
|
Username: user.Username,
|
||||||
|
Email: user.Email,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,23 +3,19 @@
|
|||||||
package api_auth
|
package api_auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/config"
|
"git.oblat.lv/alex/triggerssmith/internal/config"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/server"
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setRefreshCookie(w http.ResponseWriter, token string, ttl time.Duration, secure bool) {
|
func setRefreshCookie(w http.ResponseWriter, token string, ttl time.Duration, secure bool) {
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "refresh_token",
|
Name: "refresh_token",
|
||||||
Value: token,
|
Value: token,
|
||||||
Path: "/api/auth/refresh",
|
Path: "/api/auth/",
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
SameSite: http.SameSiteLaxMode,
|
SameSite: http.SameSiteLaxMode,
|
||||||
MaxAge: int(ttl.Seconds()),
|
MaxAge: int(ttl.Seconds()),
|
||||||
@@ -57,164 +53,3 @@ func MustRoute(config *config.Config, authService *auth.Service) func(chi.Router
|
|||||||
r.Post("/revoke", h.handleRevoke) // not implemented
|
r.Post("/revoke", h.handleRevoke) // not implemented
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type registerRequest struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type registerResponse struct {
|
|
||||||
UserID uint `json:"id"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req registerRequest
|
|
||||||
err := json.NewDecoder(r.Body).Decode(&req)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid request payload", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := h.a.Register(req.Username, req.Email, req.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Registration failed", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
err = json.NewEncoder(w).Encode(registerResponse{
|
|
||||||
UserID: user.ID,
|
|
||||||
Username: user.Username,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginRequest struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginResponse struct {
|
|
||||||
Token string `json:"accessToken"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req loginRequest
|
|
||||||
err := json.NewDecoder(r.Body).Decode(&req)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Invalid request payload", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
tokens, err := h.a.Login(req.Username, req.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Authentication failed", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setRefreshCookie(w, tokens.Refresh, h.cfg.Auth.RefreshTokenTTL, false)
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
err = json.NewEncoder(w).Encode(loginResponse{Token: tokens.Access})
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
||||||
claims, err := h.a.AuthenticateRequest(r)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
rjti := claims.(jwt.MapClaims)["rjti"].(string)
|
|
||||||
err = h.a.Logout(rjti)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to logout, taking cookie anyways", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: "refresh_token",
|
|
||||||
Value: "",
|
|
||||||
MaxAge: -1,
|
|
||||||
Path: "/api/users/refresh",
|
|
||||||
HttpOnly: true,
|
|
||||||
SameSite: http.SameSiteLaxMode,
|
|
||||||
})
|
|
||||||
if err == nil {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type meResponse struct {
|
|
||||||
UserID uint `json:"id"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
Email string `json:"email"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleMe(w http.ResponseWriter, r *http.Request) {
|
|
||||||
refresh_token_cookie, err := r.Cookie("refresh_token")
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
userID, err := h.a.ValidateRefreshToken(refresh_token_cookie.Value)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
user, err := h.a.Get("id", fmt.Sprint(userID))
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to get user", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
err = json.NewEncoder(w).Encode(meResponse{
|
|
||||||
UserID: user.ID,
|
|
||||||
Username: user.Username,
|
|
||||||
Email: user.Email,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetUserDataResponse meResponse
|
|
||||||
|
|
||||||
func (h *authHandler) handleGetUserData(w http.ResponseWriter, r *http.Request) {
|
|
||||||
by := r.URL.Query().Get("by")
|
|
||||||
value := r.URL.Query().Get("value")
|
|
||||||
if value == "" {
|
|
||||||
value = r.URL.Query().Get(by)
|
|
||||||
}
|
|
||||||
user, err := h.a.Get(by, value)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to get user", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
err = json.NewEncoder(w).Encode(meResponse{
|
|
||||||
UserID: user.ID,
|
|
||||||
Username: user.Username,
|
|
||||||
Email: user.Email,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleRevoke(w http.ResponseWriter, r *http.Request) {
|
|
||||||
server.NotImplemented(w)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *authHandler) handleRefresh(w http.ResponseWriter, r *http.Request) {
|
|
||||||
server.NotImplemented(w)
|
|
||||||
}
|
|
||||||
|
|||||||
55
api/auth/login.go
Normal file
55
api/auth/login.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
type loginRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type loginResponse struct {
|
||||||
|
Token string `json:"accessToken"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Login
|
||||||
|
// @Tags auth
|
||||||
|
// @Produce json
|
||||||
|
// @Param request body loginRequest true "Login request"
|
||||||
|
// @Success 200 {object} loginResponse
|
||||||
|
// @Failure 400 {object} server.ProblemDetails
|
||||||
|
// @Failure 401 {object} server.ProblemDetails
|
||||||
|
// @Router /api/auth/login [post]
|
||||||
|
func (h *authHandler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
var req loginRequest
|
||||||
|
err := json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
if err != nil {
|
||||||
|
server.WriteProblem(w, http.StatusBadRequest, "/errors/invalid-request-body", "Invalid request body", "Body is not valid JSON", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, err := h.a.Login(req.Username, req.Password)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Login failed", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case auth.ErrInvalidUsername:
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-credentials", "Invalid credentials", fmt.Sprintf("User with username %s not found", req.Username), r)
|
||||||
|
case auth.ErrInvalidPassword:
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-credentials", "Invalid credentials", fmt.Sprintf("Invalid password for user %s", req.Username), r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setRefreshCookie(w, tokens.Refresh, h.cfg.Auth.RefreshTokenTTL, false)
|
||||||
|
_ = json.NewEncoder(w).Encode(loginResponse{Token: tokens.Access})
|
||||||
|
}
|
||||||
82
api/auth/logout.go
Normal file
82
api/auth/logout.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary Logout
|
||||||
|
// @Description Requires valid refresh token
|
||||||
|
// @Tags auth
|
||||||
|
// @Success 204
|
||||||
|
// @Failure 401 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/auth/logout [post]
|
||||||
|
func (h *authHandler) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// claims, err := h.a.AuthenticateRequest(r)
|
||||||
|
// if err != nil {
|
||||||
|
// slog.Error("failed to AuthenticateRequest", "error", err.Error())
|
||||||
|
// switch err {
|
||||||
|
// case auth.ErrInvalidToken:
|
||||||
|
// server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-token", "Invalid token", "Invalid token: taking cookies anyways", r)
|
||||||
|
// case auth.ErrTokenIsMissing:
|
||||||
|
// server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/invalid-token", "Invalid token", "Token is missing: taking cookies anyway", r)
|
||||||
|
// default:
|
||||||
|
// server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error: taking cookies anyway", r)
|
||||||
|
// }
|
||||||
|
// http.SetCookie(w, &http.Cookie{
|
||||||
|
// Name: "refresh_token",
|
||||||
|
// Value: "",
|
||||||
|
// MaxAge: -1,
|
||||||
|
// Path: "/api/auth/",
|
||||||
|
// HttpOnly: true,
|
||||||
|
// SameSite: http.SameSiteLaxMode,
|
||||||
|
// })
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// rjti := claims.(jwt.MapClaims)["rjti"].(string)
|
||||||
|
refreshCookie, err := r.Cookie("refresh_token")
|
||||||
|
if err != nil && errors.Is(err, http.ErrNoCookie) {
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/refresh-token-not-found", "Refresh token is missing", "Refresh token is missing", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
refreshStr := refreshCookie.Value
|
||||||
|
if refreshStr == "" {
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/refresh-token-not-found", "Refresh token is missing", "Refresh token is missing", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
claims, err := h.a.ValidateRefreshToken(refreshStr)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("failed to ValidateRefreshToken", "error", err.Error())
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error while validating refresh token: maybe invalid", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rjti := claims.(jwt.MapClaims)["jti"].(string)
|
||||||
|
err = h.a.Logout(rjti)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("failed to Logout", "error", err.Error())
|
||||||
|
switch err {
|
||||||
|
case auth.ErrInvalidToken:
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/already-revoked", "Token already revoked", fmt.Sprintf("Token with rjti '%s' is already revoked", rjti), r)
|
||||||
|
default:
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error: taking cookies anyway", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: "refresh_token",
|
||||||
|
Value: "",
|
||||||
|
MaxAge: -1,
|
||||||
|
Path: "/api/auth/",
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
}
|
||||||
42
api/auth/me.go
Normal file
42
api/auth/me.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
type meResponse struct {
|
||||||
|
UserID uint `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *authHandler) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||||
|
server.NotImplemented(w)
|
||||||
|
// refresh_token_cookie, err := r.Cookie("refresh_token")
|
||||||
|
// if err != nil {
|
||||||
|
// w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// userID, err := h.a.ValidateRefreshToken(refresh_token_cookie.Value)
|
||||||
|
// if err != nil {
|
||||||
|
// w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// user, err := h.a.Get("id", fmt.Sprint(userID))
|
||||||
|
// if err != nil {
|
||||||
|
// http.Error(w, "Failed to get user", http.StatusInternalServerError)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// w.Header().Set("Content-Type", "application/json")
|
||||||
|
// err = json.NewEncoder(w).Encode(meResponse{
|
||||||
|
// UserID: user.ID,
|
||||||
|
// Username: user.Username,
|
||||||
|
// Email: user.Email,
|
||||||
|
// })
|
||||||
|
// if err != nil {
|
||||||
|
// http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
}
|
||||||
56
api/auth/refresh.go
Normal file
56
api/auth/refresh.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
type refreshResponse struct {
|
||||||
|
Access string `json:"accessToken"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Summary Refresh tokens
|
||||||
|
// @Description Requires valid HttpOnly refresh_token cookie
|
||||||
|
// @Tags auth
|
||||||
|
// @Produce json
|
||||||
|
// @Security RefreshCookieAuth
|
||||||
|
// @Success 200 {object} refreshResponse
|
||||||
|
// @Failure 401 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/auth/refresh [post]
|
||||||
|
func (h *authHandler) handleRefresh(w http.ResponseWriter, r *http.Request) {
|
||||||
|
refreshCookie, err := r.Cookie("refresh_token")
|
||||||
|
if err != nil && errors.Is(err, http.ErrNoCookie) {
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/refresh-token-not-found", "Refresh token is missing", "Refresh token is missing", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
refreshStr := refreshCookie.Value
|
||||||
|
if refreshStr == "" {
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/refresh-token-not-found", "Refresh token is missing", "Refresh token is missing", r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tokens, err := h.a.RefreshTokens(refreshStr)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, auth.ErrInvalidToken) {
|
||||||
|
server.WriteProblem(w, http.StatusUnauthorized, "/errors/auth/refresh-token-invalid", "Refresh token is invalid", "Refresh token is invalid", r)
|
||||||
|
} else {
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "unexpected error: taking cookies anyway", r)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: "refresh_token",
|
||||||
|
Value: tokens.Refresh,
|
||||||
|
MaxAge: 3600,
|
||||||
|
Path: "/api/auth/refresh",
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
})
|
||||||
|
var resp refreshResponse
|
||||||
|
resp.Access = tokens.Access
|
||||||
|
_ = json.NewEncoder(w).Encode(resp)
|
||||||
|
}
|
||||||
45
api/auth/register.go
Normal file
45
api/auth/register.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type registerRequest struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type registerResponse struct {
|
||||||
|
UserID uint `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *authHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req registerRequest
|
||||||
|
err := json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid request payload", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := h.a.Register(req.Username, req.Email, req.Password)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to register user", "error", err)
|
||||||
|
http.Error(w, "Registration failed", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
err = json.NewEncoder(w).Encode(registerResponse{
|
||||||
|
UserID: user.ID,
|
||||||
|
Username: user.Username,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
11
api/auth/revoke.go
Normal file
11
api/auth/revoke.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package api_auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *authHandler) handleRevoke(w http.ResponseWriter, r *http.Request) {
|
||||||
|
server.NotImplemented(w)
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/config"
|
"git.oblat.lv/alex/triggerssmith/internal/config"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -41,16 +42,26 @@ func MustRoute(config *config.Config) func(chi.Router) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @Summary Get block
|
||||||
|
// @Tags block
|
||||||
|
// @Produce json
|
||||||
|
// @Param blockPath path string true "Block Path" example(menu)
|
||||||
|
// @Success 200 {object} Block
|
||||||
|
// @Failure 403 {object} server.ProblemDetails
|
||||||
|
// @Failure 404 {object} server.ProblemDetails
|
||||||
|
// @Failure 500 {object} server.ProblemDetails
|
||||||
|
// @Router /api/block/{blockPath} [get]
|
||||||
func (h *blockHandler) handleBlock(w http.ResponseWriter, r *http.Request) {
|
func (h *blockHandler) handleBlock(w http.ResponseWriter, r *http.Request) {
|
||||||
if !h.cfg.Server.BlockConfig.Enabled {
|
if !h.cfg.Server.BlockConfig.Enabled {
|
||||||
http.Error(w, "Block serving is disabled", http.StatusForbidden)
|
server.WriteProblem(w, http.StatusForbidden, "/errors/block/block-serving-disabled", "Block serving is disabled", "Block serving is disabled", r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
blockPath := r.URL.Path[len("/api/block/"):]
|
blockPath := r.URL.Path[len("/api/block/"):]
|
||||||
block, err := LoadBlock(blockPath, h.cfg)
|
block, err := LoadBlock(blockPath, h.cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
slog.Error("failed to load block", slog.String("path", blockPath), slog.String("err", err.Error()))
|
||||||
|
server.WriteProblem(w, http.StatusInternalServerError, "/errors/internal-server-error", "Internal Server Error", "failed to load block", r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
"git.oblat.lv/alex/triggerssmith/internal/auth"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/config"
|
"git.oblat.lv/alex/triggerssmith/internal/config"
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/server"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/vars"
|
"git.oblat.lv/alex/triggerssmith/internal/vars"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
@@ -59,6 +60,7 @@ func NewRouter(deps RouterDependencies) *Router {
|
|||||||
// RouteHandler sets up the routes and middleware for the router.
|
// RouteHandler sets up the routes and middleware for the router.
|
||||||
// TODO: implement hot reload for static files enabled/disabled
|
// TODO: implement hot reload for static files enabled/disabled
|
||||||
func (r *Router) MustRoute() chi.Router {
|
func (r *Router) MustRoute() chi.Router {
|
||||||
|
r.r.Use(middleware.RealIP)
|
||||||
r.r.Use(middleware.Logger)
|
r.r.Use(middleware.Logger)
|
||||||
r.r.Use(middleware.Recoverer)
|
r.r.Use(middleware.Recoverer)
|
||||||
r.r.Use(middleware.Timeout(r.cfg.Server.TimeoutSeconds))
|
r.r.Use(middleware.Timeout(r.cfg.Server.TimeoutSeconds))
|
||||||
@@ -90,7 +92,7 @@ func (r *Router) MustRoute() chi.Router {
|
|||||||
api.Route("/block", api_block.MustRoute(r.cfg))
|
api.Route("/block", api_block.MustRoute(r.cfg))
|
||||||
authRoute := api_auth.MustRoute(r.cfg, r.authService)
|
authRoute := api_auth.MustRoute(r.cfg, r.authService)
|
||||||
api.Route("/auth", authRoute)
|
api.Route("/auth", authRoute)
|
||||||
api.Route("/users", authRoute) // legacy support
|
//api.Route("/users", authRoute) // legacy support
|
||||||
aclAdminRoute := api_acladmin.MustRoute(r.cfg, r.aclService, r.authService)
|
aclAdminRoute := api_acladmin.MustRoute(r.cfg, r.aclService, r.authService)
|
||||||
api.Route("/acl", aclAdminRoute)
|
api.Route("/acl", aclAdminRoute)
|
||||||
api.Route("/acl-admin", aclAdminRoute) // legacy support
|
api.Route("/acl-admin", aclAdminRoute) // legacy support
|
||||||
@@ -106,6 +108,14 @@ func (r *Router) MustRoute() chi.Router {
|
|||||||
})
|
})
|
||||||
w.Write([]byte(b))
|
w.Write([]byte(b))
|
||||||
})
|
})
|
||||||
|
r.r.NotFound(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
server.WriteProblem(w, http.StatusNotFound, "/errors/not-found", "Not found", "Requested page not found", req)
|
||||||
|
})
|
||||||
|
r.r.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
server.WriteProblem(w, http.StatusMethodNotAllowed, "/errors/method-not-allowed", "Method not allowed", "Requested method not allowed", req)
|
||||||
|
})
|
||||||
//r.r.Handle("/invoke/function/{function_id}/{function_version}", invoke.InvokeHandler(r.cfg))
|
//r.r.Handle("/invoke/function/{function_id}/{function_version}", invoke.InvokeHandler(r.cfg))
|
||||||
return r.r
|
return r.r
|
||||||
}
|
}
|
||||||
|
|||||||
959
docs/docs.go
959
docs/docs.go
@@ -1,959 +0,0 @@
|
|||||||
// 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)
|
|
||||||
}
|
|
||||||
@@ -1,930 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,625 +0,0 @@
|
|||||||
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"
|
|
||||||
@@ -7,15 +7,21 @@ import "fmt"
|
|||||||
var (
|
var (
|
||||||
ErrNotInitialized = fmt.Errorf("acl service is not initialized")
|
ErrNotInitialized = fmt.Errorf("acl service is not initialized")
|
||||||
|
|
||||||
ErrRoleNotFound = fmt.Errorf("role not found")
|
ErrRoleNotFound = fmt.Errorf("role not found")
|
||||||
ErrRoleAlreadyExists = fmt.Errorf("role already exists")
|
ErrRoleAlreadyExists = fmt.Errorf("role already exists")
|
||||||
ErrInvalidRoleName = fmt.Errorf("role name is invalid")
|
ErrInvalidRoleName = fmt.Errorf("role name is invalid")
|
||||||
ErrSameRoleName = fmt.Errorf("role name is the same as another role")
|
ErrSameRoleName = fmt.Errorf("role name is the same as another role")
|
||||||
ErrRoleInUse = fmt.Errorf("role is in use")
|
ErrRoleInUse = fmt.Errorf("role is in use")
|
||||||
|
ErrRoleAlreadyAssigned = fmt.Errorf("role is already assigned to user")
|
||||||
|
|
||||||
ErrResourceNotFound = fmt.Errorf("resource not found")
|
ErrResourceNotFound = fmt.Errorf("resource not found")
|
||||||
ErrResourceAlreadyExists = fmt.Errorf("resource already exists")
|
ErrResourceAlreadyExists = fmt.Errorf("resource already exists")
|
||||||
ErrInvalidResourceKey = fmt.Errorf("invalid resource key")
|
ErrInvalidResourceKey = fmt.Errorf("invalid resource key")
|
||||||
ErrResourceInUse = fmt.Errorf("resource is in use")
|
ErrResourceInUse = fmt.Errorf("resource is in use")
|
||||||
ErrSameResourceKey = fmt.Errorf("resource key is the same as another resource")
|
ErrSameResourceKey = fmt.Errorf("resource key is the same as another resource")
|
||||||
|
ErrResourceAlreadyAssigned = fmt.Errorf("resource is already assigned to role")
|
||||||
|
ErrRoleResourceNotFound = fmt.Errorf("assigned resource to role is not found")
|
||||||
|
|
||||||
|
ErrUserNotFound = fmt.Errorf("user not found")
|
||||||
|
ErrUserRoleNotFound = fmt.Errorf("user role not found")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package acl
|
package acl
|
||||||
|
|
||||||
|
import "git.oblat.lv/alex/triggerssmith/internal/user"
|
||||||
|
|
||||||
type UserRole struct {
|
type UserRole struct {
|
||||||
UserID uint `gorm:"index;not null;uniqueIndex:ux_user_role"`
|
UserID uint `gorm:"index;not null;uniqueIndex:ux_user_role"`
|
||||||
RoleID 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"`
|
Role Role `gorm:"constraint:OnDelete:CASCADE;foreignKey:RoleID;references:ID" json:"role"`
|
||||||
//User user.User `gorm:"constraint:OnDelete:CASCADE;foreignKey:UserID;references:ID"`
|
User user.User `gorm:"constraint:OnDelete:CASCADE;foreignKey:UserID;references:ID"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Resource struct {
|
type Resource struct {
|
||||||
@@ -17,8 +19,8 @@ type Role struct {
|
|||||||
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
ID uint `gorm:"primaryKey;autoIncrement" json:"id"`
|
||||||
Name string `gorm:"unique;not null" json:"name"`
|
Name string `gorm:"unique;not null" json:"name"`
|
||||||
|
|
||||||
Resources []Resource `gorm:"many2many:role_resources" json:"resources"`
|
Resources []Resource `gorm:"many2many:role_resources" json:"resources"`
|
||||||
//Users []user.User `gorm:"many2many:user_roles"`
|
Users []user.User `gorm:"many2many:user_roles"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RoleResource struct {
|
type RoleResource struct {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetResources returns all resources.
|
// GetResources returns all resources.
|
||||||
@@ -138,3 +139,82 @@ func (s *Service) DeleteResource(resourceID uint) error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AssignResourceToRole assigns a resource to a role
|
||||||
|
// May return [ErrNotInitialized], [ErrRoleNotFound], [ErrResourceNotFound], [ErrAlreadyAssigned] or db error.
|
||||||
|
func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
|
||||||
|
if !s.isInitialized() {
|
||||||
|
return ErrNotInitialized
|
||||||
|
}
|
||||||
|
|
||||||
|
// check role exists
|
||||||
|
var r Role
|
||||||
|
if err := s.db.First(&r, roleID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrRoleNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch role: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// check resource exists
|
||||||
|
var res Resource
|
||||||
|
if err := s.db.First(&res, resourceID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrResourceNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch resource: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rr := RoleResource{
|
||||||
|
RoleID: roleID,
|
||||||
|
ResourceID: resourceID,
|
||||||
|
}
|
||||||
|
|
||||||
|
tx := s.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rr)
|
||||||
|
if tx.Error != nil {
|
||||||
|
return fmt.Errorf("failed to assign resource to role: %w", tx.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// if nothing inserted — already assigned
|
||||||
|
if tx.RowsAffected == 0 {
|
||||||
|
return ErrResourceAlreadyAssigned
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveResourceFromRole removes a resource from a role
|
||||||
|
// May return [ErrNotInitialized], [ErrRoleNotFound], [ErrResourceNotFound], [ErrRoleResourceNotFound] or db error.
|
||||||
|
func (s *Service) RemoveResourceFromRole(roleID, resourceID uint) error {
|
||||||
|
if !s.isInitialized() {
|
||||||
|
return ErrNotInitialized
|
||||||
|
}
|
||||||
|
// check role exists
|
||||||
|
var r Role
|
||||||
|
if err := s.db.First(&r, roleID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrRoleNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch role: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// check resource exists
|
||||||
|
var res Resource
|
||||||
|
if err := s.db.First(&res, resourceID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrResourceNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch resource: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tx := s.db.Where("role_id = ? AND resource_id = ?", roleID, resourceID).Delete(&RoleResource{})
|
||||||
|
if tx.Error != nil {
|
||||||
|
return fmt.Errorf("failed to remove resource from role: %w", tx.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tx.RowsAffected == 0 {
|
||||||
|
return ErrRoleResourceNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.oblat.lv/alex/triggerssmith/internal/user"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetRoles returns all roles.
|
// GetRoles returns all roles.
|
||||||
@@ -16,7 +18,7 @@ func (s *Service) GetRoles() ([]Role, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var roles []Role
|
var roles []Role
|
||||||
if err := s.db.Preload("Resources").Order("id").Find(&roles).Error; err != nil {
|
if err := s.db.Preload("Resources").Preload("Users").Order("id").Find(&roles).Error; err != nil {
|
||||||
return nil, fmt.Errorf("db error: %w", err)
|
return nil, fmt.Errorf("db error: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +62,7 @@ func (s *Service) GetRoleByID(roleID uint) (*Role, error) {
|
|||||||
return nil, ErrNotInitialized
|
return nil, ErrNotInitialized
|
||||||
}
|
}
|
||||||
var role Role
|
var role Role
|
||||||
err := s.db.Preload("Resources").First(&role, roleID).Error
|
err := s.db.Preload("Resources").Preload("Users").First(&role, roleID).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
return nil, ErrRoleNotFound
|
return nil, ErrRoleNotFound
|
||||||
@@ -134,3 +136,105 @@ func (s *Service) DeleteRole(roleID uint) error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUserRoles returns all roles for a given user.
|
||||||
|
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound] or db error.
|
||||||
|
func (s *Service) GetUserRoles(userID uint) ([]Role, error) {
|
||||||
|
if !s.isInitialized() {
|
||||||
|
return nil, ErrNotInitialized
|
||||||
|
}
|
||||||
|
var user user.User
|
||||||
|
if err := s.db.First(&user, userID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrUserNotFound
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to fetch user: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var roles []Role
|
||||||
|
err := s.db.
|
||||||
|
Joins("JOIN user_roles ur ON ur.role_id = roles.id").
|
||||||
|
Where("ur.user_id = ?", userID).
|
||||||
|
Find(&roles).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get user roles: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(roles) == 0 {
|
||||||
|
return nil, ErrRoleNotFound
|
||||||
|
}
|
||||||
|
return roles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AssignRoleToUser assigns a role to a user.
|
||||||
|
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound], [ErrRoleAlreadyAssigned] or db error.
|
||||||
|
func (s *Service) AssignRoleToUser(roleID, userID uint) error {
|
||||||
|
if !s.isInitialized() {
|
||||||
|
return ErrNotInitialized
|
||||||
|
}
|
||||||
|
var user user.User
|
||||||
|
if err := s.db.First(&user, userID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrUserNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch user: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var r Role
|
||||||
|
if err := s.db.First(&r, roleID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrRoleNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch role: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ur := UserRole{
|
||||||
|
UserID: userID,
|
||||||
|
RoleID: roleID,
|
||||||
|
}
|
||||||
|
|
||||||
|
tx := s.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&ur)
|
||||||
|
if tx.Error != nil {
|
||||||
|
return fmt.Errorf("failed to assign resource to role: %w", tx.Error)
|
||||||
|
}
|
||||||
|
if tx.RowsAffected == 0 {
|
||||||
|
return ErrRoleAlreadyAssigned
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveRoleFromUser removes a role from a user.
|
||||||
|
// May return [ErrNotInitialized], [ErrUserNotFound], [ErrRoleNotFound], [ErrUserRoleNotFound] or db error.
|
||||||
|
func (s *Service) RemoveRoleFromUser(roleID, userID uint) error {
|
||||||
|
if !s.isInitialized() {
|
||||||
|
return ErrNotInitialized
|
||||||
|
}
|
||||||
|
|
||||||
|
var user user.User
|
||||||
|
if err := s.db.First(&user, userID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrUserNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch user: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var r Role
|
||||||
|
if err := s.db.First(&r, roleID).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return ErrRoleNotFound
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to fetch role: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tx := s.db.Where("role_id = ? AND user_id = ?", roleID, userID).Delete(&UserRole{})
|
||||||
|
if tx.Error != nil {
|
||||||
|
return fmt.Errorf("failed to remove role from user: %w", tx.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tx.RowsAffected == 0 {
|
||||||
|
return ErrUserRoleNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package acl
|
package acl
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -40,75 +39,3 @@ func (s *Service) Init() error {
|
|||||||
s.initialized = true
|
s.initialized = true
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Admin crud functions //
|
|
||||||
|
|
||||||
// Resources
|
|
||||||
|
|
||||||
// AssignResourceToRole assigns a resource to a role
|
|
||||||
func (s *Service) AssignResourceToRole(roleID, resourceID uint) error {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return ErrNotInitialized
|
|
||||||
}
|
|
||||||
rr := RoleResource{
|
|
||||||
RoleID: roleID,
|
|
||||||
ResourceID: resourceID,
|
|
||||||
}
|
|
||||||
return s.db.FirstOrCreate(&rr, RoleResource{RoleID: roleID, ResourceID: resourceID}).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
// AssignRoleToUser assigns a role to a user
|
|
||||||
func (s *Service) AssignRoleToUser(roleID, userID uint) error {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return ErrNotInitialized
|
|
||||||
}
|
|
||||||
ur := UserRole{
|
|
||||||
UserID: userID,
|
|
||||||
RoleID: roleID,
|
|
||||||
}
|
|
||||||
if err := s.db.Create(&ur).Error; err != nil {
|
|
||||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
|
||||||
return fmt.Errorf("role already assigned to user")
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoveResourceFromRole removes a resource from a role
|
|
||||||
func (s *Service) RemoveResourceFromRole(roleID, resourceID uint) error {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return ErrNotInitialized
|
|
||||||
}
|
|
||||||
return s.db.Where("role_id = ? AND resource_id = ?", roleID, resourceID).Delete(&RoleResource{}).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoveRoleFromUser removes a role from a user
|
|
||||||
func (s *Service) RemoveRoleFromUser(roleID, userID uint) error {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return ErrNotInitialized
|
|
||||||
}
|
|
||||||
return s.db.Where("role_id = ? AND user_id = ?", roleID, userID).Delete(&UserRole{}).Error
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRoleResources returns all resources for a given role
|
|
||||||
func (s *Service) GetRoleResources(roleID uint) ([]Resource, error) {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return nil, ErrNotInitialized
|
|
||||||
}
|
|
||||||
var resources []Resource
|
|
||||||
err := s.db.Joins("JOIN role_resources rr ON rr.resource_id = resources.id").
|
|
||||||
Where("rr.role_id = ?", roleID).Find(&resources).Error
|
|
||||||
return resources, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserRoles returns all roles for a given user
|
|
||||||
func (s *Service) GetUserRoles(userID uint) ([]Role, error) {
|
|
||||||
if !s.isInitialized() {
|
|
||||||
return nil, ErrNotInitialized
|
|
||||||
}
|
|
||||||
var roles []Role
|
|
||||||
err := s.db.Joins("JOIN user_roles ur ON ur.role_id = roles.id").
|
|
||||||
Where("ur.user_id = ?", userID).Find(&roles).Error
|
|
||||||
return roles, err
|
|
||||||
}
|
|
||||||
|
|||||||
13
internal/auth/errors.go
Normal file
13
internal/auth/errors.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUserNotFound = fmt.Errorf("user not found")
|
||||||
|
ErrInvalidPassword = fmt.Errorf("invalid password")
|
||||||
|
ErrInvalidEmail = fmt.Errorf("invalid email")
|
||||||
|
ErrInvalidUsername = fmt.Errorf("invalid username")
|
||||||
|
|
||||||
|
ErrTokenIsMissing = fmt.Errorf("token is missing")
|
||||||
|
ErrInvalidToken = fmt.Errorf("invalid token")
|
||||||
|
)
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -8,7 +9,7 @@ import (
|
|||||||
"git.oblat.lv/alex/triggerssmith/internal/config"
|
"git.oblat.lv/alex/triggerssmith/internal/config"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/jwt"
|
"git.oblat.lv/alex/triggerssmith/internal/jwt"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/token"
|
"git.oblat.lv/alex/triggerssmith/internal/token"
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/user"
|
user_p "git.oblat.lv/alex/triggerssmith/internal/user"
|
||||||
ejwt "github.com/golang-jwt/jwt/v5"
|
ejwt "github.com/golang-jwt/jwt/v5"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
@@ -23,7 +24,7 @@ type Service struct {
|
|||||||
|
|
||||||
services struct {
|
services struct {
|
||||||
jwt *jwt.Service
|
jwt *jwt.Service
|
||||||
user *user.Service
|
user *user_p.Service
|
||||||
token *token.Service
|
token *token.Service
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,7 +33,7 @@ type AuthServiceDependencies struct {
|
|||||||
Configuration *config.Config
|
Configuration *config.Config
|
||||||
|
|
||||||
JWTService *jwt.Service
|
JWTService *jwt.Service
|
||||||
UserService *user.Service
|
UserService *user_p.Service
|
||||||
TokenService *token.Service
|
TokenService *token.Service
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +54,7 @@ func NewAuthService(deps AuthServiceDependencies) (*Service, error) {
|
|||||||
cfg: deps.Configuration,
|
cfg: deps.Configuration,
|
||||||
services: struct {
|
services: struct {
|
||||||
jwt *jwt.Service
|
jwt *jwt.Service
|
||||||
user *user.Service
|
user *user_p.Service
|
||||||
token *token.Service
|
token *token.Service
|
||||||
}{
|
}{
|
||||||
jwt: deps.JWTService,
|
jwt: deps.JWTService,
|
||||||
@@ -65,20 +66,20 @@ func NewAuthService(deps AuthServiceDependencies) (*Service, error) {
|
|||||||
|
|
||||||
// Users
|
// Users
|
||||||
|
|
||||||
func (s *Service) Get(by, value string) (*user.User, error) {
|
func (s *Service) Get(by, value string) (*user_p.User, error) {
|
||||||
return s.services.user.GetBy(by, value)
|
return s.services.user.GetBy(by, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Register creates a new user with the given username, email, and password.
|
// Register creates a new user with the given username, email, and password.
|
||||||
// Password is hashed before storing.
|
// Password is hashed before storing.
|
||||||
// Returns the created user or an error.
|
// Returns the created user or an error.
|
||||||
func (s *Service) Register(username, email, password string) (*user.User, error) {
|
func (s *Service) Register(username, email, password string) (*user_p.User, error) {
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to hash password: %w", err)
|
return nil, fmt.Errorf("failed to hash password: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
user := &user.User{
|
user := &user_p.User{
|
||||||
Username: username,
|
Username: username,
|
||||||
Email: email,
|
Email: email,
|
||||||
Password: string(hashedPassword),
|
Password: string(hashedPassword),
|
||||||
@@ -97,12 +98,15 @@ func (s *Service) Register(username, email, password string) (*user.User, error)
|
|||||||
func (s *Service) Login(username, password string) (*Tokens, error) {
|
func (s *Service) Login(username, password string) (*Tokens, error) {
|
||||||
user, err := s.services.user.GetBy("username", username)
|
user, err := s.services.user.GetBy("username", username)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if err == user_p.ErrUserNotFound {
|
||||||
|
return nil, ErrInvalidUsername
|
||||||
|
}
|
||||||
return nil, fmt.Errorf("failed to get user by username: %w", err)
|
return nil, fmt.Errorf("failed to get user by username: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid password: %w", err)
|
return nil, ErrInvalidPassword
|
||||||
}
|
}
|
||||||
refreshToken, rjti, err := s.services.jwt.Generate(s.cfg.Auth.RefreshTokenTTL, ejwt.MapClaims{
|
refreshToken, rjti, err := s.services.jwt.Generate(s.cfg.Auth.RefreshTokenTTL, ejwt.MapClaims{
|
||||||
"sub": user.ID,
|
"sub": user.ID,
|
||||||
@@ -122,39 +126,46 @@ func (s *Service) Login(username, password string) (*Tokens, error) {
|
|||||||
|
|
||||||
// Logout revokes the refresh token identified by the given rjti.
|
// Logout revokes the refresh token identified by the given rjti.
|
||||||
func (s *Service) Logout(rjti string) error {
|
func (s *Service) Logout(rjti string) error {
|
||||||
return s.services.token.RevokeByRefreshDefault(rjti)
|
err := s.services.token.RevokeByRefreshDefault(rjti)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, token.ErrTokenIsRevoked) {
|
||||||
|
return ErrInvalidToken
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to revoke token: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Access tokens
|
// Access tokens
|
||||||
|
|
||||||
// ValidateAccessToken validates the given access token string.
|
// ValidateAccessToken validates the given access token string.
|
||||||
// Returns the user ID (sub claim) if valid, or an error.
|
// Returns claims if valid, or an error.
|
||||||
func (s *Service) ValidateAccessToken(tokenStr string) (int64, error) {
|
func (s *Service) ValidateAccessToken(tokenStr string) (ejwt.Claims, error) {
|
||||||
claims, _, err := s.services.jwt.Validate(tokenStr)
|
claims, _, err := s.services.jwt.Validate(tokenStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("failed to validate access token: %w", err)
|
return nil, fmt.Errorf("failed to validate access token: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
isRevoked, err := s.services.token.IsRevoked(claims["rjti"].(string))
|
isRevoked, err := s.services.token.IsRevoked(claims["rjti"].(string))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("failed to check if token is revoked: %w", err)
|
return nil, fmt.Errorf("failed to check if token is revoked: %w", err)
|
||||||
}
|
}
|
||||||
if isRevoked {
|
if isRevoked {
|
||||||
return 0, fmt.Errorf("token is revoked")
|
return nil, fmt.Errorf("token is revoked")
|
||||||
}
|
}
|
||||||
|
|
||||||
sub := claims["sub"].(float64)
|
return claims, nil
|
||||||
return int64(sub), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh tokens
|
// Refresh tokens
|
||||||
|
|
||||||
// RefreshTokens validates the given refresh token and issues new access and refresh tokens.
|
// RefreshTokens validates the given refresh token and issues new access and refresh tokens.
|
||||||
// Returns the new access and refresh tokens or an error.
|
// Returns the new access and refresh tokens or an error.
|
||||||
|
// May return [ErrInvalidToken] if the refresh token is invalid or revoked.
|
||||||
func (s *Service) RefreshTokens(refreshTokenStr string) (*Tokens, error) {
|
func (s *Service) RefreshTokens(refreshTokenStr string) (*Tokens, error) {
|
||||||
claims, rjti, err := s.services.jwt.Validate(refreshTokenStr)
|
claims, rjti, err := s.services.jwt.Validate(refreshTokenStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to validate refresh token: %w", err)
|
return nil, errors.Join(ErrInvalidToken, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
isRevoked, err := s.services.token.IsRevoked(rjti)
|
isRevoked, err := s.services.token.IsRevoked(rjti)
|
||||||
@@ -162,7 +173,7 @@ func (s *Service) RefreshTokens(refreshTokenStr string) (*Tokens, error) {
|
|||||||
return nil, fmt.Errorf("failed to check if token is revoked: %w", err)
|
return nil, fmt.Errorf("failed to check if token is revoked: %w", err)
|
||||||
}
|
}
|
||||||
if isRevoked {
|
if isRevoked {
|
||||||
return nil, fmt.Errorf("refresh token is revoked")
|
return nil, ErrInvalidToken
|
||||||
}
|
}
|
||||||
|
|
||||||
sub := claims["sub"].(float64)
|
sub := claims["sub"].(float64)
|
||||||
@@ -190,23 +201,22 @@ func (s *Service) RefreshTokens(refreshTokenStr string) (*Tokens, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ValidateRefreshToken validates the given refresh token string.
|
// ValidateRefreshToken validates the given refresh token string.
|
||||||
// Returns user id and error.
|
// Returns claims and error.
|
||||||
func (s *Service) ValidateRefreshToken(tokenStr string) (int64, error) {
|
func (s *Service) ValidateRefreshToken(tokenStr string) (ejwt.Claims, error) {
|
||||||
claims, _, err := s.services.jwt.Validate(tokenStr)
|
claims, _, err := s.services.jwt.Validate(tokenStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("failed to validate refresh token: %w", err)
|
return nil, fmt.Errorf("failed to validate refresh token: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
isRevoked, err := s.services.token.IsRevoked(claims["jti"].(string))
|
isRevoked, err := s.services.token.IsRevoked(claims["jti"].(string))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("failed to check if token is revoked: %w", err)
|
return nil, fmt.Errorf("failed to check if token is revoked: %w", err)
|
||||||
}
|
}
|
||||||
if isRevoked {
|
if isRevoked {
|
||||||
return 0, fmt.Errorf("refresh token is revoked")
|
return nil, fmt.Errorf("refresh token is revoked")
|
||||||
}
|
}
|
||||||
|
|
||||||
sub := claims["sub"].(float64)
|
return claims, nil
|
||||||
return int64(sub), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RevokeRefresh revokes the refresh token identified by the given token string.
|
// RevokeRefresh revokes the refresh token identified by the given token string.
|
||||||
@@ -232,10 +242,10 @@ func (s *Service) IsRefreshRevoked(token string) (bool, error) {
|
|||||||
func (s *Service) AuthenticateRequest(r *http.Request) (ejwt.Claims, error) {
|
func (s *Service) AuthenticateRequest(r *http.Request) (ejwt.Claims, error) {
|
||||||
header := r.Header.Get("Authorization")
|
header := r.Header.Get("Authorization")
|
||||||
if header == "" {
|
if header == "" {
|
||||||
return nil, fmt.Errorf("token is missing")
|
return nil, ErrTokenIsMissing
|
||||||
}
|
}
|
||||||
if !strings.HasPrefix(header, "Bearer ") {
|
if !strings.HasPrefix(header, "Bearer ") {
|
||||||
return nil, fmt.Errorf("token is missing")
|
return nil, ErrTokenIsMissing
|
||||||
}
|
}
|
||||||
tokenString := strings.TrimPrefix(header, "Bearer ")
|
tokenString := strings.TrimPrefix(header, "Bearer ")
|
||||||
tokenClaims, _, err := s.services.jwt.Validate(tokenString)
|
tokenClaims, _, err := s.services.jwt.Validate(tokenString)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package server
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,3 +19,28 @@ func WriteError(w http.ResponseWriter, error, details string, statusCode int) {
|
|||||||
Details: details,
|
Details: details,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RFC-7807 (Problem Details)
|
||||||
|
type ProblemDetails struct {
|
||||||
|
Type string `json:"type" example:"https://api.triggerssmith.com/errors/role-not-found"`
|
||||||
|
Title string `json:"title" example:"Role not found"`
|
||||||
|
Status int `json:"status" example:"404"`
|
||||||
|
Detail string `json:"detail" example:"No role with ID 42"`
|
||||||
|
Instance string `json:"instance" example:"/api/acl/roles/42"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var typeDomain = "https://api.triggerssmith.com"
|
||||||
|
|
||||||
|
func WriteProblem(w http.ResponseWriter, status int, typ, title, detail string, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
prob := ProblemDetails{
|
||||||
|
Type: typeDomain + typ,
|
||||||
|
Title: title,
|
||||||
|
Status: status,
|
||||||
|
Detail: detail,
|
||||||
|
Instance: r.URL.Path,
|
||||||
|
}
|
||||||
|
slog.Warn("new problem", "type", typ, "title", title, "detail", detail, "instance", r.URL.Path, "status", status)
|
||||||
|
_ = json.NewEncoder(w).Encode(prob)
|
||||||
|
}
|
||||||
|
|||||||
7
internal/token/errors.go
Normal file
7
internal/token/errors.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package token
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrTokenIsRevoked = fmt.Errorf("token is revoked")
|
||||||
|
)
|
||||||
@@ -29,6 +29,13 @@ func NewSQLiteTokenStore(db *gorm.DB) (*SQLiteTokenStore, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *SQLiteTokenStore) revoke(tokenID string, expiresAt time.Time) error {
|
func (s *SQLiteTokenStore) revoke(tokenID string, expiresAt time.Time) error {
|
||||||
|
if revoked, err := s.isRevoked(tokenID); err == nil {
|
||||||
|
if revoked {
|
||||||
|
return ErrTokenIsRevoked
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return err
|
||||||
|
}
|
||||||
return s.db.Create(&Token{
|
return s.db.Create(&Token{
|
||||||
TokenID: tokenID,
|
TokenID: tokenID,
|
||||||
Expiration: expiresAt,
|
Expiration: expiresAt,
|
||||||
|
|||||||
7
internal/user/errors.go
Normal file
7
internal/user/errors.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package user
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUserNotFound = fmt.Errorf("user not found")
|
||||||
|
)
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package user
|
package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -24,6 +25,7 @@ func (s *GormUserStore) Create(user *User) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Search returns a user by username or id or email
|
// Search returns a user by username or id or email
|
||||||
|
// May return [ErrUserNotFound] if user not found
|
||||||
func (s *GormUserStore) GetBy(by, value string) (*User, error) {
|
func (s *GormUserStore) GetBy(by, value string) (*User, error) {
|
||||||
if by != "username" && by != "id" && by != "email" {
|
if by != "username" && by != "id" && by != "email" {
|
||||||
return nil, fmt.Errorf("unsuppored field %s", by)
|
return nil, fmt.Errorf("unsuppored field %s", by)
|
||||||
@@ -31,7 +33,10 @@ func (s *GormUserStore) GetBy(by, value string) (*User, error) {
|
|||||||
var user User
|
var user User
|
||||||
err := s.db.Where(fmt.Sprintf("%s = ?", by), value).First(&user).Error
|
err := s.db.Where(fmt.Sprintf("%s = ?", by), value).First(&user).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, ErrUserNotFound
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to get user: %w", err)
|
||||||
}
|
}
|
||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package user
|
package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"git.oblat.lv/alex/triggerssmith/internal/acl"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -10,6 +9,5 @@ type User struct {
|
|||||||
Username string `gorm:"uniqueIndex;not null"`
|
Username string `gorm:"uniqueIndex;not null"`
|
||||||
Email string `gorm:"uniqueIndex;not null"`
|
Email string `gorm:"uniqueIndex;not null"`
|
||||||
Password string `gorm:"not null"`
|
Password string `gorm:"not null"`
|
||||||
Roles []acl.Role `gorm:"many2many:user_roles"`
|
|
||||||
DeletedAt gorm.DeletedAt `gorm:"index"`
|
DeletedAt gorm.DeletedAt `gorm:"index"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,120 +1,33 @@
|
|||||||
body {
|
body {font-family: system-ui, sans-serif; margin: 0; display: flex; flex-direction: column; min-height: 100vh;}
|
||||||
font-family: system-ui, sans-serif;
|
header {display: flex; align-items: center; justify-content: space-between; background: #333; color: white; padding: 10px 15px; position: relative;}
|
||||||
margin: 0;
|
footer {background: #333; color: white; text-align: center; padding: 10px;}
|
||||||
display: flex;
|
main {flex: 1; padding: 20px; max-width: 1000px; margin: 0 auto;}
|
||||||
flex-direction: column;
|
button {cursor:pointer; border-radius: 8px; border: 1px solid #ccc; background:#e4e4e4; padding: 10px 12px; font-size: 16px;}
|
||||||
min-height: 100vh;
|
button:hover {background: #aa92f8;}
|
||||||
}
|
input {background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:200px;}
|
||||||
|
input:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;}
|
||||||
header {
|
select{background: #ffffff; padding: 10px 12px; font-size: 15px; border-radius: 8px; border: 1px solid #ccc; transition: border 0.2s, box-shadow 0.2s; width:225px;}
|
||||||
display: flex;
|
select:focus {border-color: #7f57ff; box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2); outline: none;}
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
background: #333;
|
|
||||||
color: white;
|
|
||||||
padding: 10px 15px;
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
footer {
|
|
||||||
background: #333;
|
|
||||||
color: white;
|
|
||||||
text-align: center;
|
|
||||||
padding: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
main {
|
|
||||||
flex: 1;
|
|
||||||
padding: 20px;
|
|
||||||
max-width: 1000px;
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* навигация */
|
/* навигация */
|
||||||
nav ul {
|
nav ul {list-style: none; display: flex; gap: 20px; margin: 0; padding: 0;}
|
||||||
list-style: none;
|
nav a {color: white; text-decoration: none; font-weight: 500;}
|
||||||
display: flex;
|
nav a:hover {text-decoration: underline;}
|
||||||
gap: 20px;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav a {
|
|
||||||
color: white;
|
|
||||||
text-decoration: none;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav a:hover {
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* бургер */
|
/* бургер */
|
||||||
.burger {
|
.burger {display: none; flex-direction: column; justify-content: center; gap: 5px; width: 30px; height: 25px; background: none; border: none; cursor: pointer;}
|
||||||
display: none;
|
.burger span {display: block; height: 3px; width: 100%; background: white; border-radius: 2px; transition: 0.3s;}
|
||||||
flex-direction: column;
|
.burger.active span:nth-child(1) {transform: translateY(8px) rotate(45deg);}
|
||||||
justify-content: center;
|
.burger.active span:nth-child(2) {opacity: 0;}
|
||||||
gap: 5px;
|
.burger.active span:nth-child(3) {transform: translateY(-8px) rotate(-45deg);}
|
||||||
width: 30px;
|
|
||||||
height: 25px;
|
|
||||||
background: none;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger span {
|
|
||||||
display: block;
|
|
||||||
height: 3px;
|
|
||||||
width: 100%;
|
|
||||||
background: white;
|
|
||||||
border-radius: 2px;
|
|
||||||
transition: 0.3s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(1) {
|
|
||||||
transform: translateY(8px) rotate(45deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(2) {
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.burger.active span:nth-child(3) {
|
|
||||||
transform: translateY(-8px) rotate(-45deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* сетка */
|
/* сетка */
|
||||||
.grid-3 {
|
.grid-3 {display: grid; grid-template-columns: 15% 70% 15%; gap: 20px; margin-top: 20px;}
|
||||||
display: grid;
|
.grid-block {background: #f5f5f5; padding: 15px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);}
|
||||||
grid-template-columns: 15% 70% 15%;
|
/* Полупрозрачный фон */
|
||||||
gap: 20px;
|
.overlay {position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 1000;}
|
||||||
margin-top: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.grid-block {
|
/* Окна */
|
||||||
background: #f5f5f5;
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 10px;
|
|
||||||
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
|
|
||||||
}
|
|
||||||
/* Полупрозрачный фон */
|
|
||||||
.overlay {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background: rgba(0,0,0,0.5);
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
z-index: 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Окна */
|
|
||||||
/* Message */
|
/* Message */
|
||||||
.window-popup { width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); }
|
.window-popup {width:400px; height:150px; background:#fff; border-radius:10px; display:flex; flex-direction:column; justify-content:center; align-items:center; padding:20px; box-shadow:0 0 10px rgba(0,0,0,0.3); }
|
||||||
.window-popup button { margin-top:20px; padding:5px 10px; cursor:pointer; }
|
|
||||||
|
|
||||||
/* Menu */
|
/* Menu */
|
||||||
.window-menu { position:absolute; background:#fff; border-radius:10px; border:1px solid rgba(0,0,0,0.12); box-shadow:0 6px 18px rgba(0,0,0,0.12); min-width:160px; z-index:9999; overflow:hidden; }
|
.window-menu { position:absolute; background:#fff; border-radius:10px; border:1px solid rgba(0,0,0,0.12); box-shadow:0 6px 18px rgba(0,0,0,0.12); min-width:160px; z-index:9999; overflow:hidden; }
|
||||||
@@ -135,39 +48,29 @@ nav a:hover {
|
|||||||
|
|
||||||
/* адаптив */
|
/* адаптив */
|
||||||
@media (max-width: 425px) {
|
@media (max-width: 425px) {
|
||||||
.grid-3 {
|
.grid-3 {grid-template-columns: 1fr;}
|
||||||
grid-template-columns: 1fr;
|
.burger {display: flex;}
|
||||||
}
|
nav {position: absolute; top: 100%; left: 0; width: 100%; background: #222; display: none; flex-direction: column; text-align: center; padding: 10px 0; z-index: 10;}
|
||||||
|
nav.open {display: flex; animation: slideDown 0.3s ease;}
|
||||||
.burger {
|
nav ul {flex-direction: column; gap: 10px;}
|
||||||
display: flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav {
|
|
||||||
position: absolute;
|
|
||||||
top: 100%;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
background: #222;
|
|
||||||
display: none;
|
|
||||||
flex-direction: column;
|
|
||||||
text-align: center;
|
|
||||||
padding: 10px 0;
|
|
||||||
z-index: 10;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav.open {
|
|
||||||
display: flex;
|
|
||||||
animation: slideDown 0.3s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
nav ul {
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@keyframes slideDown {
|
@keyframes slideDown {
|
||||||
from { opacity: 0; transform: translateY(-10px); }
|
from { opacity: 0; transform: translateY(-10px); }
|
||||||
to { opacity: 1; transform: translateY(0); }
|
to { opacity: 1; transform: translateY(0); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.ui-overlay {position: fixed; inset: 0; background: rgba(0,0,0,.4); display: flex; align-items: center; justify-content: center;}
|
||||||
|
.ui-alert {background: #fff; padding: 20px; border-radius: 16px; min-width: 300px; font-family: sans-serif; text-align: center;}
|
||||||
|
/* .ui-alert button {margin-top: 20px; border: 1px solid #ccc; padding: 8px 16px; cursor: pointer; border-radius: 8px;} */
|
||||||
|
.ui-popup-list {position: fixed; background: #fff; border: 1px solid #ccc; border-radius: 6px; box-shadow: 0 4px 10px rgba(0,0,0,.15); z-index: 1000;}
|
||||||
|
.ui-popup-list .icon {width: 16px; text-align: center;}
|
||||||
|
.ui-popup-list div {padding: 8px 12px; cursor: pointer; display: flex; align-items: center;}
|
||||||
|
.ui-popup-list div:hover {background: #eee;}
|
||||||
|
.ui-window {background: #fff; padding: 16px; border-radius: 8px; min-width: 300px; font-family: sans-serif; width: 360px;}
|
||||||
|
.ui-window .header {display: flex; justify-content: space-between; font-weight: bold; margin-bottom: 10px; cursor: move; user-select: none;}
|
||||||
|
.ui-window .row {display: flex; justify-content: space-between; padding: 4px 0;}
|
||||||
|
/* Tabs */
|
||||||
|
.tabs {display: flex; border-bottom: 1px solid #ccc; margin-bottom: 10px;}
|
||||||
|
.tab {padding: 6px 12px; cursor: pointer;}
|
||||||
|
.tab.active {border-bottom: 2px solid #0078d7; font-weight: bold;}
|
||||||
|
.tab-content {display: none;}
|
||||||
|
.tab-content.active {display: block;}
|
||||||
|
|||||||
@@ -1,117 +1,126 @@
|
|||||||
/***********************************************************************
|
/***********************************************************************
|
||||||
* ГЛОБАЛЬНОЕ СОСТОЯНИЕ
|
* access-token хранится только в памяти (без localStorage)
|
||||||
**********************************************************************/
|
**********************************************************************/
|
||||||
let accessToken = null; // access-token хранится только в памяти (без localStorage)
|
let accessToken = null;
|
||||||
|
|
||||||
/***********************************************************************
|
/***********************************************************************
|
||||||
* sendRequest УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ДЛЯ ОТПРАВКИ HTTP-ЗАПРОСОВ
|
* user объект в котором хранятся данные пользователя
|
||||||
*
|
|
||||||
* sendRequest(url, options)
|
|
||||||
* - автоматически добавляет Content-Type и credentials
|
|
||||||
* - автоматически превращает body в JSON
|
|
||||||
* - проверяет response.ok
|
|
||||||
* - пробрасывает текст ошибки
|
|
||||||
* - возвращает JSON-ответ
|
|
||||||
**********************************************************************/
|
**********************************************************************/
|
||||||
//let accessToken = ""; // access только в памяти
|
const user = {
|
||||||
|
id: 0,
|
||||||
async function apiProtected(path, options = {}) {
|
name: ""
|
||||||
const send = async () =>
|
|
||||||
fetch(path, {
|
|
||||||
...options,
|
|
||||||
headers: {
|
|
||||||
...(options.headers || {}),
|
|
||||||
Authorization: "Bearer " + accessToken,
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let r = await send();
|
|
||||||
|
|
||||||
if ((r.status === 401)) {
|
|
||||||
// обновляем access
|
|
||||||
const rr = await fetch("/api/users/refresh", {
|
|
||||||
method: "POST",
|
|
||||||
credentials: "include"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!rr.ok) throw "refresh failed";
|
|
||||||
|
|
||||||
const j = await rr.json();
|
|
||||||
accessToken = j.access_token;
|
|
||||||
|
|
||||||
r = await send();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!r.ok) throw await r.text();
|
|
||||||
return r.json();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/***********************************************************************
|
||||||
async function sendRequest(url, options = {}) {
|
* apiProtected — это удобная функция для защищённых API-запросов,
|
||||||
// Базовые параметры
|
* которая:
|
||||||
|
*
|
||||||
|
* - Подставляет стандартные и пользовательские настройки запроса.
|
||||||
|
* - Добавляет Authorization с токеном.
|
||||||
|
* - Автоматически сериализует JSON-тело.
|
||||||
|
* - Парсит ответ.
|
||||||
|
* - Обрабатывает устаревший токен (401) и повторяет запрос.
|
||||||
|
* - Выбрасывает ошибки для внешнего try...catch.
|
||||||
|
***********************************************************************/
|
||||||
|
async function apiProtected(path, options = {}) {
|
||||||
|
// Базовые настройки
|
||||||
const defaultOptions = {
|
const defaultOptions = {
|
||||||
|
//method: "GET",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
credentials: "include"
|
credentials: "include"
|
||||||
};
|
};
|
||||||
|
|
||||||
// Объединяем настройки
|
// Объединяем настройки
|
||||||
const finalOptions = {
|
const finalOptions = {
|
||||||
...defaultOptions,
|
...defaultOptions,
|
||||||
...options,
|
...options,
|
||||||
headers: { ...defaultOptions.headers, ...(options.headers || {}) }
|
headers: { ...defaultOptions.headers, ...(options.headers || {}) }
|
||||||
};
|
};
|
||||||
|
// Если есть тело и это объект — сериализуем
|
||||||
// Если тело — объект, превращаем в JSON
|
|
||||||
if (finalOptions.body && typeof finalOptions.body === "object") {
|
if (finalOptions.body && typeof finalOptions.body === "object") {
|
||||||
finalOptions.body = JSON.stringify(finalOptions.body);
|
finalOptions.body = JSON.stringify(finalOptions.body);
|
||||||
}
|
}
|
||||||
|
// Вспомогательная функция отправки запроса
|
||||||
let response;
|
const send = async () => {
|
||||||
try {
|
try {
|
||||||
response = await fetch(url, finalOptions);
|
// Добавляем Authorization, если токен есть
|
||||||
} catch (err) {
|
if (accessToken) {
|
||||||
// Сетевые ошибки (сервер не доступен, нет интернета, CORS и т.д.)
|
finalOptions.headers.Authorization = `Bearer ${accessToken}`;
|
||||||
return {
|
}
|
||||||
ok: false,
|
// Отправляем fetch запрос.
|
||||||
status: 0,
|
const res = await fetch(path, finalOptions);
|
||||||
data: err.toString()
|
const text = await res.text();
|
||||||
};
|
let data;
|
||||||
}
|
// Пытаемся распарсить ответ как JSON, если не получается
|
||||||
|
// — возвращаем текст.
|
||||||
// Читаем тело ответа только один раз
|
try {
|
||||||
let text = await response.text();
|
data = JSON.parse(text);
|
||||||
let data;
|
} catch {
|
||||||
try {
|
data = text;
|
||||||
data = JSON.parse(text);
|
}
|
||||||
} catch {
|
return { res, data };
|
||||||
data = text;
|
} catch (err) {
|
||||||
}
|
return { res: null, data: err.toString() };
|
||||||
|
}
|
||||||
return {
|
|
||||||
ok: response.ok,
|
|
||||||
status: response.status,
|
|
||||||
data
|
|
||||||
};
|
};
|
||||||
|
// Первый запрос
|
||||||
|
let { res, data } = await send();
|
||||||
|
// Если 401 — обновляем токен и повторяем
|
||||||
|
if (res && res.status === 401) {
|
||||||
|
await refreshAccess(); // обновляем accessToken
|
||||||
|
({ res, data } = await send()); // повторный запрос
|
||||||
|
}
|
||||||
|
// Если всё равно ошибка — кидаем
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
throw { status: res ? res.status : 0, data };
|
||||||
|
}
|
||||||
|
return data; // возвращаем распарсенный JSON или текст
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/***************************************************************************
|
||||||
|
* refreshAccess() Обнавление токенов:
|
||||||
|
*
|
||||||
|
* - Отправляет POST на /api/users/refresh, используя refresh-токен в cookie.
|
||||||
|
* - Проверяет успешность ответа.
|
||||||
|
* - Сохраняет новый access-токен.
|
||||||
|
* - Декодирует токен, чтобы получить user_id.
|
||||||
|
* - Обновляет глобальные данные о пользователе (id и name).
|
||||||
|
****************************************************************************/
|
||||||
|
async function refreshAccess (){
|
||||||
|
//Отправка запроса на обновление токена
|
||||||
|
const rr = await fetch("/api/auth/refresh", {
|
||||||
|
method: "POST",
|
||||||
|
credentials: "include"
|
||||||
|
});
|
||||||
|
// Проверка ответа
|
||||||
|
if (!rr.ok) throw "refresh failed";
|
||||||
|
// Получение нового токена
|
||||||
|
const j = await rr.json();
|
||||||
|
accessToken = j.access_token;
|
||||||
|
// Декодирование payload JWT
|
||||||
|
const payload = JSON.parse(
|
||||||
|
atob(accessToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))
|
||||||
|
);
|
||||||
|
// Обновление данных пользователя
|
||||||
|
user.id = payload.user_id;
|
||||||
|
user.name = (await getUserDataByID(user.id)).name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/********************************************************************************
|
||||||
/********************************************************************
|
* loadMenu функция загрузки блока меню страницы в формате Markdown
|
||||||
* loadMenu функция загрузки блока меню страницы в формате Markdown *
|
********************************************************************************/
|
||||||
********************************************************************/
|
|
||||||
async function loadMenu() {
|
async function loadMenu() {
|
||||||
await loadBlock("menu/top1", "header");
|
await loadBlock("menu/top1", "header");
|
||||||
}
|
}
|
||||||
/********************************************************************
|
/********************************************************************************
|
||||||
* loadPage функция загрузки блока страницы в формате Markdown *
|
* loadPage функция загрузки блока страницы в формате Markdown
|
||||||
********************************************************************/
|
********************************************************************************/
|
||||||
async function loadPage(path) {
|
async function loadPage(path) {
|
||||||
await loadBlock(path, "content");
|
await loadBlock(path, "content");
|
||||||
}
|
}
|
||||||
|
|
||||||
/********************************************************************
|
/*********************************************************************************
|
||||||
* loadMdScript функция загрузки Markdown библиотеки *
|
* loadMdScript функция загрузки Markdown библиотеки
|
||||||
********************************************************************/
|
*********************************************************************************/
|
||||||
function loadMdScript(src) {
|
function loadMdScript(src) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
@@ -123,24 +132,32 @@ async function loadMenu() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/********************************************************************
|
/**********************************************************************************
|
||||||
* loadBlock функция загрузки блока в формате Markdown *
|
* loadBlock — это универсальная функция для динамического контента:
|
||||||
********************************************************************/
|
*
|
||||||
|
* - Находит контейнер по id.
|
||||||
|
* - Очищает старый контент и связанные скрипты/стили.
|
||||||
|
* - Запрашивает блок через apiProtected.
|
||||||
|
* - Преобразует Markdown в HTML.
|
||||||
|
* - Добавляет CSS и JS динамически.
|
||||||
|
* - Вызывает pageInit() блока, если есть.
|
||||||
|
* - Обрабатывает ошибки.
|
||||||
|
**********************************************************************************/
|
||||||
async function loadBlock(path, block_Name) {
|
async function loadBlock(path, block_Name) {
|
||||||
|
// Получаем контейнер блока
|
||||||
const container = document.getElementById(block_Name);
|
const container = document.getElementById(block_Name);
|
||||||
if (!container) {
|
if (!container) {
|
||||||
//console.warn(`loadBlock: контейнер #${block_Name} не найден — игнорируем`);
|
return;
|
||||||
return;
|
}
|
||||||
}
|
// Обработка пути
|
||||||
path = path.replace(/\/$/, "");
|
path = path.replace(/\/$/, "");
|
||||||
//console.log(path);
|
|
||||||
if (!container) {
|
if (!container) {
|
||||||
console.error(`loadBlock ERROR: element #${block_Name} not found`);
|
console.error(`loadBlock ERROR: element #${block_Name} not found`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const blockName = path === "pages" ? "pages/home" : path;
|
const blockName = path === "pages" ? "pages/home" : path;
|
||||||
//console.log(blockName);
|
|
||||||
try {
|
try {
|
||||||
|
// Очистка контейнера и старых динамических стилей/скриптов
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
document.querySelectorAll('style[data-dynamic], script[data-dynamic]').forEach(el => {
|
document.querySelectorAll('style[data-dynamic], script[data-dynamic]').forEach(el => {
|
||||||
const name = el.getAttribute('data-dynamic');
|
const name = el.getAttribute('data-dynamic');
|
||||||
@@ -148,28 +165,27 @@ if (!container) {
|
|||||||
el.remove();
|
el.remove();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const response = await sendRequest(`/api/block/${blockName}`);
|
// Получение блока с сервера
|
||||||
if (!response.ok) {
|
const response = await apiProtected(`/api/block/${blockName}`, {method: "GET"});
|
||||||
throw new Error(`Failed to load block: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Динамически подгружаем markdown-it, если он ещё не загружен
|
// Динамически подгружаем markdown-it, если он ещё не загружен
|
||||||
if (!window.markdownit) {
|
if (!window.markdownit) {
|
||||||
await loadMdScript('/static/js/markdown-it.min.js');
|
await loadMdScript('/static/js/markdown-it.min.js');
|
||||||
}
|
}
|
||||||
|
const { content: mdContent, css, js } = response;
|
||||||
const { content: mdContent, css, js } = response.data;
|
|
||||||
// Преобразуем markdown в HTML
|
// Преобразуем markdown в HTML
|
||||||
if (mdContent) {
|
if (mdContent) {
|
||||||
const md = window.markdownit({ html: true, linkify: true, typographer: true });
|
const md = window.markdownit({ html: true, linkify: true, typographer: true });
|
||||||
container.innerHTML = md.render(mdContent);
|
container.innerHTML = md.render(mdContent);
|
||||||
|
container?.id?.match(/^loadedBlock_\d+_view$/) && (document.getElementById(container.id.replace('_view', '_html')).innerHTML = mdContent);
|
||||||
}
|
}
|
||||||
|
// Добавление CSS блока
|
||||||
if (css) {
|
if (css) {
|
||||||
const style = document.createElement('style');
|
const style = document.createElement('style');
|
||||||
style.dataset.dynamic = block_Name;
|
style.dataset.dynamic = block_Name;
|
||||||
style.textContent = css;
|
style.textContent = css;
|
||||||
document.head.appendChild(style);
|
document.head.appendChild(style);
|
||||||
}
|
}
|
||||||
|
// Добавление JS блока
|
||||||
if (js) {
|
if (js) {
|
||||||
const script = document.createElement('script');
|
const script = document.createElement('script');
|
||||||
script.dataset.dynamic = block_Name;
|
script.dataset.dynamic = block_Name;
|
||||||
@@ -185,24 +201,35 @@ if (!container) {
|
|||||||
`;
|
`;
|
||||||
document.body.appendChild(script);
|
document.body.appendChild(script);
|
||||||
}
|
}
|
||||||
|
// Обработка ошибок
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
container.innerHTML = "<h2>блок не найден</h2>";
|
container.innerHTML = "<h2>блок не найден</h2>";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SPA-навигация
|
/*****************************************************************************
|
||||||
|
* SPA-навигация
|
||||||
|
*****************************************************************************/
|
||||||
function navigateTo(url, target) {
|
function navigateTo(url, target) {
|
||||||
const clean = url.replace(/^\//, "");
|
const clean = url.replace(/^\//, "");
|
||||||
history.pushState({}, "", "/" + clean);
|
history.pushState({}, "", "/" + clean);
|
||||||
loadBlock("pages/" + clean, target);
|
loadBlock("pages/" + clean, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Поддержка кнопки "назад/вперед"
|
/*****************************************************************************
|
||||||
|
* Поддержка кнопки "назад/вперед"
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("popstate", () => {loadBlock(location.pathname);});
|
window.addEventListener("popstate", () => {loadBlock(location.pathname);});
|
||||||
// Обработка истории браузера
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Обработка истории браузера
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("popstate", () => loadBlock(window.location.pathname));
|
window.addEventListener("popstate", () => loadBlock(window.location.pathname));
|
||||||
// Инициализация после загрузки DOM
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Инициализация после загрузки DOM
|
||||||
|
*****************************************************************************/
|
||||||
window.onload = async function () {
|
window.onload = async function () {
|
||||||
let url = window.location.href;
|
let url = window.location.href;
|
||||||
// Убираем слеш в конце, если он есть
|
// Убираем слеш в конце, если он есть
|
||||||
@@ -215,13 +242,14 @@ window.onload = async function () {
|
|||||||
await loadMenu();
|
await loadMenu();
|
||||||
await loadPage("pages"+window.location.pathname);
|
await loadPage("pages"+window.location.pathname);
|
||||||
};
|
};
|
||||||
// Перехватчик ссылок
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Перехватчик ссылок
|
||||||
|
*****************************************************************************/
|
||||||
window.addEventListener("click", (event) => {
|
window.addEventListener("click", (event) => {
|
||||||
const a = event.target.closest("a");
|
const a = event.target.closest("a");
|
||||||
if (!a) return;
|
if (!a) return;
|
||||||
|
|
||||||
const href = a.getAttribute("href");
|
const href = a.getAttribute("href");
|
||||||
|
|
||||||
// игнорируем внешние ссылки и mailto:
|
// игнорируем внешние ссылки и mailto:
|
||||||
if (!href || href.startsWith("http") || href.startsWith("mailto:")) return;
|
if (!href || href.startsWith("http") || href.startsWith("mailto:")) return;
|
||||||
const target = a.dataset.target || "content"; // default = content
|
const target = a.dataset.target || "content"; // default = content
|
||||||
@@ -229,64 +257,305 @@ window.addEventListener("click", (event) => {
|
|||||||
navigateTo(href, target);
|
navigateTo(href, target);
|
||||||
});
|
});
|
||||||
|
|
||||||
//popup
|
|
||||||
function popup(message, afterClose){
|
|
||||||
// Создаём overlay
|
|
||||||
const overlay = document.createElement('div');
|
|
||||||
overlay.className = 'overlay';
|
|
||||||
// Создаём popup
|
|
||||||
const popup = document.createElement('div');
|
|
||||||
popup.className = 'popup';
|
|
||||||
// Добавляем текст
|
|
||||||
const text = document.createElement('div');
|
|
||||||
text.textContent = message;
|
|
||||||
// Добавляем кнопку закрытия
|
|
||||||
const closeBtn = document.createElement('button');
|
|
||||||
closeBtn.textContent = 'Закрыть';
|
|
||||||
closeBtn.addEventListener('click', () => {
|
|
||||||
overlay.remove();
|
|
||||||
if (typeof afterClose === 'function') {
|
|
||||||
afterClose(); // ← ВАША ФУНКЦИЯ ПОСЛЕ ЗАКРЫТИЯ
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
//popupMenu
|
|
||||||
function popupMenu(message, afterClose){
|
|
||||||
// Создаём popupMenu
|
|
||||||
const popupMenu = document.createElement('div');
|
|
||||||
popup.className = 'popup_Menu';
|
|
||||||
// Добавляем текст
|
|
||||||
const text = document.createElement('div');
|
|
||||||
text.textContent = message;
|
|
||||||
// Добавляем кнопку закрытия
|
|
||||||
const closeBtn = document.createElement('button');
|
|
||||||
closeBtn.textContent = 'Закрыть';
|
|
||||||
closeBtn.addEventListener('click', () => {
|
|
||||||
overlay.remove();
|
|
||||||
if (typeof afterClose === 'function') {
|
|
||||||
afterClose(); // ← ВАША ФУНКЦИЯ ПОСЛЕ ЗАКРЫТИЯ
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
popup.appendChild(text);
|
|
||||||
popup.appendChild(closeBtn);
|
|
||||||
overlay.appendChild(popup);
|
|
||||||
document.body.appendChild(overlay);
|
|
||||||
};
|
|
||||||
|
|
||||||
/* ------------------- Переключение видимости пароля ------------------- */
|
|
||||||
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Переключение видимости пароля
|
||||||
|
*****************************************************************************/
|
||||||
document.addEventListener("click", (e) => {
|
document.addEventListener("click", (e) => {
|
||||||
if (!e.target.classList.contains("toggle-pass")) return;
|
if (!e.target.classList.contains("toggle-pass")) return;
|
||||||
//console.log("toggle");
|
console.log("toggle");
|
||||||
const input = e.target.previousElementSibling;
|
const input = e.target.previousElementSibling;
|
||||||
if (!input) return;
|
if (!input) return;
|
||||||
|
|
||||||
if (input.type === "password") {
|
if (input.type === "password") {
|
||||||
input.type = "text";
|
input.type = "text";
|
||||||
e.target.textContent = "🙈";
|
e.target.textContent = "*";//🔓
|
||||||
} else {
|
} else {
|
||||||
input.type = "password";
|
input.type = "password";
|
||||||
e.target.textContent = "👁";
|
e.target.textContent = "A";//🔒
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/*****************************************************************************
|
||||||
|
* Получение данных пользователя. Пример использования:
|
||||||
|
* btn.onclick = async function () {
|
||||||
|
* const user = await getUserDataByID(3);
|
||||||
|
* alert(user.name);
|
||||||
|
* };
|
||||||
|
*****************************************************************************/
|
||||||
|
async function getUserDataByID(id) {
|
||||||
|
const data = await apiProtected(
|
||||||
|
`/api/users/getUserData?userid=${encodeURIComponent(id)}&by=id`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
id: data.ID,
|
||||||
|
name: data.Username
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* Функция userLogin:
|
||||||
|
*
|
||||||
|
* - пытается залогиниться через API,
|
||||||
|
* - возвращает accessToken при успехе,
|
||||||
|
* - бросает понятные ошибки (INVALID_CREDENTIALS, LOGIN_FAILED) при неудаче.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userLogin(username, password) {
|
||||||
|
try {
|
||||||
|
// Запрос логина
|
||||||
|
const r = await apiProtected(`/api/auth/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
})
|
||||||
|
});
|
||||||
|
// Проверка access token
|
||||||
|
if (!r?.access_token) {
|
||||||
|
throw new Error("Token not received");
|
||||||
|
}
|
||||||
|
const payload = JSON.parse(
|
||||||
|
atob(r.access_token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))
|
||||||
|
);
|
||||||
|
// Успешный результат
|
||||||
|
user.name = username;
|
||||||
|
user.id = payload.user_id;
|
||||||
|
return {
|
||||||
|
accessToken: r.access_token
|
||||||
|
};
|
||||||
|
// Обработка ошибок (catch)
|
||||||
|
} catch (err) {
|
||||||
|
// err — объект { status, data } из apiProtected
|
||||||
|
if (err?.status === 401) {
|
||||||
|
throw new Error("INVALID_CREDENTIALS");
|
||||||
|
}
|
||||||
|
// Неверный логин / пароль
|
||||||
|
console.error("Login error:", err);
|
||||||
|
throw new Error("LOGIN_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* userLogout — это функция выхода пользователя из системы.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userLogout() {
|
||||||
|
accessToken = "";
|
||||||
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||||
|
};
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* userRegister функция которая:
|
||||||
|
*
|
||||||
|
* - регистрирует нового пользователя,
|
||||||
|
* - возвращает ответ сервера при успехе,
|
||||||
|
* - преобразует HTTP-ошибки в бизнес-ошибки, понятные UI.
|
||||||
|
******************************************************************************/
|
||||||
|
async function userRegister(username, password) {
|
||||||
|
try {
|
||||||
|
// Запрос регистрации
|
||||||
|
const data = await apiProtected("/api/auth/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Успешный результат
|
||||||
|
return data;
|
||||||
|
// Перехват ошибок
|
||||||
|
} catch (err) {
|
||||||
|
// Сюда прилетают ошибки, брошенные apiProtected:
|
||||||
|
// Логирование
|
||||||
|
console.error("Register error:", err);
|
||||||
|
// Маппинг HTTP → бизнес-ошибки
|
||||||
|
// Некорректные данные
|
||||||
|
if (err?.status === 400) {
|
||||||
|
throw new Error("BAD_REQUEST");
|
||||||
|
}
|
||||||
|
// Пользователь уже существует
|
||||||
|
if (err?.status === 409) {
|
||||||
|
throw new Error("USER_EXISTS");
|
||||||
|
}
|
||||||
|
// Любая другая ошибка
|
||||||
|
throw new Error("REGISTER_FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************************************************************************
|
||||||
|
* Класса UIComponents это статический UI-helper, который:
|
||||||
|
*
|
||||||
|
* - не хранит состояние приложения
|
||||||
|
* - не зависит от фреймворков
|
||||||
|
* - создаёт всплывающие UI-элементы поверх страницы
|
||||||
|
*
|
||||||
|
* Содержит методы:
|
||||||
|
*
|
||||||
|
* - UIComponents.showAlert(...)
|
||||||
|
* - UIComponents.confirm(...)
|
||||||
|
* - UIComponents.showPopupList(...)
|
||||||
|
* - UIComponents.showFileProperties(...)
|
||||||
|
***************************************************************************/
|
||||||
|
class UIComponents {
|
||||||
|
/* ============== 1. АЛЕРТ С ОВЕРЛЕЕМ ============== */
|
||||||
|
/* Показывает модальное окно с кнопкой OK.
|
||||||
|
с затемняющим фоном, который перекрывает страницу*/
|
||||||
|
static showAlert(message) {//, title = 'Сообщение'
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const alertBox = document.createElement('div');
|
||||||
|
alertBox.className = 'window-popup';//ui-alert
|
||||||
|
|
||||||
|
alertBox.innerHTML =
|
||||||
|
//<h3>${title}</h3>
|
||||||
|
`<p>${message}</p>
|
||||||
|
<button>OK</button>
|
||||||
|
`;
|
||||||
|
|
||||||
|
alertBox.querySelector('button').onclick = () => {
|
||||||
|
overlay.remove();
|
||||||
|
};
|
||||||
|
|
||||||
|
overlay.appendChild(alertBox);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*==================== 2. confirm ===================== */
|
||||||
|
/* Аналог window.confirm */
|
||||||
|
static confirm(message, title = 'Подтверждение') {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const box = document.createElement('div');
|
||||||
|
box.className = 'ui-alert';
|
||||||
|
|
||||||
|
box.innerHTML = `
|
||||||
|
<h3>${title}</h3>
|
||||||
|
<p>${message}</p>
|
||||||
|
<div style="display:flex;justify-content:center;gap:12px;margin-top:16px">
|
||||||
|
<button data-yes>Да</button>
|
||||||
|
<button data-no>Нет</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const close = (result) => {
|
||||||
|
overlay.remove();
|
||||||
|
resolve(result);
|
||||||
|
};
|
||||||
|
|
||||||
|
box.querySelector('[data-yes]').onclick = () => close(true);
|
||||||
|
box.querySelector('[data-no]').onclick = () => close(false);
|
||||||
|
|
||||||
|
overlay.appendChild(box);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ========== 3. ПОПАП СПИСОК ========== */
|
||||||
|
static showPopupList(items = {}, x = 0, y = 0) {
|
||||||
|
// Удаляем предыдущий popup
|
||||||
|
if (UIComponents.currentPopup) {
|
||||||
|
UIComponents.currentPopup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const popup = document.createElement('div');
|
||||||
|
popup.className = 'ui-popup-list';
|
||||||
|
popup.style.left = x + 'px';
|
||||||
|
popup.style.top = y + 'px';
|
||||||
|
|
||||||
|
for (const [name, fn] of Object.entries(items)) {
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.textContent = name;
|
||||||
|
el.onclick = () => {
|
||||||
|
fn(); // вызываем конкретную функцию
|
||||||
|
popup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
};
|
||||||
|
popup.appendChild(el);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.body.appendChild(popup);
|
||||||
|
UIComponents.currentPopup = popup;
|
||||||
|
|
||||||
|
const removePopup = () => {
|
||||||
|
if (UIComponents.currentPopup) {
|
||||||
|
UIComponents.currentPopup.remove();
|
||||||
|
UIComponents.currentPopup = null;
|
||||||
|
}
|
||||||
|
document.removeEventListener('click', removePopup);
|
||||||
|
};
|
||||||
|
setTimeout(() => document.addEventListener('click', removePopup), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ========== 4. ОКНО "СВОЙСТВА ФАЙЛА" ========== */
|
||||||
|
static showFileProperties(general = {}, details = {}) {
|
||||||
|
const overlay = document.createElement('div');
|
||||||
|
overlay.className = 'ui-overlay';
|
||||||
|
|
||||||
|
const win = document.createElement('div');
|
||||||
|
win.className = 'ui-window';
|
||||||
|
win.style.position = 'absolute';
|
||||||
|
|
||||||
|
const rows = obj =>
|
||||||
|
Object.entries(obj)
|
||||||
|
.map(([k, v]) => `<div class="row"><span>${k}</span><span>${v}</span></div>`)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
win.innerHTML = `
|
||||||
|
<div class="header">
|
||||||
|
<span>Свойства</span>
|
||||||
|
<button>×</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tabs">
|
||||||
|
<div class="tab active" data-tab="general">Общие</div>
|
||||||
|
<div class="tab" data-tab="details">Подробно</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tab-content active" id="general">${rows(general)}</div>
|
||||||
|
<div class="tab-content" id="details">${rows(details)}</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
win.querySelector('button').onclick = () => overlay.remove();
|
||||||
|
|
||||||
|
/* tabs */
|
||||||
|
win.querySelectorAll('.tab').forEach(tab => {
|
||||||
|
tab.onclick = () => {
|
||||||
|
win.querySelectorAll('.tab, .tab-content')
|
||||||
|
.forEach(e => e.classList.remove('active'));
|
||||||
|
|
||||||
|
tab.classList.add('active');
|
||||||
|
win.querySelector('#' + tab.dataset.tab).classList.add('active');
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/* drag */
|
||||||
|
const header = win.querySelector('.header');
|
||||||
|
header.onmousedown = (e) => {
|
||||||
|
const r = win.getBoundingClientRect();
|
||||||
|
const dx = e.clientX - r.left;
|
||||||
|
const dy = e.clientY - r.top;
|
||||||
|
|
||||||
|
document.onmousemove = e =>
|
||||||
|
Object.assign(win.style, {
|
||||||
|
left: e.clientX - dx + 'px',
|
||||||
|
top: e.clientY - dy + 'px'
|
||||||
|
});
|
||||||
|
|
||||||
|
document.onmouseup = () => document.onmousemove = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
overlay.appendChild(win);
|
||||||
|
document.body.appendChild(overlay);
|
||||||
|
|
||||||
|
win.style.left = 'calc(50% - 180px)';
|
||||||
|
win.style.top = '20%';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
|
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="ru">
|
<html lang="ru">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<base href="/">
|
<base href="/">
|
||||||
<link rel="icon" type="image/png" href="/static/img/favicon.png">
|
<link rel="icon" type="image/png" href="/img/favicon.png">
|
||||||
<title>JWT SPA project</title>
|
<title>TS Web</title>
|
||||||
<link rel="stylesheet" href="/static/css/style.css">
|
<link rel="stylesheet" href="/static/css/style.css">
|
||||||
<script defer src="/static/js/app.js"></script>
|
<script defer src="/static/js/app.js"></script>
|
||||||
</head>
|
</head>
|
||||||
@@ -18,7 +17,7 @@
|
|||||||
<main id="content"></main>
|
<main id="content"></main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>© 2025 Go Markdown SPA</p>
|
<p>© 2025 TriggersSmith web</p>
|
||||||
</footer>
|
</footer>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -17,5 +17,6 @@
|
|||||||
<li><a href="/gpt" data-link="true" data-target="content">GPT</a></li>
|
<li><a href="/gpt" data-link="true" data-target="content">GPT</a></li>
|
||||||
<li><a href="/ACL" data-link="true" data-target="content">ACL</a></li>
|
<li><a href="/ACL" data-link="true" data-target="content">ACL</a></li>
|
||||||
<li><a href="/userSlava/popup" data-link="true" data-target="content">Сообщения popup</a></li>
|
<li><a href="/userSlava/popup" data-link="true" data-target="content">Сообщения popup</a></li>
|
||||||
|
<li><a href="/session" data-link="true" data-target="content">Сессия</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ async function UserLogin() {
|
|||||||
const p = document.getElementById("password").value;
|
const p = document.getElementById("password").value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const r = await fetch("/api/users/login", {
|
const r = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -35,7 +35,7 @@ async function UserLogin() {
|
|||||||
|
|
||||||
async function UserLogout() {
|
async function UserLogout() {
|
||||||
try {
|
try {
|
||||||
await fetch("/api/users/logout", { method: "POST", credentials: "include" });
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||||
accessToken = "";
|
accessToken = "";
|
||||||
alert("logged out");
|
alert("logged out");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
19
static/blocks/pages/session/content.md
Normal file
19
static/blocks/pages/session/content.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<div class="form1" id="login_block">
|
||||||
|
|
||||||
|
# Вход в систему
|
||||||
|
|
||||||
|
Пожалуйста, введите ваши данные для входа.
|
||||||
|
|
||||||
|
<div class="grid-block">
|
||||||
|
<label for="username">Имя пользователя</label>
|
||||||
|
<input type="text" id="username" name="username" required>
|
||||||
|
<label for="password">Пароль</label>
|
||||||
|
<input type="password" id="password" name="password" required>
|
||||||
|
<button type="submit" id="login_btn">Войти</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form1" id="user_block">
|
||||||
|
<p id="user_info"></p>
|
||||||
|
<button id="logout_btn">Выйти</button>
|
||||||
|
</div>
|
||||||
67
static/blocks/pages/session/script.js
Normal file
67
static/blocks/pages/session/script.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
async function initUser() {
|
||||||
|
try {
|
||||||
|
// Если нет токена, делаем refresh
|
||||||
|
if (!accessToken) {
|
||||||
|
await refreshAccess ();
|
||||||
|
}
|
||||||
|
// Проверяем, получили ли токен
|
||||||
|
if (!accessToken) throw new Error("no token");
|
||||||
|
// выводим имя пользователя
|
||||||
|
user_info.innerHTML = `Вы зашли как: ${user.name}. </br> Ваш ID:${user.id}`;
|
||||||
|
// Показываем блок пользователя
|
||||||
|
showUser()
|
||||||
|
} catch (e) {
|
||||||
|
// Показываем блок логина
|
||||||
|
showLogin()
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function showLogin() {
|
||||||
|
login_block.classList.remove("hiden_block");
|
||||||
|
user_block.classList.add("hiden_block");
|
||||||
|
}
|
||||||
|
|
||||||
|
function showUser() {
|
||||||
|
login_block.classList.add("hiden_block");
|
||||||
|
user_block.classList.remove("hiden_block");
|
||||||
|
}
|
||||||
|
initUser();
|
||||||
|
|
||||||
|
/* --------------------------- Логин ------------------------------- */
|
||||||
|
|
||||||
|
async function onLoginClick() {
|
||||||
|
try {
|
||||||
|
const { accessToken: token } = await userLogin(
|
||||||
|
username.value.trim(),
|
||||||
|
password.value
|
||||||
|
);
|
||||||
|
|
||||||
|
accessToken = token;
|
||||||
|
// UIComponents.showAlert("Вы успешно вошли как "+user.name+".</br> Ваш ID:"+user.id);
|
||||||
|
|
||||||
|
username.value = "";
|
||||||
|
password.value = "";
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
switch (e.message) {
|
||||||
|
case "INVALID_CREDENTIALS":
|
||||||
|
UIComponents.showAlert("Неверный логин или пароль");
|
||||||
|
break;
|
||||||
|
case "BAD_REQUEST":
|
||||||
|
UIComponents.showAlert("Некорректный запрос");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
UIComponents.showAlert("Ошибка при логине");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initUser();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------- Кнопки ------------------- */
|
||||||
|
logout_btn.onclick = async () => {
|
||||||
|
await userLogout(); // вызываем существующую функцию
|
||||||
|
initUser(); // делаем своё
|
||||||
|
};
|
||||||
|
login_btn.onclick = onLoginClick;
|
||||||
78
static/blocks/pages/session/style.css
Normal file
78
static/blocks/pages/session/style.css
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
.hiden_block{
|
||||||
|
display:none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 {
|
||||||
|
background: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 16px;
|
||||||
|
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
|
||||||
|
/*max-width: 250px;
|
||||||
|
width: 100%;*/
|
||||||
|
width: 250px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 h1 {
|
||||||
|
margin-top: 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 26px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 p {
|
||||||
|
text-align: center;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 25px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 .grid-block h3 {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
color: #444;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 label {
|
||||||
|
font-size: 15px;
|
||||||
|
color: #555;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 input {
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 15px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
transition: border 0.2s, box-shadow 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 input:focus {
|
||||||
|
border-color: #7f57ff;
|
||||||
|
box-shadow: 0 0 0 2px rgba(127, 87, 255, 0.2);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 16px;
|
||||||
|
background:#e4e4e4;
|
||||||
|
/* color: white; */
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-top: 10px;
|
||||||
|
transition: background 0.25s, transform 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button:hover {
|
||||||
|
background: #aa92f8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form1 button:active {
|
||||||
|
transform: scale(0.98);
|
||||||
|
}
|
||||||
@@ -12,14 +12,14 @@ btn_prot.onclick = async () => {
|
|||||||
|
|
||||||
async function UserLogout() {
|
async function UserLogout() {
|
||||||
accessToken = "";
|
accessToken = "";
|
||||||
await fetch("/api/users/logout", { method: "POST", credentials: "include" });
|
await fetch("/api/auth/logout", { method: "POST", credentials: "include"});
|
||||||
};
|
};
|
||||||
|
|
||||||
async function UserLogin() {
|
async function UserLogin() {
|
||||||
const u = log_user.value,
|
const u = log_user.value,
|
||||||
p = log_pass.value;
|
p = log_pass.value;
|
||||||
|
|
||||||
const r = await fetch("/api/users/login", {
|
const r = await fetch("/api/auth/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
|
|||||||
Reference in New Issue
Block a user