MSP-8520 rename sudir to oauth
This commit is contained in:
1 parent
c32459f73d
commit
5bd389757c
23 files changed
+254
-252
No files matched your search
@@ -27,7 +27,7 @@ type Assembly struct {
|
|||||||
boot *bootstrap.Bootstrap
|
boot *bootstrap.Bootstrap
|
||||||
db *dbrx.Client
|
db *dbrx.Client
|
||||||
server *grpc.Server
|
server *grpc.Server
|
||||||
sudirCli *httpcli.Client
|
oauthCli *httpcli.Client
|
||||||
logger *log.Adapter
|
logger *log.Adapter
|
||||||
bgjobCli *bgjobx.Client
|
bgjobCli *bgjobx.Client
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
|||||||
db: db,
|
db: db,
|
||||||
server: grpc.NewServer(),
|
server: grpc.NewServer(),
|
||||||
logger: logger,
|
logger: logger,
|
||||||
sudirCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||||
bgjobCli: bgjobCli,
|
bgjobCli: bgjobCli,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -67,13 +67,13 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
|||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
||||||
}
|
}
|
||||||
|
|
||||||
sudirBaseUrl := ""
|
oauthBaseUrl := ""
|
||||||
if newCfg.SudirAuth != nil {
|
if newCfg.Oauth != nil {
|
||||||
sudirBaseUrl = newCfg.SudirAuth.Host
|
oauthBaseUrl = newCfg.Oauth.Host
|
||||||
}
|
}
|
||||||
a.sudirCli.GlobalRequestConfig().BaseUrl = sudirBaseUrl
|
a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl
|
||||||
|
|
||||||
locator := NewLocator(a.logger, a.sudirCli, a.db)
|
locator := NewLocator(a.logger, a.oauthCli, a.db)
|
||||||
config, err := locator.Config(ctx, newCfg, time.Minute)
|
config, err := locator.Config(ctx, newCfg, time.Minute)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
|
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
|
||||||
|
|||||||
+13
-13
@@ -31,14 +31,14 @@ type DB interface {
|
|||||||
|
|
||||||
type Locator struct {
|
type Locator struct {
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
sudirCli *httpcli.Client
|
oauthCli *httpcli.Client
|
||||||
db DB
|
db DB
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLocator(logger log.Logger, sudirCli *httpcli.Client, db DB) Locator {
|
func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
||||||
return Locator{
|
return Locator{
|
||||||
logger: logger,
|
logger: logger,
|
||||||
sudirCli: sudirCli,
|
oauthCli: oauthCli,
|
||||||
db: db,
|
db: db,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ func (l Locator) Config(
|
|||||||
cfg conf.Remote,
|
cfg conf.Remote,
|
||||||
jobPollInterval time.Duration,
|
jobPollInterval time.Duration,
|
||||||
) (Config, error) {
|
) (Config, error) {
|
||||||
sudirRepo := repository.NewSudir(l.sudirCli)
|
oauthRepo := repository.NewOauth(l.oauthCli)
|
||||||
roleRepo := repository.NewRole(l.db)
|
roleRepo := repository.NewRole(l.db)
|
||||||
userRepo := repository.NewUser(l.db)
|
userRepo := repository.NewUser(l.db)
|
||||||
tokenRepo := repository.NewToken(l.db)
|
tokenRepo := repository.NewToken(l.db)
|
||||||
@@ -65,10 +65,10 @@ func (l Locator) Config(
|
|||||||
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
||||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||||
|
|
||||||
sudirBaseUrl, sudirSettings := l.getSudirSettings(cfg.SudirAuth)
|
oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth)
|
||||||
sudirService, err := service.NewSudir(sudirSettings, sudirRepo)
|
oauthService, err := service.NewOauth(oauthSettings, oauthRepo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, errors.WithMessage(err, "new sudir")
|
return Config{}, errors.WithMessage(err, "new oauth")
|
||||||
}
|
}
|
||||||
|
|
||||||
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
||||||
@@ -87,7 +87,7 @@ func (l Locator) Config(
|
|||||||
l.logger,
|
l.logger,
|
||||||
)
|
)
|
||||||
authService := service.NewAuth(
|
authService := service.NewAuth(
|
||||||
userRepo, txManager, tokenService, sudirService, auditService, l.logger,
|
userRepo, txManager, tokenService, oauthService, auditService, l.logger,
|
||||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||||
)
|
)
|
||||||
@@ -95,7 +95,7 @@ func (l Locator) Config(
|
|||||||
|
|
||||||
permissionsService := service.NewPermission(cfg.Permissions)
|
permissionsService := service.NewPermission(cfg.Permissions)
|
||||||
|
|
||||||
uiSettingsService := service.NewUiSettings(sudirBaseUrl, sudirSettings)
|
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
||||||
|
|
||||||
userController := controller.NewUser(userService)
|
userController := controller.NewUser(userService)
|
||||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||||
@@ -152,10 +152,10 @@ func (l Locator) Config(
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l Locator) getSudirSettings(sudirAuth *conf.SudirAuth) (string, []conf.SudirClientConfig) {
|
func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) {
|
||||||
if sudirAuth == nil {
|
if oauthAuth == nil {
|
||||||
return "", []conf.SudirClientConfig{}
|
return "", []conf.OauthClientConfig{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return sudirAuth.Host, sudirAuth.Clients
|
return oauthAuth.Host, oauthAuth.Clients
|
||||||
}
|
}
|
||||||
+11
-12
@@ -24,7 +24,7 @@ type Remote struct {
|
|||||||
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||||
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
||||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
Oauth *Oauth `schema:"OAuth авторизация"`
|
||||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||||
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
||||||
@@ -51,23 +51,22 @@ type UIDesign struct {
|
|||||||
PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SudirAuth struct {
|
type Oauth struct {
|
||||||
Host string `validate:"required" schema:"Базовый путь до методов СУДИР, пример https://sudir.mos.ru"`
|
Host string `validate:"required" schema:"Базовый путь до методов, пример https://oauth.example.com"`
|
||||||
Clients []SudirClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия с СУДИР для логина по authCode"`
|
Clients []OauthClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия для логина по authCode"`
|
||||||
}
|
}
|
||||||
|
|
||||||
//nolint:lll
|
type OauthClientConfig struct {
|
||||||
type SudirClientConfig struct {
|
|
||||||
ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"`
|
ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"`
|
||||||
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный СУДИР для basicAuth"`
|
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный для basicAuth"`
|
||||||
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный СУДИР для basicAuth"`
|
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный для basicAuth"`
|
||||||
RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"`
|
RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"`
|
||||||
UiSetting *UiSudirSetting `schema:"Настройки СУДИР для админки"`
|
UiSetting *UiOauthSetting `schema:"Настройки OAuth для админки"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UiSudirSetting struct {
|
type UiOauthSetting struct {
|
||||||
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через СУДИР в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через OAuth в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
||||||
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через СУДИР в адмиинке"`
|
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через OAuth в адмиинке"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type AntiBruteforce struct {
|
type AntiBruteforce struct {
|
||||||
|
|||||||
+12
-12
@@ -16,7 +16,7 @@ import (
|
|||||||
|
|
||||||
type authService interface {
|
type authService interface {
|
||||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||||
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error)
|
||||||
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
|||||||
auth, err := a.authService.Login(ctx, authRequest)
|
auth, err := a.authService.Login(ctx, authRequest)
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrSudirAuthorization):
|
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
a.logger.Error(ctx, err.Error())
|
a.logger.Error(ctx, err.Error())
|
||||||
@@ -113,28 +113,28 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoginWithSudir
|
// LoginWithOauth
|
||||||
// @Tags auth
|
// @Tags auth
|
||||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
// @Summary Авторизация по авторизационному коду от OAuth
|
||||||
// @Description Авторизация с получением токена администратора
|
// @Description Авторизация с получением токена администратора
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param body body domain.LoginSudirRequest true "Тело запроса"
|
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||||
// @Success 200 {object} domain.LoginResponse
|
// @Success 200 {object} domain.LoginResponse
|
||||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
|
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
|
||||||
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /auth/login_with_sudir [POST]
|
// @Router /auth/login_with_oauth [POST]
|
||||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||||
auth, err := a.authService.LoginWithSudir(ctx, request)
|
auth, err := a.authService.LoginWithOauth(ctx, request)
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||||
return nil, status.Error(codes.FailedPrecondition, "sudir auth is not configured")
|
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "login with sudir")
|
return nil, errors.WithMessage(err, "login with oauth")
|
||||||
default:
|
default:
|
||||||
return auth, nil
|
return auth, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type UiSettingsService interface {
|
type UiSettingsService interface {
|
||||||
SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error)
|
OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type UiSettings struct {
|
type UiSettings struct {
|
||||||
@@ -23,20 +23,20 @@ func NewUiSettings(service UiSettingsService) UiSettings {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// UiSudirSettings
|
// UiOauthSettings
|
||||||
// @Tags ui_settings
|
// @Tags ui_settings
|
||||||
// @Summary Получение настроек для ui для авторизации через СУДИР
|
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||||
// @Description Получение настроек для ui для авторизации через СУДИР
|
// @Description Получение настроек для ui для авторизации через OAuth
|
||||||
// @Accept json
|
// @Accept json
|
||||||
// @Produce json
|
// @Produce json
|
||||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||||
// @Success 200 {object} domain.UiSudirSetting
|
// @Success 200 {object} domain.UiOauthSetting
|
||||||
// @Failure 400 {object} domain.GrpcError
|
// @Failure 400 {object} domain.GrpcError
|
||||||
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
|
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /ui_settings/sudir [POST]
|
// @Router /ui_settings/oauth [POST]
|
||||||
func (c UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error) {
|
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||||
resp, err := c.service.SudirSettings(ctx, req)
|
resp, err := c.service.OauthSettings(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrUnknownClient):
|
case errors.Is(err, domain.ErrUnknownClient):
|
||||||
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
||||||
|
|||||||
+27
-27
@@ -64,7 +64,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/auth/login_with_sudir": {
|
"/auth/login_with_oauth": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "Авторизация с получением токена администратора",
|
"description": "Авторизация с получением токена администратора",
|
||||||
"consumes": [
|
"consumes": [
|
||||||
@@ -76,7 +76,7 @@
|
|||||||
"tags": [
|
"tags": [
|
||||||
"auth"
|
"auth"
|
||||||
],
|
],
|
||||||
"summary": "Авторизация по авторизационному коду от СУДИР",
|
"summary": "Авторизация по авторизационному коду от OAuth",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
{
|
{
|
||||||
"description": "Тело запроса",
|
"description": "Тело запроса",
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
"in": "body",
|
"in": "body",
|
||||||
"required": true,
|
"required": true,
|
||||||
"schema": {
|
"schema": {
|
||||||
"$ref": "#/definitions/domain.LoginSudirRequest"
|
"$ref": "#/definitions/domain.LoginOauthRequest"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -102,7 +102,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"412": {
|
"412": {
|
||||||
"description": "Авторизация СУДИР не настроена на сервере",
|
"description": "Авторизация OAuth не настроена на сервере",
|
||||||
"schema": {
|
"schema": {
|
||||||
"$ref": "#/definitions/domain.GrpcError"
|
"$ref": "#/definitions/domain.GrpcError"
|
||||||
}
|
}
|
||||||
@@ -761,9 +761,9 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/ui_settings/sudir": {
|
"/ui_settings/oauth": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "Получение настроек для ui для авторизации через СУДИР",
|
"description": "Получение настроек для ui для авторизации через OAuth",
|
||||||
"consumes": [
|
"consumes": [
|
||||||
"application/json"
|
"application/json"
|
||||||
],
|
],
|
||||||
@@ -773,7 +773,7 @@
|
|||||||
"tags": [
|
"tags": [
|
||||||
"ui_settings"
|
"ui_settings"
|
||||||
],
|
],
|
||||||
"summary": "Получение настроек для ui для авторизации через СУДИР",
|
"summary": "Получение настроек для ui для авторизации через OAuth",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
{
|
{
|
||||||
"description": "Тело запроса",
|
"description": "Тело запроса",
|
||||||
@@ -789,7 +789,7 @@
|
|||||||
"200": {
|
"200": {
|
||||||
"description": "OK",
|
"description": "OK",
|
||||||
"schema": {
|
"schema": {
|
||||||
"$ref": "#/definitions/domain.UiSudirSetting"
|
"$ref": "#/definitions/domain.UiOauthSetting"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"400": {
|
"400": {
|
||||||
@@ -1698,6 +1698,23 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"domain.LoginOauthRequest": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"authCode",
|
||||||
|
"clientName"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"authCode": {
|
||||||
|
"description": "Код для авторизации у OAuth-провайдера",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"clientName": {
|
||||||
|
"description": "Уникальное имя конфигурации клиента",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"domain.LoginRequest": {
|
"domain.LoginRequest": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
@@ -1732,23 +1749,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"domain.LoginSudirRequest": {
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"authCode",
|
|
||||||
"clientName"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"authCode": {
|
|
||||||
"description": "Код для авторизации в СУДИР",
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"clientName": {
|
|
||||||
"description": "Уникальное имя конфигурации клиента",
|
|
||||||
"type": "string"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"domain.LogoutRequest": {
|
"domain.LogoutRequest": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@@ -2033,11 +2033,11 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"domain.UiSudirSetting": {
|
"domain.UiOauthSetting": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"loginUrl": {
|
"loginUrl": {
|
||||||
"description": "URL для получения authCode для авторизации через СУДИР",
|
"description": "URL для получения authCode для авторизации через OAuth",
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
"logoutUrl": {
|
"logoutUrl": {
|
||||||
|
|||||||
+2
-2
@@ -13,8 +13,8 @@ const (
|
|||||||
var (
|
var (
|
||||||
ErrNotFound = errors.New("not found")
|
ErrNotFound = errors.New("not found")
|
||||||
ErrUnauthenticated = errors.New("authentication failure")
|
ErrUnauthenticated = errors.New("authentication failure")
|
||||||
ErrSudirAuthorization = errors.New("User is authorized only with SUDIR")
|
ErrOauthAuthorization = errors.New("user is authorized only with oauth")
|
||||||
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
|
ErrOauthIsMissed = errors.New("oauth is not configured on the server")
|
||||||
ErrInvalid = errors.New("entity is invalid")
|
ErrInvalid = errors.New("entity is invalid")
|
||||||
ErrAlreadyExists = errors.New("already exists")
|
ErrAlreadyExists = errors.New("already exists")
|
||||||
ErrTokenExpired = errors.New("token expired")
|
ErrTokenExpired = errors.New("token expired")
|
||||||
|
|||||||
+2
-2
@@ -14,8 +14,8 @@ type LoginRequest struct {
|
|||||||
Password string ` validate:"required"` // Пароль
|
Password string ` validate:"required"` // Пароль
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginSudirRequest struct {
|
type LoginOauthRequest struct {
|
||||||
AuthCode string `validate:"required"` // Код для авторизации в СУДИР
|
AuthCode string `validate:"required"` // Код для авторизации у OAuth-провайдера
|
||||||
ClientName string `validate:"required"` // Уникальное имя конфигурации клиента
|
ClientName string `validate:"required"` // Уникальное имя конфигурации клиента
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ type ClientNameRequest struct {
|
|||||||
ClientName string `validate:"required"`
|
ClientName string `validate:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UiSudirSetting struct {
|
type UiOauthSetting struct {
|
||||||
LoginUrl string // URL для получения authCode для авторизации через СУДИР
|
LoginUrl string // URL для получения authCode для авторизации через OAuth
|
||||||
LogoutUrl string // URL для завершения сессии
|
LogoutUrl string // URL для завершения сессии
|
||||||
}
|
}
|
||||||
@@ -12,18 +12,18 @@ type ClientSetting struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,godoclint
|
// nolint:tagliatelle,godoclint
|
||||||
type SudirAuthError struct {
|
type OauthAuthError struct {
|
||||||
ErrorName string `json:"error"`
|
ErrorName string `json:"error"`
|
||||||
ErrorDescription string `json:"error_description"`
|
ErrorDescription string `json:"error_description"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *SudirAuthError) Error() string {
|
func (s *OauthAuthError) Error() string {
|
||||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,errname,godoclint
|
// nolint:tagliatelle,errname,godoclint
|
||||||
type SudirUserResponse struct {
|
type OauthUserResponse struct {
|
||||||
*SudirAuthError
|
*OauthAuthError
|
||||||
|
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Groups []string `json:"groups"`
|
Groups []string `json:"groups"`
|
||||||
@@ -34,8 +34,8 @@ type SudirUserResponse struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// nolint:tagliatelle,errname,godoclint
|
// nolint:tagliatelle,errname,godoclint
|
||||||
type SudirTokenResponse struct {
|
type OauthTokenResponse struct {
|
||||||
*SudirAuthError
|
*OauthAuthError
|
||||||
|
|
||||||
IdToken string `json:"id_token"`
|
IdToken string `json:"id_token"`
|
||||||
AccessToken string `json:"access_token"`
|
AccessToken string `json:"access_token"`
|
||||||
+3
-3
@@ -3,7 +3,7 @@ package entity
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
SudirUserId *string
|
OauthUserId *string
|
||||||
Id int64
|
Id int64
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
@@ -18,9 +18,9 @@ type User struct {
|
|||||||
LastSessionCreatedAt *time.Time
|
LastSessionCreatedAt *time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type SudirUser struct {
|
type OauthUser struct {
|
||||||
RoleIds []int
|
RoleIds []int
|
||||||
SudirUserId string
|
OauthUserId string
|
||||||
FirstName string
|
FirstName string
|
||||||
LastName string
|
LastName string
|
||||||
Email string
|
Email string
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- +goose Up
|
||||||
|
ALTER TABLE users RENAME COLUMN sudir_user_id TO oauth_user_id;
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
ALTER TABLE users RENAME COLUMN oauth_user_id TO sudir_user_id;
|
||||||
@@ -17,20 +17,20 @@ const (
|
|||||||
getUserEndpoint = "/oauth/me"
|
getUserEndpoint = "/oauth/me"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Sudir struct {
|
type Oauth struct {
|
||||||
cli *httpcli.Client
|
cli *httpcli.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSudir(cli *httpcli.Client) Sudir {
|
func NewOauth(cli *httpcli.Client) Oauth {
|
||||||
return Sudir{
|
return Oauth{
|
||||||
cli: cli,
|
cli: cli,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Sudir) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.SudirTokenResponse, error) {
|
func (s Oauth) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.OauthTokenResponse, error) {
|
||||||
ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint)
|
ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint)
|
||||||
|
|
||||||
response := entity.SudirTokenResponse{}
|
response := entity.OauthTokenResponse{}
|
||||||
err := s.cli.Post(getTokenEndpoint).
|
err := s.cli.Post(getTokenEndpoint).
|
||||||
BasicAuth(httpcli.BasicAuth{
|
BasicAuth(httpcli.BasicAuth{
|
||||||
Username: clientSetting.ClientId,
|
Username: clientSetting.ClientId,
|
||||||
@@ -52,10 +52,10 @@ func (s Sudir) GetToken(ctx context.Context, clientSetting entity.ClientSetting)
|
|||||||
return &response, nil
|
return &response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) {
|
func (s Oauth) GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error) {
|
||||||
ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint)
|
ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint)
|
||||||
|
|
||||||
response := entity.SudirUserResponse{}
|
response := entity.OauthUserResponse{}
|
||||||
err := s.cli.Get(getUserEndpoint).
|
err := s.cli.Get(getUserEndpoint).
|
||||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
+18
-18
@@ -25,7 +25,7 @@ const (
|
|||||||
passwordUsersColumn = "password"
|
passwordUsersColumn = "password"
|
||||||
createdAtUsersColumn = "created_at"
|
createdAtUsersColumn = "created_at"
|
||||||
updatedAtUsersColumn = "updated_at"
|
updatedAtUsersColumn = "updated_at"
|
||||||
sudirUserIdUsersColumn = "sudir_user_id"
|
oauthUserIdUsersColumn = "oauth_user_id"
|
||||||
blockedUsersColumn = "blocked"
|
blockedUsersColumn = "blocked"
|
||||||
descriptionUsersColumn = "description"
|
descriptionUsersColumn = "description"
|
||||||
lastActiveAtUsersColumn = "last_active_at"
|
lastActiveAtUsersColumn = "last_active_at"
|
||||||
@@ -45,7 +45,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
|
|||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn).
|
fullNameUsersColumn).
|
||||||
From("users").
|
From("users").
|
||||||
Where(squirrel.Eq{"email": email}).
|
Where(squirrel.Eq{"email": email}).
|
||||||
@@ -72,7 +72,7 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
|||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn).
|
fullNameUsersColumn).
|
||||||
From("users").
|
From("users").
|
||||||
Where(squirrel.Eq{"id": identity}).
|
Where(squirrel.Eq{"id": identity}).
|
||||||
@@ -94,17 +94,17 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error) {
|
func (u User) GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmailAndOauthId")
|
||||||
|
|
||||||
equalClause := squirrel.Eq{"email": email, "sudir_user_id": nil}
|
equalClause := squirrel.Eq{"email": email, "oauth_user_id": nil}
|
||||||
if sudirUserId != "" {
|
if oauthUserId != "" {
|
||||||
equalClause["sudir_user_id"] = sudirUserId
|
equalClause["oauth_user_id"] = oauthUserId
|
||||||
}
|
}
|
||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn).
|
fullNameUsersColumn).
|
||||||
From("users").
|
From("users").
|
||||||
Where(equalClause).
|
Where(equalClause).
|
||||||
@@ -126,13 +126,13 @@ func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirU
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertByOauthUserId")
|
||||||
|
|
||||||
selectQ := `
|
selectQ := `
|
||||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, sudir_user_id)
|
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, oauth_user_id)
|
||||||
values ($1, $2, $3, $4, $5, $6, $7)
|
values ($1, $2, $3, $4, $5, $6, $7)
|
||||||
on conflict (sudir_user_id) do update
|
on conflict (oauth_user_id) do update
|
||||||
set first_name = excluded.first_name,
|
set first_name = excluded.first_name,
|
||||||
last_name = excluded.last_name,
|
last_name = excluded.last_name,
|
||||||
full_name = excluded.full_name,
|
full_name = excluded.full_name,
|
||||||
@@ -145,7 +145,7 @@ func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entit
|
|||||||
err := u.db.SelectRow(ctx,
|
err := u.db.SelectRow(ctx,
|
||||||
&result,
|
&result,
|
||||||
selectQ,
|
selectQ,
|
||||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.SudirUserId,
|
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.OauthUserId,
|
||||||
)
|
)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return nil, domain.ErrUserIsBlocked
|
return nil, domain.ErrUserIsBlocked
|
||||||
@@ -162,7 +162,7 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]enti
|
|||||||
|
|
||||||
q := query.New().
|
q := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||||
From("users").
|
From("users").
|
||||||
Offset(req.Offset).
|
Offset(req.Offset).
|
||||||
@@ -193,7 +193,7 @@ func (u User) GetAllUsers(ctx context.Context) ([]entity.User, error) {
|
|||||||
|
|
||||||
query, args, err := query.New().
|
query, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||||
From("users").ToSql()
|
From("users").ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -214,7 +214,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
|
|||||||
|
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||||
fullNameUsersColumn).
|
fullNameUsersColumn).
|
||||||
From("users").
|
From("users").
|
||||||
Where(squirrel.Eq{"email": email}).
|
Where(squirrel.Eq{"email": email}).
|
||||||
@@ -274,7 +274,7 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
|
|||||||
descriptionUsersColumn: user.Description,
|
descriptionUsersColumn: user.Description,
|
||||||
}).
|
}).
|
||||||
Where(squirrel.Eq{"id": id}).
|
Where(squirrel.Eq{"id": id}).
|
||||||
Suffix("RETURNING id, first_name, last_name, full_name, email, sudir_user_id, description, created_at, updated_at").
|
Suffix("RETURNING id, first_name, last_name, full_name, email, oauth_user_id, description, created_at, updated_at").
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.WithMessage(err, "build query")
|
return nil, errors.WithMessage(err, "build query")
|
||||||
|
|||||||
+4
-4
@@ -50,9 +50,9 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
|||||||
Handler: c.Auth.Login,
|
Handler: c.Auth.Login,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/auth/login_with_sudir",
|
Path: "admin/auth/login_with_oauth",
|
||||||
Inner: false,
|
Inner: false,
|
||||||
Handler: c.Auth.LoginWithSudir,
|
Handler: c.Auth.LoginWithOauth,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/auth/logout",
|
Path: "admin/auth/logout",
|
||||||
@@ -189,9 +189,9 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
|||||||
Handler: c.Secure.Authorize,
|
Handler: c.Secure.Authorize,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Path: "admin/ui_settings/sudir",
|
Path: "admin/ui_settings/oauth",
|
||||||
Inner: false,
|
Inner: false,
|
||||||
Handler: c.UiSettings.SudirSettings,
|
Handler: c.UiSettings.OauthSettings,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-27
@@ -30,7 +30,7 @@ type auditService interface {
|
|||||||
|
|
||||||
type userRepository interface {
|
type userRepository interface {
|
||||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||||
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||||
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
||||||
}
|
}
|
||||||
@@ -40,15 +40,15 @@ type tokenService interface {
|
|||||||
RevokeAllByUserId(ctx context.Context, userId int64) error
|
RevokeAllByUserId(ctx context.Context, userId int64) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type sudirService interface {
|
type oauthService interface {
|
||||||
Authenticate(ctx context.Context, request domain.LoginSudirRequest, repo roleRepo) (*entity.SudirUser, error)
|
Authenticate(ctx context.Context, request domain.LoginOauthRequest, repo roleRepo) (*entity.OauthUser, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Auth struct {
|
type Auth struct {
|
||||||
userRepository userRepository
|
userRepository userRepository
|
||||||
txRunner AuthTransactionRunner
|
txRunner AuthTransactionRunner
|
||||||
tokenService tokenService
|
tokenService tokenService
|
||||||
sudirService sudirService
|
oauthService oauthService
|
||||||
auditService auditService
|
auditService auditService
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
maxInFlightLoginRequests int64
|
maxInFlightLoginRequests int64
|
||||||
@@ -60,7 +60,7 @@ func NewAuth(
|
|||||||
userRepository userRepository,
|
userRepository userRepository,
|
||||||
txRunner AuthTransactionRunner,
|
txRunner AuthTransactionRunner,
|
||||||
tokenService tokenService,
|
tokenService tokenService,
|
||||||
sudirService sudirService,
|
oauthService oauthService,
|
||||||
auditService auditService,
|
auditService auditService,
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
delayLoginRequestInSec int,
|
delayLoginRequestInSec int,
|
||||||
@@ -70,7 +70,7 @@ func NewAuth(
|
|||||||
userRepository: userRepository,
|
userRepository: userRepository,
|
||||||
txRunner: txRunner,
|
txRunner: txRunner,
|
||||||
tokenService: tokenService,
|
tokenService: tokenService,
|
||||||
sudirService: sudirService,
|
oauthService: oauthService,
|
||||||
auditService: auditService,
|
auditService: auditService,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
||||||
@@ -100,8 +100,8 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
|||||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return errors.WithMessage(err, "get user by email")
|
return errors.WithMessage(err, "get user by email")
|
||||||
case user.SudirUserId != nil:
|
case user.OauthUserId != nil:
|
||||||
return domain.ErrSudirAuthorization
|
return domain.ErrOauthAuthorization
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Blocked {
|
if user.Blocked {
|
||||||
@@ -141,7 +141,7 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||||
var (
|
var (
|
||||||
user *entity.User
|
user *entity.User
|
||||||
|
|
||||||
@@ -150,41 +150,41 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
|||||||
)
|
)
|
||||||
|
|
||||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||||
sudirUser, err := a.sudirService.Authenticate(ctx, request, tx)
|
oauthUser, err := a.oauthService.Authenticate(ctx, request, tx)
|
||||||
|
|
||||||
var authErr *entity.SudirAuthError
|
var authErr *entity.OauthAuthError
|
||||||
switch {
|
switch {
|
||||||
case errors.As(err, &authErr):
|
case errors.As(err, &authErr):
|
||||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
a.logger.Error(ctx, "oauth authenticate: error occurred", log.String("error", err.Error()))
|
||||||
return domain.ErrUnauthenticated
|
return domain.ErrUnauthenticated
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return errors.WithMessage(err, "sudir authenticate")
|
return errors.WithMessage(err, "oauth authenticate")
|
||||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
case oauthUser.OauthUserId == "" || oauthUser.Email == "":
|
||||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
a.logger.Error(ctx, "oauth authenticate: missing oauthUserId or email",
|
||||||
log.String("userId", sudirUser.SudirUserId),
|
log.String("userId", oauthUser.OauthUserId),
|
||||||
log.String("email", sudirUser.Email))
|
log.String("email", oauthUser.Email))
|
||||||
return domain.ErrUnauthenticated
|
return domain.ErrUnauthenticated
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err = tx.UpsertBySudirUserId(ctx, entity.User{
|
user, err = tx.UpsertByOauthUserId(ctx, entity.User{
|
||||||
SudirUserId: &sudirUser.SudirUserId,
|
OauthUserId: &oauthUser.OauthUserId,
|
||||||
FirstName: sudirUser.FirstName,
|
FirstName: oauthUser.FirstName,
|
||||||
LastName: sudirUser.LastName,
|
LastName: oauthUser.LastName,
|
||||||
FullName: sudirUser.FullName,
|
FullName: oauthUser.FullName,
|
||||||
Email: sudirUser.Email,
|
Email: oauthUser.Email,
|
||||||
Password: "",
|
Password: "",
|
||||||
Blocked: false,
|
Blocked: false,
|
||||||
UpdatedAt: time.Now().UTC(),
|
UpdatedAt: time.Now().UTC(),
|
||||||
CreatedAt: time.Now().UTC(),
|
CreatedAt: time.Now().UTC(),
|
||||||
})
|
})
|
||||||
if errors.Is(err, domain.ErrUserIsBlocked) {
|
if errors.Is(err, domain.ErrUserIsBlocked) {
|
||||||
return errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
return errors.Errorf("user with oauth user id = %s is blocked", oauthUser.OauthUserId)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "upsert by sudir user id")
|
return errors.WithMessage(err, "upsert by oauth user id")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), sudirUser.RoleIds)
|
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), oauthUser.RoleIds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "upsert user role links")
|
return errors.WithMessage(err, "upsert user role links")
|
||||||
}
|
}
|
||||||
@@ -206,7 +206,7 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
|||||||
return nil, errors.WithMessage(err, "auth transaction")
|
return nil, errors.WithMessage(err, "auth transaction")
|
||||||
}
|
}
|
||||||
|
|
||||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР", entity.EventSuccessLogin)
|
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через OAuth", entity.EventSuccessLogin)
|
||||||
|
|
||||||
return &domain.LoginResponse{
|
return &domain.LoginResponse{
|
||||||
Token: tokenString,
|
Token: tokenString,
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type sudirRepo interface {
|
type oauthRepo interface {
|
||||||
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.SudirTokenResponse, error)
|
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.OauthTokenResponse, error)
|
||||||
GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error)
|
GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type roleRepo interface {
|
type roleRepo interface {
|
||||||
@@ -20,30 +20,30 @@ type roleRepo interface {
|
|||||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Sudir struct {
|
type Oauth struct {
|
||||||
sudirRepo sudirRepo
|
oauthRepo oauthRepo
|
||||||
clientSettings map[string]conf.SudirClientConfig
|
clientSettings map[string]conf.OauthClientConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSudir(settings []conf.SudirClientConfig, sudirRepo sudirRepo) (Sudir, error) {
|
func NewOauth(settings []conf.OauthClientConfig, oauthRepo oauthRepo) (Oauth, error) {
|
||||||
clientSettings := make(map[string]conf.SudirClientConfig, len(settings))
|
clientSettings := make(map[string]conf.OauthClientConfig, len(settings))
|
||||||
for i, setting := range settings {
|
for i, setting := range settings {
|
||||||
_, ok := clientSettings[setting.ClientName]
|
_, ok := clientSettings[setting.ClientName]
|
||||||
if ok {
|
if ok {
|
||||||
return Sudir{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
return Oauth{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
||||||
}
|
}
|
||||||
clientSettings[setting.ClientName] = setting
|
clientSettings[setting.ClientName] = setting
|
||||||
}
|
}
|
||||||
|
|
||||||
return Sudir{
|
return Oauth{
|
||||||
sudirRepo: sudirRepo,
|
oauthRepo: oauthRepo,
|
||||||
clientSettings: clientSettings,
|
clientSettings: clientSettings,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, roleRepo roleRepo) (*entity.SudirUser, error) {
|
func (s Oauth) Authenticate(ctx context.Context, req domain.LoginOauthRequest, roleRepo roleRepo) (*entity.OauthUser, error) {
|
||||||
if len(s.clientSettings) == 0 {
|
if len(s.clientSettings) == 0 {
|
||||||
return nil, domain.ErrSudirAuthIsMissed
|
return nil, domain.ErrOauthIsMissed
|
||||||
}
|
}
|
||||||
|
|
||||||
setting, ok := s.clientSettings[req.ClientName]
|
setting, ok := s.clientSettings[req.ClientName]
|
||||||
@@ -57,20 +57,20 @@ func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, r
|
|||||||
ClientSecret: setting.ClientSecret,
|
ClientSecret: setting.ClientSecret,
|
||||||
RedirectURI: setting.RedirectURI,
|
RedirectURI: setting.RedirectURI,
|
||||||
}
|
}
|
||||||
tokenResponse, err := s.sudirRepo.GetToken(ctx, creds)
|
tokenResponse, err := s.oauthRepo.GetToken(ctx, creds)
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "get token")
|
return nil, errors.WithMessage(err, "get token")
|
||||||
case tokenResponse.SudirAuthError != nil:
|
case tokenResponse.OauthAuthError != nil:
|
||||||
return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token")
|
return nil, errors.WithMessage(tokenResponse.OauthAuthError, "get token")
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := s.sudirRepo.GetUser(ctx, tokenResponse.AccessToken)
|
user, err := s.oauthRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "get user")
|
return nil, errors.WithMessage(err, "get user")
|
||||||
case user.SudirAuthError != nil:
|
case user.OauthAuthError != nil:
|
||||||
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
return nil, errors.WithMessage(user.OauthAuthError, "get user")
|
||||||
}
|
}
|
||||||
email := user.Email
|
email := user.Email
|
||||||
if email == "" {
|
if email == "" {
|
||||||
@@ -88,9 +88,9 @@ func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, r
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &entity.SudirUser{
|
return &entity.OauthUser{
|
||||||
RoleIds: rolesIds,
|
RoleIds: rolesIds,
|
||||||
SudirUserId: user.Sub,
|
OauthUserId: user.Sub,
|
||||||
FirstName: user.GivenName,
|
FirstName: user.GivenName,
|
||||||
LastName: user.FamilyName,
|
LastName: user.FamilyName,
|
||||||
FullName: user.Name,
|
FullName: user.Name,
|
||||||
@@ -10,12 +10,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type UiSettings struct {
|
type UiSettings struct {
|
||||||
sudirBaseUrl string
|
oauthBaseUrl string
|
||||||
settings map[string]conf.SudirClientConfig
|
settings map[string]conf.OauthClientConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUiSettings(sudirBaseUrl string, settings []conf.SudirClientConfig) UiSettings {
|
func NewUiSettings(oauthBaseUrl string, settings []conf.OauthClientConfig) UiSettings {
|
||||||
settingsMap := make(map[string]conf.SudirClientConfig, len(settings))
|
settingsMap := make(map[string]conf.OauthClientConfig, len(settings))
|
||||||
for _, setting := range settings {
|
for _, setting := range settings {
|
||||||
if setting.UiSetting == nil {
|
if setting.UiSetting == nil {
|
||||||
continue
|
continue
|
||||||
@@ -23,12 +23,12 @@ func NewUiSettings(sudirBaseUrl string, settings []conf.SudirClientConfig) UiSet
|
|||||||
settingsMap[setting.ClientName] = setting
|
settingsMap[setting.ClientName] = setting
|
||||||
}
|
}
|
||||||
return UiSettings{
|
return UiSettings{
|
||||||
sudirBaseUrl: sudirBaseUrl,
|
oauthBaseUrl: oauthBaseUrl,
|
||||||
settings: settingsMap,
|
settings: settingsMap,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error) {
|
func (s UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||||
setting, ok := s.settings[req.ClientName]
|
setting, ok := s.settings[req.ClientName]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, domain.ErrUnknownClient
|
return nil, domain.ErrUnknownClient
|
||||||
@@ -48,7 +48,7 @@ func (s UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequ
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Errorf("build url for logout: %w", err)
|
return nil, errors.Errorf("build url for logout: %w", err)
|
||||||
}
|
}
|
||||||
return &domain.UiSudirSetting{
|
return &domain.UiOauthSetting{
|
||||||
LoginUrl: loginUrl,
|
LoginUrl: loginUrl,
|
||||||
LogoutUrl: logoutUrl,
|
LogoutUrl: logoutUrl,
|
||||||
}, nil
|
}, nil
|
||||||
@@ -60,7 +60,7 @@ func (s UiSettings) buildUrl(methodPath string, additionalQuery map[string]strin
|
|||||||
return "", errors.Errorf("parse method path")
|
return "", errors.Errorf("parse method path")
|
||||||
}
|
}
|
||||||
|
|
||||||
joined, err := url.JoinPath(s.sudirBaseUrl, method.Path)
|
joined, err := url.JoinPath(s.oauthBaseUrl, method.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", errors.Errorf("join method path and baseUrl")
|
return "", errors.Errorf("join method path and baseUrl")
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -31,7 +31,7 @@ type UserRepo interface {
|
|||||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||||
GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error)
|
GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error)
|
||||||
GetAllUsers(ctx context.Context) ([]entity.User, error)
|
GetAllUsers(ctx context.Context) ([]entity.User, error)
|
||||||
GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error)
|
GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error)
|
||||||
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
||||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||||
@@ -207,7 +207,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
var usr entity.User
|
var usr entity.User
|
||||||
|
|
||||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||||
user, err := tx.GetUserByEmailAndSudirId(ctx, req.Email, "")
|
user, err := tx.GetUserByEmailAndOauthId(ctx, req.Email, "")
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
break
|
break
|
||||||
@@ -223,7 +223,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
|||||||
}
|
}
|
||||||
|
|
||||||
usr = entity.User{
|
usr = entity.User{
|
||||||
SudirUserId: nil,
|
OauthUserId: nil,
|
||||||
Id: 0,
|
Id: 0,
|
||||||
FirstName: req.FirstName,
|
FirstName: req.FirstName,
|
||||||
LastName: req.LastName,
|
LastName: req.LastName,
|
||||||
@@ -301,12 +301,12 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
|||||||
|
|
||||||
for _, usr := range users {
|
for _, usr := range users {
|
||||||
// check in internal user space
|
// check in internal user space
|
||||||
if (user.SudirUserId == nil && usr.SudirUserId == nil) && (usr.Id != req.Id) {
|
if (user.OauthUserId == nil && usr.OauthUserId == nil) && (usr.Id != req.Id) {
|
||||||
return domain.ErrAlreadyExists
|
return domain.ErrAlreadyExists
|
||||||
}
|
}
|
||||||
|
|
||||||
// check in sudir user space
|
// check in oauth user space
|
||||||
if usr.SudirUserId != nil && user.SudirUserId != nil && (*user.SudirUserId != *usr.SudirUserId) {
|
if usr.OauthUserId != nil && user.OauthUserId != nil && (*user.OauthUserId != *usr.OauthUserId) {
|
||||||
return domain.ErrAlreadyExists
|
return domain.ErrAlreadyExists
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-32
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -43,27 +42,26 @@ type AuthTestSuite struct {
|
|||||||
test *test.Test
|
test *test.Test
|
||||||
db *dbt.TestDb
|
db *dbt.TestDb
|
||||||
grpcCli *client.Client
|
grpcCli *client.Client
|
||||||
sudirCli *httpcli.Client
|
oauthCli *httpcli.Client
|
||||||
sudirClientName string
|
oauthClientName string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) SetupTest() {
|
func (s *AuthTestSuite) SetupTest() {
|
||||||
testInstance, _ := test.New(s.T())
|
testInstance, _ := test.New(s.T())
|
||||||
s.test = testInstance
|
s.test = testInstance
|
||||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||||
s.sudirCli = httpcli.New()
|
s.oauthCli = httpcli.New()
|
||||||
s.sudirClientName = fake.It[string]()
|
s.oauthClientName = fake.It[string]()
|
||||||
|
|
||||||
mocksrv, host := s.initMockSudir()
|
mocksrv, host := s.initMockOauth()
|
||||||
sudirHost, _ := url.JoinPath(host, "/blitz/")
|
s.oauthCli.GlobalRequestConfig().BaseUrl = host
|
||||||
s.sudirCli.GlobalRequestConfig().BaseUrl = sudirHost
|
|
||||||
|
|
||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
SudirAuth: &conf.SudirAuth{
|
Oauth: &conf.Oauth{
|
||||||
Host: sudirHost,
|
Host: host,
|
||||||
Clients: []conf.SudirClientConfig{
|
Clients: []conf.OauthClientConfig{
|
||||||
{
|
{
|
||||||
ClientName: s.sudirClientName,
|
ClientName: s.oauthClientName,
|
||||||
ClientId: "admin",
|
ClientId: "admin",
|
||||||
ClientSecret: "admin",
|
ClientSecret: "admin",
|
||||||
RedirectURI: "http://localhost",
|
RedirectURI: "http://localhost",
|
||||||
@@ -77,7 +75,7 @@ func (s *AuthTestSuite) SetupTest() {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.sudirCli, s.db).
|
cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db).
|
||||||
Config(s.T().Context(), remote, time.Minute)
|
Config(s.T().Context(), remote, time.Minute)
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
@@ -174,20 +172,20 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
|||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||||
response := domain.LoginResponse{}
|
response := domain.LoginResponse{}
|
||||||
|
|
||||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||||
JsonRequestBody(domain.LoginSudirRequest{
|
JsonRequestBody(domain.LoginOauthRequest{
|
||||||
AuthCode: "code",
|
AuthCode: "code",
|
||||||
ClientName: s.sudirClientName,
|
ClientName: s.oauthClientName,
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
Do(s.T().Context())
|
Do(s.T().Context())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
user := entity.User{}
|
user := entity.User{}
|
||||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where sudir_user_id = $1", "sudirUser1")
|
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
||||||
s.Require().Equal("sudir@email.ru", user.Email)
|
s.Require().Equal("oauth@email.ru", user.Email)
|
||||||
s.Require().Equal("surname name patronymic", user.FullName)
|
s.Require().Equal("surname name patronymic", user.FullName)
|
||||||
|
|
||||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||||
@@ -196,13 +194,13 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
|||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestSudirLogin_UnknownClient() {
|
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
||||||
response := domain.LoginResponse{}
|
response := domain.LoginResponse{}
|
||||||
|
|
||||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||||
JsonRequestBody(domain.LoginSudirRequest{
|
JsonRequestBody(domain.LoginOauthRequest{
|
||||||
AuthCode: "code",
|
AuthCode: "code",
|
||||||
ClientName: s.sudirClientName + fake.It[string](),
|
ClientName: s.oauthClientName + fake.It[string](),
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
Do(s.T().Context())
|
Do(s.T().Context())
|
||||||
@@ -325,11 +323,11 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
|||||||
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
func (s *AuthTestSuite) initMockOauth() (*httptest.Server, string) {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
mux.HandleFunc("/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
res := entity.SudirTokenResponse{
|
res := entity.OauthTokenResponse{
|
||||||
SudirAuthError: nil,
|
OauthAuthError: nil,
|
||||||
IdToken: "1",
|
IdToken: "1",
|
||||||
AccessToken: "token",
|
AccessToken: "token",
|
||||||
}
|
}
|
||||||
@@ -338,12 +336,12 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
|||||||
_, err = writer.Write(data)
|
_, err = writer.Write(data)
|
||||||
s.NoError(err)
|
s.NoError(err)
|
||||||
})
|
})
|
||||||
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
mux.HandleFunc("/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
res := entity.SudirUserResponse{
|
res := entity.OauthUserResponse{
|
||||||
SudirAuthError: nil,
|
OauthAuthError: nil,
|
||||||
Email: "sudir@email.ru",
|
Email: "oauth@email.ru",
|
||||||
Groups: []string{"DIT-KKD-Admins"},
|
Groups: []string{"DIT-KKD-Admins"},
|
||||||
Sub: "sudirUser1",
|
Sub: "oauthUser1",
|
||||||
GivenName: "name",
|
GivenName: "name",
|
||||||
FamilyName: "surname",
|
FamilyName: "surname",
|
||||||
Name: "surname name patronymic",
|
Name: "surname name patronymic",
|
||||||
|
|||||||
@@ -21,15 +21,15 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) int64 {
|
func InsertOauthUser(db *dbt.TestDb, user entity.OauthUser) int64 {
|
||||||
q, args, err := query.New().
|
q, args, err := query.New().
|
||||||
Insert("users").
|
Insert("users").
|
||||||
Columns("sudir_user_id", "first_name", "last_name", "full_name", "email").
|
Columns("oauth_user_id", "first_name", "last_name", "full_name", "email").
|
||||||
Values(user.SudirUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
Values(user.OauthUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
||||||
Suffix("RETURNING id").
|
Suffix("RETURNING id").
|
||||||
ToSql()
|
ToSql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(errors.WithMessagef(err, "insert sudir user"))
|
panic(errors.WithMessagef(err, "insert oauth user"))
|
||||||
}
|
}
|
||||||
var id int64
|
var id int64
|
||||||
db.Must().SelectRow(&id, q, args...)
|
db.Must().SelectRow(&id, q, args...)
|
||||||
|
|||||||
+17
-17
@@ -21,20 +21,20 @@ type UiSettingsSuite struct {
|
|||||||
|
|
||||||
test *test.Test
|
test *test.Test
|
||||||
apiCli *client.Client
|
apiCli *client.Client
|
||||||
sudirClientSetting conf.SudirClientConfig
|
oauthClientSetting conf.OauthClientConfig
|
||||||
baseSudirUrl string
|
baseOauthUrl string
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUiSettingsSuite(t *testing.T) {
|
func TestUiSettingsSuite(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
suite.Run(t, &UiSettingsSuite{
|
suite.Run(t, &UiSettingsSuite{
|
||||||
baseSudirUrl: "http://127.0.0.1/sudir",
|
baseOauthUrl: "http://127.0.0.1/oauth",
|
||||||
sudirClientSetting: conf.SudirClientConfig{
|
oauthClientSetting: conf.OauthClientConfig{
|
||||||
ClientName: fake.It[string](),
|
ClientName: fake.It[string](),
|
||||||
ClientId: fake.It[string](),
|
ClientId: fake.It[string](),
|
||||||
ClientSecret: fake.It[string](),
|
ClientSecret: fake.It[string](),
|
||||||
RedirectURI: "https://127.0.0.1/test/redirected",
|
RedirectURI: "https://127.0.0.1/test/redirected",
|
||||||
UiSetting: &conf.UiSudirSetting{
|
UiSetting: &conf.UiOauthSetting{
|
||||||
LoginEndpoint: "/login?someQueryParam=1&test=true",
|
LoginEndpoint: "/login?someQueryParam=1&test=true",
|
||||||
LogoutEndpoint: "/logout?redirect=url",
|
LogoutEndpoint: "/logout?redirect=url",
|
||||||
},
|
},
|
||||||
@@ -45,9 +45,9 @@ func TestUiSettingsSuite(t *testing.T) {
|
|||||||
func (s *UiSettingsSuite) SetupTest() {
|
func (s *UiSettingsSuite) SetupTest() {
|
||||||
s.test, _ = test.New(s.T())
|
s.test, _ = test.New(s.T())
|
||||||
remote := conf.Remote{
|
remote := conf.Remote{
|
||||||
SudirAuth: &conf.SudirAuth{
|
Oauth: &conf.Oauth{
|
||||||
Host: s.baseSudirUrl,
|
Host: s.baseOauthUrl,
|
||||||
Clients: []conf.SudirClientConfig{s.sudirClientSetting},
|
Clients: []conf.OauthClientConfig{s.oauthClientSetting},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil).
|
cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil).
|
||||||
@@ -58,11 +58,11 @@ func (s *UiSettingsSuite) SetupTest() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
func (s *UiSettingsSuite) Test_HappyPath() {
|
||||||
var resp domain.UiSudirSetting
|
var resp domain.UiOauthSetting
|
||||||
|
|
||||||
err := s.apiCli.Invoke("admin/ui_settings/sudir").
|
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||||
JsonRequestBody(domain.ClientNameRequest{
|
JsonRequestBody(domain.ClientNameRequest{
|
||||||
ClientName: s.sudirClientSetting.ClientName,
|
ClientName: s.oauthClientSetting.ClientName,
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
Do(s.T().Context())
|
Do(s.T().Context())
|
||||||
@@ -72,13 +72,13 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
|||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
s.Require().Equal(
|
s.Require().Equal(
|
||||||
"http://127.0.0.1/sudir/login",
|
"http://127.0.0.1/oauth/login",
|
||||||
loginURL.Scheme+"://"+loginURL.Host+loginURL.Path,
|
loginURL.Scheme+"://"+loginURL.Host+loginURL.Path,
|
||||||
)
|
)
|
||||||
|
|
||||||
query := loginURL.Query()
|
query := loginURL.Query()
|
||||||
s.Require().Equal(s.sudirClientSetting.ClientId, query.Get("client_id"))
|
s.Require().Equal(s.oauthClientSetting.ClientId, query.Get("client_id"))
|
||||||
s.Require().Equal(s.sudirClientSetting.RedirectURI, query.Get("redirect_uri"))
|
s.Require().Equal(s.oauthClientSetting.RedirectURI, query.Get("redirect_uri"))
|
||||||
s.Require().Equal("1", query.Get("someQueryParam"))
|
s.Require().Equal("1", query.Get("someQueryParam"))
|
||||||
s.Require().Equal("true", query.Get("test"))
|
s.Require().Equal("true", query.Get("test"))
|
||||||
|
|
||||||
@@ -86,16 +86,16 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
|||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
s.Require().Equal(
|
s.Require().Equal(
|
||||||
"http://127.0.0.1/sudir/logout",
|
"http://127.0.0.1/oauth/logout",
|
||||||
logoutURL.Scheme+"://"+logoutURL.Host+logoutURL.Path,
|
logoutURL.Scheme+"://"+logoutURL.Host+logoutURL.Path,
|
||||||
)
|
)
|
||||||
s.Require().Equal("url", logoutURL.Query().Get("redirect"))
|
s.Require().Equal("url", logoutURL.Query().Get("redirect"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
func (s *UiSettingsSuite) Test_UnknownClient() {
|
||||||
err := s.apiCli.Invoke("admin/ui_settings/sudir").
|
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||||
JsonRequestBody(domain.ClientNameRequest{
|
JsonRequestBody(domain.ClientNameRequest{
|
||||||
ClientName: s.sudirClientSetting.ClientName + fake.It[string](),
|
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||||
}).
|
}).
|
||||||
Do(s.T().Context())
|
Do(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
|||||||
+14
-14
@@ -126,9 +126,9 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
|||||||
s.Require().Equal(codes.NotFound, st.Code())
|
s.Require().Equal(codes.NotFound, st.Code())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestGetProfileSudir() {
|
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||||
id := InsertSudirUser(s.db, entity.SudirUser{
|
id := InsertOauthUser(s.db, entity.OauthUser{
|
||||||
SudirUserId: "sudirUser1",
|
OauthUserId: "oauthUser1",
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
FullName: "surname name",
|
FullName: "surname name",
|
||||||
@@ -384,9 +384,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
|||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||||
firstSudirId := "user_a"
|
firstOauthId := "user_a"
|
||||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a2@a.ru"})
|
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a2@a.ru"})
|
||||||
|
|
||||||
preCount := 0
|
preCount := 0
|
||||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||||
@@ -458,13 +458,13 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
|||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
||||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: "123", Email: "sudir@a.ru", FullName: "surname name patronymic"})
|
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: "123", Email: "oauth@a.ru", FullName: "surname name patronymic"})
|
||||||
req := domain.UpdateUserRequest{
|
req := domain.UpdateUserRequest{
|
||||||
Id: id,
|
Id: id,
|
||||||
FirstName: "nameUpd",
|
FirstName: "nameUpd",
|
||||||
LastName: "surnameUpd",
|
LastName: "surnameUpd",
|
||||||
Email: "sudir@a.ru",
|
Email: "oauth@a.ru",
|
||||||
}
|
}
|
||||||
response := domain.User{}
|
response := domain.User{}
|
||||||
err := s.grpcCli.
|
err := s.grpcCli.
|
||||||
@@ -506,12 +506,12 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
|||||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() {
|
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||||
firstSudirId := "user_a"
|
firstOauthId := "user_a"
|
||||||
secondSudirId := "user_b"
|
secondOauthId := "user_b"
|
||||||
|
|
||||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a_exists@a.ru"})
|
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a_exists@a.ru"})
|
||||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: secondSudirId, Email: "b_exists@b.ru"})
|
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: secondOauthId, Email: "b_exists@b.ru"})
|
||||||
req := domain.UpdateUserRequest{
|
req := domain.UpdateUserRequest{
|
||||||
Id: id,
|
Id: id,
|
||||||
FirstName: "name",
|
FirstName: "name",
|
||||||
|
|||||||
Reference in new issue
Block a user