MSP-1538 reimplement user api
This commit is contained in:
1 parent
060c5a09de
commit
72e89b1c9f
10 files changed
+456
-137
No files matched your search
+44
-13
@@ -12,10 +12,13 @@ import (
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type auditService interface {
|
||||
SaveAuditAsync(ctx context.Context, userId int64, message string)
|
||||
}
|
||||
|
||||
type userRepository interface {
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
GetUserBySudirUserId(ctx context.Context, id string) (*entity.User, error)
|
||||
CreateSudirUser(ctx context.Context, user entity.SudirUser) (*entity.User, error)
|
||||
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||
}
|
||||
|
||||
type tokenService interface {
|
||||
@@ -31,17 +34,27 @@ type Auth struct {
|
||||
userRepository userRepository
|
||||
tokenService tokenService
|
||||
sudirService sudirService
|
||||
auditService auditService
|
||||
logger log.Logger
|
||||
maxInFlightLoginRequests int
|
||||
delayLoginRequest time.Duration
|
||||
inFlight *atomic.Int32
|
||||
}
|
||||
|
||||
func NewAuth(userRepository userRepository, tokenService tokenService, sudirService sudirService, logger log.Logger, delayLoginRequestInSec int, maxInFlightLoginRequests int) Auth {
|
||||
func NewAuth(
|
||||
userRepository userRepository,
|
||||
tokenService tokenService,
|
||||
sudirService sudirService,
|
||||
auditService auditService,
|
||||
logger log.Logger,
|
||||
delayLoginRequestInSec int,
|
||||
maxInFlightLoginRequests int,
|
||||
) Auth {
|
||||
return Auth{
|
||||
userRepository: userRepository,
|
||||
tokenService: tokenService,
|
||||
sudirService: sudirService,
|
||||
auditService: auditService,
|
||||
logger: logger,
|
||||
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
||||
maxInFlightLoginRequests: maxInFlightLoginRequests,
|
||||
@@ -68,8 +81,14 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
return nil, domain.ErrSudirAuthorization
|
||||
}
|
||||
|
||||
if user.Blocked {
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Неуспешный вход. Пользователь заблокирован")
|
||||
return nil, 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 nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong password")
|
||||
}
|
||||
|
||||
@@ -78,6 +97,8 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа")
|
||||
|
||||
return &domain.LoginResponse{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
@@ -102,16 +123,22 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
user, err := a.userRepository.GetUserBySudirUserId(ctx, sudirUser.SudirUserId)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
user, err = a.userRepository.CreateSudirUser(ctx, *sudirUser)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create sudir user")
|
||||
}
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
user, err := a.userRepository.UpsertBySudirUserId(ctx, entity.User{
|
||||
SudirUserId: &sudirUser.SudirUserId,
|
||||
RoleId: sudirUser.RoleId,
|
||||
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")
|
||||
}
|
||||
|
||||
tokenString, expired, err := a.tokenService.GenerateToken(ctx, user.Id)
|
||||
@@ -119,6 +146,8 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР")
|
||||
|
||||
return &domain.LoginResponse{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
@@ -132,5 +161,7 @@ func (a Auth) Logout(ctx context.Context, adminId int64) error {
|
||||
return errors.WithMessage(err, "revoke all tokens by user id")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, adminId, "Выход")
|
||||
|
||||
return nil
|
||||
}
|
||||
+11
-21
@@ -11,12 +11,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
innerAdminRole = "admin"
|
||||
innerReadOnlyAdminRole = "read_only_admin"
|
||||
|
||||
sudirRolePrefix = "CN="
|
||||
sudirAdminRole = "DIT-KKD-Admins"
|
||||
sudirReadOnlyAdminRole = "DIT-KKD-Operators"
|
||||
sudirRolePrefix = "CN="
|
||||
)
|
||||
|
||||
type sudirRepo interface {
|
||||
@@ -26,6 +21,7 @@ type sudirRepo interface {
|
||||
|
||||
type roleRepo interface {
|
||||
GetRoleByName(ctx context.Context, name string) (*entity.Role, error)
|
||||
UpsertRoleByName(ctx context.Context, role entity.Role) (int, error)
|
||||
}
|
||||
|
||||
type Sudir struct {
|
||||
@@ -68,16 +64,16 @@ func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.Sudir
|
||||
return nil, errors.New("undefined role")
|
||||
}
|
||||
|
||||
roleInfo, err := s.roleRepo.GetRoleByName(ctx, role)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, errors.WithMessagef(err, "get unknown role '%s'", role)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get role")
|
||||
roleId, err := s.roleRepo.UpsertRoleByName(ctx, entity.Role{
|
||||
Name: role,
|
||||
Rights: map[string]string{},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "upsert role")
|
||||
}
|
||||
|
||||
return &entity.SudirUser{
|
||||
RoleId: roleInfo.Id,
|
||||
RoleId: roleId,
|
||||
SudirUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
@@ -86,18 +82,12 @@ func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.Sudir
|
||||
}
|
||||
|
||||
func getRole(groups []string) string {
|
||||
var role string
|
||||
for _, group := range groups {
|
||||
part := strings.Split(group, ",")
|
||||
for _, p := range part {
|
||||
sudirRole := strings.TrimPrefix(p, sudirRolePrefix)
|
||||
switch sudirRole {
|
||||
case sudirAdminRole:
|
||||
return innerAdminRole
|
||||
case sudirReadOnlyAdminRole:
|
||||
role = innerReadOnlyAdminRole
|
||||
}
|
||||
return sudirRole
|
||||
}
|
||||
}
|
||||
return role
|
||||
return ""
|
||||
}
|
||||
+131
-16
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
@@ -14,25 +15,33 @@ 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)
|
||||
CreateUser(ctx context.Context, user entity.CreateUser) (*entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||
Insert(ctx context.Context, user entity.User) (int, error)
|
||||
ChangeBlockStatus(ctx context.Context, userId int) (bool, error)
|
||||
}
|
||||
|
||||
type tokenRepo interface {
|
||||
UpdateStatusByUserId(ctx context.Context, userId int, status string) error
|
||||
}
|
||||
|
||||
type userRoleRepo interface {
|
||||
GetRoleById(ctx context.Context, id int) (*entity.Role, error)
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
userRepo userRepo
|
||||
userRoleRepo userRoleRepo
|
||||
tokenRepo tokenRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewUser(userRepo userRepo, userRoleRepo userRoleRepo, logger log.Logger) User {
|
||||
func NewUser(userRepo userRepo, userRoleRepo userRoleRepo, tokenRepo tokenRepo, logger log.Logger) User {
|
||||
return User{
|
||||
userRepo: userRepo,
|
||||
userRoleRepo: userRoleRepo,
|
||||
tokenRepo: tokenRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
@@ -42,6 +51,9 @@ func (u User) GetProfileById(ctx context.Context, userId int64) (*domain.AdminUs
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get user by id: %d", userId)
|
||||
}
|
||||
if user.Blocked {
|
||||
return nil, errors.Errorf("user is blocked")
|
||||
}
|
||||
|
||||
role, err := u.userRoleRepo.GetRoleById(ctx, user.RoleId)
|
||||
switch {
|
||||
@@ -59,15 +71,20 @@ func (u User) GetProfileById(ctx context.Context, userId int64) (*domain.AdminUs
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (u User) GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||
users, err := u.userRepo.GetUsers(ctx, identities.Ids, identities.Offset, identities.Limit, identities.Email)
|
||||
func (u User) GetUsers(ctx context.Context, req domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||
users, err := u.userRepo.GetUsers(ctx, req.Ids, req.Offset, req.Limit, req.Email)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users from repo")
|
||||
}
|
||||
|
||||
roleNames, err := u.roleNames(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "role names")
|
||||
}
|
||||
|
||||
items := make([]domain.User, 0, len(users))
|
||||
for _, user := range users {
|
||||
items = append(items, domain.User(user))
|
||||
items = append(items, u.toDomain(user, roleNames))
|
||||
}
|
||||
|
||||
return &domain.UsersResponse{Items: items}, err
|
||||
@@ -89,18 +106,29 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest) (*do
|
||||
return nil, errors.WithMessage(err, "crypt password")
|
||||
}
|
||||
|
||||
user, err = u.userRepo.CreateUser(ctx, entity.CreateUser{
|
||||
RoleId: req.RoleId,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Password: encryptedPassword,
|
||||
})
|
||||
roleNames, err := u.roleNames(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "role names")
|
||||
}
|
||||
|
||||
usr := entity.User{
|
||||
SudirUserId: nil,
|
||||
Id: 0,
|
||||
RoleId: req.RoleId,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Password: encryptedPassword,
|
||||
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")
|
||||
}
|
||||
|
||||
result := domain.User(*user)
|
||||
usr.Id = int64(id)
|
||||
result := u.toDomain(usr, roleNames)
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
@@ -127,10 +155,15 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*do
|
||||
if req.Password != "" {
|
||||
req.Password, err = u.cryptPassword(req.Password)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "")
|
||||
return nil, errors.WithMessage(err, "encrypt password")
|
||||
}
|
||||
}
|
||||
|
||||
roleNames, err := u.roleNames(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "role names")
|
||||
}
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
RoleId: req.RoleId,
|
||||
FirstName: req.FirstName,
|
||||
@@ -144,7 +177,7 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*do
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
}
|
||||
|
||||
result := domain.User(*user)
|
||||
result := u.toDomain(*user, roleNames)
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
@@ -160,6 +193,62 @@ func (u User) DeleteUsers(ctx context.Context, ids []int64) (int, error) {
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (u User) GetById(ctx context.Context, userId int) (*domain.User, error) {
|
||||
roleNames, err := u.roleNames(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "role names")
|
||||
}
|
||||
|
||||
user, err := u.userRepo.GetUserById(ctx, int64(userId))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get user by id %d", userId)
|
||||
}
|
||||
|
||||
result := u.toDomain(*user, roleNames)
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "revoke tokens")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u User) Roles(ctx context.Context) ([]domain.Role, error) {
|
||||
roles, err := u.userRoleRepo.All(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
|
||||
result := make([]domain.Role, 0)
|
||||
for _, role := range roles {
|
||||
desc := ""
|
||||
if role.Description != nil {
|
||||
desc = *role.Description
|
||||
}
|
||||
result = append(result, domain.Role{
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
Description: desc,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
//nolint:gomnd
|
||||
func (u User) cryptPassword(password string) (string, error) {
|
||||
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(password), 12)
|
||||
@@ -169,3 +258,29 @@ func (u User) cryptPassword(password string) (string, error) {
|
||||
|
||||
return string(passwordBytes), nil
|
||||
}
|
||||
|
||||
func (u User) toDomain(user entity.User, roleNames map[int]string) domain.User {
|
||||
return domain.User{
|
||||
Id: user.Id,
|
||||
RoleId: user.RoleId,
|
||||
RoleName: roleNames[user.RoleId],
|
||||
FirstName: user.FirstName,
|
||||
LastName: user.LastName,
|
||||
Email: user.Email,
|
||||
Blocked: user.Blocked,
|
||||
UpdatedAt: user.UpdatedAt,
|
||||
CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) roleNames(ctx context.Context) (map[int]string, error) {
|
||||
roles, err := u.userRoleRepo.All(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
result := make(map[int]string)
|
||||
for _, role := range roles {
|
||||
result[role.Id] = role.Name
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in new issue
Block a user