feat(admin): add super admin initialization endpoint
Add POST /api/v1/admin/setup-super-admin endpoint to initialize the first super admin. The endpoint can only be used once - after a super admin exists, subsequent requests are rejected. Requires valid setup_secret configured via APP_SETUP_SECRET environment variable or setup_secret in config file.
This commit is contained in:
63
internal/service/setup_service.go
Normal file
63
internal/service/setup_service.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
apperrors "with_you/internal/errors"
|
||||
"with_you/internal/model"
|
||||
"with_you/internal/repository"
|
||||
)
|
||||
|
||||
type SetupService interface {
|
||||
SetupSuperAdmin(ctx context.Context, userID, setupSecret string) error
|
||||
}
|
||||
|
||||
type setupService struct {
|
||||
userRepo repository.UserRepository
|
||||
roleRepo repository.RoleRepository
|
||||
casbinSvc CasbinService
|
||||
setupSecret string
|
||||
}
|
||||
|
||||
func NewSetupService(
|
||||
userRepo repository.UserRepository,
|
||||
roleRepo repository.RoleRepository,
|
||||
casbinSvc CasbinService,
|
||||
setupSecret string,
|
||||
) SetupService {
|
||||
return &setupService{
|
||||
userRepo: userRepo,
|
||||
roleRepo: roleRepo,
|
||||
casbinSvc: casbinSvc,
|
||||
setupSecret: setupSecret,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *setupService) SetupSuperAdmin(ctx context.Context, userID, setupSecret string) error {
|
||||
if s.setupSecret == "" {
|
||||
return apperrors.ErrSetupSecretNotConfigured
|
||||
}
|
||||
|
||||
if setupSecret != s.setupSecret {
|
||||
return apperrors.ErrInvalidSetupSecret
|
||||
}
|
||||
|
||||
count, err := s.roleRepo.GetRoleUserCount(ctx, model.RoleSuperAdmin)
|
||||
if err != nil {
|
||||
return apperrors.ErrInternal
|
||||
}
|
||||
if count > 0 {
|
||||
return apperrors.ErrSetupAlreadyCompleted
|
||||
}
|
||||
|
||||
user, err := s.userRepo.GetByID(userID)
|
||||
if err != nil {
|
||||
return apperrors.ErrUserNotFound
|
||||
}
|
||||
|
||||
if user.Status == model.UserStatusBanned {
|
||||
return apperrors.ErrUserBanned
|
||||
}
|
||||
|
||||
return s.casbinSvc.AddRoleForUser(ctx, user.ID, model.RoleSuperAdmin)
|
||||
}
|
||||
Reference in New Issue
Block a user