Merge branch 'MSP-1538' into 'master'
Resolve MSP-1538 Closes MSP-1538 See merge request msp2.0/msp-admin-service!17
This commit is contained in:
commit
a355338d40
38 files changed
+1581
-1809
No files matched your search
@@ -20,7 +20,6 @@ linters:
|
||||
- govet
|
||||
- nakedret
|
||||
- nestif
|
||||
- nolintlint
|
||||
- prealloc
|
||||
- rowserrcheck
|
||||
- staticcheck
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
### v4.3.0
|
||||
* реализован метод получения списка доступных ролей
|
||||
* реализован метод блокировки пользователей
|
||||
* реализован метод отзыва сессии
|
||||
* реализован метод получения списка сессий
|
||||
* реализован сбор аудита
|
||||
* реализован метод просмотра журнала аудита
|
||||
* роли полученные от СУДИР сохраняются автоматически
|
||||
* профиль администратора полученный от СУДИР обновляются автоматически
|
||||
* реализована блокировка УЗ при неактивности больше n дней
|
||||
* обновлены зависимости
|
||||
* добавлены SQL метрики
|
||||
### v4.2.0
|
||||
* добавлена защита от брутфорса админ пароля
|
||||
### v4.1.1
|
||||
|
||||
+14
-2
@@ -2,6 +2,7 @@ package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/app"
|
||||
"github.com/integration-system/isp-kit/bootstrap"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/http/httpclix"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/integration-system/isp-kit/worker"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
@@ -21,6 +23,7 @@ type Assembly struct {
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
httpCli *httpcli.Client
|
||||
worker *worker.Worker
|
||||
logger *log.Adapter
|
||||
}
|
||||
|
||||
@@ -55,9 +58,18 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
}
|
||||
|
||||
locator := NewLocator(a.logger, a.httpCli, a.db)
|
||||
handler := locator.Handler(newCfg)
|
||||
config := locator.Config(newCfg)
|
||||
|
||||
a.server.Upgrade(handler)
|
||||
a.server.Upgrade(config.Handler)
|
||||
|
||||
if a.worker != nil {
|
||||
a.worker.Shutdown()
|
||||
}
|
||||
a.worker = worker.New(
|
||||
config.InactiveBlocker,
|
||||
worker.WithInterval(time.Duration(newCfg.BlockInactiveWorker.RunIntervalInMinutes)*time.Minute),
|
||||
)
|
||||
a.worker.Run(a.boot.App.Context())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+33
-3
@@ -11,6 +11,7 @@ import (
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/routes"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/worker"
|
||||
)
|
||||
|
||||
type Locator struct {
|
||||
@@ -27,26 +28,42 @@ func NewLocator(logger log.Logger, httpCli *httpcli.Client, db db.DB) Locator {
|
||||
}
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Handler isp.BackendServiceServer
|
||||
InactiveBlocker worker.InactiveBlocker
|
||||
}
|
||||
|
||||
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
|
||||
return l.Config(cfg).Handler
|
||||
}
|
||||
|
||||
func (l Locator) Config(cfg conf.Remote) Config {
|
||||
sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth)
|
||||
roleRepo := repository.NewRole(l.db)
|
||||
userRepo := repository.NewUser(l.db)
|
||||
tokenRepo := repository.NewToken(l.db)
|
||||
auditRepo := repository.NewAudit(l.db)
|
||||
|
||||
auditService := service.NewAudit(auditRepo, l.logger)
|
||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo, roleRepo)
|
||||
userService := service.NewUser(userRepo, roleRepo, l.logger)
|
||||
authService := service.NewAuth(userRepo,
|
||||
userService := service.NewUser(userRepo, roleRepo, tokenRepo, l.logger)
|
||||
authService := service.NewAuth(
|
||||
userRepo,
|
||||
tokenService,
|
||||
sudirService,
|
||||
auditService,
|
||||
l.logger,
|
||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||
)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
authController := controller.NewAuth(authService, l.logger)
|
||||
secureController := controller.NewSecure(tokenService)
|
||||
sessionController := controller.NewSession(tokenService)
|
||||
auditController := controller.NewAudit(auditService)
|
||||
|
||||
handler := routes.Handler(
|
||||
endpoint.DefaultWrapper(l.logger),
|
||||
@@ -55,8 +72,21 @@ func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
|
||||
Customization: customizationController,
|
||||
Auth: authController,
|
||||
Secure: secureController,
|
||||
Session: sessionController,
|
||||
Audit: auditController,
|
||||
},
|
||||
)
|
||||
|
||||
return handler
|
||||
inactiveBlocker := worker.NewInactiveBlocker(
|
||||
tokenRepo,
|
||||
userRepo,
|
||||
auditService,
|
||||
cfg.BlockInactiveWorker.DaysThreshold,
|
||||
l.logger,
|
||||
)
|
||||
|
||||
return Config{
|
||||
Handler: handler,
|
||||
InactiveBlocker: inactiveBlocker,
|
||||
}
|
||||
}
|
||||
@@ -12,5 +12,9 @@
|
||||
"maxInFlightLoginRequests" : 3,
|
||||
"delayLoginRequestInSec": 3
|
||||
},
|
||||
"expireSec": 3600
|
||||
"expireSec": 3600,
|
||||
"blockInactiveWorker" : {
|
||||
"daysThreshold": 90,
|
||||
"runIntervalInMinutes": 60
|
||||
}
|
||||
}
|
||||
+12
-6
@@ -17,12 +17,13 @@ func init() {
|
||||
}
|
||||
|
||||
type Remote struct {
|
||||
Database dbx.Config
|
||||
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||
Database dbx.Config
|
||||
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||
BlockInactiveWorker BlockInactiveWorker `valid:"required" schema:"Блокировка неактивных УЗ"`
|
||||
}
|
||||
|
||||
type UIDesign struct {
|
||||
@@ -41,3 +42,8 @@ type AntiBruteforce struct {
|
||||
MaxInFlightLoginRequests int `valid:"required~Required" schema:"Количество одновременных запросов /login"`
|
||||
DelayLoginRequestInSec int `valid:"required~Required" schema:"Задержка выполнения /login"`
|
||||
}
|
||||
|
||||
type BlockInactiveWorker struct {
|
||||
DaysThreshold int `valid:"required" schema:"Кол-во дней"`
|
||||
RunIntervalInMinutes int `valid:"required" schema:"Интервал запуска,в минутах"`
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/integration-system/isp-kit/test/rct"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
func TestDefaultRemoteConfig(t *testing.T) {
|
||||
t.Parallel()
|
||||
rct.Test(t, "default_remote_config.json", conf.Remote{})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type AuditService interface {
|
||||
All(ctx context.Context, limit int, offset int) (*domain.AuditResponse, 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.AuditResponse true "Тело запроса"
|
||||
// @Success 200 {object} domain.PageRequest
|
||||
// @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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -18,6 +18,9 @@ type userService interface {
|
||||
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)
|
||||
Block(ctx context.Context, userId int) error
|
||||
Roles(ctx context.Context) ([]domain.Role, error)
|
||||
GetById(ctx context.Context, userId int) (*domain.User, error)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
@@ -55,6 +58,8 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
||||
profile, err := u.userService.GetProfileById(ctx, int64(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:
|
||||
@@ -162,3 +167,55 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques
|
||||
|
||||
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, identities domain.IdRequest) error {
|
||||
err := u.userService.Block(ctx, identities.UserId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "block")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRoles
|
||||
// @Tags user
|
||||
// @Summary Список доступных ролей
|
||||
// @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 /user/get_roles [POST]
|
||||
func (u User) GetRoles(ctx context.Context) ([]domain.Role, error) {
|
||||
users, err := u.userService.Roles(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
return users, 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)
|
||||
}
|
||||
-800
@@ -1,800 +0,0 @@
|
||||
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
|
||||
// This file was generated by swaggo/swag
|
||||
package docs
|
||||
|
||||
import "github.com/integration-system/isp-lib/v2/docs"
|
||||
|
||||
var doc = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{.Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"contact": {},
|
||||
"license": {
|
||||
"name": "GNU GPL v3.0"
|
||||
},
|
||||
"version": "{{.Version}}"
|
||||
},
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/auth/login": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Авторизация по логину и паролю",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LoginRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LoginResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Данные для авторизации не верны",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/auth/login_with_sudir": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Авторизация по авторизационному коду от СУДИР",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LoginSudirRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LoginResponse"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Некорректный код для авторизации",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация СУДИР не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/auth/logout": {
|
||||
"post": {
|
||||
"description": "Выход из авторизованной сессии администрирования",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Выход из авторизованной сессии",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": ""
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/secure/authenticate": {
|
||||
"post": {
|
||||
"description": "Проверяет токен и возвращает идентификатор администратора",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"secure"
|
||||
],
|
||||
"summary": "Метод аутентификации токена",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.SecureAuthRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.SecureAuthResponse"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/create_user": {
|
||||
"post": {
|
||||
"description": "Создать пользователя",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Создать пользователя",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.CreateUserRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/delete_user": {
|
||||
"post": {
|
||||
"description": "Удалить существующего пользователя",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Удалить пользователя",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.IdentitiesRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.DeleteResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/get_design": {
|
||||
"post": {
|
||||
"description": "Получение внешнего вида (палитра и наименование) админ-интерфейса",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Получение внешнего вида",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/conf.UIDesign"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/get_profile": {
|
||||
"post": {
|
||||
"description": "Получить данные профиля",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Получить профиль",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.AdminUserShort"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователя не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/get_users": {
|
||||
"post": {
|
||||
"description": "Получить список пользователей",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Список пользователей",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UsersRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UsersResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/update_user": {
|
||||
"post": {
|
||||
"description": "Обновить данные существующего пользователя",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Обновить пользователя",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UpdateUserRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователь с указанным id не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"conf.UIDesign": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"primaryColor": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.AdminUserShort": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"role": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.CreateUserRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"password"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"roleId": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.DeleteResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"deleted": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.GrpcError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"details": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"errorCode": {
|
||||
"type": "string"
|
||||
},
|
||||
"errorMessage": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.IdentitiesRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ids"
|
||||
],
|
||||
"properties": {
|
||||
"ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
"password"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"expired": {
|
||||
"type": "string"
|
||||
},
|
||||
"headerName": {
|
||||
"type": "string"
|
||||
},
|
||||
"token": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginSudirRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authCode"
|
||||
],
|
||||
"properties": {
|
||||
"authCode": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.SecureAuthRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"token": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.SecureAuthResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"adminId": {
|
||||
"type": "integer"
|
||||
},
|
||||
"authenticated": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"errorReason": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.UpdateUserRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"roleId": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.User": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"createdAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"roleId": {
|
||||
"type": "integer"
|
||||
},
|
||||
"sudirUserId": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.UsersRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.UsersResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||
var SwaggerInfo = docs.SwaggerInfo{
|
||||
Version: "1.0.0",
|
||||
Host: "localhost:9000",
|
||||
BasePath: "/api/admin",
|
||||
Schemes: []string{},
|
||||
Title: "msp-admin-service",
|
||||
Description: "сервис администрирования",
|
||||
}
|
||||
|
||||
func init() {
|
||||
docs.InitSwagger(SwaggerInfo, doc)
|
||||
}
|
||||
+258
-4
@@ -20,6 +20,26 @@ definitions:
|
||||
required:
|
||||
- email
|
||||
type: object
|
||||
domain.Audit:
|
||||
properties:
|
||||
createdAt:
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
message:
|
||||
type: string
|
||||
userId:
|
||||
type: integer
|
||||
type: object
|
||||
domain.AuditResponse:
|
||||
properties:
|
||||
items:
|
||||
items:
|
||||
$ref: '#/definitions/domain.Audit'
|
||||
type: array
|
||||
totalCount:
|
||||
type: integer
|
||||
type: object
|
||||
domain.CreateUserRequest:
|
||||
properties:
|
||||
email:
|
||||
@@ -52,6 +72,13 @@ definitions:
|
||||
errorMessage:
|
||||
type: string
|
||||
type: object
|
||||
domain.IdRequest:
|
||||
properties:
|
||||
userId:
|
||||
type: integer
|
||||
required:
|
||||
- userId
|
||||
type: object
|
||||
domain.IdentitiesRequest:
|
||||
properties:
|
||||
ids:
|
||||
@@ -87,6 +114,35 @@ definitions:
|
||||
required:
|
||||
- authCode
|
||||
type: object
|
||||
domain.PageRequest:
|
||||
properties:
|
||||
limit:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
required:
|
||||
- limit
|
||||
type: object
|
||||
domain.RevokeRequest:
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
type: object
|
||||
domain.Role:
|
||||
properties:
|
||||
createdAt:
|
||||
type: string
|
||||
description:
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
name:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
type: object
|
||||
domain.SecureAuthRequest:
|
||||
properties:
|
||||
token:
|
||||
@@ -101,6 +157,13 @@ definitions:
|
||||
errorReason:
|
||||
type: string
|
||||
type: object
|
||||
domain.SessionRequest:
|
||||
properties:
|
||||
limit:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
type: object
|
||||
domain.UpdateUserRequest:
|
||||
properties:
|
||||
email:
|
||||
@@ -120,6 +183,8 @@ definitions:
|
||||
type: object
|
||||
domain.User:
|
||||
properties:
|
||||
blocked:
|
||||
type: boolean
|
||||
createdAt:
|
||||
type: string
|
||||
email:
|
||||
@@ -130,11 +195,9 @@ definitions:
|
||||
type: integer
|
||||
lastName:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
roleId:
|
||||
type: integer
|
||||
sudirUserId:
|
||||
roleName:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
@@ -162,7 +225,7 @@ definitions:
|
||||
host: localhost:9000
|
||||
info:
|
||||
contact: {}
|
||||
description: сервис администрирования
|
||||
description: сервис управления администраторами
|
||||
license:
|
||||
name: GNU GPL v3.0
|
||||
title: msp-admin-service
|
||||
@@ -263,6 +326,40 @@ paths:
|
||||
summary: Выход из авторизованной сессии
|
||||
tags:
|
||||
- auth
|
||||
/log/all:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.AuditResponse'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/domain.PageRequest'
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получение списка логов
|
||||
tags:
|
||||
- log
|
||||
/secure/authenticate:
|
||||
post:
|
||||
consumes:
|
||||
@@ -294,6 +391,104 @@ paths:
|
||||
summary: Метод аутентификации токена
|
||||
tags:
|
||||
- secure
|
||||
/session/all:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.SessionRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/domain.PageRequest'
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получение списка сессий
|
||||
tags:
|
||||
- session
|
||||
/session/revoke:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.RevokeRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: ""
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Отзыв сессии
|
||||
tags:
|
||||
- session
|
||||
/user/block_user:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.IdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: ""
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Метод блокировки/разблокировки пользователя
|
||||
tags:
|
||||
- user
|
||||
/user/create_user:
|
||||
post:
|
||||
consumes:
|
||||
@@ -368,6 +563,35 @@ paths:
|
||||
summary: Удалить пользователя
|
||||
tags:
|
||||
- user
|
||||
/user/get_by_id:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.IdRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/domain.User'
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Метод получения данных по пользователю
|
||||
tags:
|
||||
- user
|
||||
/user/get_design:
|
||||
post:
|
||||
consumes:
|
||||
@@ -430,6 +654,36 @@ paths:
|
||||
summary: Получить профиль
|
||||
tags:
|
||||
- user
|
||||
/user/get_roles:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/domain.Role'
|
||||
type: array
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Список доступных ролей
|
||||
tags:
|
||||
- user
|
||||
/user/get_users:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Audit struct {
|
||||
Id int
|
||||
UserId int
|
||||
Message string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AuditResponse struct {
|
||||
TotalCount int
|
||||
Items []Audit
|
||||
}
|
||||
|
||||
type PageRequest struct {
|
||||
Limit int `valid:"required"`
|
||||
Offset int
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int
|
||||
UserId int
|
||||
Status string
|
||||
ExpiredAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
TotalCount int
|
||||
Items []Session
|
||||
}
|
||||
|
||||
type SessionRequest struct {
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
type RevokeRequest struct {
|
||||
Id int `valid:"required"`
|
||||
}
|
||||
+21
-9
@@ -5,15 +5,15 @@ import (
|
||||
)
|
||||
|
||||
type User struct {
|
||||
SudirUserId *string `json:",omitempty"`
|
||||
Id int64
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string `json:",omitempty"`
|
||||
UpdatedAt time.Time
|
||||
CreatedAt time.Time
|
||||
Id int64
|
||||
RoleId int
|
||||
RoleName string
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Blocked bool
|
||||
UpdatedAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UsersResponse struct {
|
||||
@@ -58,3 +58,15 @@ type DeleteResponse struct {
|
||||
type IdentitiesRequest struct {
|
||||
Ids []int64 `valid:"required"`
|
||||
}
|
||||
|
||||
type IdRequest struct {
|
||||
UserId int `valid:"required"`
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
Id int
|
||||
Name string
|
||||
Description string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type Audit struct {
|
||||
Id int
|
||||
UserId int
|
||||
Message string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
const (
|
||||
TokenStatusAllowed = "ALLOWED"
|
||||
TokenStatusRevoked = "REVOKED"
|
||||
TokenStatusExpired = "EXPIRED"
|
||||
)
|
||||
|
||||
type Token struct {
|
||||
Id int
|
||||
Token string
|
||||
UserId int64
|
||||
Status string
|
||||
|
||||
+1
-8
@@ -10,6 +10,7 @@ type User struct {
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
Blocked bool
|
||||
UpdatedAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -22,14 +23,6 @@ type SudirUser struct {
|
||||
Email string
|
||||
}
|
||||
|
||||
type CreateUser struct {
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
type UpdateUser struct {
|
||||
RoleId int
|
||||
FirstName string
|
||||
|
||||
@@ -4,82 +4,68 @@ go 1.19
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.3
|
||||
github.com/integration-system/isp-kit v1.12.2
|
||||
github.com/integration-system/isp-lib/v2 v2.8.7
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/integration-system/isp-kit v1.17.0
|
||||
github.com/integration-system/jsonschema v1.0.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.8.0
|
||||
golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b
|
||||
golang.org/x/sync v0.0.0-20220907140024-f12130a52804
|
||||
google.golang.org/grpc v1.50.0
|
||||
github.com/stretchr/testify v1.8.1
|
||||
golang.org/x/crypto v0.6.0
|
||||
golang.org/x/sync v0.1.0
|
||||
google.golang.org/grpc v1.53.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.5.4 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.19.5 // indirect
|
||||
github.com/go-openapi/spec v0.20.0 // indirect
|
||||
github.com/go-openapi/swag v0.19.12 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/iancoleman/strcase v0.2.0 // indirect
|
||||
github.com/integration-system/bellows v1.0.1 // indirect
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.13.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.3.1 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.12.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.17.2 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.3.0 // indirect
|
||||
github.com/jmoiron/sqlx v1.3.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.15.11 // indirect
|
||||
github.com/klauspost/compress v1.15.15 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/magiconair/properties v1.8.6 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.2 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/pressly/goose v2.7.0+incompatible // indirect
|
||||
github.com/prometheus/client_golang v1.13.0 // indirect
|
||||
github.com/prometheus/client_model v0.2.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/spf13/afero v1.9.2 // indirect
|
||||
github.com/prometheus/client_golang v1.14.0 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.39.0 // indirect
|
||||
github.com/prometheus/procfs v0.9.0 // indirect
|
||||
github.com/spf13/afero v1.9.3 // indirect
|
||||
github.com/spf13/cast v1.5.0 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/viper v1.13.0 // indirect
|
||||
github.com/subosito/gotenv v1.4.1 // indirect
|
||||
github.com/swaggo/swag v1.7.0 // indirect
|
||||
github.com/spf13/viper v1.15.0 // indirect
|
||||
github.com/subosito/gotenv v1.4.2 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.8.0 // indirect
|
||||
go.uber.org/zap v1.23.0 // indirect
|
||||
golang.org/x/net v0.0.0-20221004154528-8021a29435af // indirect
|
||||
golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
golang.org/x/tools v0.1.2 // indirect
|
||||
google.golang.org/genproto v0.0.0-20220930163606-c98284e70a91 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
go.uber.org/zap v1.24.0 // indirect
|
||||
golang.org/x/net v0.6.0 // indirect
|
||||
golang.org/x/sys v0.5.0 // indirect
|
||||
golang.org/x/text v0.7.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230209215440-0dfe4f8abfcc // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
nhooyr.io/websocket v1.8.7 // indirect
|
||||
)
|
||||
@@ -12,7 +12,7 @@ var version = "1.0.0"
|
||||
|
||||
// @title msp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис администрирования
|
||||
// @description сервис управления администраторами
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- +goose Up
|
||||
alter table roles
|
||||
add unique (name);
|
||||
|
||||
alter table tokens
|
||||
add column id serial8 not null;
|
||||
|
||||
alter table tokens
|
||||
add constraint fk_user_id__user_id
|
||||
foreign key (user_id) references users (id)
|
||||
on update cascade on delete cascade;
|
||||
|
||||
create index ix_tokens__user_id on tokens (user_id);
|
||||
|
||||
create table audit
|
||||
(
|
||||
id serial8 primary key,
|
||||
user_id int8 not null,
|
||||
message text not null,
|
||||
created_at timestamp not null
|
||||
);
|
||||
|
||||
create index ix_audit__created_at on audit (created_at DESC);
|
||||
|
||||
alter table users
|
||||
add column blocked boolean not null default false;
|
||||
|
||||
alter table users
|
||||
add unique (sudir_user_id);
|
||||
|
||||
-- +goose Down
|
||||
@@ -0,0 +1,77 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Audit struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewAudit(db db.DB) Audit {
|
||||
return Audit{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r Audit) Insert(ctx context.Context, log entity.Audit) (int, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Audit.Insert")
|
||||
|
||||
query, args, err := query.New().
|
||||
Insert("audit").
|
||||
Columns("user_id", "message", "created_at").
|
||||
Values(log.UserId, log.Message, log.CreatedAt).
|
||||
Suffix("returning id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
id := 0
|
||||
err = r.db.SelectRow(ctx, &id, query, args...)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r Audit) All(ctx context.Context, limit int, offset int) ([]entity.Audit, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Audit.All")
|
||||
|
||||
query, args, err := query.New().
|
||||
Select("*").
|
||||
From("audit").
|
||||
OrderBy("created_at DESC").
|
||||
Offset(uint64(offset)).
|
||||
Limit(uint64(limit)).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
tokens := make([]entity.Audit, 0)
|
||||
err = r.db.Select(ctx, &tokens, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select query: %s", query)
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (r Audit) Count(ctx context.Context) (int64, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Audit.Count")
|
||||
|
||||
count := int64(0)
|
||||
err := r.db.SelectRow(ctx, &count, "select count(*) from audit")
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "select count")
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
@@ -21,6 +22,8 @@ func NewRole(db db.DB) Role {
|
||||
}
|
||||
|
||||
func (r Role) GetRoleById(ctx context.Context, id int) (*entity.Role, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleById")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("roles").
|
||||
@@ -44,6 +47,8 @@ func (r Role) GetRoleById(ctx context.Context, id int) (*entity.Role, error) {
|
||||
}
|
||||
|
||||
func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByName")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("roles").
|
||||
@@ -65,3 +70,32 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
|
||||
return &role, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r Role) UpsertRoleByName(ctx context.Context, role entity.Role) (int, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Role.UpsertRoleByName")
|
||||
|
||||
query := `
|
||||
insert into roles (name, rights, description)
|
||||
values ($1, $2, $3) on conflict (name) do update
|
||||
set name = excluded.name, rights = excluded.rights, description = excluded.description
|
||||
returning id
|
||||
`
|
||||
id := 0
|
||||
err := r.db.SelectRow(ctx, &id, query, role.Name, role.Rights, role.Description)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "select %s", query)
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
||||
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, "select * from roles order by created_at")
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "select all roles")
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
@@ -22,6 +24,8 @@ func NewToken(db db.DB) Token {
|
||||
}
|
||||
|
||||
func (r Token) Save(ctx context.Context, token entity.Token) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.Save")
|
||||
|
||||
q := `
|
||||
INSERT INTO tokens
|
||||
(token, user_id, status, expired_at, created_at, updated_at)
|
||||
@@ -36,6 +40,8 @@ func (r Token) Save(ctx context.Context, token entity.Token) error {
|
||||
}
|
||||
|
||||
func (r Token) GetEntity(ctx context.Context, token string) (*entity.Token, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.GetEntity")
|
||||
|
||||
result := entity.Token{}
|
||||
q := `
|
||||
SELECT token, user_id, status, expired_at, created_at, updated_at
|
||||
@@ -54,6 +60,8 @@ func (r Token) GetEntity(ctx context.Context, token string) (*entity.Token, erro
|
||||
}
|
||||
|
||||
func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.RevokeByUserId")
|
||||
|
||||
q := `
|
||||
UPDATE tokens
|
||||
SET status = $1, updated_at = $2
|
||||
@@ -66,3 +74,88 @@ func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) All(ctx context.Context, limit int, offset int) ([]entity.Token, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.All")
|
||||
|
||||
query, args, err := query.New().
|
||||
Select("*").
|
||||
From("tokens").
|
||||
OrderBy("created_at DESC").
|
||||
Offset(uint64(offset)).
|
||||
Limit(uint64(limit)).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
tokens := make([]entity.Token, 0)
|
||||
err = r.db.Select(ctx, &tokens, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select query %s", query)
|
||||
}
|
||||
|
||||
return tokens, nil
|
||||
}
|
||||
|
||||
func (r Token) UpdateStatus(ctx context.Context, id int, status string) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.UpdateStatus")
|
||||
|
||||
q := `
|
||||
UPDATE tokens SET status = $1, updated_at = $2 where id = $3;
|
||||
`
|
||||
_, err := r.db.Exec(ctx, q, status, time.Now().UTC(), id)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update token status")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) Count(ctx context.Context) (int64, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.Count")
|
||||
|
||||
count := int64(0)
|
||||
err := r.db.SelectRow(ctx, &count, "select count(*) from tokens")
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "select count")
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r Token) UpdateStatusByUserId(ctx context.Context, userId int, status string) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.UpdateStatusByUserId")
|
||||
|
||||
q := `
|
||||
UPDATE tokens SET status = $1, updated_at = $2 where user_id = $3;
|
||||
`
|
||||
_, err := r.db.Exec(ctx, q, status, time.Now().UTC(), userId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update token status")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Token) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
|
||||
|
||||
query := `
|
||||
select t.user_id, max(t.created_at) as created_at from tokens t
|
||||
join users u on t.user_id = u.id
|
||||
where u.blocked = false
|
||||
group by t.user_id
|
||||
`
|
||||
tokens := make([]entity.Token, 0)
|
||||
err := r.db.Select(ctx, &tokens, query)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select query: %s", query)
|
||||
}
|
||||
|
||||
result := make(map[int64]time.Time, 0)
|
||||
for _, token := range tokens {
|
||||
result[token.UserId] = token.CreatedAt
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
+77
-58
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
@@ -21,9 +22,10 @@ func NewUser(db db.DB) User {
|
||||
}
|
||||
|
||||
func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("id", "role_id", "first_name", "last_name", "password",
|
||||
"email", "sudir_user_id", "created_at", "updated_at").
|
||||
Select("*").
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
ToSql()
|
||||
@@ -45,9 +47,10 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
|
||||
}
|
||||
|
||||
func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.GetUserById")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("id", "role_id", "first_name", "last_name", "password",
|
||||
"email", "sudir_user_id", "created_at", "updated_at").
|
||||
Select("*").
|
||||
From("users").
|
||||
Where(squirrel.Eq{"id": identity}).
|
||||
ToSql()
|
||||
@@ -68,35 +71,42 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUserBySudirUserId(ctx context.Context, id string) (*entity.User, error) {
|
||||
q, args, err := query.New().
|
||||
Select("id", "role_id", "first_name", "last_name", "password",
|
||||
"email", "sudir_user_id", "created_at", "updated_at").
|
||||
From("users").
|
||||
Where(squirrel.Eq{"sudir_user_id": id}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
||||
|
||||
user := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
query := `
|
||||
insert into users as u (role_id, first_name, last_name, email, created_at, updated_at, sudir_user_id)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)
|
||||
on conflict (sudir_user_id) do update
|
||||
set role_id = excluded.role_id,
|
||||
first_name = excluded.first_name,
|
||||
last_name = excluded.last_name,
|
||||
email = excluded.email,
|
||||
updated_at = excluded.updated_at
|
||||
where u.blocked = false
|
||||
returning *
|
||||
`
|
||||
result := entity.User{}
|
||||
err := u.db.SelectRow(ctx,
|
||||
&result,
|
||||
query,
|
||||
user.RoleId, user.FirstName, user.LastName, user.Email, user.CreatedAt, user.UpdatedAt, user.SudirUserId,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &user, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (u User) GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error) {
|
||||
// take every except password
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.GetUsers")
|
||||
|
||||
q := query.New().
|
||||
Select("id", "role_id", "first_name", "last_name",
|
||||
"email", "sudir_user_id", "created_at", "updated_at").
|
||||
Select("*").
|
||||
From("users")
|
||||
|
||||
if len(ids) > 0 {
|
||||
@@ -123,49 +133,33 @@ func (u User) GetUsers(ctx context.Context, ids []int64, offset, limit int, emai
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (u User) CreateUser(ctx context.Context, user entity.CreateUser) (*entity.User, error) {
|
||||
// return every except password
|
||||
q, args, err := query.New().
|
||||
func (u User) Insert(ctx context.Context, user entity.User) (int, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.Insert")
|
||||
|
||||
query, args, err := query.New().
|
||||
Insert("users").
|
||||
Columns("role_id", "first_name", "last_name", "email", "password").
|
||||
Values(user.RoleId, user.FirstName, user.LastName, user.Email, user.Password).
|
||||
Suffix("RETURNING id, role_id, first_name, last_name, email, sudir_user_id, created_at, updated_at").
|
||||
Columns("role_id", "first_name", "last_name",
|
||||
"email", "password", "created_at", "updated_at").
|
||||
Values(user.RoleId, user.FirstName, user.LastName,
|
||||
user.Email, user.Password, user.CreatedAt, user.UpdatedAt).
|
||||
Suffix("returning id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
return 0, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
returning := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &returning, q, args...)
|
||||
id := 0
|
||||
err = u.db.SelectRow(ctx, &id, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
return 0, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
|
||||
return &returning, err
|
||||
}
|
||||
|
||||
func (u User) CreateSudirUser(ctx context.Context, user entity.SudirUser) (*entity.User, error) {
|
||||
// return every except password
|
||||
q, args, err := query.New().
|
||||
Insert("users").
|
||||
Columns("role_id", "sudir_user_id", "first_name", "last_name", "email").
|
||||
Values(user.RoleId, user.SudirUserId, user.FirstName, user.LastName, user.Email).
|
||||
Suffix("RETURNING id, role_id, first_name, last_name, email, sudir_user_id, created_at, updated_at").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
returning := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &returning, q, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
}
|
||||
|
||||
return &returning, err
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.UpdateUser")
|
||||
|
||||
// return every except password
|
||||
q, args, err := query.New().
|
||||
Update("users").
|
||||
@@ -193,6 +187,8 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
|
||||
}
|
||||
|
||||
func (u User) DeleteUser(ctx context.Context, ids []int64) (int, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.DeleteUser")
|
||||
|
||||
q, args, err := query.New().
|
||||
Delete("users").
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
@@ -213,3 +209,26 @@ func (u User) DeleteUser(ctx context.Context, ids []int64) (int, error) {
|
||||
|
||||
return int(affected), err
|
||||
}
|
||||
|
||||
func (u User) ChangeBlockStatus(ctx context.Context, userId int) (bool, error) {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.ChangeBlockStatus")
|
||||
|
||||
query := "update users set blocked = not blocked where id = $1 returning blocked"
|
||||
blocked := false
|
||||
err := u.db.SelectRow(ctx, &blocked, query, userId)
|
||||
if err != nil {
|
||||
return false, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
func (u User) Block(ctx context.Context, userId int) error {
|
||||
sql_metrics.OperationLabelToContext(ctx, "User.Block")
|
||||
|
||||
query := "update users set blocked = true where id = $1"
|
||||
_, err := u.db.Exec(ctx, query, userId)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -13,6 +13,8 @@ type Controllers struct {
|
||||
User controller.User
|
||||
Customization controller.Customization
|
||||
Secure controller.Secure
|
||||
Session controller.Session
|
||||
Audit controller.Audit
|
||||
}
|
||||
|
||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
@@ -27,6 +29,7 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
||||
return muxer
|
||||
}
|
||||
|
||||
//nolint:funlen
|
||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
return []cluster.EndpointDescriptor{
|
||||
{
|
||||
@@ -83,6 +86,42 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.DeleteUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.Block,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_roles",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.GetRoles,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.GetById,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Session.All,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Session.Revoke,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Audit.All,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type AuditRepo interface {
|
||||
Insert(ctx context.Context, log entity.Audit) (int, error)
|
||||
All(ctx context.Context, limit int, offset int) ([]entity.Audit, error)
|
||||
Count(ctx context.Context) (int64, error)
|
||||
}
|
||||
|
||||
type Audit struct {
|
||||
repo AuditRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewAudit(repo AuditRepo, logger log.Logger) Audit {
|
||||
return Audit{
|
||||
repo: repo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Audit) SaveAuditAsync(ctx context.Context, userId int64, message string) {
|
||||
go func() {
|
||||
audit := entity.Audit{
|
||||
UserId: int(userId),
|
||||
Message: message,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
_, err := s.repo.Insert(context.Background(), audit)
|
||||
if err != nil {
|
||||
s.logger.Error(ctx, "insert audit", log.Any("error", err))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s Audit) All(ctx context.Context, limit int, offset int) (*domain.AuditResponse, error) {
|
||||
group, ctx := errgroup.WithContext(ctx)
|
||||
var tokens []entity.Audit
|
||||
var total int64
|
||||
var err error
|
||||
group.Go(func() error {
|
||||
tokens, err = s.repo.All(ctx, limit, offset)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
group.Go(func() error {
|
||||
total, err = s.repo.Count(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "count all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
err = group.Wait()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "wait workers")
|
||||
}
|
||||
|
||||
items := make([]domain.Audit, 0)
|
||||
for _, token := range tokens {
|
||||
items = append(items, domain.Audit(token))
|
||||
}
|
||||
result := domain.AuditResponse{
|
||||
TotalCount: int(total),
|
||||
Items: items,
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
+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
|
||||
}
|
||||
+20
-23
@@ -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 {
|
||||
@@ -63,41 +59,42 @@ func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.Sudir
|
||||
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
||||
}
|
||||
|
||||
role := getRole(user.Groups)
|
||||
//nolint
|
||||
/*role := getRole(user.Groups)
|
||||
if role == "" {
|
||||
return nil, errors.New("undefined role")
|
||||
}*/
|
||||
|
||||
roleId, err := s.roleRepo.UpsertRoleByName(ctx, entity.Role{
|
||||
Name: user.GivenName,
|
||||
Rights: map[string]string{},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "upsert 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")
|
||||
email := user.Email
|
||||
if email == "" {
|
||||
email = user.Sub
|
||||
}
|
||||
|
||||
return &entity.SudirUser{
|
||||
RoleId: roleInfo.Id,
|
||||
RoleId: roleId,
|
||||
SudirUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
Email: user.Email,
|
||||
Email: email,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// nolint
|
||||
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 ""
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
@@ -15,6 +16,9 @@ type TokenRep interface {
|
||||
Save(ctx context.Context, token entity.Token) error
|
||||
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)
|
||||
Count(ctx context.Context) (int64, error)
|
||||
UpdateStatus(ctx context.Context, id int, status string) error
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
@@ -78,3 +82,57 @@ func (s Token) RevokeAllByUserId(ctx context.Context, userId int64) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Token) All(ctx context.Context, limit int, offset int) (*domain.SessionResponse, error) {
|
||||
group, ctx := errgroup.WithContext(ctx)
|
||||
var tokens []entity.Token
|
||||
var total int64
|
||||
var err error
|
||||
group.Go(func() error {
|
||||
tokens, err = s.tokenRep.All(ctx, limit, offset)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
group.Go(func() error {
|
||||
total, err = s.tokenRep.Count(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "count all tokens")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
err = group.Wait()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "wait workers")
|
||||
}
|
||||
|
||||
items := make([]domain.Session, 0)
|
||||
for _, token := range tokens {
|
||||
status := token.Status
|
||||
if time.Now().UTC().After(token.ExpiredAt) {
|
||||
status = entity.TokenStatusExpired
|
||||
}
|
||||
items = append(items, domain.Session{
|
||||
Id: token.Id,
|
||||
UserId: int(token.UserId),
|
||||
Status: status,
|
||||
ExpiredAt: token.ExpiredAt,
|
||||
CreatedAt: token.CreatedAt,
|
||||
})
|
||||
}
|
||||
result := domain.SessionResponse{
|
||||
TotalCount: int(total),
|
||||
Items: items,
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (s Token) Revoke(ctx context.Context, id int) error {
|
||||
err := s.tokenRep.UpdateStatus(ctx, id, entity.TokenStatusRevoked)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "token update status")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+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.WithMessagef(domain.ErrUnauthenticated, "user '%d' is blocked", user.Id)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type AuditRepo interface {
|
||||
SaveAuditAsync(ctx context.Context, userId int64, message string)
|
||||
}
|
||||
|
||||
type TokenRepo interface {
|
||||
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
|
||||
}
|
||||
|
||||
type UserRepo interface {
|
||||
Block(ctx context.Context, userId int) error
|
||||
}
|
||||
|
||||
type InactiveBlocker struct {
|
||||
tokenRepo TokenRepo
|
||||
userRepo UserRepo
|
||||
auditRepo AuditRepo
|
||||
threshold time.Duration
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewInactiveBlocker(
|
||||
tokensRepo TokenRepo,
|
||||
userRepo UserRepo,
|
||||
auditRepo AuditRepo,
|
||||
inactiveThresholdInDays int,
|
||||
logger log.Logger,
|
||||
) InactiveBlocker {
|
||||
return InactiveBlocker{
|
||||
tokenRepo: tokensRepo,
|
||||
userRepo: userRepo,
|
||||
auditRepo: auditRepo,
|
||||
threshold: time.Duration(inactiveThresholdInDays) * 24 * time.Hour,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (w InactiveBlocker) Do(ctx context.Context) {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
|
||||
w.logger.Debug(ctx, "begin work")
|
||||
err := w.do(ctx)
|
||||
if err != nil {
|
||||
w.logger.Error(ctx, "error", log.Any("error", err))
|
||||
}
|
||||
w.logger.Debug(ctx, "end work")
|
||||
}
|
||||
|
||||
func (w InactiveBlocker) do(ctx context.Context) error {
|
||||
lastAccess, err := w.tokenRepo.LastAccessNotBlockedUsers(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get last access times")
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
for userId, lastAccess := range lastAccess {
|
||||
dur := now.Sub(lastAccess)
|
||||
if dur < w.threshold {
|
||||
continue
|
||||
}
|
||||
|
||||
w.logger.Info(ctx, "block inactive user", log.Int64("userId", userId), log.Any("lastAccessTime", lastAccess))
|
||||
err := w.userRepo.Block(ctx, int(userId))
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "block user %d", userId)
|
||||
}
|
||||
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+32
-8
@@ -76,7 +76,7 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
@@ -111,8 +111,30 @@ func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestBlockedUser() {
|
||||
InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
Blocked: true,
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
Do(context.Background())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
InsertUser(s.db, entity.CreateUser{
|
||||
InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
@@ -144,7 +166,7 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
s.Require().NoError(err)
|
||||
user := entity.User{}
|
||||
s.db.Must().SelectRow(&user, "select id, role_id, email from users where sudir_user_id = $1", "sudirUser1")
|
||||
s.Require().Equal(1, user.RoleId)
|
||||
s.Require().Equal(3, user.RoleId)
|
||||
s.Require().Equal("sudir@email.ru", user.Email)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -183,15 +205,16 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
userId := InsertUser(s.db, entity.User{RoleId: 1})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token-841297641213",
|
||||
UserId: 841297641213,
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, "841297641213").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
@@ -207,15 +230,16 @@ func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
userId := InsertUser(s.db, entity.User{RoleId: 1})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token-148623719462",
|
||||
UserId: 148623719462,
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, "148623719462").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
@@ -224,7 +248,7 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
_ = InsertUser(s.db, entity.CreateUser{
|
||||
_ = InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
|
||||
+4
-4
@@ -8,15 +8,15 @@ import (
|
||||
)
|
||||
|
||||
//nolint:gomnd
|
||||
func InsertUser(db *dbt.TestDb, user entity.CreateUser) int64 {
|
||||
func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
||||
if user.Password != "" {
|
||||
passwordBytes, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 12)
|
||||
user.Password = string(passwordBytes)
|
||||
}
|
||||
var id int64
|
||||
db.Must().SelectRow(&id, `insert into users (role_id, first_name, last_name, email, password)
|
||||
values($1,$2,$3,$4,$5) returning id`,
|
||||
user.RoleId, user.FirstName, user.LastName, user.Email, user.Password)
|
||||
db.Must().SelectRow(&id, `insert into users (role_id, first_name, last_name, email, password, blocked)
|
||||
values($1,$2,$3,$4,$5, $6) returning id`,
|
||||
user.RoleId, user.FirstName, user.LastName, user.Email, user.Password, user.Blocked)
|
||||
return id
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
)
|
||||
|
||||
func TestInactiveWorker(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
test, require := test.New(t)
|
||||
db := dbt.New(test, dbx.WithMigration("../migrations"))
|
||||
|
||||
userId := InsertUser(db, entity.User{RoleId: 1, Email: "a@test"})
|
||||
InsertUser(db, entity.User{RoleId: 1, Email: "b@test"})
|
||||
InsertTokenEntity(db, entity.Token{
|
||||
Id: 0,
|
||||
Token: "123",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
CreatedAt: time.Now().UTC().Add(-48 * time.Hour),
|
||||
})
|
||||
InsertTokenEntity(db, entity.Token{
|
||||
Id: 0,
|
||||
Token: "234",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
CreatedAt: time.Now().UTC().Add(-5 * 24 * time.Hour),
|
||||
})
|
||||
|
||||
worker := assembly.NewLocator(test.Logger(), nil, db).
|
||||
Config(conf.Remote{BlockInactiveWorker: conf.BlockInactiveWorker{DaysThreshold: 1}}).
|
||||
InactiveBlocker
|
||||
worker.Do(context.Background())
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
user, err := repository.NewUser(db).GetUserById(context.Background(), userId)
|
||||
require.NoError(err)
|
||||
require.True(user.Blocked)
|
||||
|
||||
list, err := repository.NewAudit(db).All(context.Background(), 10, 0)
|
||||
require.NoError(err)
|
||||
require.Len(list, 1)
|
||||
}
|
||||
+50
-14
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
@@ -63,7 +65,7 @@ func (s *UserTestSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -87,7 +89,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -130,10 +132,10 @@ func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetUsers() {
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "b@a.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@b.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@c.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@a.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "b@a.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@b.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@c.ru"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
@@ -147,6 +149,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
|
||||
s.Require().Equal(1, len(response.Items))
|
||||
s.Require().Equal(int64(5), response.Items[0].Id)
|
||||
s.Require().EqualValues("admin", response.Items[0].RoleName)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
@@ -174,7 +177,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@a.ru"})
|
||||
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
@@ -193,7 +196,7 @@ func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru", Password: "password"})
|
||||
id := InsertUser(s.db, entity.User{RoleId: 1, Email: "a@a.ru", Password: "password"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
@@ -269,8 +272,8 @@ func (s *AuthTestSuite) TestUpdateSudirUserInvalidRequest() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru", Password: "password"})
|
||||
id := InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "b@b.ru", Password: "password"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@a.ru", Password: "password"})
|
||||
id := InsertUser(s.db, entity.User{RoleId: 1, Email: "b@b.ru", Password: "password"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
@@ -290,10 +293,10 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "b@a.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@b.ru"})
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@c.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@a.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "b@a.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@b.ru"})
|
||||
InsertUser(s.db, entity.User{RoleId: 1, Email: "a@c.ru"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/delete_user").
|
||||
@@ -302,3 +305,36 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
||||
|
||||
s.Require().Equal(2, response.Deleted)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestBlockUser() {
|
||||
id := InsertUser(s.db, entity.User{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
Blocked: false,
|
||||
})
|
||||
token := uuid.New().String()
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: token,
|
||||
UserId: id,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: time.Now().Add(5 * time.Second),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/user/block_user").
|
||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := repository.NewUser(s.db).GetUserById(context.Background(), id)
|
||||
s.Require().NoError(err)
|
||||
s.Require().True(user.Blocked)
|
||||
|
||||
t, err := repository.NewToken(s.db).GetEntity(context.Background(), token)
|
||||
s.Require().NoError(err)
|
||||
s.EqualValues(entity.TokenStatusRevoked, t.Status)
|
||||
}
|
||||
Reference in new issue
Block a user