new version

This commit is contained in:
Ivan Rezchikov
2026-07-11 19:04:41 +03:00
parent 3c64666299
commit b7334696e4
16 changed files with 313 additions and 269 deletions
+20 -5
View File
@@ -34,10 +34,22 @@ func NewRouter(
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("/session/attach",
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_attach")),
oauth.SessionAttach,
)
o.POST("/session/approve",
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.IPKeyFn("session_approve")),
oauth.SessionApprove,
)
o.POST("/token",
middleware.RateLimit(limiter, services.TokenRateLimit, middleware.TokenKeyFn),
oauth.Token,
)
o.POST("/revoke",
middleware.RateLimit(limiter, services.RevokeRateLimit, middleware.RevokeKeyFn),
oauth.Revoke,
)
o.POST("/introspect", positions.Introspect)
}
@@ -49,7 +61,10 @@ func NewRouter(
middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")),
auth.Register,
)
a.POST("/refresh", auth.Refresh)
a.POST("/refresh",
middleware.RateLimit(limiter, services.RefreshRateLimit, middleware.RefreshKeyFn),
auth.Refresh,
)
me := api.Group("/me")
me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile)
@@ -41,6 +41,18 @@ func IPKeyFn(prefix string) func(c *gin.Context) string {
}
}
func TokenKeyFn(c *gin.Context) string {
return "token:" + c.ClientIP()
}
func RevokeKeyFn(c *gin.Context) string {
return "revoke:" + c.ClientIP()
}
func RefreshKeyFn(c *gin.Context) string {
return "refresh:" + c.ClientIP()
}
func itoa(n int) string {
if n < 0 {
return "0"
+1 -1
View File
@@ -10,7 +10,7 @@ import (
type OAuthClient struct {
ID uuid.UUID `db:"id" json:"id"`
ClientID string `db:"client_id" json:"client_id"`
ClientSecret string `db:"client_secret" json:"client_secret"`
ClientSecret string `db:"client_secret" json:"-"`
Name string `db:"name" json:"name"`
RedirectURIs json.RawMessage `db:"redirect_uris" json:"redirect_uris"`
GrantTypes json.RawMessage `db:"grant_types" json:"grant_types"`
@@ -211,24 +211,32 @@ func (r *PositionRepository) GetUserPositions(ctx context.Context, userID uuid.U
}
defer rows.Close()
var result []models.PositionLocalized
var positions []posRow
for rows.Next() {
var p models.PositionLocalized
var positionID uuid.UUID
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
var r posRow
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
return nil, err
}
perms, err := r.GetPositionPermissions(ctx, positionID, locale)
if err != nil {
return nil, err
}
p.Permissions = perms
if p.Permissions == nil {
p.Permissions = []models.Permission{}
}
result = append(result, p)
positions = append(positions, r)
}
return result, rows.Err()
if err := rows.Err(); err != nil {
return nil, err
}
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
if err != nil {
return nil, err
}
result := make([]models.PositionLocalized, len(positions))
for i, pos := range positions {
pos.p.Permissions = permMap[pos.id]
if pos.p.Permissions == nil {
pos.p.Permissions = []models.Permission{}
}
result[i] = pos.p
}
return result, nil
}
func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string) ([]models.PositionLocalized, error) {
@@ -246,24 +254,32 @@ func (r *PositionRepository) GetAllPositions(ctx context.Context, locale string)
}
defer rows.Close()
var result []models.PositionLocalized
var positions []posRow
for rows.Next() {
var p models.PositionLocalized
var positionID uuid.UUID
if err := rows.Scan(&positionID, &p.Code, &p.Name, &p.Description); err != nil {
var r posRow
if err := rows.Scan(&r.id, &r.p.Code, &r.p.Name, &r.p.Description); err != nil {
return nil, err
}
perms, err := r.GetPositionPermissions(ctx, positionID, locale)
if err != nil {
return nil, err
}
p.Permissions = perms
if p.Permissions == nil {
p.Permissions = []models.Permission{}
}
result = append(result, p)
positions = append(positions, r)
}
return result, rows.Err()
if err := rows.Err(); err != nil {
return nil, err
}
permMap, err := r.getPositionPermissionsBatch(ctx, positionIDs(positions), locale)
if err != nil {
return nil, err
}
result := make([]models.PositionLocalized, len(positions))
for i, pos := range positions {
pos.p.Permissions = permMap[pos.id]
if pos.p.Permissions == nil {
pos.p.Permissions = []models.Permission{}
}
result[i] = pos.p
}
return result, nil
}
func (r *PositionRepository) GetUsersWithPositions(ctx context.Context, locale string) ([]models.UserWithPositions, error) {
@@ -295,7 +311,57 @@ func (r *PositionRepository) GetUsersWithPositions(ctx context.Context, locale s
result = append(result, u)
}
return result, rows.Err()
}
type posRow struct {
id uuid.UUID
p models.PositionLocalized
}
func (pr posRow) getID() uuid.UUID { return pr.id }
func positionIDs(items []posRow) []uuid.UUID {
ids := make([]uuid.UUID, len(items))
for i, item := range items {
ids[i] = item.id
}
return ids
}
func (r *PositionRepository) getPositionPermissionsBatch(ctx context.Context, pIDs []uuid.UUID, locale string) (map[uuid.UUID][]models.Permission, error) {
if len(pIDs) == 0 {
return nil, nil
}
rows, err := r.db.Query(ctx, `
SELECT pp.position_id,
p.id, p.code,
COALESCE(pl.name, pe.name, p.code) AS name,
COALESCE(pl.description, pe.description, p.description, '') AS description,
p.created_at
FROM position_permissions pp
JOIN permissions p ON pp.permission_id = p.id
LEFT JOIN permission_translations pl
ON pl.permission_id = p.id AND pl.locale = $2
LEFT JOIN permission_translations pe
ON pe.permission_id = p.id AND pe.locale = 'en'
WHERE pp.position_id = ANY($1)
ORDER BY pp.position_id, p.code
`, pIDs, strings.ToLower(locale))
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[uuid.UUID][]models.Permission)
for rows.Next() {
var positionID uuid.UUID
var perm models.Permission
if err := rows.Scan(&positionID, &perm.ID, &perm.Code, &perm.Name, &perm.Description, &perm.CreatedAt); err != nil {
return nil, err
}
result[positionID] = append(result[positionID], perm)
}
return result, rows.Err()
}
@@ -88,10 +88,7 @@ func redirectURIMatches(redirectURIsJSON json.RawMessage, redirectURI string) bo
}
func verifyClientSecret(stored, provided string) bool {
if stored == "" {
return true
}
if provided == "" {
if stored == "" || provided == "" {
return false
}
if strings.HasPrefix(stored, "$2") {
@@ -268,7 +268,9 @@ func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken str
return nil
}
_ = s.oauth.DeleteRefreshTokenByID(ctx, row.ID)
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
return models.ErrInternal
}
return nil
}
@@ -25,6 +25,23 @@ var (
Max: 5,
Window: time.Hour,
}
TokenRateLimit = RateLimitConfig{
Max: 20,
Window: time.Minute,
BlockFor: 5 * time.Minute,
}
RevokeRateLimit = RateLimitConfig{
Max: 30,
Window: time.Minute,
}
RefreshRateLimit = RateLimitConfig{
Max: 30,
Window: time.Minute,
BlockFor: 5 * time.Minute,
}
)
type RateLimiter struct {
@@ -42,7 +59,7 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig
if cfg.BlockFor > 0 {
blocked, err := r.redis.Exists(ctx, blockKey).Result()
if err != nil {
return true, 0, nil
return false, 0, fmt.Errorf("rate limiter: %w", err)
}
if blocked > 0 {
return false, 0, nil
@@ -53,7 +70,7 @@ func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig
incrCmd := pipe.Incr(ctx, counterKey)
pipe.Expire(ctx, counterKey, cfg.Window)
if _, err := pipe.Exec(ctx); err != nil {
return true, 0, nil
return false, 0, fmt.Errorf("rate limiter: %w", err)
}
count := int(incrCmd.Val())