Merge branch 'MSP-1068' into 'master'
Resolve MSP-1068 Closes MSP-1068 See merge request msp2.0/msp-admin-service!10
This commit is contained in:
commit
68e15a3c78
52 files changed
+2811
-1379
No files matched your search
@@ -0,0 +1,69 @@
|
||||
run:
|
||||
timeout: 2m
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- asciicheck
|
||||
- bodyclose
|
||||
- deadcode
|
||||
- dogsled
|
||||
- errcheck
|
||||
- funlen
|
||||
- goconst
|
||||
- gocritic
|
||||
- gocyclo
|
||||
- gofmt
|
||||
- gomnd
|
||||
- goprintffuncname
|
||||
- gosimple
|
||||
- govet
|
||||
- nakedret
|
||||
- nestif
|
||||
- nolintlint
|
||||
- prealloc
|
||||
- rowserrcheck
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- typecheck
|
||||
- unconvert
|
||||
- unparam
|
||||
- unused
|
||||
- varcheck
|
||||
- gosec
|
||||
- misspell
|
||||
- whitespace
|
||||
- exhaustive #смотрит на соответствие между элементами enum и swich кейсами
|
||||
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
|
||||
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
|
||||
linters-settings:
|
||||
funlen:
|
||||
lines: 80
|
||||
statements: 40
|
||||
prealloc:
|
||||
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
|
||||
# True by default.
|
||||
simple: true
|
||||
range-loops: true # Report preallocation suggestions on range loops, true by default
|
||||
for-loops: true # Report preallocation suggestions on for loops, false by default
|
||||
gocritic:
|
||||
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
|
||||
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
|
||||
enabled-tags:
|
||||
- diagnostic
|
||||
- performance
|
||||
disabled-checks:
|
||||
- hugeParam
|
||||
- rangeValCopy
|
||||
- ifElseChain
|
||||
exhaustive:
|
||||
default-signifies-exhaustive: true
|
||||
|
||||
issues:
|
||||
exclude-rules:
|
||||
- path: _test\.go # to exclude all test files for linter errcheck
|
||||
linters:
|
||||
- errcheck
|
||||
- linters:
|
||||
- gosec
|
||||
text: "G101:"
|
||||
@@ -1,3 +1,8 @@
|
||||
### v4.0.0
|
||||
* миграция сервиса на isp-kit
|
||||
* миграция на версию GO 1.19.1
|
||||
* обновлен формат логов в json
|
||||
* обновлена документация swagger: разделены ручки создания и обновления пользователя
|
||||
### v3.5.0
|
||||
* add role to response /user/get_profile
|
||||
* add read_only_admin role
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbrx"
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/http/httpclix"
|
||||
"msp-admin-service/conf"
|
||||
|
||||
"github.com/integration-system/isp-kit/app"
|
||||
"github.com/integration-system/isp-kit/bootstrap"
|
||||
"github.com/integration-system/isp-kit/cluster"
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
httpCli *httpcli.Client
|
||||
logger *log.Adapter
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
server := grpc.NewServer()
|
||||
httpCli := httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(boot.App.Logger())))
|
||||
db := dbrx.New(dbx.WithMigration(boot.MigrationsDir))
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
db: db,
|
||||
server: server,
|
||||
logger: boot.App.Logger(),
|
||||
httpCli: httpCli,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
|
||||
var (
|
||||
newCfg conf.Remote
|
||||
prevCfg conf.Remote
|
||||
)
|
||||
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
|
||||
}
|
||||
|
||||
a.logger.SetLevel(newCfg.LogLevel)
|
||||
|
||||
err = a.db.Upgrade(ctx, newCfg.Database)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", a.hiddenSecret(newCfg.Database)))
|
||||
}
|
||||
|
||||
locator := NewLocator(a.logger, a.httpCli, a.db)
|
||||
handler := locator.Handler(newCfg)
|
||||
|
||||
a.server.Upgrade(handler)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Assembly) Runners() []app.Runner {
|
||||
eventHandler := cluster.NewEventHandler().
|
||||
RemoteConfigReceiver(a)
|
||||
return []app.Runner{
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
return a.server.ListenAndServe(a.boot.BindingAddress)
|
||||
}),
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
return a.boot.ClusterCli.Run(ctx, eventHandler)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Assembly) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
a.boot.ClusterCli,
|
||||
app.CloserFunc(func() error {
|
||||
a.server.Shutdown()
|
||||
return nil
|
||||
}),
|
||||
a.db,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Assembly) hiddenSecret(conf dbx.Config) dbx.Config {
|
||||
conf.Password = "***"
|
||||
return conf
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package assembly
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/controller"
|
||||
"msp-admin-service/middleware"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc/endpoint"
|
||||
"github.com/integration-system/isp-kit/grpc/isp"
|
||||
"msp-admin-service/routes"
|
||||
)
|
||||
|
||||
type Locator struct {
|
||||
logger log.Logger
|
||||
httpCli *httpcli.Client
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewLocator(logger log.Logger, httpCli *httpcli.Client, db db.DB) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
httpCli: httpCli,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
|
||||
sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth)
|
||||
roleRepo := repository.NewRole(l.db)
|
||||
userRepo := repository.NewUser(l.db)
|
||||
|
||||
tokenService := service.NewToken(time.Second*time.Duration(cfg.ExpireSec), cfg.SecretKey)
|
||||
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo, roleRepo)
|
||||
userService := service.NewUser(tokenService, userRepo, roleRepo, l.logger)
|
||||
authService := service.NewAuth(userRepo, tokenService, sudirService, l.logger)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
authController := controller.NewAuth(authService, l.logger)
|
||||
|
||||
handler := routes.Handler(
|
||||
endpoint.DefaultWrapper(
|
||||
l.logger,
|
||||
middleware.ErrorHandler(l.logger),
|
||||
),
|
||||
routes.Controllers{
|
||||
User: userController,
|
||||
Customization: customizationController,
|
||||
Auth: authController,
|
||||
},
|
||||
)
|
||||
|
||||
return handler
|
||||
}
|
||||
+8
-4
@@ -7,7 +7,11 @@ grpcOuterAddress:
|
||||
grpcInnerAddress:
|
||||
ip: 0.0.0.0
|
||||
port: 9007
|
||||
webSocketAddress:
|
||||
ip: 0.0.0.0
|
||||
port: 9100
|
||||
moduleName: admin
|
||||
moduleName: msp-admin-service
|
||||
infraServerPort: 9557
|
||||
|
||||
logfile:
|
||||
path: /var/log/msp-admin-service/runtime.log
|
||||
maxSizeMb: 512
|
||||
maxBackups: 4
|
||||
compress: true
|
||||
@@ -5,17 +5,9 @@
|
||||
"username": "name",
|
||||
"createSchema": true,
|
||||
"port": "5432",
|
||||
"schema": "admin_service",
|
||||
"schema": "msp_admin_service",
|
||||
"address": "127.0.0.1"
|
||||
},
|
||||
"metrics": {
|
||||
"gc": true,
|
||||
"memory": true,
|
||||
"address": {
|
||||
"path": "/metrics",
|
||||
"port": "9557",
|
||||
"ip": "0.0.0.0"
|
||||
}
|
||||
},
|
||||
"logLevel": "debug",
|
||||
"secretKey": "secret"
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
)
|
||||
|
||||
type Configuration struct {
|
||||
config.CommonLocalConfig
|
||||
GrpcOuterAddress structure.AddressConfiguration `valid:"required~Required"`
|
||||
GrpcInnerAddress structure.AddressConfiguration `valid:"required~Required"`
|
||||
WebSocketAddress structure.AddressConfiguration `valid:"required~Required"` //TODO : оставить поле - после модификации гейта, вернёмся к использованию
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/integration-system/isp-kit/rc/schema"
|
||||
"github.com/integration-system/jsonschema"
|
||||
)
|
||||
|
||||
func init() {
|
||||
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
|
||||
t.Type = "string"
|
||||
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
|
||||
})
|
||||
}
|
||||
|
||||
type Remote struct {
|
||||
Database dbx.Config
|
||||
SecretKey string `valid:"required~Required" schema:"JWT secret"`
|
||||
ExpireSec int `schema:"Token expire time,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
}
|
||||
|
||||
type UIDesign struct {
|
||||
Name string `schema:"Название стенда"`
|
||||
PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
}
|
||||
|
||||
type SudirAuth struct {
|
||||
ClientId string `valid:"required~Required"`
|
||||
ClientSecret string `valid:"required~Required"`
|
||||
Host string `valid:"required~Required" schema:"Хост, пример https://sudir.mos.ru"`
|
||||
RedirectURI string `valid:"required~Required"`
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
)
|
||||
|
||||
type RemoteConfig struct {
|
||||
Database structure.DBConfiguration `valid:"required~Required" json:"database" schema:"Database"`
|
||||
Metrics structure.MetricConfiguration `schema:"Metrics"`
|
||||
SecretKey string `valid:"required~Required" schema:"JWT secret"`
|
||||
ExpireSec int `schema:"Token expire time,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
}
|
||||
|
||||
type UIDesign struct {
|
||||
Name string `schema:"Название стенда"`
|
||||
PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
}
|
||||
|
||||
type SudirAuth struct {
|
||||
ClientId string `valid:"required~Required"`
|
||||
ClientSecret string `valid:"required~Required"`
|
||||
Host string `valid:"required~Required" schema:"Хост, пример https://sudir.mos.ru"`
|
||||
RedirectURI string `valid:"required~Required"`
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type authService interface {
|
||||
Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error)
|
||||
LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error)
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
authService authService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewAuth(authService authService, logger log.Logger) Auth {
|
||||
return Auth{
|
||||
authService: authService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Logout
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Login
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.AuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Auth
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error) {
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthorization):
|
||||
return nil, status.Error(codes.InvalidArgument, "Пользователь имеет только авторизацию СУДИР")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
return nil, status.Error(codes.Unauthenticated, "Данные для авторизации не верны")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
}
|
||||
|
||||
// LoginWithSudir
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SudirAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Auth
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error) {
|
||||
auth, err := a.authService.LoginWithSudir(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "Авторизация СУДИР не настроена на сервере")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "Некорректный код для авторизации")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with sudir")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
type Customization struct {
|
||||
uiCfg conf.UIDesign
|
||||
}
|
||||
|
||||
func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||
return Customization{
|
||||
uiCfg: uiCfg,
|
||||
}
|
||||
}
|
||||
|
||||
// GetUIDesign
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
@@ -13,9 +22,9 @@ import (
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} conf.UIDesign
|
||||
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_design [POST]
|
||||
func GetUIDesign(_ metadata.MD) (conf.UIDesign, error) {
|
||||
return config.GetRemote().(*conf.RemoteConfig).UiDesign, nil
|
||||
func (c Customization) GetUIDesign() (conf.UIDesign, error) {
|
||||
return c.uiCfg, nil
|
||||
}
|
||||
+103
-258
@@ -1,313 +1,158 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/invoker/sudir"
|
||||
"msp-admin-service/model"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/structure"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
const adminAuthHeaderName = "x-auth-admin"
|
||||
|
||||
const (
|
||||
ValidationError = "Validation errors"
|
||||
)
|
||||
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func Logout(_ metadata.MD) error {
|
||||
return nil
|
||||
type userService interface {
|
||||
GetProfileByToken(ctx context.Context, token string) (*domain.AdminUserShort, error)
|
||||
GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error)
|
||||
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)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
userService userService
|
||||
}
|
||||
|
||||
func NewUser(userService userService) User {
|
||||
return User{
|
||||
userService: userService,
|
||||
}
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} structure.AdminUserShort
|
||||
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
|
||||
// @Failure 401 {object} structure.GrpcError "Токен не соответствует ни одному пользователю"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 401 {object} domain.GrpcError "Токен не соответствует ни одному пользователю"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_profile [POST]
|
||||
func GetProfile(metadata metadata.MD) (*structure.AdminUserShort, error) {
|
||||
token := metadata.Get(adminAuthHeaderName)
|
||||
userId, err := service.GetUserId(token[0])
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unauthenticated, "Invalid auth token")
|
||||
func (u User) GetProfile(ctx context.Context, metadata metadata.MD) (*domain.AdminUserShort, error) {
|
||||
token := metadata.Get(domain.AdminAuthHeaderName)
|
||||
if len(token) == 0 {
|
||||
return nil, status.Error(codes.InvalidArgument, "Невалидный токен")
|
||||
}
|
||||
|
||||
user, err := model.GetUserById(userId)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get user by id %d", userId)
|
||||
}
|
||||
profile, err := u.userService.GetProfileByToken(ctx, token[0])
|
||||
|
||||
role, err := model.RoleRep.GetRoleById(user.RoleId)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "get role by id %d", user.RoleId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "Токен не соответствует ни одному пользователю")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get profile")
|
||||
default:
|
||||
return profile, nil
|
||||
}
|
||||
if role == nil {
|
||||
return nil, errors.Errorf("unexpected role id %d", user.RoleId)
|
||||
}
|
||||
|
||||
return &structure.AdminUserShort{
|
||||
Image: user.Image,
|
||||
FirstName: user.FirstName,
|
||||
LastName: user.LastName,
|
||||
Email: user.Email,
|
||||
Phone: user.Phone,
|
||||
Role: role.Name,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body structure.AuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.Auth
|
||||
// @Failure 400 {object} structure.GrpcError
|
||||
// @Failure 401 {object} structure.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 404 {object} structure.GrpcError "Пользователь не найден"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
|
||||
user, err := model.GetUserByEmail(authRequest.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if user == nil {
|
||||
return nil, status.Error(codes.NotFound, "User not found")
|
||||
} else if user.SudirUserId != "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "User is authorized only with SUDIR")
|
||||
}
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authRequest.Password))
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Unauthenticated, "Email or password is incorrect")
|
||||
}
|
||||
|
||||
tokenString, expired, err := service.GenerateToken(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &structure.Auth{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
HeaderName: adminAuthHeaderName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body structure.SudirAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.Auth
|
||||
// @Failure 401 {object} structure.GrpcError "Некорректный код для авторизации"
|
||||
// @Failure 412 {object} structure.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func LoginWithSudir(request structure.SudirAuthRequest) (*structure.Auth, error) {
|
||||
remoteConfig := config.GetRemote().(*conf.RemoteConfig)
|
||||
if remoteConfig.SudirAuth == nil {
|
||||
return nil, status.Error(codes.FailedPrecondition, "SUDIR authorization is not configured on the server")
|
||||
}
|
||||
|
||||
sudirUser, err := service.AuthSudir(*remoteConfig.SudirAuth, request.AuthCode)
|
||||
var authErr *sudir.SudirAuthError
|
||||
if errors.As(err, &authErr) {
|
||||
return nil, status.Error(codes.Unauthenticated, err.Error())
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if sudirUser.SudirUserId == "" || sudirUser.Email == "" {
|
||||
return nil, status.Errorf(codes.Unauthenticated, "missing sudirUserId '%s' or email '%s'", sudirUser.SudirUserId, sudirUser.Email)
|
||||
}
|
||||
|
||||
existedUser, err := model.GetUserBySudirUserId(sudirUser.SudirUserId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existedUser != nil {
|
||||
sudirUser = *existedUser
|
||||
} else {
|
||||
sudirUser, err = model.CreateUser(sudirUser)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
tokenString, expired, err := service.GenerateToken(sudirUser.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &structure.Auth{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
HeaderName: adminAuthHeaderName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetUsers
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body structure.UsersRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.UsersResponse
|
||||
// @Failure 400 {object} structure.GrpcError
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Param body body domain.UsersRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_users [POST]
|
||||
func GetUsers(identities structure.UsersRequest) (*structure.UsersResponse, error) {
|
||||
users, err := model.GetUsers(identities)
|
||||
func (u User) GetUsers(ctx context.Context, identities domain.UsersRequest) (*domain.UsersResponse, error) {
|
||||
users, err := u.userService.GetUsers(ctx, identities)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.WithMessage(err, "get users")
|
||||
}
|
||||
for i := range *users {
|
||||
(*users)[i].Password = ""
|
||||
}
|
||||
return &structure.UsersResponse{Items: users}, err
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// CreateUser
|
||||
// @Tags user
|
||||
// @Summary Создать/Обновить пользователя
|
||||
// @Description Создать пользователя или обновить данные существующего
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body entity.AdminUser true "Тело запроса"
|
||||
// @Success 200 {object} entity.AdminUser
|
||||
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /user/create_update_user [POST]
|
||||
func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
|
||||
if user.Id == 0 {
|
||||
if user.Password == "" {
|
||||
validationErrors := map[string]string{"password": "Required"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
} else if user.SudirUserId != "" {
|
||||
validationErrors := map[string]string{"sudirUserId": "Could not create user with sudirUserId"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
user, err := u.userService.CreateUser(ctx, req)
|
||||
|
||||
userExists, err := model.GetUserByEmail(user.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if userExists != nil && userExists.Id != 0 {
|
||||
validationErrors := map[string]string{
|
||||
"email": fmt.Sprintf("User with email: %s already exists", user.Email),
|
||||
}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.AlreadyExists,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
|
||||
err = cryptPassword(&user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, err = model.CreateUser(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
userExists, err := model.GetUserById(user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if userExists.Id == 0 {
|
||||
validationErrors := map[string]string{
|
||||
"id": fmt.Sprintf("User with id: %d not found", user.Id),
|
||||
}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.NotFound,
|
||||
ValidationError, validationErrors)
|
||||
} else if userExists.SudirUserId != user.SudirUserId {
|
||||
validationErrors := map[string]string{"sudirUserId": "Could not change sudirUserId of an existing user"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
} else if user.Password != "" && user.SudirUserId != "" {
|
||||
validationErrors := map[string]string{"password": "Could not set password of a user logged in with SUDIR"}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
|
||||
if user.Password != "" {
|
||||
err = cryptPassword(&user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
user, err = model.UpdateUser(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.CreatedAt = userExists.CreatedAt
|
||||
user.UpdatedAt = userExists.UpdatedAt
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "Пользователь с указанным email уже существует")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
default:
|
||||
return user, nil
|
||||
}
|
||||
|
||||
user.Password = ""
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// UpdateUser
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
result, err := u.userService.UpdateUser(ctx, req)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, status.Error(codes.NotFound, "Пользователь с указанным id не существует")
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
return nil, status.Error(codes.InvalidArgument, "Пользователь авторизован через СУДИР, смена пароля для него запрещена")
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, status.Error(codes.AlreadyExists, "Пользователь с указанным email уже существует")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteUser
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body structure.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} structure.DeleteResponse
|
||||
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/delete_user [POST]
|
||||
func DeleteUser(identities structure.IdentitiesRequest) (*structure.DeleteResponse, error) {
|
||||
if len(identities.Ids) == 0 {
|
||||
validationErrors := map[string]string{
|
||||
"ids": "Required",
|
||||
}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument,
|
||||
ValidationError, validationErrors)
|
||||
}
|
||||
count, err := model.DeleteUser(identities)
|
||||
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||
deletedCount, err := u.userService.DeleteUsers(ctx, identities.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, errors.WithMessage(err, "delete")
|
||||
}
|
||||
return &structure.DeleteResponse{Deleted: count}, err
|
||||
}
|
||||
|
||||
func cryptPassword(user *entity.AdminUser) error {
|
||||
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(user.Password), 12)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user.Password = string(passwordBytes)
|
||||
return nil
|
||||
return &domain.DeleteResponse{Deleted: deletedCount}, nil
|
||||
}
|
||||
+200
-94
@@ -39,7 +39,7 @@ var doc = `{
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.AuthRequest"
|
||||
"$ref": "#/definitions/domain.AuthRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -47,31 +47,25 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.Auth"
|
||||
"$ref": "#/definitions/domain.Auth"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Данные для авторизации не верны",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователь не найден",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +91,7 @@ var doc = `{
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.SudirAuthRequest"
|
||||
"$ref": "#/definitions/domain.SudirAuthRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -105,25 +99,25 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.Auth"
|
||||
"$ref": "#/definitions/domain.Auth"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Некорректный код для авторизации",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация СУДИР не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,21 +152,21 @@ var doc = `{
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/create_update_user": {
|
||||
"/user/create_user": {
|
||||
"post": {
|
||||
"description": "Создать пользователя или обновить данные существующего",
|
||||
"description": "Создать пользователя",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -182,7 +176,7 @@ var doc = `{
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Создать/Обновить пользователя",
|
||||
"summary": "Создать пользователя",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
@@ -197,7 +191,7 @@ var doc = `{
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/entity.AdminUser"
|
||||
"$ref": "#/definitions/domain.CreateUserRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -205,19 +199,25 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/entity.AdminUser"
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -250,7 +250,7 @@ var doc = `{
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.IdentitiesRequest"
|
||||
"$ref": "#/definitions/domain.IdentitiesRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -258,19 +258,19 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.DeleteResponse"
|
||||
"$ref": "#/definitions/domain.DeleteResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,13 +308,13 @@ var doc = `{
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,25 +346,25 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.AdminUserShort"
|
||||
"$ref": "#/definitions/domain.AdminUserShort"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Токен не соответствует ни одному пользователю",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,7 +397,7 @@ var doc = `{
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.UsersRequest"
|
||||
"$ref": "#/definitions/domain.UsersRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -405,19 +405,84 @@ var doc = `{
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.UsersResponse"
|
||||
"$ref": "#/definitions/domain.UsersResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/structure.GrpcError"
|
||||
"$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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,45 +501,7 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"entity.AdminUser": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email"
|
||||
],
|
||||
"properties": {
|
||||
"createdAt": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"image": {
|
||||
"type": "string"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"phone": {
|
||||
"type": "string"
|
||||
},
|
||||
"sudirUserId": {
|
||||
"type": "string"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.AdminUserShort": {
|
||||
"domain.AdminUserShort": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email"
|
||||
@@ -486,18 +513,15 @@ var doc = `{
|
||||
"firstName": {
|
||||
"type": "string"
|
||||
},
|
||||
"image": {
|
||||
"type": "string"
|
||||
},
|
||||
"lastName": {
|
||||
"type": "string"
|
||||
},
|
||||
"phone": {
|
||||
"role": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.Auth": {
|
||||
"domain.Auth": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"expired": {
|
||||
@@ -511,7 +535,7 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.AuthRequest": {
|
||||
"domain.AuthRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"email",
|
||||
@@ -526,7 +550,31 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.DeleteResponse": {
|
||||
"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": {
|
||||
@@ -534,7 +582,7 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.GrpcError": {
|
||||
"domain.GrpcError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"details": {
|
||||
@@ -551,8 +599,11 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.IdentitiesRequest": {
|
||||
"domain.IdentitiesRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ids"
|
||||
],
|
||||
"properties": {
|
||||
"ids": {
|
||||
"type": "array",
|
||||
@@ -562,7 +613,7 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.SudirAuthRequest": {
|
||||
"domain.SudirAuthRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authCode"
|
||||
@@ -573,7 +624,65 @@ var doc = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.UsersRequest": {
|
||||
"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": {
|
||||
"created_at": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"first_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"last_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"type": "string"
|
||||
},
|
||||
"role_id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"sudir_user_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"updated_at": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.UsersRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
@@ -590,19 +699,16 @@ var doc = `{
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"phone": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"structure.UsersResponse": {
|
||||
"domain.UsersResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/entity.AdminUser"
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+147
-77
@@ -7,47 +7,20 @@ definitions:
|
||||
primaryColor:
|
||||
type: string
|
||||
type: object
|
||||
entity.AdminUser:
|
||||
properties:
|
||||
createdAt:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
firstName:
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
image:
|
||||
type: string
|
||||
lastName:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
phone:
|
||||
type: string
|
||||
sudirUserId:
|
||||
type: string
|
||||
updatedAt:
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
type: object
|
||||
structure.AdminUserShort:
|
||||
domain.AdminUserShort:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
firstName:
|
||||
type: string
|
||||
image:
|
||||
type: string
|
||||
lastName:
|
||||
type: string
|
||||
phone:
|
||||
role:
|
||||
type: string
|
||||
required:
|
||||
- email
|
||||
type: object
|
||||
structure.Auth:
|
||||
domain.Auth:
|
||||
properties:
|
||||
expired:
|
||||
type: string
|
||||
@@ -56,7 +29,7 @@ definitions:
|
||||
token:
|
||||
type: string
|
||||
type: object
|
||||
structure.AuthRequest:
|
||||
domain.AuthRequest:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
@@ -66,12 +39,28 @@ definitions:
|
||||
- email
|
||||
- password
|
||||
type: object
|
||||
structure.DeleteResponse:
|
||||
domain.CreateUserRequest:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
firstName:
|
||||
type: string
|
||||
lastName:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
roleId:
|
||||
type: integer
|
||||
required:
|
||||
- email
|
||||
- password
|
||||
type: object
|
||||
domain.DeleteResponse:
|
||||
properties:
|
||||
deleted:
|
||||
type: integer
|
||||
type: object
|
||||
structure.GrpcError:
|
||||
domain.GrpcError:
|
||||
properties:
|
||||
details:
|
||||
items:
|
||||
@@ -82,21 +71,61 @@ definitions:
|
||||
errorMessage:
|
||||
type: string
|
||||
type: object
|
||||
structure.IdentitiesRequest:
|
||||
domain.IdentitiesRequest:
|
||||
properties:
|
||||
ids:
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
required:
|
||||
- ids
|
||||
type: object
|
||||
structure.SudirAuthRequest:
|
||||
domain.SudirAuthRequest:
|
||||
properties:
|
||||
authCode:
|
||||
type: string
|
||||
required:
|
||||
- authCode
|
||||
type: object
|
||||
structure.UsersRequest:
|
||||
domain.UpdateUserRequest:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
firstName:
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
lastName:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
roleId:
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
type: object
|
||||
domain.User:
|
||||
properties:
|
||||
created_at:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
first_name:
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
last_name:
|
||||
type: string
|
||||
password:
|
||||
type: string
|
||||
role_id:
|
||||
type: integer
|
||||
sudir_user_id:
|
||||
type: string
|
||||
updated_at:
|
||||
type: string
|
||||
type: object
|
||||
domain.UsersRequest:
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
@@ -108,14 +137,12 @@ definitions:
|
||||
type: integer
|
||||
offset:
|
||||
type: integer
|
||||
phone:
|
||||
type: string
|
||||
type: object
|
||||
structure.UsersResponse:
|
||||
domain.UsersResponse:
|
||||
properties:
|
||||
items:
|
||||
items:
|
||||
$ref: '#/definitions/entity.AdminUser'
|
||||
$ref: '#/definitions/domain.User'
|
||||
type: array
|
||||
type: object
|
||||
host: localhost:9000
|
||||
@@ -138,30 +165,26 @@ paths:
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/structure.AuthRequest'
|
||||
$ref: '#/definitions/domain.AuthRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.Auth'
|
||||
$ref: '#/definitions/domain.Auth'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"401":
|
||||
description: Данные для авторизации не верны
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
"404":
|
||||
description: Пользователь не найден
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Авторизация по логину и паролю
|
||||
tags:
|
||||
- auth
|
||||
@@ -176,26 +199,26 @@ paths:
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/structure.SudirAuthRequest'
|
||||
$ref: '#/definitions/domain.SudirAuthRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.Auth'
|
||||
$ref: '#/definitions/domain.Auth'
|
||||
"401":
|
||||
description: Некорректный код для авторизации
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"412":
|
||||
description: Авторизация СУДИР не настроена на сервере
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Авторизация по авторизационному коду от СУДИР
|
||||
tags:
|
||||
- auth
|
||||
@@ -218,19 +241,19 @@ paths:
|
||||
"400":
|
||||
description: Невалидный токен
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Выход из авторизованной сессии
|
||||
tags:
|
||||
- auth
|
||||
/user/create_update_user:
|
||||
/user/create_user:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Создать пользователя или обновить данные существующего
|
||||
description: Создать пользователя
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
@@ -242,23 +265,27 @@ paths:
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/entity.AdminUser'
|
||||
$ref: '#/definitions/domain.CreateUserRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/entity.AdminUser'
|
||||
$ref: '#/definitions/domain.User'
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"409":
|
||||
description: Пользователь с указанным email уже существует
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
summary: Создать/Обновить пользователя
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Создать пользователя
|
||||
tags:
|
||||
- user
|
||||
/user/delete_user:
|
||||
@@ -277,22 +304,22 @@ paths:
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/structure.IdentitiesRequest'
|
||||
$ref: '#/definitions/domain.IdentitiesRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.DeleteResponse'
|
||||
$ref: '#/definitions/domain.DeleteResponse'
|
||||
"400":
|
||||
description: Невалидное тело запроса
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Удалить пользователя
|
||||
tags:
|
||||
- user
|
||||
@@ -317,11 +344,11 @@ paths:
|
||||
"400":
|
||||
description: Невалидный токен
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получение внешнего вида
|
||||
tags:
|
||||
- user
|
||||
@@ -342,19 +369,19 @@ paths:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.AdminUserShort'
|
||||
$ref: '#/definitions/domain.AdminUserShort'
|
||||
"400":
|
||||
description: Невалидный токен
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"401":
|
||||
description: Токен не соответствует ни одному пользователю
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получить профиль
|
||||
tags:
|
||||
- user
|
||||
@@ -374,23 +401,66 @@ paths:
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/structure.UsersRequest'
|
||||
$ref: '#/definitions/domain.UsersRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/structure.UsersResponse'
|
||||
$ref: '#/definitions/domain.UsersResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/structure.GrpcError'
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Список пользователей
|
||||
tags:
|
||||
- user
|
||||
/user/update_user:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Обновить данные существующего пользователя
|
||||
parameters:
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.UpdateUserRequest'
|
||||
produces:
|
||||
- application/json
|
||||
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'
|
||||
summary: Обновить пользователя
|
||||
tags:
|
||||
- user
|
||||
swagger: "2.0"
|
||||
@@ -0,0 +1,18 @@
|
||||
package domain
|
||||
|
||||
const AdminAuthHeaderName = "x-auth-admin"
|
||||
|
||||
type Auth struct {
|
||||
Token string
|
||||
Expired string `json:",omitempty"`
|
||||
HeaderName string
|
||||
}
|
||||
|
||||
type AuthRequest struct {
|
||||
Email string `valid:"required"`
|
||||
Password string ` valid:"required"`
|
||||
}
|
||||
|
||||
type SudirAuthRequest struct {
|
||||
AuthCode string `valid:"required"`
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnauthenticated = errors.New("authentication failure")
|
||||
ErrSudirAuthorization = errors.New("User is authorized only with SUDIR")
|
||||
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
|
||||
ErrInvalid = errors.New("entity is invalid")
|
||||
ErrAlreadyExists = errors.New("already exists")
|
||||
)
|
||||
@@ -0,0 +1,7 @@
|
||||
package domain
|
||||
|
||||
type GrpcError struct {
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Details []interface{} `json:"details"`
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
type UsersResponse struct {
|
||||
Items []User
|
||||
}
|
||||
|
||||
type UsersRequest struct {
|
||||
Ids []int64
|
||||
Offset int
|
||||
Limit int
|
||||
Email string
|
||||
}
|
||||
|
||||
type AdminUserShort struct {
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string `valid:"required"`
|
||||
Role string
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string `valid:"required"`
|
||||
Password string `valid:"required"`
|
||||
}
|
||||
|
||||
type UpdateUserRequest struct {
|
||||
Id int64 `valid:"required"`
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
type DeleteResponse struct {
|
||||
Deleted int
|
||||
}
|
||||
|
||||
type IdentitiesRequest struct {
|
||||
Ids []int64 `valid:"required"`
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package entity
|
||||
|
||||
import "time"
|
||||
|
||||
type AdminToken struct {
|
||||
tableName string `pg:"?db_schema.tokens" json:"-"`
|
||||
Id int64 `json:"id"`
|
||||
UserId int64 `json:"userId"`
|
||||
Token string `json:"token"`
|
||||
ExpiredAt *time.Time `json:"expiredAt"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
}
|
||||
|
||||
type AdminUser struct {
|
||||
tableName string `pg:"?db_schema.users" json:"-"`
|
||||
SudirUserId string `json:"sudirUserId"`
|
||||
Id int64 `json:"id"`
|
||||
RoleId int `json:"roleId"`
|
||||
Image string `json:"image"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Phone string `json:"phone"`
|
||||
UpdatedAt time.Time `json:"updatedAt" sql:",null"`
|
||||
CreatedAt time.Time `json:"createdAt" sql:",null"`
|
||||
}
|
||||
+1
-2
@@ -5,11 +5,10 @@ import (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
tableName string `pg:"?db_schema.roles" json:"-"`
|
||||
Id int
|
||||
Name string
|
||||
Rights interface{}
|
||||
Description string
|
||||
Description *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
@@ -1,6 +1,19 @@
|
||||
package sudir
|
||||
package entity
|
||||
|
||||
type UserResponse struct {
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type SudirAuthError struct {
|
||||
ErrorName string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
func (s *SudirAuthError) Error() string {
|
||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||
}
|
||||
|
||||
type SudirUserResponse struct {
|
||||
*SudirAuthError
|
||||
|
||||
Email string `json:"email"`
|
||||
@@ -10,7 +23,7 @@ type UserResponse struct {
|
||||
FamilyName string `json:"family_name"`
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
type SudirTokenResponse struct {
|
||||
*SudirAuthError
|
||||
|
||||
IdToken string `json:"id_token"`
|
||||
@@ -0,0 +1,39 @@
|
||||
package entity
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
SudirUserId *string
|
||||
Id int64
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
UpdatedAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type SudirUser struct {
|
||||
RoleId int
|
||||
SudirUserId string
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
}
|
||||
|
||||
type CreateUser struct {
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
type UpdateUser struct {
|
||||
RoleId int
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
@@ -1,16 +1,85 @@
|
||||
module msp-admin-service
|
||||
|
||||
go 1.13
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.3
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/go-pg/pg/v9 v9.2.1
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3
|
||||
github.com/integration-system/isp-kit v1.12.0
|
||||
github.com/integration-system/isp-lib/v2 v2.8.7
|
||||
github.com/integration-system/isp-log v1.1.8
|
||||
github.com/integration-system/jsonschema v1.0.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/soheilhy/cmux v0.1.4
|
||||
golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b
|
||||
google.golang.org/grpc v1.38.0
|
||||
google.golang.org/grpc/examples v0.0.0-20201119011251-78864797b877 // indirect
|
||||
github.com/stretchr/testify v1.8.0
|
||||
golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0
|
||||
google.golang.org/grpc v1.49.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/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/golang/protobuf v1.5.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/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.10 // 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.1 // 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/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/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
|
||||
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-20220921203646-d300de134e69 // indirect
|
||||
golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
golang.org/x/tools v0.1.2 // indirect
|
||||
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737 // 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/yaml.v3 v3.0.1 // indirect
|
||||
nhooyr.io/websocket v1.8.7 // indirect
|
||||
)
|
||||
@@ -1,41 +0,0 @@
|
||||
package helper
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/metadata"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/controller"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/structure"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
// ===== AUTH =====
|
||||
Login func(structure.AuthRequest) (*structure.Auth, error) `method:"login" group:"auth" inner:"false"`
|
||||
LoginWithSudir func(structure.SudirAuthRequest) (*structure.Auth, error) `method:"login_with_sudir" group:"auth" inner:"false"`
|
||||
Logout func(metadata.MD) error `method:"logout" group:"auth" inner:"true"`
|
||||
|
||||
// ===== USER =====
|
||||
GetProfile func(metadata.MD) (*structure.AdminUserShort, error) `method:"get_profile" group:"user" inner:"true"`
|
||||
GetUIDesign func(metadata metadata.MD) (conf.UIDesign, error) `method:"get_design" group:"user" inner:"true"`
|
||||
GetUsers func(structure.UsersRequest) (*structure.UsersResponse, error) `method:"get_users" group:"user" inner:"true"`
|
||||
CreateUpdateUser func(user entity.AdminUser) (*entity.AdminUser, error) `method:"create_update_user" group:"user" inner:"true"`
|
||||
DeleteUser func(identities structure.IdentitiesRequest) (*structure.DeleteResponse, error) `method:"delete_user" group:"user" inner:"true"`
|
||||
|
||||
Notify func() `method:"notify" group:"" inner:"false"`
|
||||
}
|
||||
|
||||
func GetHandlers() []interface{} {
|
||||
return []interface{}{
|
||||
&Handlers{
|
||||
Login: controller.Login,
|
||||
LoginWithSudir: controller.LoginWithSudir,
|
||||
Logout: controller.Logout,
|
||||
GetProfile: controller.GetProfile,
|
||||
GetUIDesign: controller.GetUIDesign,
|
||||
GetUsers: controller.GetUsers,
|
||||
CreateUpdateUser: controller.CreateUpdateUser,
|
||||
DeleteUser: controller.DeleteUser,
|
||||
Notify: nil,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package invoker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/config/schema"
|
||||
log "github.com/integration-system/isp-log"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/backend"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type (
|
||||
ModuleInfo struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Active bool `json:"active"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
LastConnectedAt time.Time `json:"lastConnectedAt"`
|
||||
LastDisconnectedAt time.Time `json:"lastDisconnectedAt"`
|
||||
ConfigSchema *schema.Schema `json:"configSchema"`
|
||||
Status interface{} `json:"status"`
|
||||
RequiredModules interface{} `json:"requiredModules"`
|
||||
}
|
||||
|
||||
ConfigRequest struct {
|
||||
ModuleId string `json:"moduleId"`
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
ConfigClient = backend.NewRxGrpcClient(
|
||||
backend.WithDialOptions(grpc.WithInsecure()),
|
||||
)
|
||||
)
|
||||
|
||||
func GetConfigsById(request ConfigRequest) json.RawMessage {
|
||||
var response json.RawMessage
|
||||
if err := ConfigClient.Invoke("config/config/get_configs_by_module_id", 0, request, &response); err != nil {
|
||||
log.Errorf(77, "can't get response from grpc request : %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func GetModulesInfo() []ModuleInfo {
|
||||
var response []ModuleInfo
|
||||
if err := ConfigClient.Invoke("config/module/get_modules_info", 0, nil, &response); err != nil {
|
||||
log.Errorf(77, "can't get response from grpc request : %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package invoker
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/http"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/invoker/sudir"
|
||||
)
|
||||
|
||||
var Sudir = sudirCli{
|
||||
cli: http.NewJsonRestClient(),
|
||||
}
|
||||
|
||||
type sudirCli struct {
|
||||
cli http.RestClient
|
||||
}
|
||||
|
||||
func (c sudirCli) GetToken(cfg conf.SudirAuth, authCode string) (*sudir.TokenResponse, error) {
|
||||
method := fmt.Sprintf("%s/blitz/oauth/te?grant_type=authorization_code&code=%s&redirect_uri=%s",
|
||||
cfg.Host, authCode, cfg.RedirectURI,
|
||||
)
|
||||
basicAuth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", cfg.ClientId, cfg.ClientSecret)))
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Authorization": fmt.Sprintf("Basic %s", basicAuth),
|
||||
}
|
||||
response := new(sudir.TokenResponse)
|
||||
err := c.cli.Invoke(http.POST, method, headers, nil, response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (c sudirCli) GetUser(host, accessToken string) (*sudir.UserResponse, error) {
|
||||
method := fmt.Sprintf("%s/blitz/oauth/me", host)
|
||||
headers := map[string]string{
|
||||
"Authorization": fmt.Sprintf("Bearer %s", accessToken),
|
||||
}
|
||||
response := new(sudir.UserResponse)
|
||||
err := c.cli.Invoke(http.GET, method, headers, nil, response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package sudir
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type SudirAuthError struct {
|
||||
ErrorName string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
func (s *SudirAuthError) Error() string {
|
||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||
}
|
||||
@@ -1,31 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/backend"
|
||||
"github.com/integration-system/isp-lib/v2/bootstrap"
|
||||
"github.com/integration-system/isp-lib/v2/config/schema"
|
||||
"github.com/integration-system/isp-lib/v2/metric"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"github.com/soheilhy/cmux"
|
||||
"github.com/integration-system/isp-kit/bootstrap"
|
||||
"github.com/integration-system/isp-kit/shutdown"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
_ "msp-admin-service/docs"
|
||||
"msp-admin-service/helper"
|
||||
"msp-admin-service/invoker"
|
||||
"msp-admin-service/model"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/routes"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "0.1.0"
|
||||
grpcLn net.Listener
|
||||
wsLn net.Listener
|
||||
)
|
||||
var version = "1.0.0"
|
||||
|
||||
// @title msp-admin-service
|
||||
// @version 1.0.0
|
||||
@@ -40,88 +23,26 @@ var (
|
||||
//go:generate rm -f docs/swagger.json
|
||||
|
||||
func main() {
|
||||
bootstrap.
|
||||
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}).
|
||||
OnLocalConfigLoad(onLocalConfigLoad).
|
||||
DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")).
|
||||
SocketConfiguration(socketConfiguration).
|
||||
DeclareMe(routesData).
|
||||
RequireModule("config", invoker.ConfigClient.ReceiveAddressList, true).
|
||||
RequireRoutes(service.SessionManager.RoutesUpdateSessionCallback).
|
||||
OnRemoteConfigReceive(onRemoteConfigReceive).
|
||||
OnShutdown(onShutdown).
|
||||
Run()
|
||||
}
|
||||
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
|
||||
appConfig := cfg.(*conf.Configuration)
|
||||
return structure.SocketConfiguration{
|
||||
Host: appConfig.ConfigServiceAddress.IP,
|
||||
Port: appConfig.ConfigServiceAddress.Port,
|
||||
Secure: false,
|
||||
UrlParams: map[string]string{
|
||||
"module_name": appConfig.ModuleName,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func onShutdown(ctx context.Context, _ os.Signal) {
|
||||
service.SessionManager.ShutdownSocket(ctx)
|
||||
backend.StopGrpcServer()
|
||||
closeListeners(wsLn, grpcLn)
|
||||
}
|
||||
|
||||
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||
model.DbClient.ReceiveConfiguration(remoteConfig.Database)
|
||||
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
|
||||
metric.InitHttpServer(remoteConfig.Metrics)
|
||||
}
|
||||
|
||||
func onLocalConfigLoad(cfg *conf.Configuration) {
|
||||
handlers := helper.GetHandlers()
|
||||
defaultService := backend.GetDefaultService(cfg.ModuleName, handlers...)
|
||||
|
||||
if err := serve(cfg.GrpcInnerAddress, defaultService); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
|
||||
}
|
||||
}
|
||||
|
||||
func serve(addr structure.AddressConfiguration, grpcService *backend.DefaultService) error {
|
||||
ln, err := net.Listen("tcp", addr.GetAddress())
|
||||
assembly, err := assembly.New(boot)
|
||||
if err != nil {
|
||||
return err
|
||||
logger.Fatal(app.Context(), err)
|
||||
}
|
||||
app.AddRunners(assembly.Runners()...)
|
||||
app.AddClosers(assembly.Closers()...)
|
||||
|
||||
m := cmux.New(ln)
|
||||
grpcLn = m.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
|
||||
wsLn = m.Match(cmux.HTTP1HeaderField("Upgrade", "websocket"))
|
||||
shutdown.On(func() {
|
||||
logger.Info(app.Context(), "starting shutdown")
|
||||
app.Shutdown()
|
||||
logger.Info(app.Context(), "shutdown completed")
|
||||
})
|
||||
|
||||
service.SessionManager.InitWebSocket(wsLn)
|
||||
|
||||
backend.StartBackendGrpcServerOn(addr, grpcLn, grpcService)
|
||||
go func() {
|
||||
if err := m.Serve(); err != nil {
|
||||
log.Warn(stdcodes.ModuleGrpcServiceStartError, err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func routesData(localConfig interface{}) bootstrap.ModuleInfo {
|
||||
cfg := localConfig.(*conf.Configuration)
|
||||
return bootstrap.ModuleInfo{
|
||||
ModuleName: cfg.ModuleName,
|
||||
ModuleVersion: version,
|
||||
GrpcOuterAddress: cfg.GrpcOuterAddress,
|
||||
Handlers: helper.GetHandlers(),
|
||||
}
|
||||
}
|
||||
|
||||
func closeListeners(lns ...net.Listener) {
|
||||
for _, ln := range lns {
|
||||
if ln != nil {
|
||||
_ = ln.Close()
|
||||
}
|
||||
err = app.Run()
|
||||
if err != nil {
|
||||
app.Shutdown()
|
||||
logger.Fatal(app.Context(), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/grpc/endpoint"
|
||||
"github.com/integration-system/isp-kit/grpc/isp"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func ErrorHandler(logger log.Logger) endpoint.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
result, err := next(ctx, message)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
logger.Error(ctx, err)
|
||||
_, ok := status.FromError(err)
|
||||
if ok {
|
||||
return result, err
|
||||
}
|
||||
// hide error details to prevent potential security leaks
|
||||
return result, status.Error(codes.Internal, "Internal service error")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users
|
||||
DROP CONSTRAINT users_phone_key,
|
||||
DROP COLUMN phone,
|
||||
DROP COLUMN image;
|
||||
|
||||
ALTER TABLE users ALTER COLUMN first_name SET DEFAULT '';
|
||||
UPDATE users SET first_name=DEFAULT WHERE first_name IS NULL;
|
||||
ALTER TABLE users ALTER COLUMN first_name SET NOT NULL;
|
||||
|
||||
ALTER TABLE users ALTER COLUMN last_name SET DEFAULT '';
|
||||
UPDATE users SET last_name=DEFAULT WHERE last_name IS NULL;
|
||||
ALTER TABLE users ALTER COLUMN last_name SET NOT NULL;
|
||||
|
||||
ALTER TABLE users ALTER COLUMN password SET DEFAULT '';
|
||||
UPDATE users SET password=DEFAULT WHERE password IS NULL;
|
||||
ALTER TABLE users ALTER COLUMN password SET NOT NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users
|
||||
ADD COLUMN phone varchar(255) UNIQUE,
|
||||
ADD COLUMN image varchar(255),
|
||||
ALTER COLUMN first_name DROP NOT NULL,
|
||||
ALTER COLUMN last_name DROP NOT NULL,
|
||||
ALTER COLUMN password DROP NOT NULL;
|
||||
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/database"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
)
|
||||
|
||||
var (
|
||||
DbClient = database.NewRxDbClient(
|
||||
database.WithSchemaEnsuring(),
|
||||
database.WithSchemaAutoInjecting(),
|
||||
database.WithMigrationsEnsuring(),
|
||||
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
|
||||
log.Fatal(stdcodes.InitializingDbError, err.Error())
|
||||
}),
|
||||
)
|
||||
RoleRep = RoleRepository{client: DbClient}
|
||||
)
|
||||
@@ -1,44 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg/v9"
|
||||
"github.com/go-pg/pg/v9/orm"
|
||||
"github.com/integration-system/isp-lib/v2/database"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type RoleRepository struct {
|
||||
DB orm.DB
|
||||
client *database.RxDbClient
|
||||
}
|
||||
|
||||
func (r *RoleRepository) GetRoleById(id int) (*entity.Role, error) {
|
||||
role := new(entity.Role)
|
||||
err := r.getDb().Model(role).Where("id = ?", id).Select()
|
||||
if err != nil {
|
||||
if err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
func (r *RoleRepository) GetRoleByName(name string) (*entity.Role, error) {
|
||||
role := new(entity.Role)
|
||||
err := r.getDb().Model(role).Where("name = ?", name).Select()
|
||||
if err != nil {
|
||||
if err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
func (r *RoleRepository) getDb() orm.DB {
|
||||
if r.DB != nil {
|
||||
return r.DB
|
||||
}
|
||||
return r.client.Unsafe()
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg/v9"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/structure"
|
||||
)
|
||||
|
||||
const DELETE_USERS = "DELETE FROM admin_service.users WHERE id IN (?)"
|
||||
|
||||
/*func GetUserByToken(token string) (*structure.AdminUserShort, error) {
|
||||
var user structure.AdminUserShort
|
||||
_, err := database.GetDBManager().Db.Model(&user).
|
||||
Query(&user, `SELECT
|
||||
u.image,
|
||||
u.email,
|
||||
u.phone,
|
||||
u.first_name,
|
||||
u.last_name
|
||||
FROM
|
||||
`+utils.DB_SCHEME+`.tokens
|
||||
t LEFT JOIN `+utils.DB_SCHEME+`.users u ON t.user_id = u.ID
|
||||
WHERE
|
||||
token = ?`, token)
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, err
|
||||
}*/
|
||||
|
||||
func GetUserByEmail(email string) (*entity.AdminUser, error) {
|
||||
var user entity.AdminUser
|
||||
DbClient.Unsafe()
|
||||
err := DbClient.Unsafe().Model(&user).
|
||||
Where("email = ?", email).
|
||||
First()
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func GetUserById(identity int64) (*entity.AdminUser, error) {
|
||||
var user entity.AdminUser
|
||||
err := DbClient.Unsafe().Model(&user).
|
||||
Where("id = ?", identity).
|
||||
First()
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func GetUserBySudirUserId(id string) (*entity.AdminUser, error) {
|
||||
var user entity.AdminUser
|
||||
err := DbClient.Unsafe().Model(&user).
|
||||
Where("sudir_user_id = ?", id).
|
||||
First()
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &user, err
|
||||
}
|
||||
|
||||
func GetUsers(usersRequest structure.UsersRequest) (*[]entity.AdminUser, error) {
|
||||
var users []entity.AdminUser
|
||||
query := DbClient.Unsafe().Model(&users)
|
||||
if len(usersRequest.Ids) > 0 {
|
||||
query.Where("id IN (?)", pg.In(usersRequest.Ids))
|
||||
}
|
||||
if usersRequest.Email != "" {
|
||||
query.Where("email LIKE ?", "%"+usersRequest.Email+"%")
|
||||
}
|
||||
if usersRequest.Phone != "" {
|
||||
query.Where("phone LIKE ?", "%"+usersRequest.Phone+"%")
|
||||
}
|
||||
err := query.
|
||||
Order("created_at DESC").
|
||||
Limit(usersRequest.Limit).
|
||||
Offset(usersRequest.Offset).
|
||||
Select()
|
||||
if err != nil && err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return &users, err
|
||||
}
|
||||
|
||||
func CreateUser(user entity.AdminUser) (entity.AdminUser, error) {
|
||||
_, err := DbClient.Unsafe().Model(&user).
|
||||
Returning("id").
|
||||
Returning("created_at").
|
||||
Returning("updated_at").
|
||||
Insert()
|
||||
return user, err
|
||||
}
|
||||
|
||||
func UpdateUser(user entity.AdminUser) (entity.AdminUser, error) {
|
||||
_, err := DbClient.Unsafe().Model(&user).
|
||||
WherePK().
|
||||
Returning("id").
|
||||
Returning("created_at").
|
||||
Returning("updated_at").
|
||||
Update()
|
||||
return user, err
|
||||
}
|
||||
|
||||
func DeleteUser(identities structure.IdentitiesRequest) (int, error) {
|
||||
result, err := DbClient.Unsafe().Exec(DELETE_USERS, pg.In(identities.Ids))
|
||||
return result.RowsAffected(), err
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewRole(db db.DB) Role {
|
||||
return Role{db: db}
|
||||
}
|
||||
|
||||
func (r Role) GetRoleById(ctx context.Context, id int) (*entity.Role, error) {
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("roles").
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
role := entity.Role{}
|
||||
err = r.db.SelectRow(ctx, &role, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &role, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, error) {
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("roles").
|
||||
Where(squirrel.Eq{"name": name}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
role := entity.Role{}
|
||||
err = r.db.SelectRow(ctx, &role, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &role, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Sudir struct {
|
||||
httpCli *httpcli.Client
|
||||
cfg *conf.SudirAuth
|
||||
}
|
||||
|
||||
func NewSudir(httpCli *httpcli.Client, cfg *conf.SudirAuth) Sudir {
|
||||
return Sudir{
|
||||
httpCli: httpCli,
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error) {
|
||||
urlString, err := url.JoinPath(s.cfg.Host, "/blitz/oauth/te")
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build url")
|
||||
}
|
||||
|
||||
response := entity.SudirTokenResponse{}
|
||||
|
||||
res, err := s.httpCli.Post(urlString).
|
||||
BasicAuth(httpcli.BasicAuth{
|
||||
Username: s.cfg.ClientId,
|
||||
Password: s.cfg.ClientSecret,
|
||||
}).
|
||||
Header("Content-Type", "application/x-www-form-urlencoded").
|
||||
QueryParams(map[string]any{
|
||||
"grant_type": "authorization_code",
|
||||
"code": authCode,
|
||||
"redirect_uri": s.cfg.RedirectURI,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(ctx)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "http request")
|
||||
}
|
||||
|
||||
defer res.Close()
|
||||
|
||||
if !res.IsSuccess() {
|
||||
return nil, errors.Errorf("unexpected response: code: %d, status: %s", res.StatusCode(), res.Raw.Status)
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) {
|
||||
urlString, err := url.JoinPath(s.cfg.Host, "/blitz/oauth/me")
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build url")
|
||||
}
|
||||
|
||||
response := entity.SudirUserResponse{}
|
||||
|
||||
res, err := s.httpCli.
|
||||
Get(urlString).
|
||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||
JsonResponseBody(&response).
|
||||
Do(ctx)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "http request")
|
||||
}
|
||||
|
||||
defer res.Close()
|
||||
|
||||
if !res.IsSuccess() {
|
||||
return nil, errors.Errorf("unexpected response: code: %d, status: %s", res.StatusCode(), res.Raw.Status)
|
||||
}
|
||||
|
||||
return &response, nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/integration-system/isp-kit/db"
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewUser(db db.DB) User {
|
||||
return User{db: db}
|
||||
}
|
||||
|
||||
func (u User) GetUserByEmail(ctx context.Context, email 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{"email": email}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
user := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &user, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUserById(ctx context.Context, identity int64) (*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{"id": identity}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
user := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &user, nil
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
user := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &user, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error) {
|
||||
// take every except password
|
||||
q := query.New().
|
||||
Select("id", "role_id", "first_name", "last_name",
|
||||
"email", "sudir_user_id", "created_at", "updated_at").
|
||||
From("users")
|
||||
|
||||
if len(ids) > 0 {
|
||||
q = q.Where(squirrel.Eq{"id": ids})
|
||||
}
|
||||
if email != "" {
|
||||
q = q.Where("email LIKE ?", "%"+email+"%")
|
||||
}
|
||||
qstring, args, err := q.
|
||||
Limit(uint64(limit)).
|
||||
Offset(uint64(offset)).
|
||||
OrderBy("created_at DESC").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
users := make([]entity.User, 0)
|
||||
err = u.db.Select(ctx, &users, qstring, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
}
|
||||
|
||||
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().
|
||||
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").
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error) {
|
||||
// return every except password
|
||||
q, args, err := query.New().
|
||||
Update("users").
|
||||
SetMap(map[string]interface{}{
|
||||
"role_id": user.RoleId,
|
||||
"first_name": user.FirstName,
|
||||
"last_name": user.LastName,
|
||||
"email": user.Email,
|
||||
"password": user.Password,
|
||||
}).
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
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
|
||||
}
|
||||
|
||||
func (u User) DeleteUser(ctx context.Context, ids []int64) (int, error) {
|
||||
q, args, err := query.New().
|
||||
Delete("users").
|
||||
Where(squirrel.Eq{"id": ids}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result, err := u.db.Exec(ctx, q, args...)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "db exec")
|
||||
}
|
||||
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "get row affected")
|
||||
}
|
||||
|
||||
return int(affected), err
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-kit/cluster"
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/grpc/endpoint"
|
||||
"github.com/integration-system/isp-kit/grpc/isp"
|
||||
"msp-admin-service/controller"
|
||||
)
|
||||
|
||||
type Controllers struct {
|
||||
Auth controller.Auth
|
||||
User controller.User
|
||||
Customization controller.Customization
|
||||
}
|
||||
|
||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
return endpointDescriptors(Controllers{})
|
||||
}
|
||||
|
||||
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
|
||||
muxer := grpc.NewMux()
|
||||
for _, descriptor := range endpointDescriptors(c) {
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
return muxer
|
||||
}
|
||||
|
||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
return []cluster.EndpointDescriptor{
|
||||
{
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Auth.Login,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/login_with_sudir",
|
||||
Inner: false,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Auth.LoginWithSudir,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Auth.Logout,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.GetProfile,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.GetUsers,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.CreateUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.UpdateUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
UserAuthRequired: false,
|
||||
Handler: c.User.DeleteUser,
|
||||
},
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
type tokenService interface {
|
||||
GenerateToken(id int64) (string, string, error)
|
||||
}
|
||||
|
||||
type sudirService interface {
|
||||
Authenticate(ctx context.Context, authCode string) (*entity.SudirUser, error)
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
userRepository userRepository
|
||||
tokenService tokenService
|
||||
sudirService sudirService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewAuth(userRepository userRepository, tokenService tokenService, sudirService sudirService, logger log.Logger) Auth {
|
||||
return Auth{
|
||||
userRepository: userRepository,
|
||||
tokenService: tokenService,
|
||||
sudirService: sudirService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error) {
|
||||
user, err := a.userRepository.GetUserByEmail(ctx, authRequest.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email")
|
||||
case user.SudirUserId != nil:
|
||||
return nil, domain.ErrSudirAuthorization
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authRequest.Password))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong password")
|
||||
}
|
||||
|
||||
tokenString, expired, err := a.tokenService.GenerateToken(user.Id)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
return &domain.Auth{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
HeaderName: domain.AdminAuthHeaderName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error) {
|
||||
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode)
|
||||
|
||||
var authErr *entity.SudirAuthError
|
||||
switch {
|
||||
case errors.As(err, &authErr):
|
||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||
return nil, domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "sudir authenticate")
|
||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||
log.String("userId", sudirUser.SudirUserId),
|
||||
log.String("email", sudirUser.Email))
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
tokenString, expired, err := a.tokenService.GenerateToken(user.Id)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "generate token")
|
||||
}
|
||||
|
||||
return &domain.Auth{
|
||||
Token: tokenString,
|
||||
Expired: expired,
|
||||
HeaderName: domain.AdminAuthHeaderName,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
etp "github.com/integration-system/isp-etp-go/v2"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"msp-admin-service/invoker"
|
||||
)
|
||||
|
||||
const (
|
||||
onConfigInEvent = "config_in"
|
||||
onConfigOutEvent = "config_out"
|
||||
onConfigUpdateEvent = "config_upd"
|
||||
onModuleUpdateEvent = "module_upd"
|
||||
onUniversalUpdateEvent = "universal_upd"
|
||||
|
||||
broadcastConfigUpdateEvent = "force_config_update"
|
||||
broadcastModuleUpdateEvent = "force_module_update"
|
||||
)
|
||||
|
||||
type (
|
||||
sessionManager struct {
|
||||
lock sync.Mutex
|
||||
session map[string]sessionInfo
|
||||
wsServer etp.Server
|
||||
httpServer *http.Server
|
||||
}
|
||||
sessionInfo struct {
|
||||
ConfigID string `json:"id"`
|
||||
ModuleID string `json:"module"`
|
||||
Version int `json:"version"`
|
||||
}
|
||||
sessionSend struct {
|
||||
Module string `json:"module"`
|
||||
Data []sessionInfo `json:"data"`
|
||||
}
|
||||
)
|
||||
|
||||
var SessionManager = sessionManager{
|
||||
session: make(map[string]sessionInfo),
|
||||
}
|
||||
|
||||
func (s *sessionManager) GetConfSessionByModule(id string) []sessionInfo {
|
||||
var data []sessionInfo
|
||||
s.lock.Lock()
|
||||
for _, v := range s.session {
|
||||
if v.ModuleID == id {
|
||||
data = append(data, v)
|
||||
}
|
||||
}
|
||||
s.lock.Unlock()
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func (s *sessionManager) AddConfSession(data []byte, id string) {
|
||||
var sessionData sessionInfo
|
||||
if err := json.Unmarshal(data, &sessionData); err != nil {
|
||||
log.Error(44, "get date from request: This session can't be registered")
|
||||
return
|
||||
}
|
||||
s.lock.Lock()
|
||||
s.session[id] = sessionData
|
||||
s.lock.Unlock()
|
||||
|
||||
send := sessionSend{
|
||||
Module: sessionData.ModuleID,
|
||||
Data: s.GetConfSessionByModule(sessionData.ModuleID),
|
||||
}
|
||||
|
||||
if err := s.wsServer.BroadcastToAll(broadcastConfigUpdateEvent, jsoner(send)); err != nil {
|
||||
log.Error(44, "send new session info to clients")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sessionManager) DropConfSession(id string) {
|
||||
var modID string
|
||||
s.lock.Lock()
|
||||
if value, ok := s.session[id]; !ok {
|
||||
s.lock.Unlock()
|
||||
return
|
||||
} else {
|
||||
modID = value.ModuleID
|
||||
}
|
||||
|
||||
delete(s.session, id)
|
||||
s.lock.Unlock()
|
||||
|
||||
send := sessionSend{
|
||||
Module: modID,
|
||||
Data: s.GetConfSessionByModule(modID),
|
||||
}
|
||||
|
||||
if err := s.wsServer.BroadcastToAll(broadcastConfigUpdateEvent, jsoner(send)); err != nil {
|
||||
log.Error(44, "send new session info to clients")
|
||||
}
|
||||
}
|
||||
|
||||
func jsoner(data interface{}) []byte {
|
||||
byt, _ := json.Marshal(data)
|
||||
return byt
|
||||
}
|
||||
|
||||
func (s *sessionManager) updateModulesList() bool {
|
||||
result := invoker.GetModulesInfo()
|
||||
if result != nil {
|
||||
if err := s.wsServer.BroadcastToAll(broadcastModuleUpdateEvent, jsoner(result)); err != nil {
|
||||
log.Error(44, "sending new module info to clients")
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *sessionManager) RoutesUpdateSessionCallback(_ structure.RoutingConfig) bool {
|
||||
return s.updateModulesList()
|
||||
}
|
||||
|
||||
func (s *sessionManager) InitWebSocket(ln net.Listener) {
|
||||
etpServerConfig := etp.ServerConfig{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
|
||||
s.wsServer = etp.NewServer(context.TODO(), etpServerConfig).
|
||||
OnDisconnect(func(conn etp.Conn, err error) {
|
||||
s.DropConfSession(conn.ID())
|
||||
}).
|
||||
OnError(func(conn etp.Conn, err error) {
|
||||
s.DropConfSession(conn.ID())
|
||||
log.Errorf(44, "On WebSocket client connection error occurred: %v", err)
|
||||
}).
|
||||
//on open session
|
||||
On(onConfigInEvent, func(conn etp.Conn, data []byte) {
|
||||
s.AddConfSession(data, conn.ID())
|
||||
}).
|
||||
//on close session
|
||||
On(onConfigOutEvent, func(conn etp.Conn, data []byte) {
|
||||
s.DropConfSession(conn.ID())
|
||||
}).
|
||||
//on update data session
|
||||
On(onUniversalUpdateEvent, func(conn etp.Conn, data []byte) {
|
||||
var (
|
||||
responseData json.RawMessage
|
||||
requestData invoker.ConfigRequest
|
||||
)
|
||||
|
||||
if err := json.Unmarshal(data, &requestData); err != nil {
|
||||
log.Errorf(44, "parse request data: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if responseData = invoker.GetConfigsById(requestData); responseData == nil {
|
||||
return
|
||||
}
|
||||
|
||||
send := struct {
|
||||
ModuleId string `json:"moduleId"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}{
|
||||
ModuleId: requestData.ModuleId,
|
||||
Data: responseData,
|
||||
}
|
||||
|
||||
if err := s.wsServer.BroadcastToAll("force_update", jsoner(send)); err != nil {
|
||||
log.Errorf(44, "send new config info for module with id %v : %v", requestData.ModuleId, err)
|
||||
}
|
||||
}).
|
||||
//on session info request (on mount config page)
|
||||
On(onConfigUpdateEvent, func(conn etp.Conn, data []byte) {
|
||||
var request struct {
|
||||
Module string `json:"module"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &request); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
modID := request.Module
|
||||
|
||||
send := sessionSend{
|
||||
Module: modID,
|
||||
Data: s.GetConfSessionByModule(modID),
|
||||
}
|
||||
if err := conn.Emit(context.TODO(), broadcastConfigUpdateEvent, jsoner(send)); err != nil {
|
||||
log.Errorf(44, "send new session info to clients : %v", err)
|
||||
}
|
||||
}).
|
||||
//on modules info request (on delete module in module list (client))
|
||||
On(onModuleUpdateEvent, func(conn etp.Conn, data []byte) {
|
||||
s.updateModulesList()
|
||||
})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/admin/notify", s.wsServer.ServeHttp)
|
||||
s.httpServer = &http.Server{Handler: mux}
|
||||
go func() {
|
||||
if err := s.httpServer.Serve(ln); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf(0, "Unable to start http server. err: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *sessionManager) ShutdownSocket(ctx context.Context) {
|
||||
if err := s.httpServer.Shutdown(ctx); err != nil {
|
||||
log.Errorf(44, "Unable to shutdown http server. err: %v", err)
|
||||
}
|
||||
|
||||
s.wsServer.Close()
|
||||
}
|
||||
+50
-22
@@ -1,13 +1,13 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/invoker"
|
||||
"msp-admin-service/model"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,41 +19,69 @@ const (
|
||||
sudirReadOnlyAdminRole = "DIT-KKD-Operators"
|
||||
)
|
||||
|
||||
func AuthSudir(cfg conf.SudirAuth, authCode string) (entity.AdminUser, error) {
|
||||
tokenResponse, err := invoker.Sudir.GetToken(cfg, authCode)
|
||||
if err != nil {
|
||||
return entity.AdminUser{}, err
|
||||
} else if tokenResponse.SudirAuthError != nil {
|
||||
return entity.AdminUser{}, tokenResponse.SudirAuthError
|
||||
type sudirRepo interface {
|
||||
GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error)
|
||||
GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error)
|
||||
}
|
||||
|
||||
type roleRepo interface {
|
||||
GetRoleByName(ctx context.Context, name string) (*entity.Role, error)
|
||||
}
|
||||
|
||||
type Sudir struct {
|
||||
cfg *conf.SudirAuth
|
||||
sudirRepo sudirRepo
|
||||
roleRepo roleRepo
|
||||
}
|
||||
|
||||
func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo, roleRepo roleRepo) Sudir {
|
||||
return Sudir{
|
||||
cfg: cfg,
|
||||
sudirRepo: sudirRepo,
|
||||
roleRepo: roleRepo,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) Authenticate(ctx context.Context, authCode string) (*entity.SudirUser, error) {
|
||||
if s.cfg == nil {
|
||||
return nil, domain.ErrSudirAuthIsMissed
|
||||
}
|
||||
|
||||
user, err := invoker.Sudir.GetUser(cfg.Host, tokenResponse.AccessToken)
|
||||
if err != nil {
|
||||
return entity.AdminUser{}, err
|
||||
} else if user.SudirAuthError != nil {
|
||||
return entity.AdminUser{}, user.SudirAuthError
|
||||
tokenResponse, err := s.sudirRepo.GetToken(ctx, authCode)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get token")
|
||||
case tokenResponse.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token")
|
||||
}
|
||||
|
||||
user, err := s.sudirRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
case user.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
||||
}
|
||||
|
||||
role := getRole(user.Groups)
|
||||
if role == "" {
|
||||
return entity.AdminUser{}, errors.New("undefined role")
|
||||
return nil, errors.New("undefined role")
|
||||
}
|
||||
|
||||
roleInfo, err := model.RoleRep.GetRoleByName(role)
|
||||
if err != nil {
|
||||
return entity.AdminUser{}, errors.WithMessage(err, "get role")
|
||||
}
|
||||
if roleInfo == nil {
|
||||
return entity.AdminUser{}, errors.Errorf("get unknown role: %s", 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")
|
||||
}
|
||||
|
||||
return entity.AdminUser{
|
||||
return &entity.SudirUser{
|
||||
RoleId: roleInfo.Id,
|
||||
SudirUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
Email: user.Email,
|
||||
Password: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
+26
-16
@@ -1,13 +1,10 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
type customClaims struct {
|
||||
@@ -15,37 +12,50 @@ type customClaims struct {
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
func GenerateToken(id int64) (string, string, error) {
|
||||
type Token struct {
|
||||
ttl time.Duration
|
||||
secretKey string
|
||||
}
|
||||
|
||||
func NewToken(ttl time.Duration, secretKey string) Token {
|
||||
return Token{
|
||||
ttl: ttl,
|
||||
secretKey: secretKey,
|
||||
}
|
||||
}
|
||||
|
||||
func (t Token) GenerateToken(id int64) (string, string, error) {
|
||||
expired := ""
|
||||
claims := customClaims{Id: id}
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
if cfg.ExpireSec != 0 {
|
||||
exp := time.Now().Add(time.Second * time.Duration(cfg.ExpireSec))
|
||||
|
||||
if t.ttl != 0 {
|
||||
exp := time.Now().Add(t.ttl)
|
||||
expired = exp.String()
|
||||
claims.ExpiresAt = exp.Unix()
|
||||
}
|
||||
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(cfg.SecretKey))
|
||||
|
||||
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(t.secretKey))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
return "", "", errors.WithMessage(err, "generate jwt with claims")
|
||||
}
|
||||
|
||||
return tokenString, expired, nil
|
||||
}
|
||||
|
||||
func GetUserId(token string) (int64, error) {
|
||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||
func (t Token) GetUserId(token string) (int64, error) {
|
||||
parsed, err := jwt.ParseWithClaims(token, &customClaims{}, func(token *jwt.Token) (i interface{}, e error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
return nil, errors.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(cfg.SecretKey), nil
|
||||
return []byte(t.secretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, errors.WithMessage(err, "parse jwt with claims")
|
||||
}
|
||||
|
||||
if claims, ok := parsed.Claims.(*customClaims); ok && parsed.Valid {
|
||||
return claims.Id, nil
|
||||
} else {
|
||||
return 0, errors.New("token is invalid")
|
||||
}
|
||||
|
||||
return 0, errors.New("token is invalid")
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type userTokenService interface {
|
||||
GetUserId(token string) (int64, error)
|
||||
}
|
||||
|
||||
type userRepo interface {
|
||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||
GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
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)
|
||||
}
|
||||
|
||||
type userRoleRepo interface {
|
||||
GetRoleById(ctx context.Context, id int) (*entity.Role, error)
|
||||
}
|
||||
|
||||
type User struct {
|
||||
userTokenService userTokenService
|
||||
userRepo userRepo
|
||||
userRoleRepo userRoleRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewUser(userTokenService userTokenService, userRepo userRepo, userRoleRepo userRoleRepo, logger log.Logger) User {
|
||||
return User{
|
||||
userTokenService: userTokenService,
|
||||
userRepo: userRepo,
|
||||
userRoleRepo: userRoleRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetProfileByToken(ctx context.Context, token string) (*domain.AdminUserShort, error) {
|
||||
userId, err := u.userTokenService.GetUserId(token)
|
||||
if err != nil {
|
||||
u.logger.Error(ctx, "get user id by token error", log.String("cause", err.Error()))
|
||||
return nil, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
user, err := u.userRepo.GetUserById(ctx, userId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by id")
|
||||
}
|
||||
|
||||
role, err := u.userRoleRepo.GetRoleById(ctx, user.RoleId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, errors.Errorf("unexpected role id %d", user.RoleId)
|
||||
case err != nil:
|
||||
return nil, errors.WithMessagef(err, "get role by id %d", user.RoleId)
|
||||
}
|
||||
|
||||
return &domain.AdminUserShort{
|
||||
FirstName: user.FirstName,
|
||||
LastName: user.LastName,
|
||||
Email: user.Email,
|
||||
Role: role.Name,
|
||||
}, 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)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users from repo")
|
||||
}
|
||||
|
||||
items := make([]domain.User, 0, len(users))
|
||||
for _, user := range users {
|
||||
items = append(items, domain.User(user))
|
||||
}
|
||||
|
||||
return &domain.UsersResponse{Items: items}, err
|
||||
}
|
||||
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
user, err := u.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email or phone")
|
||||
case user != nil:
|
||||
return nil, domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
encryptedPassword, err := u.cryptPassword(req.Password)
|
||||
if err != nil {
|
||||
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,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
}
|
||||
|
||||
result := domain.User(*user)
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
user, err := u.userRepo.GetUserById(ctx, req.Id)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
case req.Password != "" && user.SudirUserId != nil:
|
||||
return nil, domain.ErrInvalid
|
||||
}
|
||||
|
||||
if req.Email != "" && req.Email != user.Email {
|
||||
knownUser, err := u.userRepo.GetUserByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user by email")
|
||||
case knownUser != nil:
|
||||
return nil, domain.ErrAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
if req.Password != "" {
|
||||
req.Password, err = u.cryptPassword(req.Password)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "")
|
||||
}
|
||||
}
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
RoleId: req.RoleId,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
Email: req.Email,
|
||||
Password: req.Password,
|
||||
}
|
||||
|
||||
user, err = u.userRepo.UpdateUser(ctx, req.Id, updateEntity)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
}
|
||||
|
||||
result := domain.User(*user)
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (u User) DeleteUsers(ctx context.Context, ids []int64) (int, error) {
|
||||
if len(ids) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
count, err := u.userRepo.DeleteUser(ctx, ids)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "delete users")
|
||||
}
|
||||
return count, err
|
||||
}
|
||||
|
||||
//nolint:gomnd
|
||||
func (u User) cryptPassword(password string) (string, error) {
|
||||
passwordBytes, err := bcrypt.GenerateFromPassword([]byte(password), 12)
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "gen bcrypt from password")
|
||||
}
|
||||
|
||||
return string(passwordBytes), nil
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package structure
|
||||
|
||||
type Auth struct {
|
||||
Token string `json:"token"`
|
||||
Expired string `json:"expired,omitempty"`
|
||||
HeaderName string `json:"headerName"`
|
||||
}
|
||||
|
||||
type AuthRequest struct {
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Password string `json:"password" valid:"required~Required"`
|
||||
}
|
||||
|
||||
type SudirAuthRequest struct {
|
||||
AuthCode string `json:"authCode" valid:"required~Required"`
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package structure
|
||||
|
||||
type IdentitiesRequest struct {
|
||||
Ids []int64 `json:"ids"`
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package structure
|
||||
|
||||
type DeleteResponse struct {
|
||||
Deleted int
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package structure
|
||||
|
||||
import (
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type UsersResponse struct {
|
||||
Items *[]entity.AdminUser `json:"items,omitempty"`
|
||||
}
|
||||
|
||||
type UsersRequest struct {
|
||||
Ids []int64 `json:"ids"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
Email string `json:"email"`
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
|
||||
type AdminUserShort struct {
|
||||
Image string `json:"image"`
|
||||
FirstName string `json:"firstName"`
|
||||
LastName string `json:"lastName"`
|
||||
Email string `json:"email" valid:"required~Required"`
|
||||
Phone string `json:"phone"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/json"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
"github.com/integration-system/isp-kit/test/grpct"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
func TestAuthTestSuite(t *testing.T) {
|
||||
suite.Run(t, &AuthTestSuite{})
|
||||
}
|
||||
|
||||
type AuthTestSuite struct {
|
||||
suite.Suite
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigration("../migrations"))
|
||||
s.httpCli = httpcli.New()
|
||||
|
||||
mocksrv, host := s.initMockSudir()
|
||||
|
||||
cfg := conf.Remote{
|
||||
SudirAuth: &conf.SudirAuth{
|
||||
ClientId: "admin",
|
||||
ClientSecret: "admin",
|
||||
Host: host,
|
||||
RedirectURI: "http://localhost",
|
||||
},
|
||||
SecretKey: "admin",
|
||||
ExpireSec: 0,
|
||||
}
|
||||
|
||||
locator := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db)
|
||||
handler := locator.Handler(cfg)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
mocksrv.Close()
|
||||
})
|
||||
}
|
||||
|
||||
type customClaims struct {
|
||||
Id int64
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
response := domain.Auth{}
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.AuthRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
claims := customClaims{Id: id}
|
||||
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("admin"))
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal(token, response.Token)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.AuthRequest{
|
||||
Email: "a1@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{
|
||||
RoleId: 1,
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.AuthRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "WrongPassword",
|
||||
}).
|
||||
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) TestSudirLoginHappyPath() {
|
||||
response := domain.Auth{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
||||
JsonRequestBody(domain.SudirAuthRequest{
|
||||
AuthCode: "code",
|
||||
}).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
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("sudir@email.ru", user.Email)
|
||||
|
||||
claims := customClaims{Id: user.Id}
|
||||
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("admin"))
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal(token, response.Token)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirTokenResponse{
|
||||
SudirAuthError: nil,
|
||||
IdToken: "1",
|
||||
AccessToken: "token",
|
||||
}
|
||||
data, err := json.Marshal(res)
|
||||
s.Require().NoError(err)
|
||||
_, err = writer.Write(data)
|
||||
s.Require().NoError(err)
|
||||
})
|
||||
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirUserResponse{
|
||||
SudirAuthError: nil,
|
||||
Email: "sudir@email.ru",
|
||||
Groups: []string{"DIT-KKD-Admins"},
|
||||
Sub: "sudirUser1",
|
||||
GivenName: "name",
|
||||
FamilyName: "surname",
|
||||
}
|
||||
data, err := json.Marshal(res)
|
||||
s.Require().NoError(err)
|
||||
_, err = writer.Write(data)
|
||||
s.Require().NoError(err)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
return srv, srv.URL
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
"github.com/integration-system/isp-kit/test/grpct"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
func TestCustomizationTestSuite(t *testing.T) {
|
||||
suite.Run(t, &CustomizationTestSuite{})
|
||||
}
|
||||
|
||||
type CustomizationTestSuite struct {
|
||||
suite.Suite
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigration("../migrations"))
|
||||
|
||||
cfg := conf.Remote{
|
||||
UiDesign: conf.UIDesign{
|
||||
Name: "test",
|
||||
PrimaryColor: "#ff4d4f",
|
||||
},
|
||||
SecretKey: "admin",
|
||||
ExpireSec: 0,
|
||||
}
|
||||
|
||||
locator := assembly.NewLocator(testInstance.Logger(), nil, s.db)
|
||||
handler := locator.Handler(cfg)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) TestGetDesign() {
|
||||
response := conf.UIDesign{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_design").
|
||||
JsonRequestBody(struct{}{}).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
expected := conf.UIDesign{
|
||||
Name: "test",
|
||||
PrimaryColor: "#ff4d4f",
|
||||
}
|
||||
s.Require().Equal(expected, response)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
//nolint:gomnd
|
||||
func InsertUser(db *dbt.TestDb, user entity.CreateUser) 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)
|
||||
return id
|
||||
}
|
||||
|
||||
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) (int64, error) {
|
||||
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").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var id int64
|
||||
db.Must().SelectRow(&id, q, args...)
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
"github.com/integration-system/isp-kit/test/grpct"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/service"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
GenerateToken(id int64) (string, string, error)
|
||||
}
|
||||
|
||||
func TestUserTestSuite(t *testing.T) {
|
||||
suite.Run(t, &UserTestSuite{})
|
||||
}
|
||||
|
||||
type UserTestSuite struct {
|
||||
suite.Suite
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
tokenService tokenService
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigration("../migrations"))
|
||||
s.httpCli = httpcli.New()
|
||||
|
||||
cfg := conf.Remote{
|
||||
SecretKey: "secret",
|
||||
ExpireSec: 0,
|
||||
}
|
||||
locator := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db)
|
||||
handler := locator.Handler(cfg)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
})
|
||||
|
||||
s.tokenService = service.NewToken(0, "secret")
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
token, _, err := s.tokenService.GenerateToken(id)
|
||||
s.Require().NoError(err)
|
||||
|
||||
md := map[string][]string{domain.AdminAuthHeaderName: {token}}
|
||||
response := domain.AdminUserShort{}
|
||||
err = s.grpcCli.Invoke("admin/user/get_profile").
|
||||
JsonRequestBody(md).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Role: "admin",
|
||||
}
|
||||
s.Require().Equal(expected, response)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileUnauthorized() {
|
||||
id := InsertUser(s.db, entity.CreateUser{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
token, _, err := s.tokenService.GenerateToken(id + 1)
|
||||
s.Require().NoError(err)
|
||||
|
||||
md := map[string][]string{domain.AdminAuthHeaderName: {token}}
|
||||
err = s.grpcCli.Invoke("admin/user/get_profile").
|
||||
JsonRequestBody(md).
|
||||
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 *UserTestSuite) TestGetProfileSudir() {
|
||||
id, err := InsertSudirUser(s.db, entity.SudirUser{
|
||||
RoleId: 1,
|
||||
SudirUserId: "sudirUser1",
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
token, _, err := s.tokenService.GenerateToken(id)
|
||||
s.Require().NoError(err)
|
||||
|
||||
md := map[string][]string{domain.AdminAuthHeaderName: {token}}
|
||||
response := domain.AdminUserShort{}
|
||||
err = s.grpcCli.Invoke("admin/user/get_profile").
|
||||
JsonRequestBody(md).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Role: "admin",
|
||||
}
|
||||
s.Require().Equal(expected, response)
|
||||
}
|
||||
|
||||
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"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersRequest{
|
||||
Ids: []int64{3, 4, 5, 6},
|
||||
Offset: 1,
|
||||
Limit: 1,
|
||||
Email: "a@",
|
||||
}).ReadJsonResponse(&response).Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(1, len(response.Items))
|
||||
s.Require().Equal(int64(5), response.Items[0].Id)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
preCount := 0
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
s.db.Must().SelectRow(&postCount, "select count(*) from users")
|
||||
|
||||
s.Require().Equal(preCount+1, postCount)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru"})
|
||||
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
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.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
id := InsertUser(s.db, entity.CreateUser{RoleId: 1, Email: "a@a.ru", Password: "password"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
JsonRequestBody(req).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
RoleId: response.RoleId,
|
||||
FirstName: response.FirstName,
|
||||
LastName: response.LastName,
|
||||
Email: response.Email,
|
||||
Password: req.Password,
|
||||
}
|
||||
s.Require().Equal(expected, req)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
id, err := InsertSudirUser(s.db, entity.SudirUser{RoleId: 1, Email: "a@a.ru"})
|
||||
s.Require().NoError(err)
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
JsonRequestBody(req).
|
||||
ReadJsonResponse(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
RoleId: response.RoleId,
|
||||
FirstName: response.FirstName,
|
||||
LastName: response.LastName,
|
||||
Email: response.Email,
|
||||
}
|
||||
s.Require().Equal(expected, req)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserInvalidRequest() {
|
||||
id, err := InsertSudirUser(s.db, entity.SudirUser{RoleId: 1, Email: "a@a.ru"})
|
||||
s.Require().NoError(err)
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
JsonRequestBody(req).
|
||||
Do(context.Background())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.InvalidArgument, st.Code())
|
||||
}
|
||||
|
||||
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"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
RoleId: 1,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
JsonRequestBody(req).
|
||||
Do(context.Background())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
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"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/delete_user").
|
||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).ReadJsonResponse(&response).Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(2, response.Deleted)
|
||||
}
|
||||
Reference in new issue
Block a user