2024-03-25 16:24:48: merge [main:72a62d1996eb71f9a1ab21643bf294148b87ae99];
This commit is contained in:
1 parent
0669c6ec0a
commit
ed8a4eef5d
85 files changed
+7671
-93
No files matched your search
@@ -0,0 +1,79 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type AuditService interface {
|
||||
All(ctx context.Context, limit int, offset int) (*domain.AuditResponse, error)
|
||||
Events(ctx context.Context) ([]domain.AuditEvent, error)
|
||||
SetEvents(ctx context.Context, req []domain.SetAuditEvent) error
|
||||
}
|
||||
|
||||
type Audit struct {
|
||||
service AuditService
|
||||
}
|
||||
|
||||
func NewAudit(service AuditService) Audit {
|
||||
return Audit{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.PageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/all [POST]
|
||||
func (c Audit) All(ctx context.Context, req domain.PageRequest) (*domain.AuditResponse, error) {
|
||||
return c.service.All(ctx, req.Limit, req.Offset)
|
||||
}
|
||||
|
||||
// Events
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditResponse true "Тело запроса"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/events [POST]
|
||||
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
||||
return c.service.Events(ctx)
|
||||
}
|
||||
|
||||
// SetEvents
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Всегда возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SetAuditEvent true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/set_events [POST]
|
||||
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
||||
err := c.service.SetEvents(ctx, req)
|
||||
switch {
|
||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||
return status.Errorf(codes.InvalidArgument, err.Error())
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type authService interface {
|
||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
||||
Logout(ctx context.Context, adminId int64) error
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
authService authService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewAuth(authService authService, logger log.Logger) Auth {
|
||||
return Auth{
|
||||
authService: authService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Logout
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = a.authService.Logout(ctx, adminId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "logout")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Login
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthorization):
|
||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
}
|
||||
|
||||
// LoginWithSudir
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginSudirRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithSudir(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "sudir auth is not configured")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with sudir")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
}
|
||||
|
||||
func getAdminId(authData grpc.AuthData) (int64, error) {
|
||||
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
|
||||
adminId, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
||||
}
|
||||
|
||||
return int64(adminId), nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
type Customization struct {
|
||||
uiCfg conf.UIDesign
|
||||
}
|
||||
|
||||
func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||
return Customization{
|
||||
uiCfg: uiCfg,
|
||||
}
|
||||
}
|
||||
|
||||
// GetUIDesign
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} conf.UIDesign
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_design [POST]
|
||||
func (c Customization) GetUIDesign() (conf.UIDesign, error) {
|
||||
return c.uiCfg, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type permissionsService interface {
|
||||
All(ctx context.Context) []domain.Permission
|
||||
}
|
||||
|
||||
type Permissions struct {
|
||||
permissionsService permissionsService
|
||||
}
|
||||
|
||||
func NewPermissions(permissionsService permissionsService) Permissions {
|
||||
return Permissions{
|
||||
permissionsService: permissionsService,
|
||||
}
|
||||
}
|
||||
|
||||
// GetPermissions
|
||||
// @Tags user
|
||||
// @Summary Получить все разрашения
|
||||
// @Description Получить все разрашения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
||||
return u.permissionsService.All(ctx)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
All(ctx context.Context) ([]domain.Role, error)
|
||||
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
roleService roleService
|
||||
}
|
||||
|
||||
func NewRole(roleService roleService) Role {
|
||||
return Role{
|
||||
roleService: roleService,
|
||||
}
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// CreateRole
|
||||
// @Tags user
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
role, err := u.roleService.Create(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create role")
|
||||
default:
|
||||
return role, nil
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateRole
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := u.roleService.Update(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "role not found")
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update role")
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteRole
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = u.roleService.Delete(ctx, req, adminId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc/apierrors"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
Authenticate(ctx context.Context, token string) (int64, error)
|
||||
Authorize(ctx context.Context, adminId int, permission string) (bool, error)
|
||||
}
|
||||
|
||||
type Secure struct {
|
||||
service SecureService
|
||||
}
|
||||
|
||||
func NewSecure(service SecureService) Secure {
|
||||
return Secure{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authenticate [POST]
|
||||
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
||||
adminId, err := s.service.Authenticate(ctx, req.Token)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrTokenExpired):
|
||||
return &domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
ErrorReason: domain.ErrTokenExpired.Error(),
|
||||
AdminId: 0,
|
||||
}, nil
|
||||
case errors.Is(err, domain.ErrTokenNotFound):
|
||||
return &domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
ErrorReason: domain.ErrTokenNotFound.Error(),
|
||||
AdminId: 0,
|
||||
}, nil
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
return &domain.SecureAuthResponse{
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AdminId: adminId,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Authorize
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authorize [POST]
|
||||
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
||||
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
||||
if err != nil {
|
||||
return nil, apierrors.NewInternalServiceError(err)
|
||||
}
|
||||
return &domain.SecureAuthzResponse{
|
||||
Authorized: ok,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SessionService interface {
|
||||
All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error)
|
||||
Revoke(ctx context.Context, id int) error
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
service SessionService
|
||||
}
|
||||
|
||||
func NewSession(service SessionService) Session {
|
||||
return Session{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.PageRequest
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/all [POST]
|
||||
func (c Session) All(ctx context.Context, req domain.PageRequest) (*domain.SessionResponse, error) {
|
||||
return c.service.All(ctx, req.Limit, req.Offset)
|
||||
}
|
||||
|
||||
// Revoke
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/revoke [POST]
|
||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||
return c.service.Revoke(ctx, req.Id)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
GetProfileById(ctx context.Context, userId int64) (*domain.AdminUserShort, error)
|
||||
GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error)
|
||||
CreateUser(ctx context.Context, req domain.CreateUserRequest, adminId int64) (*domain.User, error)
|
||||
UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error)
|
||||
DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error)
|
||||
Block(ctx context.Context, adminId int64, userId int) error
|
||||
GetById(ctx context.Context, userId int) (*domain.User, error)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
userService userService
|
||||
}
|
||||
|
||||
func NewUser(userService userService) User {
|
||||
return User{
|
||||
userService: userService,
|
||||
}
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get profile")
|
||||
default:
|
||||
return profile, nil
|
||||
}
|
||||
}
|
||||
|
||||
// GetUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_users [POST]
|
||||
func (u User) GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||
users, err := u.userService.GetUsers(ctx, identities)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// CreateUser
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
default:
|
||||
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, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteUser
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
deletedCount, err := u.userService.DeleteUsers(ctx, identities.Ids, adminId)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "delete")
|
||||
}
|
||||
|
||||
return &domain.DeleteResponse{Deleted: deletedCount}, nil
|
||||
}
|
||||
|
||||
// Block
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = u.userService.Block(ctx, adminId, identities.UserId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "block")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetById
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_by_id [POST]
|
||||
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
||||
return u.userService.GetById(ctx, identities.UserId)
|
||||
}
|
||||
Reference in new issue
Block a user