MSP-1068 refactor user controller
This commit is contained in:
1 parent
7be37bc52d
commit
4e6b21a7d9
1 file changed
+103
-258
+103
-258
@@ -1,313 +1,158 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"context"
|
||||||
|
|
||||||
"github.com/integration-system/isp-lib/v2/config"
|
|
||||||
"github.com/integration-system/isp-lib/v2/utils"
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"google.golang.org/grpc/metadata"
|
"google.golang.org/grpc/metadata"
|
||||||
"google.golang.org/grpc/status"
|
"google.golang.org/grpc/status"
|
||||||
"msp-admin-service/conf"
|
"msp-admin-service/domain"
|
||||||
"msp-admin-service/entity"
|
|
||||||
"msp-admin-service/invoker/sudir"
|
|
||||||
"msp-admin-service/model"
|
|
||||||
"msp-admin-service/service"
|
|
||||||
"msp-admin-service/structure"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const adminAuthHeaderName = "x-auth-admin"
|
type userService interface {
|
||||||
|
GetProfileByToken(ctx context.Context, token string) (*domain.AdminUserShort, error)
|
||||||
const (
|
GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error)
|
||||||
ValidationError = "Validation errors"
|
CreateUser(ctx context.Context, req domain.CreateUserRequest) (*domain.User, error)
|
||||||
)
|
UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*domain.User, error)
|
||||||
|
DeleteUsers(ctx context.Context, ids []int64) (int, error)
|
||||||
// @Tags auth
|
|
||||||
// @Summary Выход из авторизованной сессии
|
|
||||||
// @Description Выход из авторизованной сессии администрирования
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
|
||||||
// @Success 200
|
|
||||||
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
|
|
||||||
// @Failure 500 {object} structure.GrpcError
|
|
||||||
// @Router /auth/logout [POST]
|
|
||||||
func Logout(_ metadata.MD) error {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
userService userService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUser(userService userService) User {
|
||||||
|
return User{
|
||||||
|
userService: userService,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetProfile
|
||||||
// @Tags user
|
// @Tags user
|
||||||
// @Summary Получить профиль
|
// @Summary Получить профиль
|
||||||
// @Description Получить данные профиля
|
// @Description Получить данные профиля
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Success 200 {object} structure.AdminUserShort
|
// @Success 200 {object} domain.AdminUserShort
|
||||||
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 401 {object} structure.GrpcError "Токен не соответствует ни одному пользователю"
|
// @Failure 401 {object} domain.GrpcError "Токен не соответствует ни одному пользователю"
|
||||||
// @Failure 500 {object} structure.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/get_profile [POST]
|
// @Router /user/get_profile [POST]
|
||||||
func GetProfile(metadata metadata.MD) (*structure.AdminUserShort, error) {
|
func (u User) GetProfile(ctx context.Context, metadata metadata.MD) (*domain.AdminUserShort, error) {
|
||||||
token := metadata.Get(adminAuthHeaderName)
|
token := metadata.Get(domain.AdminAuthHeaderName)
|
||||||
userId, err := service.GetUserId(token[0])
|
if len(token) == 0 {
|
||||||
if err != nil {
|
return nil, status.Error(codes.InvalidArgument, "Невалидный токен")
|
||||||
return nil, status.Error(codes.Unauthenticated, "Invalid auth token")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := model.GetUserById(userId)
|
profile, err := u.userService.GetProfileByToken(ctx, token[0])
|
||||||
if err != nil {
|
|
||||||
return nil, errors.WithMessagef(err, "get user by id %d", userId)
|
|
||||||
}
|
|
||||||
|
|
||||||
role, err := model.RoleRep.GetRoleById(user.RoleId)
|
switch {
|
||||||
if err != nil {
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, errors.WithMessagef(err, "get role by id %d", user.RoleId)
|
return nil, status.Error(codes.Unauthenticated, "Токен не соответствует ни одному пользователю")
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessage(err, "get profile")
|
||||||
|
default:
|
||||||
|
return profile, nil
|
||||||
}
|
}
|
||||||
if role == nil {
|
|
||||||
return nil, errors.Errorf("unexpected role id %d", user.RoleId)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &structure.AdminUserShort{
|
|
||||||
Image: user.Image,
|
|
||||||
FirstName: user.FirstName,
|
|
||||||
LastName: user.LastName,
|
|
||||||
Email: user.Email,
|
|
||||||
Phone: user.Phone,
|
|
||||||
Role: role.Name,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// @Tags auth
|
|
||||||
// @Summary Авторизация по логину и паролю
|
|
||||||
// @Description Авторизация с получением токена администратора
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body structure.AuthRequest true "Тело запроса"
|
|
||||||
// @Success 200 {object} structure.Auth
|
|
||||||
// @Failure 400 {object} structure.GrpcError
|
|
||||||
// @Failure 401 {object} structure.GrpcError "Данные для авторизации не верны"
|
|
||||||
// @Failure 404 {object} structure.GrpcError "Пользователь не найден"
|
|
||||||
// @Failure 500 {object} structure.GrpcError
|
|
||||||
// @Router /auth/login [POST]
|
|
||||||
func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
|
|
||||||
user, err := model.GetUserByEmail(authRequest.Email)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
} else if user == nil {
|
|
||||||
return nil, status.Error(codes.NotFound, "User not found")
|
|
||||||
} else if user.SudirUserId != "" {
|
|
||||||
return nil, status.Error(codes.InvalidArgument, "User is authorized only with SUDIR")
|
|
||||||
}
|
|
||||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authRequest.Password))
|
|
||||||
if err != nil {
|
|
||||||
return nil, status.Error(codes.Unauthenticated, "Email or password is incorrect")
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenString, expired, err := service.GenerateToken(user.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &structure.Auth{
|
|
||||||
Token: tokenString,
|
|
||||||
Expired: expired,
|
|
||||||
HeaderName: adminAuthHeaderName,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// @Tags auth
|
|
||||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
|
||||||
// @Description Авторизация с получением токена администратора
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body structure.SudirAuthRequest true "Тело запроса"
|
|
||||||
// @Success 200 {object} structure.Auth
|
|
||||||
// @Failure 401 {object} structure.GrpcError "Некорректный код для авторизации"
|
|
||||||
// @Failure 412 {object} structure.GrpcError "Авторизация СУДИР не настроена на сервере"
|
|
||||||
// @Failure 500 {object} structure.GrpcError
|
|
||||||
// @Router /auth/login_with_sudir [POST]
|
|
||||||
func LoginWithSudir(request structure.SudirAuthRequest) (*structure.Auth, error) {
|
|
||||||
remoteConfig := config.GetRemote().(*conf.RemoteConfig)
|
|
||||||
if remoteConfig.SudirAuth == nil {
|
|
||||||
return nil, status.Error(codes.FailedPrecondition, "SUDIR authorization is not configured on the server")
|
|
||||||
}
|
|
||||||
|
|
||||||
sudirUser, err := service.AuthSudir(*remoteConfig.SudirAuth, request.AuthCode)
|
|
||||||
var authErr *sudir.SudirAuthError
|
|
||||||
if errors.As(err, &authErr) {
|
|
||||||
return nil, status.Error(codes.Unauthenticated, err.Error())
|
|
||||||
} else if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if sudirUser.SudirUserId == "" || sudirUser.Email == "" {
|
|
||||||
return nil, status.Errorf(codes.Unauthenticated, "missing sudirUserId '%s' or email '%s'", sudirUser.SudirUserId, sudirUser.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
existedUser, err := model.GetUserBySudirUserId(sudirUser.SudirUserId)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if existedUser != nil {
|
|
||||||
sudirUser = *existedUser
|
|
||||||
} else {
|
|
||||||
sudirUser, err = model.CreateUser(sudirUser)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tokenString, expired, err := service.GenerateToken(sudirUser.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &structure.Auth{
|
|
||||||
Token: tokenString,
|
|
||||||
Expired: expired,
|
|
||||||
HeaderName: adminAuthHeaderName,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetUsers
|
||||||
// @Tags user
|
// @Tags user
|
||||||
// @Summary Список пользователей
|
// @Summary Список пользователей
|
||||||
// @Description Получить список пользователей
|
// @Description Получить список пользователей
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param body body structure.UsersRequest true "Тело запроса"
|
// @Param body body domain.UsersRequest true "Тело запроса"
|
||||||
// @Success 200 {object} structure.UsersResponse
|
// @Success 200 {object} domain.UsersResponse
|
||||||
// @Failure 400 {object} structure.GrpcError
|
// @Failure 400 {object} domain.GrpcError
|
||||||
// @Failure 500 {object} structure.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/get_users [POST]
|
// @Router /user/get_users [POST]
|
||||||
func GetUsers(identities structure.UsersRequest) (*structure.UsersResponse, error) {
|
func (u User) GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||||
users, err := model.GetUsers(identities)
|
users, err := u.userService.GetUsers(ctx, identities)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, errors.WithMessage(err, "get users")
|
||||||
}
|
}
|
||||||
for i := range *users {
|
|
||||||
(*users)[i].Password = ""
|
return users, nil
|
||||||
}
|
|
||||||
return &structure.UsersResponse{Items: users}, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateUser
|
||||||
// @Tags user
|
// @Tags user
|
||||||
// @Summary Создать/Обновить пользователя
|
// @Summary Создать пользователя
|
||||||
// @Description Создать пользователя или обновить данные существующего
|
// @Description Создать пользователя
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param body body entity.AdminUser true "Тело запроса"
|
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||||
// @Success 200 {object} entity.AdminUser
|
// @Success 200 {object} domain.User
|
||||||
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} structure.GrpcError
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
// @Router /user/create_update_user [POST]
|
// @Failure 500 {object} domain.GrpcError
|
||||||
func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
// @Router /user/create_user [POST]
|
||||||
if user.Id == 0 {
|
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest) (*domain.User, error) {
|
||||||
if user.Password == "" {
|
user, err := u.userService.CreateUser(ctx, req)
|
||||||
validationErrors := map[string]string{"password": "Required"}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
} else if user.SudirUserId != "" {
|
|
||||||
validationErrors := map[string]string{"sudirUserId": "Could not create user with sudirUserId"}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
}
|
|
||||||
|
|
||||||
userExists, err := model.GetUserByEmail(user.Email)
|
switch {
|
||||||
if err != nil {
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, err
|
return nil, status.Error(codes.AlreadyExists, "Пользователь с указанным email уже существует")
|
||||||
}
|
case err != nil:
|
||||||
if userExists != nil && userExists.Id != 0 {
|
return nil, errors.WithMessage(err, "create user")
|
||||||
validationErrors := map[string]string{
|
default:
|
||||||
"email": fmt.Sprintf("User with email: %s already exists", user.Email),
|
return user, nil
|
||||||
}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.AlreadyExists,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = cryptPassword(&user)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err = model.CreateUser(user)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
userExists, err := model.GetUserById(user.Id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if userExists.Id == 0 {
|
|
||||||
validationErrors := map[string]string{
|
|
||||||
"id": fmt.Sprintf("User with id: %d not found", user.Id),
|
|
||||||
}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.NotFound,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
} else if userExists.SudirUserId != user.SudirUserId {
|
|
||||||
validationErrors := map[string]string{"sudirUserId": "Could not change sudirUserId of an existing user"}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
} else if user.Password != "" && user.SudirUserId != "" {
|
|
||||||
validationErrors := map[string]string{"password": "Could not set password of a user logged in with SUDIR"}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
}
|
|
||||||
|
|
||||||
if user.Password != "" {
|
|
||||||
err = cryptPassword(&user)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err = model.UpdateUser(user)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
user.CreatedAt = userExists.CreatedAt
|
|
||||||
user.UpdatedAt = userExists.UpdatedAt
|
|
||||||
}
|
}
|
||||||
|
|
||||||
user.Password = ""
|
|
||||||
|
|
||||||
return &user, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateUser
|
||||||
|
// @Tags user
|
||||||
|
// @Summary Обновить пользователя
|
||||||
|
// @Description Обновить данные существующего пользователя
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
|
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||||
|
// @Success 200 {object} domain.User
|
||||||
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
|
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||||
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
|
// @Failure 500 {object} domain.GrpcError
|
||||||
|
// @Router /user/update_user [POST]
|
||||||
|
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||||
|
result, err := u.userService.UpdateUser(ctx, req)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
|
return nil, status.Error(codes.NotFound, "Пользователь с указанным id не существует")
|
||||||
|
case errors.Is(err, domain.ErrInvalid):
|
||||||
|
return nil, status.Error(codes.InvalidArgument, "Пользователь авторизован через СУДИР, смена пароля для него запрещена")
|
||||||
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
|
return nil, status.Error(codes.AlreadyExists, "Пользователь с указанным email уже существует")
|
||||||
|
case err != nil:
|
||||||
|
return nil, errors.WithMessage(err, "update user")
|
||||||
|
default:
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteUser
|
||||||
// @Tags user
|
// @Tags user
|
||||||
// @Summary Удалить пользователя
|
// @Summary Удалить пользователя
|
||||||
// @Description Удалить существующего пользователя
|
// @Description Удалить существующего пользователя
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||||
// @Param body body structure.IdentitiesRequest true "Тело запроса"
|
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||||
// @Success 200 {object} structure.DeleteResponse
|
// @Success 200 {object} domain.DeleteResponse
|
||||||
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} structure.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/delete_user [POST]
|
// @Router /user/delete_user [POST]
|
||||||
func DeleteUser(identities structure.IdentitiesRequest) (*structure.DeleteResponse, error) {
|
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||||
if len(identities.Ids) == 0 {
|
deletedCount, err := u.userService.DeleteUsers(ctx, identities.Ids)
|
||||||
validationErrors := map[string]string{
|
|
||||||
"ids": "Required",
|
|
||||||
}
|
|
||||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
|
||||||
ValidationError, validationErrors)
|
|
||||||
}
|
|
||||||
count, err := model.DeleteUser(identities)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, errors.WithMessage(err, "delete")
|
||||||
}
|
}
|
||||||
return &structure.DeleteResponse{Deleted: count}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func cryptPassword(user *entity.AdminUser) error {
|
return &domain.DeleteResponse{Deleted: deletedCount}, nil
|
||||||
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(user.Password), 12)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
user.Password = string(passwordBytes)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user