fix
This commit is contained in:
@@ -4,9 +4,10 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||
)
|
||||
|
||||
type PositionsHandler struct {
|
||||
@@ -24,7 +25,7 @@ func localeFromRequest(c *gin.Context) string {
|
||||
if l := c.GetHeader("Accept-Language"); l != "" {
|
||||
return l
|
||||
}
|
||||
return "ru"
|
||||
return "en"
|
||||
}
|
||||
|
||||
func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
||||
@@ -36,6 +37,15 @@ func userIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func isAdminFromContext(c *gin.Context) bool {
|
||||
v, ok := c.Get("is_admin")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
b, ok := v.(bool)
|
||||
return ok && b
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
@@ -52,25 +62,8 @@ func (h *PositionsHandler) GetMyPositions(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, positions)
|
||||
}
|
||||
|
||||
type upsertPositionRequest struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
if !isAdmin {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
@@ -84,19 +77,14 @@ func (h *PositionsHandler) ListPositions(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, positions)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
userID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
type upsertPositionRequest struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
|
||||
isAdmin, err := h.svc.UserIsPositionsAdmin(c.Request.Context(), userID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
if !isAdmin {
|
||||
func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
@@ -115,3 +103,141 @@ func (h *PositionsHandler) UpsertPosition(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type permissionCodeRequest struct {
|
||||
PermissionCode string `json:"permission_code" binding:"required"`
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) AddPermissionToPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var req permissionCodeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.Error(models.ErrBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.AddPermissionToPosition(c.Request.Context(), c.Param("code"), req.PermissionCode); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) RemovePermissionFromPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.RemovePermissionFromPosition(c.Request.Context(), c.Param("code"), c.Param("permCode")); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) ListPermissions(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
perms, err := h.svc.GetAllPermissions(c.Request.Context())
|
||||
if err != nil {
|
||||
c.Error(models.ErrInternal)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, perms)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) AssignPosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
adminID, ok := userIDFromContext(c)
|
||||
if !ok {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
targetUserID, err := uuid.Parse(c.Param("userId"))
|
||||
if err != nil {
|
||||
c.Error(models.ErrBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var input models.AssignPositionInput
|
||||
if err := c.ShouldBindJSON(&input); err != nil {
|
||||
c.Error(models.ErrBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.AssignPosition(c.Request.Context(), adminID, targetUserID, input); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) RevokePosition(c *gin.Context) {
|
||||
if !isAdminFromContext(c) {
|
||||
c.Error(models.ErrForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
targetUserID, err := uuid.Parse(c.Param("userId"))
|
||||
if err != nil {
|
||||
c.Error(models.ErrBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.RevokePosition(c.Request.Context(), targetUserID, c.Param("code")); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *PositionsHandler) Introspect(c *gin.Context) {
|
||||
var req struct {
|
||||
Token string `json:"token" form:"token" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing token"})
|
||||
return
|
||||
}
|
||||
|
||||
id, secret, ok := c.Request.BasicAuth()
|
||||
if !ok {
|
||||
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid_client"})
|
||||
return
|
||||
}
|
||||
if _, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{
|
||||
ClientID: id,
|
||||
ClientSecret: secret,
|
||||
}); err != nil {
|
||||
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid_client"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.svc.IntrospectToken(c.Request.Context(), req.Token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "server_error"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,15 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, positions *handlers.PositionsHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine {
|
||||
func NewRouter(
|
||||
auth *handlers.AuthHandler,
|
||||
oauth *handlers.OAuthHandler,
|
||||
consents *handlers.ConsentHandler,
|
||||
positions *handlers.PositionsHandler,
|
||||
svc *services.Service,
|
||||
repo *repositories.OAuthRepository,
|
||||
limiter *services.RateLimiter,
|
||||
) *gin.Engine {
|
||||
r := gin.Default()
|
||||
r.Use(errorMiddleware())
|
||||
|
||||
@@ -20,17 +28,25 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
{
|
||||
o.GET("/authorize", oauth.Authorize)
|
||||
o.GET("/session/:token", oauth.GetSession)
|
||||
o.POST("/session/login", middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn), oauth.SessionLogin)
|
||||
o.POST("/session/login",
|
||||
middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn),
|
||||
oauth.SessionLogin,
|
||||
)
|
||||
o.POST("/session/attach", oauth.SessionAttach)
|
||||
o.POST("/session/approve", oauth.SessionApprove)
|
||||
o.POST("/token", oauth.Token)
|
||||
o.POST("/revoke", oauth.Revoke)
|
||||
|
||||
o.POST("/introspect", positions.Introspect)
|
||||
}
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
a := api.Group("/auth")
|
||||
a.POST("/register", middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")), auth.Register)
|
||||
a.POST("/register",
|
||||
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
|
||||
auth.Register,
|
||||
)
|
||||
a.POST("/refresh", auth.Refresh)
|
||||
|
||||
me := api.Group("/me")
|
||||
@@ -41,9 +57,19 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent
|
||||
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
||||
me.GET("/positions", authMiddleware(svc, repo, "profile:read"), positions.GetMyPositions)
|
||||
|
||||
admin := api.Group("/admin")
|
||||
admin.GET("/positions", authMiddleware(svc, repo), positions.ListPositions)
|
||||
admin.POST("/positions", authMiddleware(svc, repo), positions.UpsertPosition)
|
||||
admin := api.Group("/admin", authMiddleware(svc, repo))
|
||||
{
|
||||
admin.GET("/permissions", positions.ListPermissions)
|
||||
|
||||
admin.GET("/positions", positions.ListPositions)
|
||||
admin.POST("/positions", positions.UpsertPosition)
|
||||
|
||||
admin.POST("/positions/:code/permissions", positions.AddPermissionToPosition)
|
||||
admin.DELETE("/positions/:code/permissions/:permCode", positions.RemovePermissionFromPosition)
|
||||
|
||||
admin.POST("/users/:userId/positions", positions.AssignPosition)
|
||||
admin.DELETE("/users/:userId/positions/:code", positions.RevokePosition)
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -77,7 +103,15 @@ func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, r
|
||||
return
|
||||
}
|
||||
|
||||
user, err := svc.GetUserByID(c.Request.Context(), info.UserID)
|
||||
if err != nil {
|
||||
c.Error(models.ErrUnauthorized)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", info.UserID)
|
||||
c.Set("is_admin", user.IsAdmin)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,30 +6,50 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Permission struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
Code string `db:"code" json:"code"`
|
||||
Description string `db:"description" json:"description"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
}
|
||||
|
||||
type Position struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
Code string `db:"code" json:"code"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
Code string `db:"code" json:"code"`
|
||||
Permissions []Permission `db:"-" json:"permissions,omitempty"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
type PositionTranslation struct {
|
||||
PositionID uuid.UUID `db:"position_id" json:"position_id"`
|
||||
Locale string `db:"locale" json:"locale"`
|
||||
Name string `db:"name" json:"name"`
|
||||
Locale string `db:"locale" json:"locale"`
|
||||
Name string `db:"name" json:"name"`
|
||||
Description *string `db:"description" json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type UserPosition struct {
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
UserID uuid.UUID `db:"user_id" json:"user_id"`
|
||||
ID uuid.UUID `db:"id" json:"id"`
|
||||
UserID uuid.UUID `db:"user_id" json:"user_id"`
|
||||
PositionID uuid.UUID `db:"position_id" json:"position_id"`
|
||||
ValidFrom time.Time `db:"valid_from" json:"valid_from"`
|
||||
ValidTo *time.Time `db:"valid_to" json:"valid_to,omitempty"`
|
||||
AssignedBy *uuid.UUID `db:"assigned_by" json:"assigned_by,omitempty"`
|
||||
ValidFrom time.Time `db:"valid_from" json:"valid_from"`
|
||||
ValidTo *time.Time `db:"valid_to" json:"valid_to,omitempty"`
|
||||
}
|
||||
|
||||
type PositionLocalized struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Permissions []Permission `json:"permissions"`
|
||||
}
|
||||
|
||||
type AssignPositionInput struct {
|
||||
PositionCode string `json:"position_code" binding:"required"`
|
||||
ValidFrom time.Time `json:"valid_from" binding:"omitempty"`
|
||||
ValidTo *time.Time `json:"valid_to" binding:"omitempty"`
|
||||
}
|
||||
|
||||
type RevokePositionInput struct {
|
||||
PositionCode string `json:"position_code" binding:"required"`
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ type User struct {
|
||||
SecondName string `db:"second_name" json:"second_name"`
|
||||
BirthDate *time.Time `db:"birth_date" json:"birth_date,omitempty"`
|
||||
Sex string `db:"sex" json:"sex"`
|
||||
IsAdmin bool `db:"is_admin" json:"is_admin"`
|
||||
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
@@ -17,15 +17,102 @@ func NewPositionRepository(db *pgxpool.Pool) *PositionRepository {
|
||||
return &PositionRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetAllPermissions(ctx context.Context) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT id, code, COALESCE(description, ''), created_at
|
||||
FROM permissions
|
||||
ORDER BY code
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.Permission
|
||||
for rows.Next() {
|
||||
var p models.Permission
|
||||
if err := rows.Scan(&p.ID, &p.Code, &p.Description, &p.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error) {
|
||||
var p models.Permission
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, code, COALESCE(description, ''), created_at
|
||||
FROM permissions WHERE code = $1
|
||||
`, code).Scan(&p.ID, &p.Code, &p.Description, &p.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetPositionPermissions(ctx context.Context, positionID uuid.UUID) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT p.id, p.code, COALESCE(p.description, ''), p.created_at
|
||||
FROM position_permissions pp
|
||||
JOIN permissions p ON pp.permission_id = p.id
|
||||
WHERE pp.position_id = $1
|
||||
ORDER BY p.code
|
||||
`, positionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.Permission
|
||||
for rows.Next() {
|
||||
var p models.Permission
|
||||
if err := rows.Scan(&p.ID, &p.Code, &p.Description, &p.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (r *PositionRepository) AddPermissionToPosition(ctx context.Context, positionID, permissionID uuid.UUID) error {
|
||||
_, err := r.db.Exec(ctx, `
|
||||
INSERT INTO position_permissions (position_id, permission_id)
|
||||
VALUES ($1, $2)
|
||||
ON CONFLICT DO NOTHING
|
||||
`, positionID, permissionID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *PositionRepository) RemovePermissionFromPosition(ctx context.Context, positionID, permissionID uuid.UUID) error {
|
||||
_, err := r.db.Exec(ctx, `
|
||||
DELETE FROM position_permissions
|
||||
WHERE position_id = $1 AND permission_id = $2
|
||||
`, positionID, permissionID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetPositionByCode(ctx context.Context, code string) (*models.Position, error) {
|
||||
var p models.Position
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, code, created_at, updated_at
|
||||
FROM positions WHERE code = $1
|
||||
`, code).Scan(&p.ID, &p.Code, &p.CreatedAt, &p.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT p.code,
|
||||
COALESCE(pt.name, p.code) AS name, pt.description
|
||||
SELECT p.id, p.code,
|
||||
COALESCE(pt.name, p.code) AS name,
|
||||
pt.description
|
||||
FROM user_positions up
|
||||
JOIN positions p ON up.position_id = p.id
|
||||
LEFT JOIN position_translations pt
|
||||
ON pt.position_id = p.id
|
||||
AND pt.locale = $2
|
||||
ON pt.position_id = p.id AND pt.locale = $2
|
||||
WHERE up.user_id = $1
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
ORDER BY name
|
||||
@@ -38,9 +125,18 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
|
||||
var result []models.PositionLocalized
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil {
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
@@ -48,27 +144,34 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
|
||||
|
||||
func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT p.code,
|
||||
COALESCE(pt.name, p.code) AS name, pt.description
|
||||
SELECT p.id, p.code,
|
||||
COALESCE(pt.name, p.code) AS name,
|
||||
pt.description
|
||||
FROM positions p
|
||||
LEFT JOIN position_translations pt
|
||||
ON pt.position_id = p.id
|
||||
AND pt.locale = $1
|
||||
ON pt.position_id = p.id AND pt.locale = $1
|
||||
ORDER BY name
|
||||
`, strings.ToLower(locale))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.PositionLocalized
|
||||
for rows.Next() {
|
||||
var p models.PositionLocalized
|
||||
if err := rows.Scan(&p.Code, &p.Name, &p.Description); err != nil {
|
||||
var positionID uuid.UUID
|
||||
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
perms, err := r.GetPositionPermissions(ctx, positionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Permissions = perms
|
||||
if p.Permissions == nil {
|
||||
p.Permissions = []models.Permission{}
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return result, rows.Err()
|
||||
@@ -85,8 +188,7 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO positions (code)
|
||||
VALUES ($1)
|
||||
ON CONFLICT (code) DO UPDATE
|
||||
SET updated_at = now()
|
||||
ON CONFLICT (code) DO UPDATE SET updated_at = now()
|
||||
RETURNING id
|
||||
`, code).Scan(&positionID)
|
||||
if err != nil {
|
||||
@@ -97,10 +199,8 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
INSERT INTO position_translations (position_id, locale, name, description)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (position_id, locale) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
description = EXCLUDED.description
|
||||
SET name = EXCLUDED.name, description = EXCLUDED.description
|
||||
`, positionID, strings.ToLower(locale), name, description)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -108,21 +208,66 @@ func (r *PositionRepository) UpsertPositionForLocale(ctx context.Context, code,
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r *PositionRepository) UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
|
||||
var exists bool
|
||||
func (r *PositionRepository) AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom interface{}, validTo *interface{}) error {
|
||||
_, err := r.db.Exec(ctx, `
|
||||
INSERT INTO user_positions (user_id, position_id, assigned_by, valid_from, valid_to)
|
||||
VALUES ($1, $2, $3, COALESCE($4, now()), $5)
|
||||
`, userID, positionID, assignedBy, validFrom, validTo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *PositionRepository) RevokePosition(ctx context.Context, userID, positionID uuid.UUID) error {
|
||||
_, err := r.db.Exec(ctx, `
|
||||
UPDATE user_positions
|
||||
SET valid_to = now()
|
||||
WHERE user_id = $1
|
||||
AND position_id = $2
|
||||
AND valid_to IS NULL
|
||||
`, userID, positionID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *PositionRepository) UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error) {
|
||||
var positionCode string
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM user_positions up
|
||||
JOIN positions p ON up.position_id = p.id
|
||||
WHERE up.user_id = $1
|
||||
AND p.code = $2
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
)
|
||||
`, userID, code).Scan(&exists)
|
||||
SELECT p.code
|
||||
FROM user_positions up
|
||||
JOIN positions p ON up.position_id = p.id
|
||||
JOIN position_permissions pp ON pp.position_id = p.id
|
||||
JOIN permissions perm ON pp.permission_id = perm.id
|
||||
WHERE up.user_id = $1
|
||||
AND perm.code = $2
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
LIMIT 1
|
||||
`, userID, permissionCode).Scan(&positionCode)
|
||||
if err != nil {
|
||||
return false, "", nil
|
||||
}
|
||||
return true, positionCode, nil
|
||||
}
|
||||
|
||||
func (r *PositionRepository) GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]models.Permission, error) {
|
||||
rows, err := r.db.Query(ctx, `
|
||||
SELECT DISTINCT perm.id, perm.code, COALESCE(perm.description, ''), perm.created_at
|
||||
FROM user_positions up
|
||||
JOIN position_permissions pp ON pp.position_id = up.position_id
|
||||
JOIN permissions perm ON pp.permission_id = perm.id
|
||||
WHERE up.user_id = $1
|
||||
AND (up.valid_to IS NULL OR up.valid_to > now())
|
||||
ORDER BY perm.code
|
||||
`, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []models.Permission
|
||||
for rows.Next() {
|
||||
var p models.Permission
|
||||
if err := rows.Scan(&p.ID, &p.Code, &p.Description, &p.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, p)
|
||||
}
|
||||
return exists, nil
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
@@ -27,9 +27,9 @@ func (r *UserRepository) CreateUser(ctx context.Context, user models.User) (*mod
|
||||
err := r.db.QueryRow(ctx, `
|
||||
INSERT INTO users (email, password_hash, first_name, second_name, birth_date, sex)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, created_at, updated_at
|
||||
RETURNING id, is_admin, created_at, updated_at
|
||||
`, user.Email, user.PasswordHash, user.FirstName, user.SecondName, user.BirthDate, user.Sex).
|
||||
Scan(&user.ID, &user.CreatedAt, &user.UpdatedAt)
|
||||
Scan(&user.ID, &user.IsAdmin, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
@@ -63,9 +63,15 @@ func (r *UserRepository) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
||||
func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
||||
var u models.User
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||
SELECT id, email, password_hash, first_name, second_name,
|
||||
birth_date, sex, is_admin, created_at, updated_at
|
||||
FROM users WHERE email = $1
|
||||
`, email).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||
`, email).Scan(
|
||||
&u.ID, &u.Email, &u.PasswordHash,
|
||||
&u.FirstName, &u.SecondName,
|
||||
&u.BirthDate, &u.Sex, &u.IsAdmin,
|
||||
&u.CreatedAt, &u.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -75,9 +81,15 @@ func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*mod
|
||||
func (r *UserRepository) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
|
||||
var u models.User
|
||||
err := r.db.QueryRow(ctx, `
|
||||
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||
SELECT id, email, password_hash, first_name, second_name,
|
||||
birth_date, sex, is_admin, created_at, updated_at
|
||||
FROM users WHERE id = $1
|
||||
`, id).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||
`, id).Scan(
|
||||
&u.ID, &u.Email, &u.PasswordHash,
|
||||
&u.FirstName, &u.SecondName,
|
||||
&u.BirthDate, &u.Sex, &u.IsAdmin,
|
||||
&u.CreatedAt, &u.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -2,12 +2,43 @@ package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const adminPositionCode = "PRESIDENT"
|
||||
func (s *Service) GetAllPermissions(ctx context.Context) ([]models.Permission, error) {
|
||||
return s.positions.GetAllPermissions(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) AddPermissionToPosition(ctx context.Context, positionCode, permissionCode string) error {
|
||||
position, err := s.positions.GetPositionByCode(ctx, positionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
permission, err := s.positions.GetPermissionByCode(ctx, permissionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
return s.positions.AddPermissionToPosition(ctx, position.ID, permission.ID)
|
||||
}
|
||||
|
||||
func (s *Service) RemovePermissionFromPosition(ctx context.Context, positionCode, permissionCode string) error {
|
||||
position, err := s.positions.GetPositionByCode(ctx, positionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
permission, err := s.positions.GetPermissionByCode(ctx, permissionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
return s.positions.RemovePermissionFromPosition(ctx, position.ID, permission.ID)
|
||||
}
|
||||
|
||||
func (s *Service) GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error) {
|
||||
if locale == "" {
|
||||
@@ -30,6 +61,74 @@ func (s *Service) UpsertPositionForLocale(ctx context.Context, code, locale, nam
|
||||
return s.positions.UpsertPositionForLocale(ctx, code, locale, name, description)
|
||||
}
|
||||
|
||||
func (s *Service) UserIsPositionsAdmin(ctx context.Context, userID uuid.UUID) (bool, error) {
|
||||
return s.positions.UserHasPosition(ctx, userID, adminPositionCode)
|
||||
func (s *Service) AssignPosition(ctx context.Context, adminID, targetUserID uuid.UUID, input models.AssignPositionInput) error {
|
||||
position, err := s.positions.GetPositionByCode(ctx, input.PositionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
validFrom := input.ValidFrom
|
||||
if validFrom.IsZero() {
|
||||
validFrom = time.Now()
|
||||
}
|
||||
|
||||
return s.positions.AssignPosition(ctx, targetUserID, position.ID, &adminID, validFrom, (*interface{})(nil))
|
||||
}
|
||||
|
||||
func (s *Service) RevokePosition(ctx context.Context, targetUserID uuid.UUID, positionCode string) error {
|
||||
position, err := s.positions.GetPositionByCode(ctx, positionCode)
|
||||
if err != nil {
|
||||
return models.ErrNotFound
|
||||
}
|
||||
|
||||
return s.positions.RevokePosition(ctx, targetUserID, position.ID)
|
||||
}
|
||||
|
||||
func (s *Service) UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, error) {
|
||||
allowed, _, err := s.positions.UserHasPermission(ctx, userID, permissionCode)
|
||||
return allowed, err
|
||||
}
|
||||
|
||||
type IntrospectResponse struct {
|
||||
Active bool `json:"active"`
|
||||
Sub string `json:"sub"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
Positions []models.PositionLocalized `json:"positions"`
|
||||
Permissions []models.Permission `json:"permissions"`
|
||||
}
|
||||
|
||||
func (s *Service) IntrospectToken(ctx context.Context, token string) (*IntrospectResponse, error) {
|
||||
info, err := s.ValidateAccessToken(ctx, token)
|
||||
if err != nil {
|
||||
return &IntrospectResponse{Active: false}, nil
|
||||
}
|
||||
|
||||
user, err := s.users.GetUserByID(ctx, info.UserID)
|
||||
if err != nil {
|
||||
return &IntrospectResponse{Active: false}, nil
|
||||
}
|
||||
|
||||
positions, err := s.positions.GetUserPositions(ctx, user.ID, "en")
|
||||
if err != nil {
|
||||
return &IntrospectResponse{Active: false}, nil
|
||||
}
|
||||
if positions == nil {
|
||||
positions = []models.PositionLocalized{}
|
||||
}
|
||||
|
||||
allPerms, err := s.positions.GetUserPermissions(ctx, user.ID)
|
||||
if err != nil {
|
||||
return &IntrospectResponse{Active: false}, nil
|
||||
}
|
||||
if allPerms == nil {
|
||||
allPerms = []models.Permission{}
|
||||
}
|
||||
|
||||
return &IntrospectResponse{
|
||||
Active: true,
|
||||
Sub: user.ID.String(),
|
||||
IsAdmin: user.IsAdmin,
|
||||
Positions: positions,
|
||||
Permissions: allPerms,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -43,13 +43,26 @@ type OAuthRepo interface {
|
||||
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
||||
GetUserConsentsByClientID(ctx context.Context, userID uuid.UUID, clientID uuid.UUID) ([]models.UserConsent, error)
|
||||
RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error
|
||||
UpsertClient(ctx context.Context, client models.OAuthClient) error
|
||||
}
|
||||
|
||||
type PositionRepo interface {
|
||||
GetAllPermissions(ctx context.Context) ([]models.Permission, error)
|
||||
GetPermissionByCode(ctx context.Context, code string) (*models.Permission, error)
|
||||
GetPositionPermissions(ctx context.Context, positionID uuid.UUID) ([]models.Permission, error)
|
||||
AddPermissionToPosition(ctx context.Context, positionID, permissionID uuid.UUID) error
|
||||
RemovePermissionFromPosition(ctx context.Context, positionID, permissionID uuid.UUID) error
|
||||
|
||||
GetPositionByCode(ctx context.Context, code string) (*models.Position, error)
|
||||
GetUserPositions(ctx context.Context, userID uuid.UUID, locale string) ([]models.PositionLocalized, error)
|
||||
GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error)
|
||||
UpsertPositionForLocale(ctx context.Context, code, locale, name string, description *string) error
|
||||
UserHasPosition(ctx context.Context, userID uuid.UUID, code string) (bool, error)
|
||||
|
||||
AssignPosition(ctx context.Context, userID, positionID uuid.UUID, assignedBy *uuid.UUID, validFrom any, validTo *any) error
|
||||
RevokePosition(ctx context.Context, userID, positionID uuid.UUID) error
|
||||
|
||||
UserHasPermission(ctx context.Context, userID uuid.UUID, permissionCode string) (bool, string, error)
|
||||
GetUserPermissions(ctx context.Context, userID uuid.UUID) ([]models.Permission, error)
|
||||
}
|
||||
|
||||
type TokenConfig struct {
|
||||
|
||||
Reference in New Issue
Block a user