add swagger docs, refactor

This commit is contained in:
Рябов Владислав Олегович authored and Мержанов Максим Владимирович committed 2021-02-10 16:50:12 +03:00
1 parent f5ab9c768f
commit 416013ed1d
6 files changed
+993 -55

No files matched your search

+11 -11
View File
@@ -2,20 +2,20 @@ package controller
import (
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"msp-admin-service/conf"
)
func GetUIDesign(metadata metadata.MD) (conf.UIDesign, error) {
token := metadata.Get(adminAuthHeaderName)
if len(token) == 0 || token[0] == "" {
log.Errorf(0, "Admin AUTH header: %s, not found, received: %v", adminAuthHeaderName, metadata)
return conf.UIDesign{}, status.Error(codes.InvalidArgument, ServiceError)
}
// @Tags user
// @Summary Получение внешнего вида
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} conf.UIDesign
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
// @Failure 500 {object} structure.GrpcError
// @Router /user/get_design [POST]
func GetUIDesign(_ metadata.MD) (conf.UIDesign, error) {
return config.GetRemote().(*conf.RemoteConfig).UiDesign, nil
}
+66 -14
View File
@@ -4,7 +4,6 @@ import (
"fmt"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"golang.org/x/crypto/bcrypt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
@@ -22,24 +21,33 @@ const (
ValidationError = "Validation errors"
)
func Logout(metadata metadata.MD) error {
token := metadata.Get(adminAuthHeaderName)
if len(token) == 0 || token[0] == "" {
log.Errorf(0, "Admin AUTH header: %s, not found, received: %v", adminAuthHeaderName, metadata)
return status.Error(codes.InvalidArgument, ServiceError)
}
// @Tags auth
// @Summary Выход из авторизованной сессии
// @Description Выход из авторизованной сессии администрирования
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
// @Failure 500 {object} structure.GrpcError
// @Router /auth/logout [POST]
func Logout(_ metadata.MD) error {
return nil
}
// @Tags user
// @Summary Получить профиль
// @Description Получить данные профиля
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} structure.AdminUserShort
// @Failure 400 {object} structure.GrpcError "Невалидный токен"
// @Failure 401 {object} structure.GrpcError "Токен не соответствует ни одному пользователю"
// @Failure 500 {object} structure.GrpcError
// @Router /user/get_profile [POST]
func GetProfile(metadata metadata.MD) (*structure.AdminUserShort, error) {
token := metadata.Get(adminAuthHeaderName)
if len(token) == 0 || token[0] == "" {
log.Errorf(0, "Admin AUTH header: %s, not found, received: %v", adminAuthHeaderName, metadata)
return nil, status.Error(codes.InvalidArgument, ServiceError)
}
userId, err := service.GetUserId(token[0])
if err != nil {
return nil, status.Error(codes.Unauthenticated, "Invalid auth token")
@@ -58,6 +66,17 @@ func GetProfile(metadata metadata.MD) (*structure.AdminUserShort, error) {
}, nil
}
// @Tags auth
// @Summary Авторизация
// @Description Авторизация с получением токена администратора
// @Accept json
// @Produce json
// @Param body body structure.AuthRequest true "Тело запроса"
// @Success 200 {object} structure.Auth
// @Failure 400 {object} structure.GrpcError "Данные для авторизации не верны"
// @Failure 404 {object} structure.GrpcError "Пользователь не найден"
// @Failure 500 {object} structure.GrpcError
// @Router /auth/login [POST]
func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
user, err := model.GetUserByEmail(authRequest.Email)
if user == nil {
@@ -82,6 +101,17 @@ func Login(authRequest structure.AuthRequest) (*structure.Auth, error) {
}, nil
}
// @Tags user
// @Summary Список пользователей
// @Description Получить список пользователей
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body structure.UsersRequest true "Тело запроса"
// @Success 200 {object} structure.UsersResponse
// @Failure 400 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /user/get_users [POST]
func GetUsers(identities structure.UsersRequest) (*structure.UsersResponse, error) {
users, err := model.GetUsers(identities)
if err != nil {
@@ -93,6 +123,17 @@ func GetUsers(identities structure.UsersRequest) (*structure.UsersResponse, erro
return &structure.UsersResponse{Items: users}, err
}
// @Tags user
// @Summary Создать/Обновить пользователя
// @Description Создать пользователя или обновить данные существующего
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body entity.AdminUser true "Тело запроса"
// @Success 200 {object} entity.AdminUser
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} structure.GrpcError
// @Router /user/create_update_user [POST]
func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
var err error
if user.Id == 0 {
@@ -154,6 +195,17 @@ func CreateUpdateUser(user entity.AdminUser) (*entity.AdminUser, error) {
return &user, err
}
// @Tags user
// @Summary Удалить пользователя
// @Description Удалить существующего пользователя
// @Accept json
// @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Param body body structure.IdentitiesRequest true "Тело запроса"
// @Success 200 {object} structure.DeleteResponse
// @Failure 400 {object} structure.GrpcError "Невалидное тело запроса"
// @Failure 500 {object} structure.GrpcError
// @Router /user/delete_user [POST]
func DeleteUser(identities structure.IdentitiesRequest) (*structure.DeleteResponse, error) {
if len(identities.Ids) == 0 {
validationErrors := map[string]string{
+555
View File
@@ -0,0 +1,555 @@
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag at
// 2021-02-10 16:44:23.355615962 +0300 MSK m=+107.224783060
package docs
import (
"github.com/integration-system/isp-lib/v2/docs"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{.Description}}",
"title": "{{.Title}}",
"contact": {},
"license": {
"name": "GNU GPL v3.0"
},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/auth/login": {
"post": {
"description": "Авторизация с получением токена администратора",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"auth"
],
"summary": "Авторизация",
"parameters": [
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/structure.AuthRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/structure.Auth"
}
},
"400": {
"description": "Данные для авторизации не верны",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"404": {
"description": "Пользователь не найден",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/auth/logout": {
"post": {
"description": "Выход из авторизованной сессии администрирования",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"auth"
],
"summary": "Выход из авторизованной сессии",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
}
],
"responses": {
"200": {},
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/user/create_update_user": {
"post": {
"description": "Создать пользователя или обновить данные существующего",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"user"
],
"summary": "Создать/Обновить пользователя",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/entity.AdminUser"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/entity.AdminUser"
}
},
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/user/delete_user": {
"post": {
"description": "Удалить существующего пользователя",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"user"
],
"summary": "Удалить пользователя",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/structure.IdentitiesRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/structure.DeleteResponse"
}
},
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/user/get_design": {
"post": {
"description": "Получение внешнего вида (палитра и наименование) админ-интерфейса",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"user"
],
"summary": "Получение внешнего вида",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/conf.UIDesign"
}
},
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/user/get_profile": {
"post": {
"description": "Получить данные профиля",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"user"
],
"summary": "Получить профиль",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/structure.AdminUserShort"
}
},
"400": {
"description": "Невалидный токен",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"401": {
"description": "Токен не соответствует ни одному пользователю",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
},
"/user/get_users": {
"post": {
"description": "Получить список пользователей",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"user"
],
"summary": "Список пользователей",
"parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/structure.UsersRequest"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/structure.UsersResponse"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/structure.GrpcError"
}
}
}
}
}
},
"definitions": {
"conf.UIDesign": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"primaryColor": {
"type": "string"
}
}
},
"entity.AdminUser": {
"type": "object",
"required": [
"email"
],
"properties": {
"createdAt": {
"type": "string"
},
"email": {
"type": "string"
},
"firstName": {
"type": "string"
},
"id": {
"type": "integer"
},
"image": {
"type": "string"
},
"lastName": {
"type": "string"
},
"password": {
"type": "string"
},
"phone": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
}
},
"structure.AdminUserShort": {
"type": "object",
"required": [
"email"
],
"properties": {
"email": {
"type": "string"
},
"firstName": {
"type": "string"
},
"image": {
"type": "string"
},
"lastName": {
"type": "string"
},
"phone": {
"type": "string"
}
}
},
"structure.Auth": {
"type": "object",
"properties": {
"expired": {
"type": "string"
},
"headerName": {
"type": "string"
},
"token": {
"type": "string"
}
}
},
"structure.AuthRequest": {
"type": "object",
"required": [
"email",
"password"
],
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"structure.DeleteResponse": {
"type": "object",
"properties": {
"deleted": {
"type": "integer"
}
}
},
"structure.GrpcError": {
"type": "object",
"properties": {
"details": {
"type": "array",
"items": {
"type": "object"
}
},
"errorCode": {
"type": "string"
},
"errorMessage": {
"type": "string"
}
}
},
"structure.IdentitiesRequest": {
"type": "object",
"properties": {
"ids": {
"type": "array",
"items": {
"type": "integer"
}
}
}
},
"structure.UsersRequest": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"ids": {
"type": "array",
"items": {
"type": "integer"
}
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"phone": {
"type": "string"
}
}
},
"structure.UsersResponse": {
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"$ref": "#/definitions/entity.AdminUser"
}
}
}
}
}
}`
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = docs.SwaggerInfo{
Version: "1.0.0",
Host: "localhost:9000",
BasePath: "/api/admin",
Schemes: []string{},
Title: "msp-admin-service",
Description: "сервис администрирования",
}
func init() {
docs.InitSwagger(SwaggerInfo, doc)
}
+348
View File
@@ -0,0 +1,348 @@
basePath: /api/admin
definitions:
conf.UIDesign:
properties:
name:
type: string
primaryColor:
type: string
type: object
entity.AdminUser:
properties:
createdAt:
type: string
email:
type: string
firstName:
type: string
id:
type: integer
image:
type: string
lastName:
type: string
password:
type: string
phone:
type: string
updatedAt:
type: string
required:
- email
type: object
structure.AdminUserShort:
properties:
email:
type: string
firstName:
type: string
image:
type: string
lastName:
type: string
phone:
type: string
required:
- email
type: object
structure.Auth:
properties:
expired:
type: string
headerName:
type: string
token:
type: string
type: object
structure.AuthRequest:
properties:
email:
type: string
password:
type: string
required:
- email
- password
type: object
structure.DeleteResponse:
properties:
deleted:
type: integer
type: object
structure.GrpcError:
properties:
details:
items:
type: object
type: array
errorCode:
type: string
errorMessage:
type: string
type: object
structure.IdentitiesRequest:
properties:
ids:
items:
type: integer
type: array
type: object
structure.UsersRequest:
properties:
email:
type: string
ids:
items:
type: integer
type: array
limit:
type: integer
offset:
type: integer
phone:
type: string
type: object
structure.UsersResponse:
properties:
items:
items:
$ref: '#/definitions/entity.AdminUser'
type: array
type: object
host: localhost:9000
info:
contact: {}
description: сервис администрирования
license:
name: GNU GPL v3.0
title: msp-admin-service
version: 1.0.0
paths:
/auth/login:
post:
consumes:
- application/json
description: Авторизация с получением токена администратора
parameters:
- description: Тело запроса
in: body
name: body
required: true
schema:
$ref: '#/definitions/structure.AuthRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/structure.Auth'
"400":
description: Данные для авторизации не верны
schema:
$ref: '#/definitions/structure.GrpcError'
"404":
description: Пользователь не найден
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Авторизация
tags:
- auth
/auth/logout:
post:
consumes:
- application/json
description: Выход из авторизованной сессии администрирования
parameters:
- description: Токен администратора
in: header
name: X-AUTH-ADMIN
required: true
type: string
produces:
- application/json
responses:
"200": {}
"400":
description: Невалидный токен
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Выход из авторизованной сессии
tags:
- auth
/user/create_update_user:
post:
consumes:
- application/json
description: Создать пользователя или обновить данные существующего
parameters:
- description: Токен администратора
in: header
name: X-AUTH-ADMIN
required: true
type: string
- description: Тело запроса
in: body
name: body
required: true
schema:
$ref: '#/definitions/entity.AdminUser'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/entity.AdminUser'
"400":
description: Невалидное тело запроса
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Создать/Обновить пользователя
tags:
- user
/user/delete_user:
post:
consumes:
- application/json
description: Удалить существующего пользователя
parameters:
- description: Токен администратора
in: header
name: X-AUTH-ADMIN
required: true
type: string
- description: Тело запроса
in: body
name: body
required: true
schema:
$ref: '#/definitions/structure.IdentitiesRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/structure.DeleteResponse'
"400":
description: Невалидное тело запроса
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Удалить пользователя
tags:
- user
/user/get_design:
post:
consumes:
- application/json
description: Получение внешнего вида (палитра и наименование) админ-интерфейса
parameters:
- description: Токен администратора
in: header
name: X-AUTH-ADMIN
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/conf.UIDesign'
"400":
description: Невалидный токен
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Получение внешнего вида
tags:
- user
/user/get_profile:
post:
consumes:
- application/json
description: Получить данные профиля
parameters:
- description: Токен администратора
in: header
name: X-AUTH-ADMIN
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/structure.AdminUserShort'
"400":
description: Невалидный токен
schema:
$ref: '#/definitions/structure.GrpcError'
"401":
description: Токен не соответствует ни одному пользователю
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Получить профиль
tags:
- user
/user/get_users:
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/structure.UsersRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/structure.UsersResponse'
"400":
description: Bad Request
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/structure.GrpcError'
summary: Список пользователей
tags:
- user
swagger: "2.0"
+13
View File
@@ -14,6 +14,7 @@ import (
"github.com/integration-system/isp-log/stdcodes"
"github.com/soheilhy/cmux"
"msp-admin-service/conf"
_ "msp-admin-service/docs"
"msp-admin-service/helper"
"msp-admin-service/invoker"
"msp-admin-service/model"
@@ -26,6 +27,18 @@ var (
wsLn net.Listener
)
// @title msp-admin-service
// @version 1.0.0
// @description сервис администрирования
// @license.name GNU GPL v3.0
// @host localhost:9000
// @BasePath /api/admin
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json
func main() {
bootstrap.
ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}).
-30
View File
@@ -1,30 +0,0 @@
package token
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/integration-system/isp-lib/v2/config"
"msp-admin-service/conf"
)
type customClaims struct {
Id string
jwt.StandardClaims
}
func GetToken(id string) (string, string, error) {
expired := ""
claims := customClaims{Id: id}
cfg := config.GetRemote().(*conf.RemoteConfig)
if cfg.ExpireSec != 0 {
exp := time.Now().Add(time.Second * time.Duration(cfg.ExpireSec))
expired = exp.String()
claims.ExpiresAt = exp.Unix()
}
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(cfg.SecretKey))
if err != nil {
return "", "", err
}
return tokenString, expired, nil
}