MSP-1756 add transactional
This commit is contained in:
1 parent
fa89426bcc
commit
036200a765
9 files changed
+331
-173
No files matched your search
+23
-5
@@ -12,15 +12,21 @@ import (
|
||||
"msp-admin-service/routes"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/worker"
|
||||
"msp-admin-service/transaction"
|
||||
)
|
||||
|
||||
type DB interface {
|
||||
db.DB
|
||||
db.Transactional
|
||||
}
|
||||
|
||||
type Locator struct {
|
||||
logger log.Logger
|
||||
httpCli *httpcli.Client
|
||||
db db.DB
|
||||
db DB
|
||||
}
|
||||
|
||||
func NewLocator(logger log.Logger, httpCli *httpcli.Client, db db.DB) Locator {
|
||||
func NewLocator(logger log.Logger, httpCli *httpcli.Client, db DB) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
httpCli: httpCli,
|
||||
@@ -47,10 +53,22 @@ func (l Locator) Config(cfg conf.Remote) Config {
|
||||
|
||||
auditService := service.NewAudit(auditRepo, l.logger)
|
||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo, roleRepo)
|
||||
userService := service.NewUser(userRepo, userRoleRepo, roleRepo, tokenRepo, l.logger)
|
||||
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo)
|
||||
|
||||
txManager := transaction.NewManager(l.db)
|
||||
|
||||
userService := service.NewUser(
|
||||
userRepo,
|
||||
userRoleRepo,
|
||||
roleRepo,
|
||||
tokenRepo,
|
||||
auditService,
|
||||
txManager,
|
||||
l.logger,
|
||||
)
|
||||
authService := service.NewAuth(
|
||||
userRepo,
|
||||
txManager,
|
||||
tokenService,
|
||||
sudirService,
|
||||
auditService,
|
||||
@@ -59,7 +77,7 @@ func (l Locator) Config(cfg conf.Remote) Config {
|
||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||
)
|
||||
roleService := service.NewRole(roleRepo)
|
||||
roleService := service.NewRole(roleRepo, auditService)
|
||||
|
||||
permissionsService := service.NewPermission(cfg.Permissions)
|
||||
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) Insert(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||
q, args, err := query.New().Insert("roles").
|
||||
Columns("name", "permissions", "change_message").
|
||||
Values(role.Name, role.Permissions, role.ChangeMessage).
|
||||
|
||||
@@ -49,7 +49,7 @@ func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]enti
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (u UserRole) Insert(ctx context.Context, id int, roleIds []int) error {
|
||||
func (u UserRole) InsertPairs(ctx context.Context, id int, roleIds []int) error {
|
||||
rolesQ := query.New().
|
||||
Insert("user_roles").
|
||||
Columns("user_id", "role_id")
|
||||
|
||||
+117
-76
@@ -12,6 +12,17 @@ import (
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type AuthTransaction interface {
|
||||
userRepository
|
||||
roleRepo
|
||||
UserRoleRepo
|
||||
TokenSaver
|
||||
}
|
||||
|
||||
type AuthTransactionRunner interface {
|
||||
AuthTransaction(ctx context.Context, tx func(ctx context.Context, tx AuthTransaction) error) error
|
||||
}
|
||||
|
||||
type auditService interface {
|
||||
SaveAuditAsync(ctx context.Context, userId int64, message string)
|
||||
}
|
||||
@@ -23,20 +34,21 @@ type userRepository interface {
|
||||
}
|
||||
|
||||
type tokenService interface {
|
||||
GenerateToken(ctx context.Context, id int64) (string, string, error)
|
||||
GenerateToken(ctx context.Context, repo TokenSaver, id int64) (string, string, error)
|
||||
RevokeAllByUserId(ctx context.Context, userId int64) error
|
||||
}
|
||||
|
||||
type authRoleRepository interface {
|
||||
Insert(ctx context.Context, id int, roleIds []int) error
|
||||
InsertPairs(ctx context.Context, id int, roleIds []int) error
|
||||
}
|
||||
|
||||
type sudirService interface {
|
||||
Authenticate(ctx context.Context, authCode string) (*entity.SudirUser, error)
|
||||
Authenticate(ctx context.Context, authCode string, repo roleRepo) (*entity.SudirUser, error)
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
userRepository userRepository
|
||||
txRunner AuthTransactionRunner
|
||||
tokenService tokenService
|
||||
sudirService sudirService
|
||||
auditService auditService
|
||||
@@ -49,6 +61,7 @@ type Auth struct {
|
||||
|
||||
func NewAuth(
|
||||
userRepository userRepository,
|
||||
txRunner AuthTransactionRunner,
|
||||
tokenService tokenService,
|
||||
sudirService sudirService,
|
||||
auditService auditService,
|
||||
@@ -59,6 +72,7 @@ func NewAuth(
|
||||
) Auth {
|
||||
return Auth{
|
||||
userRepository: userRepository,
|
||||
txRunner: txRunner,
|
||||
tokenService: tokenService,
|
||||
sudirService: sudirService,
|
||||
auditService: auditService,
|
||||
@@ -79,44 +93,57 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
}
|
||||
time.Sleep(a.delayLoginRequest)
|
||||
|
||||
user, err := a.userRepository.GetUserByEmail(ctx, request.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email")
|
||||
case user.SudirUserId != nil:
|
||||
return nil, domain.ErrSudirAuthorization
|
||||
}
|
||||
var (
|
||||
tokenString string
|
||||
expired string
|
||||
)
|
||||
|
||||
if user.Blocked {
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Неуспешный вход. Пользователь заблокирован")
|
||||
return nil, errors.WithMessagef(domain.ErrUnauthenticated, "user '%d' is blocked", user.Id)
|
||||
}
|
||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||
user, err := tx.GetUserByEmail(ctx, request.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email")
|
||||
case user.SudirUserId != nil:
|
||||
return domain.ErrSudirAuthorization
|
||||
}
|
||||
|
||||
if user.Blocked {
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Неуспешный вход. Пользователь заблокирован")
|
||||
return errors.WithMessagef(domain.ErrUnauthenticated, "user '%d' is blocked", user.Id)
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
|
||||
if err != nil {
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Неуспешный вход. Неверный пароль")
|
||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong password")
|
||||
}
|
||||
|
||||
tokenString, expired, err = a.tokenService.GenerateToken(ctx, tx, user.Id)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа")
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
FirstName: user.FirstName,
|
||||
LastName: user.LastName,
|
||||
Email: user.Email,
|
||||
Description: user.Description,
|
||||
LastSessionCreatedAt: time.Now().UTC(),
|
||||
}
|
||||
_, err = tx.UpdateUser(ctx, user.Id, updateEntity)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update session info")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
|
||||
if err != nil {
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Неуспешный вход. Неверный пароль")
|
||||
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong password")
|
||||
}
|
||||
|
||||
tokenString, expired, err := a.tokenService.GenerateToken(ctx, user.Id)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа")
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
FirstName: user.FirstName,
|
||||
LastName: user.LastName,
|
||||
Email: user.Email,
|
||||
Description: user.Description,
|
||||
LastSessionCreatedAt: time.Now().UTC(),
|
||||
}
|
||||
_, err = a.userRepository.UpdateUser(ctx, user.Id, updateEntity)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "update session info")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &domain.LoginResponse{
|
||||
@@ -127,50 +154,64 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
}
|
||||
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode)
|
||||
var (
|
||||
user *entity.User
|
||||
|
||||
var authErr *entity.SudirAuthError
|
||||
switch {
|
||||
case errors.As(err, &authErr):
|
||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||
return nil, domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "sudir authenticate")
|
||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||
log.String("userId", sudirUser.SudirUserId),
|
||||
log.String("email", sudirUser.Email))
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
tokenString string
|
||||
expired string
|
||||
)
|
||||
|
||||
user, err := a.userRepository.UpsertBySudirUserId(ctx, entity.User{
|
||||
SudirUserId: &sudirUser.SudirUserId,
|
||||
FirstName: sudirUser.FirstName,
|
||||
LastName: sudirUser.LastName,
|
||||
Email: sudirUser.Email,
|
||||
Password: "",
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "upsert by sudir user id")
|
||||
}
|
||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode, tx)
|
||||
|
||||
// при создании юзера СУДИР первоначально роли не указаны
|
||||
if len(sudirUser.RoleIds) > 0 {
|
||||
err = a.authRoleRepository.Insert(ctx, int(user.Id), sudirUser.RoleIds)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "insert sudir roles")
|
||||
var authErr *entity.SudirAuthError
|
||||
switch {
|
||||
case errors.As(err, &authErr):
|
||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||
return domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "sudir authenticate")
|
||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||
log.String("userId", sudirUser.SudirUserId),
|
||||
log.String("email", sudirUser.Email))
|
||||
return domain.ErrUnauthenticated
|
||||
}
|
||||
}
|
||||
|
||||
tokenString, expired, err := a.tokenService.GenerateToken(ctx, user.Id)
|
||||
user, err = tx.UpsertBySudirUserId(ctx, entity.User{
|
||||
SudirUserId: &sudirUser.SudirUserId,
|
||||
FirstName: sudirUser.FirstName,
|
||||
LastName: sudirUser.LastName,
|
||||
Email: sudirUser.Email,
|
||||
Password: "",
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert by sudir user id")
|
||||
}
|
||||
|
||||
// при создании юзера СУДИР первоначально роли не указаны
|
||||
if len(sudirUser.RoleIds) > 0 {
|
||||
err = tx.InsertPairs(ctx, int(user.Id), sudirUser.RoleIds)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert sudir roles")
|
||||
}
|
||||
}
|
||||
|
||||
tokenString, expired, err = a.tokenService.GenerateToken(ctx, tx, user.Id)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР")
|
||||
|
||||
+7
-5
@@ -11,18 +11,20 @@ import (
|
||||
|
||||
type roleRoleRepo interface {
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
Insert(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Delete(ctx context.Context, id int) error
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
roleRepo roleRoleRepo
|
||||
roleRepo roleRoleRepo
|
||||
auditService auditService
|
||||
}
|
||||
|
||||
func NewRole(roleRepo roleRoleRepo) Role {
|
||||
func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
|
||||
return Role{
|
||||
roleRepo: roleRepo,
|
||||
roleRepo: roleRepo,
|
||||
auditService: audit,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +43,7 @@ func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
}
|
||||
|
||||
func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error) {
|
||||
role, err := u.roleRepo.Insert(ctx, entity.Role{
|
||||
role, err := u.roleRepo.InsertRole(ctx, entity.Role{
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ChangeMessage: req.ChangeMessage,
|
||||
|
||||
+3
-5
@@ -27,18 +27,16 @@ type roleRepo interface {
|
||||
type Sudir struct {
|
||||
cfg *conf.SudirAuth
|
||||
sudirRepo sudirRepo
|
||||
roleRepo roleRepo
|
||||
}
|
||||
|
||||
func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo, roleRepo roleRepo) Sudir {
|
||||
func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo) Sudir {
|
||||
return Sudir{
|
||||
cfg: cfg,
|
||||
sudirRepo: sudirRepo,
|
||||
roleRepo: roleRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.SudirUser, error) {
|
||||
func (s Sudir) Authenticate(ctx context.Context, authCode string, roleRepo roleRepo) (*entity.SudirUser, error) {
|
||||
if s.cfg == nil {
|
||||
return nil, domain.ErrSudirAuthIsMissed
|
||||
}
|
||||
@@ -65,7 +63,7 @@ func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.Sudir
|
||||
return nil, errors.New("undefined role")
|
||||
}*/
|
||||
|
||||
roleId, err := s.roleRepo.UpsertRoleByName(ctx, entity.Role{
|
||||
roleId, err := roleRepo.UpsertRoleByName(ctx, entity.Role{
|
||||
Name: user.GivenName,
|
||||
Permissions: []string{},
|
||||
ExternalGroup: user.GivenName,
|
||||
|
||||
+7
-3
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
type TokenRep interface {
|
||||
Save(ctx context.Context, token entity.Token) error
|
||||
TokenSaver
|
||||
GetEntity(ctx context.Context, token string) (*entity.Token, error)
|
||||
RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error
|
||||
All(ctx context.Context, limit int, offset int) ([]entity.Token, error)
|
||||
@@ -21,6 +21,10 @@ type TokenRep interface {
|
||||
UpdateStatus(ctx context.Context, id int, status string) error
|
||||
}
|
||||
|
||||
type TokenSaver interface {
|
||||
Save(ctx context.Context, token entity.Token) error
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
tokenRep TokenRep
|
||||
lifeTime time.Duration
|
||||
@@ -33,7 +37,7 @@ func NewToken(tokenRep TokenRep, lifeTimeInSec int) Token {
|
||||
}
|
||||
}
|
||||
|
||||
func (s Token) GenerateToken(ctx context.Context, id int64) (string, string, error) {
|
||||
func (s Token) GenerateToken(ctx context.Context, repo TokenSaver, id int64) (string, string, error) {
|
||||
cryptoRand := make([]byte, 128) //nolint:gomnd
|
||||
_, err := rand.Read(cryptoRand)
|
||||
if err != nil {
|
||||
@@ -44,7 +48,7 @@ func (s Token) GenerateToken(ctx context.Context, id int64) (string, string, err
|
||||
createdAt := time.Now().UTC()
|
||||
expiredAt := createdAt.Add(s.lifeTime)
|
||||
|
||||
err = s.tokenRep.Save(ctx, entity.Token{
|
||||
err = repo.Save(ctx, entity.Token{
|
||||
Token: random,
|
||||
UserId: id,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
|
||||
+126
-77
@@ -12,7 +12,17 @@ import (
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type userRepo interface {
|
||||
type UserTransaction interface {
|
||||
UserRepo
|
||||
UserRoleRepo
|
||||
TokenRepo
|
||||
}
|
||||
|
||||
type UserTransactionRunner interface {
|
||||
UserTransaction(ctx context.Context, tx func(ctx context.Context, tx UserTransaction) error) error
|
||||
}
|
||||
|
||||
type UserRepo interface {
|
||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||
GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
@@ -22,14 +32,14 @@ type userRepo interface {
|
||||
ChangeBlockStatus(ctx context.Context, userId int) (bool, error)
|
||||
}
|
||||
|
||||
type tokenRepo interface {
|
||||
type TokenRepo interface {
|
||||
UpdateStatusByUserId(ctx context.Context, userId int, status string) error
|
||||
}
|
||||
|
||||
type userRoleRepo interface {
|
||||
type UserRoleRepo interface {
|
||||
GetRolesByUserId(ctx context.Context, identity int) ([]int, error)
|
||||
GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error)
|
||||
Insert(ctx context.Context, id int, roleIds []int) error
|
||||
InsertPairs(ctx context.Context, id int, roleIds []int) error
|
||||
ForceUpsert(ctx context.Context, id int, roleIds []int) error
|
||||
}
|
||||
|
||||
@@ -38,19 +48,31 @@ type roleRepoUser interface {
|
||||
}
|
||||
|
||||
type User struct {
|
||||
userRepo userRepo
|
||||
userRoleRepo userRoleRepo
|
||||
userRepo UserRepo
|
||||
userRoleRepo UserRoleRepo
|
||||
roleRepoUser roleRepoUser
|
||||
tokenRepo tokenRepo
|
||||
tokenRepo TokenRepo
|
||||
auditService auditService
|
||||
txRunner UserTransactionRunner
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewUser(userRepo userRepo, userRoleRepo userRoleRepo, roleRepoUser roleRepoUser, tokenRepo tokenRepo, logger log.Logger) User {
|
||||
func NewUser(
|
||||
userRepo UserRepo,
|
||||
userRoleRepo UserRoleRepo,
|
||||
roleRepoUser roleRepoUser,
|
||||
tokenRepo TokenRepo,
|
||||
service auditService,
|
||||
txRunner UserTransactionRunner,
|
||||
logger log.Logger,
|
||||
) User {
|
||||
return User{
|
||||
userRepo: userRepo,
|
||||
userRoleRepo: userRoleRepo,
|
||||
roleRepoUser: roleRepoUser,
|
||||
tokenRepo: tokenRepo,
|
||||
auditService: service,
|
||||
txRunner: txRunner,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
@@ -120,43 +142,52 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersRequest) (*domain.Us
|
||||
}
|
||||
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, adminId int64) (*domain.User, error) {
|
||||
user, err := u.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email or phone")
|
||||
case user != nil:
|
||||
return nil, domain.ErrAlreadyExists
|
||||
}
|
||||
var usr entity.User
|
||||
|
||||
encryptedPassword, err := u.cryptPassword(req.Password)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "crypt password")
|
||||
}
|
||||
|
||||
usr := entity.User{
|
||||
SudirUserId: nil,
|
||||
Id: 0,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Password: encryptedPassword,
|
||||
Description: req.Description,
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
id, err := u.userRepo.Insert(ctx, usr)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
}
|
||||
|
||||
if len(req.Roles) != 0 {
|
||||
err = u.userRoleRepo.Insert(ctx, id, req.Roles)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
user, err := tx.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email or phone")
|
||||
case user != nil:
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
encryptedPassword, err := u.cryptPassword(req.Password)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "crypt password")
|
||||
}
|
||||
|
||||
usr = entity.User{
|
||||
SudirUserId: nil,
|
||||
Id: 0,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Password: encryptedPassword,
|
||||
Description: req.Description,
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
id, err := tx.Insert(ctx, usr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "create user")
|
||||
}
|
||||
|
||||
if len(req.Roles) != 0 {
|
||||
err = tx.InsertPairs(ctx, id, req.Roles)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create user transaction")
|
||||
}
|
||||
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
@@ -168,34 +199,44 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
}
|
||||
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error) {
|
||||
user, err := u.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email or phone")
|
||||
case user.Id != req.Id:
|
||||
return nil, domain.ErrAlreadyExists
|
||||
}
|
||||
var user *entity.User
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Description: req.Description,
|
||||
LastSessionCreatedAt: req.LastSessionCreatedAt,
|
||||
}
|
||||
|
||||
user, err = u.userRepo.UpdateUser(ctx, req.Id, updateEntity)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
}
|
||||
|
||||
if len(req.Roles) > 0 {
|
||||
err = u.userRoleRepo.ForceUpsert(ctx, int(user.Id), req.Roles)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "force upsert")
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
var err error
|
||||
user, err = tx.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return err
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email or phone")
|
||||
case user.Id != req.Id:
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Description: req.Description,
|
||||
LastSessionCreatedAt: req.LastSessionCreatedAt,
|
||||
}
|
||||
|
||||
user, err = tx.UpdateUser(ctx, req.Id, updateEntity)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update user")
|
||||
}
|
||||
|
||||
if len(req.Roles) > 0 {
|
||||
err = tx.ForceUpsert(ctx, int(user.Id), req.Roles)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "force upsert")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "update user transaction")
|
||||
}
|
||||
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
@@ -239,16 +280,24 @@ func (u User) GetById(ctx context.Context, userId int) (*domain.User, error) {
|
||||
}
|
||||
|
||||
func (u User) Block(ctx context.Context, userId int) error {
|
||||
blocked, err := u.userRepo.ChangeBlockStatus(ctx, userId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "change block status")
|
||||
}
|
||||
|
||||
if blocked {
|
||||
err := u.tokenRepo.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked)
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
blocked, err := tx.ChangeBlockStatus(ctx, userId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "revoke tokens")
|
||||
return errors.WithMessage(err, "change block status")
|
||||
}
|
||||
|
||||
if blocked {
|
||||
err := tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "revoke tokens")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "block user transaction")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package transaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
db db.Transactional
|
||||
}
|
||||
|
||||
func NewManager(db db.Transactional) *Manager {
|
||||
return &Manager{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
type userTx struct {
|
||||
repository.User
|
||||
repository.Role
|
||||
repository.UserRole
|
||||
repository.Token
|
||||
}
|
||||
|
||||
func (m Manager) UserTransaction(ctx context.Context, msgTx func(ctx context.Context, tx service.UserTransaction) error) error {
|
||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||
user := repository.NewUser(tx)
|
||||
role := repository.NewRole(tx)
|
||||
userRole := repository.NewUserRole(tx)
|
||||
token := repository.NewToken(tx)
|
||||
return msgTx(ctx, userTx{user, role, userRole, token})
|
||||
})
|
||||
}
|
||||
|
||||
func (m Manager) AuthTransaction(ctx context.Context, msgTx func(ctx context.Context, tx service.AuthTransaction) error) error {
|
||||
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||
user := repository.NewUser(tx)
|
||||
role := repository.NewRole(tx)
|
||||
userRole := repository.NewUserRole(tx)
|
||||
token := repository.NewToken(tx)
|
||||
return msgTx(ctx, userTx{user, role, userRole, token})
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user