Merge branch 'MSP-1070' into 'master'

Resolve MSP-1070

Closes MSP-1070

See merge request msp2.0/msp-admin-service!13
This commit is contained in:
komissarovyv committed 2022-10-10 14:51:27 +00:00
commit 607539d47b
27 files changed
+739 -196

No files matched your search

+1 -1
View File
@@ -1 +1 @@
4.0.2
4.1.0
+4
View File
@@ -1,3 +1,7 @@
### v4.1.0
* добавлен метод аутентификации токена
* удалены бессрочные токены. Время жизни токена по умолчанию 1 час
* обновлен метод logout: закрывает все текущие сессии администратора (на всех устройствах)
### v4.0.2
* исправлена ошибка метадаты grpc
### v4.0.1
+4 -3
View File
@@ -1,8 +1,6 @@
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"
@@ -35,8 +33,9 @@ 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)
tokenRepo := repository.NewToken(l.db)
tokenService := service.NewToken(time.Second*time.Duration(cfg.ExpireSec), cfg.SecretKey)
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo, roleRepo)
userService := service.NewUser(tokenService, userRepo, roleRepo, l.logger)
authService := service.NewAuth(userRepo, tokenService, sudirService, l.logger)
@@ -44,6 +43,7 @@ func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
userController := controller.NewUser(userService)
customizationController := controller.NewCustomization(cfg.UiDesign)
authController := controller.NewAuth(authService, l.logger)
secureController := controller.NewSecure(tokenService)
handler := routes.Handler(
endpoint.DefaultWrapper(
@@ -54,6 +54,7 @@ func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
User: userController,
Customization: customizationController,
Auth: authController,
Secure: secureController,
},
)
+1 -1
View File
@@ -8,5 +8,5 @@
"password": "{{ msp_pgsql_password }}"
},
"logLevel": "debug",
"secretKey": "secret"
"expireSec": 3600
}
+1 -2
View File
@@ -18,8 +18,7 @@ func init() {
type Remote struct {
Database dbx.Config
SecretKey string `valid:"required~Required" schema:"JWT secret"`
ExpireSec int `schema:"Token expire time,in seconds"`
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
+28 -9
View File
@@ -2,17 +2,21 @@ package controller
import (
"context"
"strconv"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"msp-admin-service/domain"
)
type authService interface {
Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error)
LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error)
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
Logout(ctx context.Context, adminId int64) error
}
type Auth struct {
@@ -38,7 +42,22 @@ func NewAuth(authService authService, logger log.Logger) Auth {
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/logout [POST]
func (a Auth) Logout() error {
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
if err != nil {
return status.Error(codes.InvalidArgument, "Отсутствует идентификатор")
}
adminId, err := strconv.Atoi(token)
if err != nil {
return status.Error(codes.InvalidArgument, "Недействительный идентификатор")
}
err = a.authService.Logout(ctx, int64(adminId))
if err != nil {
return errors.WithMessage(err, "logout")
}
return nil
}
@@ -48,13 +67,13 @@ func (a Auth) Logout() error {
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body domain.AuthRequest true "Тело запроса"
// @Success 200 {object} domain.Auth
// @Param body body domain.LoginRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/login [POST]
func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error) {
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.Login(ctx, authRequest)
switch {
@@ -76,13 +95,13 @@ func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domai
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body domain.SudirAuthRequest true "Тело запроса"
// @Success 200 {object} domain.Auth
// @Param body body domain.LoginSudirRequest true "Тело запроса"
// @Success 200 {object} domain.LoginResponse
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации"
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
// @Failure 500 {object} domain.GrpcError
// @Router /auth/login_with_sudir [POST]
func (a Auth) LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error) {
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.LoginWithSudir(ctx, request)
switch {
+59
View File
@@ -0,0 +1,59 @@
package controller
import (
"context"
"github.com/pkg/errors"
"msp-admin-service/domain"
)
type SecureService interface {
GetUserId(ctx context.Context, token string) (int64, error)
}
type Secure struct {
service SecureService
}
func NewSecure(service SecureService) Secure {
return Secure{
service: service,
}
}
// Authenticate
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет токен и возвращает идентификатор администратора
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body domain.SecureAuthRequest true "Тело запроса"
// @Success 200 {object} domain.SecureAuthResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authenticate [POST]
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
adminId, err := s.service.GetUserId(ctx, req.Token)
switch {
case errors.Is(err, domain.ErrTokenExpired):
return &domain.SecureAuthResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AdminId: 0,
}, nil
case errors.Is(err, domain.ErrTokenNotFound):
return &domain.SecureAuthResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
AdminId: 0,
}, nil
case err != nil:
return nil, err
default:
return &domain.SecureAuthResponse{
Authenticated: true,
ErrorReason: "",
AdminId: adminId,
}, nil
}
}
+109 -40
View File
@@ -39,7 +39,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.AuthRequest"
"$ref": "#/definitions/domain.LoginRequest"
}
}
],
@@ -47,7 +47,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.Auth"
"$ref": "#/definitions/domain.LoginResponse"
}
},
"400": {
@@ -91,7 +91,7 @@ var doc = `{
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.SudirAuthRequest"
"$ref": "#/definitions/domain.LoginSudirRequest"
}
}
],
@@ -99,7 +99,7 @@ var doc = `{
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.Auth"
"$ref": "#/definitions/domain.LoginResponse"
}
},
"401": {
@@ -164,6 +164,53 @@ var doc = `{
}
}
},
"/secure/authenticate": {
"post": {
"description": "Проверяет токен и возвращает идентификатор администратора",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"secure"
],
"summary": "Метод аутентификации токена",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.SecureAuthRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/domain.SecureAuthResponse"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
}
}
}
}
},
"/user/create_user": {
"post": {
"description": "Создать пользователя",
@@ -521,35 +568,6 @@ var doc = `{
}
}
},
"domain.Auth": {
"type": "object",
"properties": {
"expired": {
"type": "string"
},
"headerName": {
"type": "string"
},
"token": {
"type": "string"
}
}
},
"domain.AuthRequest": {
"type": "object",
"required": [
"email",
"password"
],
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"domain.CreateUserRequest": {
"type": "object",
"required": [
@@ -613,7 +631,36 @@ var doc = `{
}
}
},
"domain.SudirAuthRequest": {
"domain.LoginRequest": {
"type": "object",
"required": [
"email",
"password"
],
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"domain.LoginResponse": {
"type": "object",
"properties": {
"expired": {
"type": "string"
},
"headerName": {
"type": "string"
},
"token": {
"type": "string"
}
}
},
"domain.LoginSudirRequest": {
"type": "object",
"required": [
"authCode"
@@ -624,6 +671,28 @@ var doc = `{
}
}
},
"domain.SecureAuthRequest": {
"type": "object",
"properties": {
"token": {
"type": "string"
}
}
},
"domain.SecureAuthResponse": {
"type": "object",
"properties": {
"adminId": {
"type": "integer"
},
"authenticated": {
"type": "boolean"
},
"errorReason": {
"type": "string"
}
}
},
"domain.UpdateUserRequest": {
"type": "object",
"required": [
@@ -653,31 +722,31 @@ var doc = `{
"domain.User": {
"type": "object",
"properties": {
"created_at": {
"createdAt": {
"type": "string"
},
"email": {
"type": "string"
},
"first_name": {
"firstName": {
"type": "string"
},
"id": {
"type": "integer"
},
"last_name": {
"lastName": {
"type": "string"
},
"password": {
"type": "string"
},
"role_id": {
"roleId": {
"type": "integer"
},
"sudir_user_id": {
"sudirUserId": {
"type": "string"
},
"updated_at": {
"updatedAt": {
"type": "string"
}
}
+75 -30
View File
@@ -20,25 +20,6 @@ definitions:
required:
- email
type: object
domain.Auth:
properties:
expired:
type: string
headerName:
type: string
token:
type: string
type: object
domain.AuthRequest:
properties:
email:
type: string
password:
type: string
required:
- email
- password
type: object
domain.CreateUserRequest:
properties:
email:
@@ -80,13 +61,46 @@ definitions:
required:
- ids
type: object
domain.SudirAuthRequest:
domain.LoginRequest:
properties:
email:
type: string
password:
type: string
required:
- email
- password
type: object
domain.LoginResponse:
properties:
expired:
type: string
headerName:
type: string
token:
type: string
type: object
domain.LoginSudirRequest:
properties:
authCode:
type: string
required:
- authCode
type: object
domain.SecureAuthRequest:
properties:
token:
type: string
type: object
domain.SecureAuthResponse:
properties:
adminId:
type: integer
authenticated:
type: boolean
errorReason:
type: string
type: object
domain.UpdateUserRequest:
properties:
email:
@@ -106,23 +120,23 @@ definitions:
type: object
domain.User:
properties:
created_at:
createdAt:
type: string
email:
type: string
first_name:
firstName:
type: string
id:
type: integer
last_name:
lastName:
type: string
password:
type: string
role_id:
roleId:
type: integer
sudir_user_id:
sudirUserId:
type: string
updated_at:
updatedAt:
type: string
type: object
domain.UsersRequest:
@@ -165,14 +179,14 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/domain.AuthRequest'
$ref: '#/definitions/domain.LoginRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.Auth'
$ref: '#/definitions/domain.LoginResponse'
"400":
description: Bad Request
schema:
@@ -199,14 +213,14 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/domain.SudirAuthRequest'
$ref: '#/definitions/domain.LoginSudirRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.Auth'
$ref: '#/definitions/domain.LoginResponse'
"401":
description: Некорректный код для авторизации
schema:
@@ -249,6 +263,37 @@ paths:
summary: Выход из авторизованной сессии
tags:
- auth
/secure/authenticate:
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.SecureAuthRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.SecureAuthResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/domain.GrpcError'
summary: Метод аутентификации токена
tags:
- secure
/user/create_user:
post:
consumes:
+2
View File
@@ -11,4 +11,6 @@ var (
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
ErrInvalid = errors.New("entity is invalid")
ErrAlreadyExists = errors.New("already exists")
ErrTokenExpired = errors.New("token expired")
ErrTokenNotFound = errors.New("token not found")
)
+12 -9
View File
@@ -1,18 +1,21 @@
package domain
const AdminAuthHeaderName = "x-auth-admin"
const (
AdminAuthHeaderName = "x-auth-admin"
AdminAuthIdHeader = "x-admin-id"
)
type Auth struct {
Token string
Expired string `json:",omitempty"`
HeaderName string
}
type AuthRequest struct {
type LoginRequest struct {
Email string `valid:"required"`
Password string ` valid:"required"`
}
type SudirAuthRequest struct {
type LoginSudirRequest struct {
AuthCode string `valid:"required"`
}
type LoginResponse struct {
Token string
Expired string `json:",omitempty"`
HeaderName string
}
+11
View File
@@ -0,0 +1,11 @@
package domain
type SecureAuthRequest struct {
Token string
}
type SecureAuthResponse struct {
Authenticated bool
ErrorReason string
AdminId int64
}
+19
View File
@@ -0,0 +1,19 @@
package entity
import (
"time"
)
const (
TokenStatusAllowed = "ALLOWED"
TokenStatusRevoked = "REVOKED"
)
type Token struct {
Token string
UserId int64
Status string
ExpiredAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
+8 -9
View File
@@ -4,14 +4,13 @@ go 1.19
require (
github.com/Masterminds/squirrel v1.5.3
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/integration-system/isp-kit v1.12.1
github.com/integration-system/isp-kit v1.12.2
github.com/integration-system/isp-lib/v2 v2.8.7
github.com/integration-system/jsonschema v1.0.1
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.0
golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0
google.golang.org/grpc v1.49.0
golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b
google.golang.org/grpc v1.50.0
)
require (
@@ -43,12 +42,12 @@ require (
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/klauspost/compress v1.15.11 // 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/matttproud/golang_protobuf_extensions v1.0.2 // 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
@@ -71,11 +70,11 @@ require (
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/net v0.0.0-20221004154528-8021a29435af // indirect
golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875 // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.2 // indirect
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737 // indirect
google.golang.org/genproto v0.0.0-20220930163606-c98284e70a91 // 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
+16 -16
View File
@@ -140,7 +140,6 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgraph-io/badger v1.6.0/go.mod h1:zwt7syl517jmP8s94KqSxTlM6IMsdhYy6psNgSztDR4=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
@@ -395,8 +394,8 @@ github.com/integration-system/isp-etp-go/v2 v2.1.3/go.mod h1:ZpB+FIH3hy7md+f8ylV
github.com/integration-system/isp-event-lib v1.6.0/go.mod h1:lCzAci6oS+vc51W8EfHVCh9p3p057r0DpMuY4T0lSj0=
github.com/integration-system/isp-event-lib v1.6.1/go.mod h1:5ZIXsMG3gC7sfQ+eICjkDpy2RSvSAxV3Cq1BVN8LFIk=
github.com/integration-system/isp-event-lib v1.6.5/go.mod h1:gQg0S8TMeISIkTLM9/DwgWwnpS3BUkNFjgByRg3+Ub0=
github.com/integration-system/isp-kit v1.12.1 h1:/8YxDL2nedt9UbZjXaDplXLh5KfP/k8enCsWA5rG8Yc=
github.com/integration-system/isp-kit v1.12.1/go.mod h1:5wHdXzI8fWeZQbPfQdel5Jnf0zZ3R+KnYdat/NN0RRo=
github.com/integration-system/isp-kit v1.12.2 h1:xpE704kTVQQTjs/7VBBueH/CR05IIG+VujR2yIXz0Qw=
github.com/integration-system/isp-kit v1.12.2/go.mod h1:5wHdXzI8fWeZQbPfQdel5Jnf0zZ3R+KnYdat/NN0RRo=
github.com/integration-system/isp-lib-test v1.5.4/go.mod h1:rD+X0QMiOIeJDhqwB4avdYhnc1hoEkL4z+7C7lwTuOA=
github.com/integration-system/isp-lib-test v1.6.0/go.mod h1:If5QK5jsXE48DZuq6WzCw8yC22k7GogLrEnMngXiE2Y=
github.com/integration-system/isp-lib-test v1.6.4/go.mod h1:k8DiXG/Bx3k8cft0QI/+BTRsL/43effW5575udzWv1M=
@@ -491,8 +490,8 @@ github.com/klauspost/compress v1.10.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYs
github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.11.8/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/klauspost/compress v1.15.10 h1:Ai8UzuomSCDw90e1qNMtb15msBXsNpH6gzkkENQNcJo=
github.com/klauspost/compress v1.15.10/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM=
github.com/klauspost/compress v1.15.11 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c=
github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM=
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
@@ -548,8 +547,9 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/matttproud/golang_protobuf_extensions v1.0.2 h1:hAHbPm5IJGijwng3PWk09JkG9WeqChjprR5s9bBZ+OM=
github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
@@ -866,8 +866,8 @@ golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0 h1:a5Yg6ylndHHYJqIPrdq0AhvR6KTvDTAvgBtaidhEevY=
golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b h1:huxqepDufQpLLIRXiVkTvnxrzJlpwmIWAObmcCcUFr0=
golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -964,8 +964,8 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220921203646-d300de134e69 h1:hUJpGDpnfwdJW8iNypFjmSY0sCBEL+spFTZ2eO+Sfps=
golang.org/x/net v0.0.0-20220921203646-d300de134e69/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/net v0.0.0-20221004154528-8021a29435af h1:wv66FM3rLZGPdxpYL+ApnDe2HzHcTFta3z5nsc13wI4=
golang.org/x/net v0.0.0-20221004154528-8021a29435af/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1074,8 +1074,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 h1:h+EGohizhe9XlX18rfpa8k8RAc5XyaeamM+0VHRd4lc=
golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875 h1:AzgQNqF+FKwyQ5LbVrVqOcuuFB67N47F9+htZYH0wFM=
golang.org/x/sys v0.0.0-20221006211917-84dc82d7e875/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -1245,8 +1245,8 @@ google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6D
google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A=
google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0=
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737 h1:K1zaaMdYBXRyX+cwFnxj7M6zwDyumLQMZ5xqwGvjreQ=
google.golang.org/genproto v0.0.0-20220921223823-23cae91e6737/go.mod h1:2r/26NEF3bFmT3eC3aZreahSal0C3Shl8Gi6vyDYqOQ=
google.golang.org/genproto v0.0.0-20220930163606-c98284e70a91 h1:Ezh2cpcnP5Rq60sLensUsFnxh7P6513NLvNtCm9iyJ4=
google.golang.org/genproto v0.0.0-20220930163606-c98284e70a91/go.mod h1:3526vdqwhZAwq4wsRUaVG555sVgsNmIjRtO7t/JH29U=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
@@ -1269,8 +1269,8 @@ google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAG
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
google.golang.org/grpc v1.49.0 h1:WTLtQzmQori5FUH25Pq4WT22oCsv8USpQ+F6rqtsmxw=
google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI=
google.golang.org/grpc v1.50.0 h1:fPVVDxY9w++VjTZsYvXWqEf9Rqar/e+9zYfxKK+W+YU=
google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+1 -1
View File
@@ -19,7 +19,7 @@ var version = "1.0.0"
// @host localhost:9000
// @BasePath /api/admin
//go:generate swag init --parseDependency
//go:generate swag init
//go:generate rm -f docs/swagger.json
func main() {
@@ -0,0 +1,14 @@
-- +goose Up
CREATE TABLE tokens
(
token TEXT PRIMARY KEY,
user_id INT8 NOT NULL,
status TEXT NOT NULL,
expired_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
-- +goose Down
DROP TABLE tokens;
+68
View File
@@ -0,0 +1,68 @@
package repository
import (
"context"
"database/sql"
"time"
"github.com/integration-system/isp-kit/db"
"github.com/pkg/errors"
"msp-admin-service/domain"
"msp-admin-service/entity"
)
type Token struct {
db db.DB
}
func NewToken(db db.DB) Token {
return Token{
db: db,
}
}
func (r Token) Save(ctx context.Context, token entity.Token) error {
q := `
INSERT INTO tokens
(token, user_id, status, expired_at, created_at, updated_at)
VALUES (:token, :user_id, :status, :expired_at, :created_at, :updated_at)
`
_, err := r.db.ExecNamed(ctx, q, token)
if err != nil {
return errors.WithMessage(err, "save token row")
}
return nil
}
func (r Token) GetEntity(ctx context.Context, token string) (*entity.Token, error) {
result := entity.Token{}
q := `
SELECT token, user_id, status, expired_at, created_at, updated_at
FROM tokens
WHERE token = $1;
`
err := r.db.SelectRow(ctx, &result, q, token)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrTokenNotFound
}
return nil, errors.WithMessage(err, "select token row by token")
}
return &result, nil
}
func (r Token) RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error {
q := `
UPDATE tokens
SET status = $1, updated_at = $2
WHERE user_id = $3 AND status = $4;
`
_, err := r.db.Exec(ctx, q, entity.TokenStatusRevoked, updatedAt, userId, entity.TokenStatusAllowed)
if err != nil {
return errors.WithMessage(err, "update token status")
}
return nil
}
+7
View File
@@ -12,6 +12,7 @@ type Controllers struct {
Auth controller.Auth
User controller.User
Customization controller.Customization
Secure controller.Secure
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
@@ -82,5 +83,11 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
UserAuthRequired: false,
Handler: c.User.DeleteUser,
},
{
Path: "admin/secure/authenticate",
Inner: true,
UserAuthRequired: false,
Handler: c.Secure.Authenticate,
},
}
}
+19 -9
View File
@@ -17,7 +17,8 @@ type userRepository interface {
}
type tokenService interface {
GenerateToken(id int64) (string, string, error)
GenerateToken(ctx context.Context, id int64) (string, string, error)
RevokeAllByUserId(ctx context.Context, userId int64) error
}
type sudirService interface {
@@ -40,8 +41,8 @@ func NewAuth(userRepository userRepository, tokenService tokenService, sudirServ
}
}
func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domain.Auth, error) {
user, err := a.userRepository.GetUserByEmail(ctx, authRequest.Email)
func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error) {
user, err := a.userRepository.GetUserByEmail(ctx, request.Email)
switch {
case errors.Is(err, domain.ErrNotFound):
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
@@ -51,24 +52,24 @@ func (a Auth) Login(ctx context.Context, authRequest domain.AuthRequest) (*domai
return nil, domain.ErrSudirAuthorization
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(authRequest.Password))
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
if err != nil {
return nil, errors.WithMessage(domain.ErrUnauthenticated, "wrong password")
}
tokenString, expired, err := a.tokenService.GenerateToken(user.Id)
tokenString, expired, err := a.tokenService.GenerateToken(ctx, user.Id)
if err != nil {
return nil, errors.WithMessage(err, "generate token")
}
return &domain.Auth{
return &domain.LoginResponse{
Token: tokenString,
Expired: expired,
HeaderName: domain.AdminAuthHeaderName,
}, nil
}
func (a Auth) LoginWithSudir(ctx context.Context, request domain.SudirAuthRequest) (*domain.Auth, error) {
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
sudirUser, err := a.sudirService.Authenticate(ctx, request.AuthCode)
var authErr *entity.SudirAuthError
@@ -97,14 +98,23 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.SudirAuthReques
return nil, errors.WithMessage(err, "get user")
}
tokenString, expired, err := a.tokenService.GenerateToken(user.Id)
tokenString, expired, err := a.tokenService.GenerateToken(ctx, user.Id)
if err != nil {
return nil, errors.WithMessage(err, "generate token")
}
return &domain.Auth{
return &domain.LoginResponse{
Token: tokenString,
Expired: expired,
HeaderName: domain.AdminAuthHeaderName,
}, nil
}
func (a Auth) Logout(ctx context.Context, adminId int64) error {
err := a.tokenService.RevokeAllByUserId(ctx, adminId)
if err != nil {
return errors.WithMessage(err, "revoke all tokens by user id")
}
return nil
}
+52 -33
View File
@@ -1,61 +1,80 @@
package service
import (
"context"
"crypto/rand"
"encoding/hex"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"msp-admin-service/domain"
"msp-admin-service/entity"
)
type customClaims struct {
Id int64
jwt.StandardClaims
type TokenRep interface {
Save(ctx context.Context, token entity.Token) error
GetEntity(ctx context.Context, token string) (*entity.Token, error)
RevokeByUserId(ctx context.Context, userId int64, updatedAt time.Time) error
}
type Token struct {
ttl time.Duration
secretKey string
tokenRep TokenRep
lifeTime time.Duration
}
func NewToken(ttl time.Duration, secretKey string) Token {
func NewToken(tokenRep TokenRep, lifeTimeInSec int) Token {
return Token{
ttl: ttl,
secretKey: secretKey,
lifeTime: time.Second * time.Duration(lifeTimeInSec),
tokenRep: tokenRep,
}
}
func (t Token) GenerateToken(id int64) (string, string, error) {
expired := ""
claims := customClaims{Id: id}
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(t.secretKey))
func (s Token) GenerateToken(ctx context.Context, id int64) (string, string, error) {
cryptoRand := make([]byte, 128) //nolint:gomnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", "", errors.WithMessage(err, "generate jwt with claims")
return "", "", errors.WithMessage(err, "crypto/rand read")
}
random := hex.EncodeToString(cryptoRand)
return tokenString, expired, nil
}
createdAt := time.Now().UTC()
expiredAt := createdAt.Add(s.lifeTime)
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, errors.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(t.secretKey), nil
err = s.tokenRep.Save(ctx, entity.Token{
Token: random,
UserId: id,
Status: entity.TokenStatusAllowed,
ExpiredAt: expiredAt,
CreatedAt: createdAt,
UpdatedAt: createdAt,
})
if err != nil {
return 0, errors.WithMessage(err, "parse jwt with claims")
return "", "", errors.WithMessage(err, "save token")
}
if claims, ok := parsed.Claims.(*customClaims); ok && parsed.Valid {
return claims.Id, nil
return random, expiredAt.String(), nil
}
func (s Token) GetUserId(ctx context.Context, token string) (int64, error) {
tokenInfo, err := s.tokenRep.GetEntity(ctx, token)
if err != nil {
return 0, errors.WithMessage(err, "get token entity")
}
if time.Now().UTC().After(tokenInfo.ExpiredAt) ||
tokenInfo.Status != entity.TokenStatusAllowed {
return 0, domain.ErrTokenExpired
}
return tokenInfo.UserId, nil
}
func (s Token) RevokeAllByUserId(ctx context.Context, userId int64) error {
updatedAt := time.Now().UTC()
err := s.tokenRep.RevokeByUserId(ctx, userId, updatedAt)
if err != nil {
return errors.WithMessage(err, "set revoked status")
}
return 0, errors.New("token is invalid")
return nil
}
+8 -4
View File
@@ -11,7 +11,7 @@ import (
)
type userTokenService interface {
GetUserId(token string) (int64, error)
GetUserId(ctx context.Context, token string) (int64, error)
}
type userRepo interface {
@@ -44,10 +44,14 @@ func NewUser(userTokenService userTokenService, userRepo userRepo, userRoleRepo
}
func (u User) GetProfileByToken(ctx context.Context, token string) (*domain.AdminUserShort, error) {
userId, err := u.userTokenService.GetUserId(token)
userId, err := u.userTokenService.GetUserId(ctx, token)
if err != nil {
u.logger.Error(ctx, "get user id by token error", log.String("cause", err.Error()))
return nil, domain.ErrUnauthenticated
if errors.Is(err, domain.ErrTokenExpired) ||
errors.Is(err, domain.ErrTokenNotFound) {
u.logger.Error(ctx, "get user id by token error", log.String("cause", err.Error()))
return nil, domain.ErrUnauthenticated
}
return nil, errors.WithMessage(err, "get user id by token")
}
user, err := u.userRepo.GetUserById(ctx, userId)
+54 -22
View File
@@ -5,8 +5,8 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"
"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"
@@ -50,8 +50,7 @@ func (s *AuthTestSuite) SetupTest() {
Host: host,
RedirectURI: "http://localhost",
},
SecretKey: "admin",
ExpireSec: 0,
ExpireSec: 3600,
}
locator := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db)
@@ -66,11 +65,6 @@ func (s *AuthTestSuite) SetupTest() {
})
}
type customClaims struct {
Id int64
jwt.StandardClaims
}
func (s *AuthTestSuite) TestLoginHappyPath() {
id := InsertUser(s.db, entity.CreateUser{
RoleId: 1,
@@ -80,24 +74,23 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
Password: "password",
})
response := domain.Auth{}
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login").
JsonRequestBody(domain.AuthRequest{
JsonRequestBody(domain.LoginRequest{
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)
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
s.Require().Equal(tokenInfo.UserId, id)
}
func (s *AuthTestSuite) TestLoginNotFound() {
err := s.grpcCli.Invoke("admin/auth/login").
JsonRequestBody(domain.AuthRequest{
JsonRequestBody(domain.LoginRequest{
Email: "a1@a.ru",
Password: "password",
}).
@@ -118,7 +111,7 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
})
err := s.grpcCli.Invoke("admin/auth/login").
JsonRequestBody(domain.AuthRequest{
JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru",
Password: "WrongPassword",
}).
@@ -130,10 +123,10 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
}
func (s *AuthTestSuite) TestSudirLoginHappyPath() {
response := domain.Auth{}
response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
JsonRequestBody(domain.SudirAuthRequest{
JsonRequestBody(domain.LoginSudirRequest{
AuthCode: "code",
}).
ReadJsonResponse(&response).
@@ -144,10 +137,8 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
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)
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
s.Require().Equal(tokenInfo.UserId, user.Id)
}
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
@@ -180,3 +171,44 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
srv := httptest.NewServer(mux)
return srv, srv.URL
}
func (s *AuthTestSuite) Test_Logout_HappyPath() {
InsertTokenEntity(s.db, entity.Token{
Token: "token-841297641213",
UserId: 841297641213,
Status: entity.TokenStatusAllowed,
CreatedAt: time.Time{},
ExpiredAt: time.Time{},
})
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, "841297641213").
Do(context.Background())
s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
}
func (s *AuthTestSuite) Test_Logout_NotFound() {
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
Do(context.Background())
s.Require().NoError(err)
}
func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
InsertTokenEntity(s.db, entity.Token{
Token: "token-148623719462",
UserId: 148623719462,
Status: entity.TokenStatusRevoked,
CreatedAt: time.Time{},
ExpiredAt: time.Time{},
})
err := s.grpcCli.Invoke("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, "148623719462").
Do(context.Background())
s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
}
-1
View File
@@ -35,7 +35,6 @@ func (s *CustomizationTestSuite) SetupTest() {
Name: "test",
PrimaryColor: "#ff4d4f",
},
SecretKey: "admin",
ExpireSec: 0,
}
@@ -34,3 +34,25 @@ func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) (int64, error) {
db.Must().SelectRow(&id, q, args...)
return id, nil
}
func SelectTokenEntityByToken(db *dbt.TestDb, token string) entity.Token {
tokenInfo := entity.Token{}
db.Must().SelectRow(&tokenInfo,
`SELECT token, user_id, status, expired_at, created_at, updated_at
FROM tokens
WHERE token = $1;`,
token,
)
return tokenInfo
}
func InsertTokenEntity(db *dbt.TestDb, token entity.Token) {
db.Must().ExecNamed(
`
INSERT INTO tokens
(token, user_id, status, expired_at, created_at, updated_at)
VALUES (:token, :user_id, :status, :expired_at, :created_at, :updated_at)
`,
token,
)
}
+137
View File
@@ -0,0 +1,137 @@
package tests
import (
"context"
"testing"
"time"
"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/require"
"github.com/stretchr/testify/suite"
"msp-admin-service/assembly"
"msp-admin-service/conf"
"msp-admin-service/domain"
"msp-admin-service/entity"
)
func TestSecureSuite(t *testing.T) {
suite.Run(t, &SecureSuite{})
}
type SecureSuite struct {
suite.Suite
test *test.Test
require *require.Assertions
db *dbt.TestDb
grpcCli *client.Client
}
func (s *SecureSuite) SetupTest() {
s.test, s.require = test.New(s.T())
s.db = dbt.New(s.test, dbx.WithMigration("../migrations"))
httpCli := httpcli.New()
locator := assembly.NewLocator(s.test.Logger(), httpCli, s.db)
handler := locator.Handler(
conf.Remote{
ExpireSec: 3600,
},
)
server, apiCli := grpct.TestServer(s.test, handler)
s.test.T().Cleanup(func() {
server.Shutdown()
})
s.grpcCli = apiCli
}
func (s *SecureSuite) Test_Authenticate_HappyPath() {
InsertTokenEntity(s.db, entity.Token{
Token: "happy_path",
UserId: 1,
Status: entity.TokenStatusAllowed,
CreatedAt: time.Now().UTC(),
ExpiredAt: time.Now().UTC().Add(time.Hour),
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "happy_path",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: true,
ErrorReason: "",
AdminId: 1,
}, result)
}
func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
InsertTokenEntity(s.db, entity.Token{
Token: "revoked",
UserId: 1,
Status: entity.TokenStatusRevoked,
CreatedAt: time.Now().UTC(),
ExpiredAt: time.Now().UTC().Add(time.Hour),
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "revoked",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AdminId: 0,
}, result)
}
func (s *SecureSuite) Test_Authenticate_Expired() {
InsertTokenEntity(s.db, entity.Token{
Token: "expired",
UserId: 1,
Status: entity.TokenStatusAllowed,
CreatedAt: time.Now().UTC(),
ExpiredAt: time.Now().UTC().Add(-2 * time.Hour),
})
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "expired",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AdminId: 0,
}, result)
}
func (s *SecureSuite) Test_Authenticate_NotFound() {
result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{
Token: "not_found",
}).
ReadJsonResponse(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
AdminId: 0,
}, result)
}
+7 -6
View File
@@ -17,11 +17,12 @@ import (
"msp-admin-service/conf"
"msp-admin-service/domain"
"msp-admin-service/entity"
"msp-admin-service/repository"
"msp-admin-service/service"
)
type tokenService interface {
GenerateToken(id int64) (string, string, error)
GenerateToken(ctx context.Context, id int64) (string, string, error)
}
func TestUserTestSuite(t *testing.T) {
@@ -44,7 +45,6 @@ func (s *UserTestSuite) SetupTest() {
s.httpCli = httpcli.New()
cfg := conf.Remote{
SecretKey: "secret",
ExpireSec: 0,
}
locator := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db)
@@ -57,7 +57,8 @@ func (s *UserTestSuite) SetupTest() {
server.Shutdown()
})
s.tokenService = service.NewToken(0, "secret")
tokenRep := repository.NewToken(s.db)
s.tokenService = service.NewToken(tokenRep, 3600)
}
func (s *UserTestSuite) TestGetProfileHappyPath() {
@@ -68,7 +69,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
Email: "a@a.ru",
Password: "password",
})
token, _, err := s.tokenService.GenerateToken(id)
token, _, err := s.tokenService.GenerateToken(context.Background(), id)
s.Require().NoError(err)
response := domain.AdminUserShort{}
@@ -94,7 +95,7 @@ func (s *UserTestSuite) TestGetProfileUnauthorized() {
Email: "a@a.ru",
Password: "password",
})
token, _, err := s.tokenService.GenerateToken(id + 1)
token, _, err := s.tokenService.GenerateToken(context.Background(), id+1)
s.Require().NoError(err)
err = s.grpcCli.Invoke("admin/user/get_profile").
@@ -116,7 +117,7 @@ func (s *UserTestSuite) TestGetProfileSudir() {
})
s.Require().NoError(err)
token, _, err := s.tokenService.GenerateToken(id)
token, _, err := s.tokenService.GenerateToken(context.Background(), id)
s.Require().NoError(err)
response := domain.AdminUserShort{}