reflect: change jwt use model

This commit is contained in:
viletyy 2021-06-10 22:41:58 +08:00
parent 95d0bb766b
commit 6646a674c2
17 changed files with 261 additions and 528 deletions

View File

@ -1,5 +1,5 @@
app:
jwt_secret: 'viletyy
jwt_secret: 'viletyy'
jwt_issuer: 'potato'
jwt_expire: '7200'
run_mode: 'debug'
@ -25,7 +25,7 @@ zap:
level: 'info'
format: 'console'
prefix: '[POTATO]'
director: 'log'
director: 'tmp/log'
link-name: 'latest_log'
show-line: true
encode-level: 'LowercaseColorLevelEncoder'

View File

@ -27,7 +27,7 @@ var doc = `{
"/v1/auth": {
"post": {
"consumes": [
"application/json"
"multipart/form-data"
],
"produces": [
"application/json"
@ -35,50 +35,20 @@ var doc = `{
"summary": "用户验证",
"parameters": [
{
"description": "用户名,密码",
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.AuthRequest"
"$ref": "#/definitions/service.AuthRequest"
}
}
],
"responses": {
"200": {
"description": "{\"code\" : 200, \"data\" : {\"token\" : \"\"}, \"msg\" : \"ok\"}",
"description": "请求成功",
"schema": {
"type": "string"
}
}
}
}
},
"/v1/register": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "注册用户",
"parameters": [
{
"description": "用户名",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.RegisterRequest"
}
}
],
"responses": {
"200": {
"description": "{\"success\":true,\"data\":{},\"msg\":\"创建成功\"}",
"schema": {
"type": "string"
"$ref": "#/definitions/errcode.Error"
}
}
}
@ -100,7 +70,7 @@ var doc = `{
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -128,19 +98,7 @@ var doc = `{
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -160,28 +118,25 @@ var doc = `{
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
{
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/service.CreateVendorRequest"
}
}
],
"responses": {
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -203,7 +158,7 @@ var doc = `{
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -219,19 +174,7 @@ var doc = `{
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -251,7 +194,7 @@ var doc = `{
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -261,25 +204,22 @@ var doc = `{
"name": "id",
"in": "path",
"required": true
},
{
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/service.UpdateVendorRequest"
}
}
],
"responses": {
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -287,6 +227,9 @@ var doc = `{
}
},
"definitions": {
"basic.Vendor": {
"type": "object"
},
"errcode.Error": {
"type": "object",
"properties": {
@ -301,36 +244,49 @@ var doc = `{
}
}
},
"v1.AuthRequest": {
"service.AuthRequest": {
"type": "object",
"required": [
"password",
"username"
"app_key",
"app_secret"
],
"properties": {
"password": {
"app_key": {
"type": "string"
},
"username": {
"app_secret": {
"type": "string"
}
}
},
"v1.RegisterRequest": {
"service.CreateVendorRequest": {
"type": "object",
"required": [
"password",
"username"
"name"
],
"properties": {
"nickname": {
"name": {
"type": "string"
},
"password": {
"uuid": {
"type": "integer"
}
}
},
"service.UpdateVendorRequest": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"username": {
"type": "string"
"uuid": {
"type": "integer"
}
}
}

View File

@ -11,7 +11,7 @@
"/v1/auth": {
"post": {
"consumes": [
"application/json"
"multipart/form-data"
],
"produces": [
"application/json"
@ -19,50 +19,20 @@
"summary": "用户验证",
"parameters": [
{
"description": "用户名,密码",
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.AuthRequest"
"$ref": "#/definitions/service.AuthRequest"
}
}
],
"responses": {
"200": {
"description": "{\"code\" : 200, \"data\" : {\"token\" : \"\"}, \"msg\" : \"ok\"}",
"description": "请求成功",
"schema": {
"type": "string"
}
}
}
}
},
"/v1/register": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"summary": "注册用户",
"parameters": [
{
"description": "用户名",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.RegisterRequest"
}
}
],
"responses": {
"200": {
"description": "{\"success\":true,\"data\":{},\"msg\":\"创建成功\"}",
"schema": {
"type": "string"
"$ref": "#/definitions/errcode.Error"
}
}
}
@ -84,7 +54,7 @@
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -112,19 +82,7 @@
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -144,28 +102,25 @@
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
{
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/service.CreateVendorRequest"
}
}
],
"responses": {
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -187,7 +142,7 @@
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -203,19 +158,7 @@
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -235,7 +178,7 @@
{
"type": "string",
"description": "auth by /auth",
"name": "Authorization",
"name": "token",
"in": "header",
"required": true
},
@ -245,25 +188,22 @@
"name": "id",
"in": "path",
"required": true
},
{
"description": "Vendor模型",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/service.UpdateVendorRequest"
}
}
],
"responses": {
"200": {
"description": "请求成功",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"400": {
"description": "请求错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
}
},
"500": {
"description": "内部错误",
"schema": {
"$ref": "#/definitions/errcode.Error"
"$ref": "#/definitions/basic.Vendor"
}
}
}
@ -271,6 +211,9 @@
}
},
"definitions": {
"basic.Vendor": {
"type": "object"
},
"errcode.Error": {
"type": "object",
"properties": {
@ -285,36 +228,49 @@
}
}
},
"v1.AuthRequest": {
"service.AuthRequest": {
"type": "object",
"required": [
"password",
"username"
"app_key",
"app_secret"
],
"properties": {
"password": {
"app_key": {
"type": "string"
},
"username": {
"app_secret": {
"type": "string"
}
}
},
"v1.RegisterRequest": {
"service.CreateVendorRequest": {
"type": "object",
"required": [
"password",
"username"
"name"
],
"properties": {
"nickname": {
"name": {
"type": "string"
},
"password": {
"uuid": {
"type": "integer"
}
}
},
"service.UpdateVendorRequest": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"username": {
"type": "string"
"uuid": {
"type": "integer"
}
}
}

View File

@ -1,5 +1,7 @@
basePath: /api
definitions:
basic.Vendor:
type: object
errcode.Error:
properties:
code:
@ -9,27 +11,35 @@ definitions:
msg:
type: string
type: object
v1.AuthRequest:
service.AuthRequest:
properties:
password:
app_key:
type: string
username:
app_secret:
type: string
required:
- password
- username
- app_key
- app_secret
type: object
v1.RegisterRequest:
service.CreateVendorRequest:
properties:
nickname:
type: string
password:
type: string
username:
name:
type: string
uuid:
type: integer
required:
- password
- username
- name
type: object
service.UpdateVendorRequest:
properties:
id:
type: integer
name:
type: string
uuid:
type: integer
required:
- id
type: object
info:
contact: {}
@ -40,41 +50,22 @@ paths:
/v1/auth:
post:
consumes:
- application/json
- multipart/form-data
parameters:
- description: 用户名,密码
- description: Vendor模型
in: body
name: data
required: true
schema:
$ref: '#/definitions/v1.AuthRequest'
$ref: '#/definitions/service.AuthRequest'
produces:
- application/json
responses:
"200":
description: '{"code" : 200, "data" : {"token" : ""}, "msg" : "ok"}'
description: 请求成功
schema:
type: string
$ref: '#/definitions/errcode.Error'
summary: 用户验证
/v1/register:
post:
consumes:
- application/json
parameters:
- description: 用户名
in: body
name: data
required: true
schema:
$ref: '#/definitions/v1.RegisterRequest'
produces:
- application/json
responses:
"200":
description: '{"success":true,"data":{},"msg":"创建成功"}'
schema:
type: string
summary: 注册用户
/v1/vendors:
get:
consumes:
@ -82,7 +73,7 @@ paths:
parameters:
- description: auth by /auth
in: header
name: Authorization
name: token
required: true
type: string
- description: 名称
@ -104,15 +95,7 @@ paths:
"200":
description: 请求成功
schema:
$ref: '#/definitions/errcode.Error'
"400":
description: 请求错误
schema:
$ref: '#/definitions/errcode.Error'
"500":
description: 内部错误
schema:
$ref: '#/definitions/errcode.Error'
$ref: '#/definitions/basic.Vendor'
summary: 系统厂商列表
tags:
- vendors
@ -122,24 +105,22 @@ paths:
parameters:
- description: auth by /auth
in: header
name: Authorization
name: token
required: true
type: string
- description: Vendor模型
in: body
name: data
required: true
schema:
$ref: '#/definitions/service.CreateVendorRequest'
produces:
- application/json
responses:
"200":
description: 请求成功
schema:
$ref: '#/definitions/errcode.Error'
"400":
description: 请求错误
schema:
$ref: '#/definitions/errcode.Error'
"500":
description: 内部错误
schema:
$ref: '#/definitions/errcode.Error'
$ref: '#/definitions/basic.Vendor'
summary: 新增系统厂商
tags:
- vendors
@ -150,7 +131,7 @@ paths:
parameters:
- description: auth by /auth
in: header
name: Authorization
name: token
required: true
type: string
- description: 系统厂商 ID
@ -164,15 +145,7 @@ paths:
"200":
description: 请求成功
schema:
$ref: '#/definitions/errcode.Error'
"400":
description: 请求错误
schema:
$ref: '#/definitions/errcode.Error'
"500":
description: 内部错误
schema:
$ref: '#/definitions/errcode.Error'
$ref: '#/definitions/basic.Vendor'
summary: 删除系统厂商
tags:
- vendors
@ -182,7 +155,7 @@ paths:
parameters:
- description: auth by /auth
in: header
name: Authorization
name: token
required: true
type: string
- description: 系统厂商 ID
@ -190,21 +163,19 @@ paths:
name: id
required: true
type: integer
- description: Vendor模型
in: body
name: data
required: true
schema:
$ref: '#/definitions/service.UpdateVendorRequest'
produces:
- application/json
responses:
"200":
description: 请求成功
schema:
$ref: '#/definitions/errcode.Error'
"400":
description: 请求错误
schema:
$ref: '#/definitions/errcode.Error'
"500":
description: 内部错误
schema:
$ref: '#/definitions/errcode.Error'
$ref: '#/definitions/basic.Vendor'
summary: 修改系统厂商
tags:
- vendors

1
go.mod
View File

@ -11,7 +11,6 @@ require (
github.com/go-playground/universal-translator v0.17.0
github.com/go-playground/validator/v10 v10.6.1
github.com/go-redis/redis v6.15.9+incompatible
github.com/google/uuid v1.2.0
github.com/jinzhu/gorm v1.9.16
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lestrrat-go/strftime v1.0.4 // indirect

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-03-22 10:12:38
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 17:52:06
* @LastEditTime: 2021-06-10 21:53:31
* @FilePath: /potato/initialize/gorm.go
*/
package initialize
@ -60,7 +60,7 @@ func GormSet(db *gorm.DB) {
// 设置迁移
db.AutoMigrate(
basic.Vendor{},
model.User{},
model.Auth{},
)
// 设置空闲连接池中的最大连接数

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-03-22 17:03:27
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 15:43:37
* @LastEditTime: 2021-06-10 22:24:39
* @FilePath: /potato/initialize/server.go
*/
package initialize
@ -16,14 +16,9 @@ import (
"github.com/viletyy/potato/global"
"github.com/viletyy/potato/internal/routers"
"github.com/viletyy/potato/pkg"
)
func RunServer() {
if err := pkg.InitTrans("zh"); err != nil {
fmt.Printf("init trans failed, err:%v\n", err)
return
}
router := routers.InitRouter()
server := &http.Server{
Addr: fmt.Sprintf(":%d", global.GO_CONFIG.Server.HttpPort),

View File

@ -1,15 +1,52 @@
/*
* @Date: 2021-06-10 18:58:25
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 19:02:14
* @LastEditTime: 2021-06-10 22:28:29
* @FilePath: /potato/internal/controller/api/v1/auth.go
*/
package v1
import (
"github.com/gin-gonic/gin"
"github.com/viletyy/potato/global"
"github.com/viletyy/potato/internal/service"
"github.com/viletyy/potato/pkg/app"
"github.com/viletyy/potato/pkg/errcode"
)
// @Summary 用户验证
// @Description
// @Accept mpfd
// @Produce json
// @Param data body service.AuthRequest true "Vendor模型"
// @Success 200 {object} errcode.Error "请求成功"
// @Router /v1/auth [post]
func GetAuth(c *gin.Context) {
param := service.AuthRequest{}
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.GO_LOG.Sugar().Errorf("app.BindAndValid errs: %v", errs)
response.ToResponseErrors(errs.Errors())
return
}
svc := service.New(c.Request.Context())
err := svc.CheckAuth(&param)
if err != nil {
global.GO_LOG.Sugar().Errorf("svc.CheckAuth err: %v", err)
response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
return
}
token, err := app.GenerateToken(param.AppKey, param.AppSecret)
if err != nil {
global.GO_LOG.Sugar().Errorf("app.GenerateToken err: %v", err)
response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
return
}
response.ToResponse(gin.H{
"token": token,
})
}

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-03-21 19:54:57
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 17:56:42
* @LastEditTime: 2021-06-10 21:49:29
* @FilePath: /potato/internal/controller/api/v1/basic/vendor.go
*/
package basic
@ -17,7 +17,7 @@ type Vendor struct{}
// @Description
// @Accept json
// @Produce json
// @Param Authorization header string true "auth by /auth"
// @Param token header string true "auth by /auth"
// @Param name query string false "名称" maxlength(100)
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
@ -30,7 +30,8 @@ func (vendor Vendor) List(c *gin.Context) {}
// @Description
// @Accept mpfd
// @Produce json
// @Param Authorization header string true "auth by /auth"
// @Param token header string true "auth by /auth"
// @Param data body service.CreateVendorRequest true "Vendor模型"
// @Success 200 {object} basic.Vendor "请求成功"
// @Router /v1/vendors [post]
func (vendor Vendor) Create(c *gin.Context) {}
@ -40,8 +41,9 @@ func (vendor Vendor) Create(c *gin.Context) {}
// @Description
// @Accept mpfd
// @Produce json
// @Param Authorization header string true "auth by /auth"
// @Param token header string true "auth by /auth"
// @Param id path int true "系统厂商 ID"
// @Param data body service.UpdateVendorRequest true "Vendor模型"
// @Success 200 {object} basic.Vendor "请求成功"
// @Router /v1/vendors/{id} [patch]
func (vendor Vendor) Update(c *gin.Context) {}
@ -51,7 +53,7 @@ func (vendor Vendor) Update(c *gin.Context) {}
// @Description
// @Accept json
// @Produce json
// @Param Authorization header string true "auth by /auth"
// @Param token header string true "auth by /auth"
// @Param id path int true "系统厂商 ID"
// @Success 200 {object} basic.Vendor "请求成功"
// @Router /v1/vendors/{id} [delete]

View File

@ -1,63 +1,48 @@
/*
* @Date: 2021-03-21 19:54:57
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 15:20:29
* @LastEditTime: 2021-06-10 21:49:20
* @FilePath: /potato/internal/middleware/jwt.go
*/
package middleware
import (
"net/http"
"strconv"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/viletyy/potato/global"
"github.com/viletyy/potato/pkg"
"github.com/viletyy/potato/pkg/app"
"github.com/viletyy/potato/pkg/errcode"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Request.Header.Get("Authorization")
var (
token string
ecode = errcode.Success
)
if s, exist := c.GetQuery("token"); exist {
token = s
} else {
token = c.GetHeader("token")
}
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "请求参数错误",
})
ecode = errcode.InvalidParams
} else {
_, err := app.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
ecode = errcode.UnauthorizedTokenTimeout
default:
ecode = errcode.UnauthorizedTokenError
}
}
}
if ecode != errcode.Success {
response := app.NewResponse(c)
response.ToErrorResponse(ecode)
c.Abort()
return
} else {
claims, err := pkg.ParseToken(token)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token验证失败",
})
c.Abort()
return
} else if time.Now().Unix() > claims.ExpiresAt {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token已超时",
})
c.Abort()
return
}
if claims != nil {
userId := claims.UserId
loginUUID := claims.StandardClaims.Id
val, _ := global.GO_REDIS.Get("login:" + loginUUID).Result()
if val != strconv.Itoa(int(userId)) {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token鉴权失败",
})
c.Abort()
return
}
} else {
c.JSON(http.StatusBadRequest, gin.H{
"error": "token鉴权失败",
})
c.Abort()
return
}
}
c.Next()

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-06-10 18:21:37
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 18:45:57
* @LastEditTime: 2021-06-10 21:59:51
* @FilePath: /potato/internal/model/auth.go
*/
package model
@ -16,7 +16,7 @@ type Auth struct {
func (a Auth) Get(db *gorm.DB) (Auth, error) {
var auth Auth
db = db.Where("app_key = ? AND app_secret = ? AND deleted_at = ?", a.AppKey, a.AppSecret, nil)
db = db.Where("app_key = ? AND app_secret = ?", a.AppKey, a.AppSecret)
err := db.First(&auth).Error
if err != nil && err != gorm.ErrRecordNotFound {
return auth, err

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-06-10 16:47:58
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 17:25:49
* @LastEditTime: 2021-06-10 22:28:15
* @FilePath: /potato/pkg/app/app.go
*/
package app
@ -32,6 +32,12 @@ func (r *Response) ToResponse(data interface{}) {
r.ToErrorResponse(err)
}
func (r *Response) ToResponseErrors(data interface{}) {
err := errcode.InvalidParams
err.WithData(data)
r.ToErrorResponse(err)
}
func (r *Response) ToResponseList(list interface{}, total int) {
err := errcode.Success
err.WithData(map[string]interface{}{

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-06-10 18:10:14
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 18:16:12
* @LastEditTime: 2021-06-10 22:04:50
* @FilePath: /potato/pkg/app/form.go
*/
package app
@ -38,7 +38,7 @@ func (v ValidErrors) Errors() (errs []string) {
func BindAndValid(c *gin.Context, v interface{}) (bool, ValidErrors) {
var errs ValidErrors
err := c.ShouldBind(v)
err := c.ShouldBindJSON(v)
if err != nil {
v := c.Value("trans")
trans, _ := v.(ut.Translator)

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-06-10 18:25:19
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 18:41:57
* @LastEditTime: 2021-06-10 22:23:51
* @FilePath: /potato/pkg/app/jwt.go
*/
package app
@ -26,7 +26,8 @@ func GetJWTSecret() []byte {
func GenerateToken(appKey, appSecret string) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(time.Duration(global.GO_CONFIG.App.JwtExpire))
expireTime := nowTime.Add(time.Duration(global.GO_CONFIG.App.JwtExpire) * time.Second)
claims := Claims{
AppKey: crypt.Md5Encode(appKey),
AppSecret: crypt.Md5Encode(appSecret),
@ -36,7 +37,7 @@ func GenerateToken(appKey, appSecret string) (string, error) {
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(GetJWTSecret())
return token, err
}

View File

@ -1,7 +1,7 @@
/*
* @Date: 2021-06-10 16:30:10
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 17:27:59
* @LastEditTime: 2021-06-10 21:43:05
* @FilePath: /potato/pkg/errcode/errcode.go
*/
package errcode

View File

@ -1,67 +0,0 @@
/*
* @Date: 2021-03-22 17:16:46
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 15:17:56
* @FilePath: /potato/pkg/jwt.go
*/
package pkg
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
"github.com/viletyy/potato/global"
)
type CustomClaims struct {
UserId int64
jwt.StandardClaims
}
func GenerateToken(userId int64) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(time.Minute * 30)
loginUUID := uuid.New().String()
claims := CustomClaims{
UserId: userId,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "data_govern",
Id: loginUUID,
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := tokenClaims.SignedString([]byte(global.GO_CONFIG.App.JwtSecret))
if err != nil {
global.GO_LOG.Error(fmt.Sprintf("General Token Error: %v", err))
}
global.GO_LOG.Info("General Token:" + tokenString)
result, err := global.GO_REDIS.Set("login:"+loginUUID, userId, 1*time.Hour).Result()
if err != nil {
global.GO_LOG.Error(fmt.Sprintf("General Token Set To Redis Error: %v", err))
}
global.GO_LOG.Info("Set Token To Redis:" + result)
return tokenString, err
}
func ParseToken(tokenString string) (*CustomClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(global.GO_CONFIG.App.JwtSecret), nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*CustomClaims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}

View File

@ -1,108 +0,0 @@
/*
* @Date: 2021-03-22 23:17:52
* @LastEditors: viletyy
* @LastEditTime: 2021-06-10 15:18:44
* @FilePath: /potato/pkg/validator.go
*/
package pkg
import (
"fmt"
"reflect"
"sync"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/locales/en"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
enTranslations "github.com/go-playground/validator/v10/translations/en"
zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)
type DefaultValidator struct {
once sync.Once
validate *validator.Validate
}
var _ binding.StructValidator = &DefaultValidator{}
// 定义一个全局翻译器T
var Trans ut.Translator
// InitTrans 初始化翻译器
func InitTrans(locale string) (err error) {
binding.Validator = new(DefaultValidator)
// 修改gin框架中的Validator引擎属性实现自定制
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
zhT := zh.New() // 中文翻译器
enT := en.New() // 英文翻译器
// 第一个参数是备用fallback的语言环境
// 后面的参数是应该支持的语言环境(支持多个)
// uni := ut.New(zhT, zhT) 也是可以的
uni := ut.New(enT, zhT, enT)
// locale 通常取决于 http 请求头的 'Accept-Language'
var ok bool
// 也可以使用 uni.FindTranslator(...) 传入多个locale进行查找
Trans, ok = uni.GetTranslator(locale)
if !ok {
return fmt.Errorf("uni.GetTranslator(%s) failed", locale)
}
// 注册翻译器
switch locale {
case "en":
err = enTranslations.RegisterDefaultTranslations(v, Trans)
case "zh":
err = zhTranslations.RegisterDefaultTranslations(v, Trans)
default:
err = enTranslations.RegisterDefaultTranslations(v, Trans)
}
return
}
return
}
// ValidateStruct 如果接收到的类型是一个结构体或指向结构体的指针,则执行验证。
func (v *DefaultValidator) ValidateStruct(obj interface{}) error {
if kindOfData(obj) == reflect.Struct {
v.lazyinit()
//如果传递不合规则的值则返回InvalidValidationError否则返回nil。
///如果返回err != nil可通过err.(validator.ValidationErrors)来访问错误数组。
if err := v.validate.Struct(obj); err != nil {
return err
}
}
return nil
}
// Engine 返回支持`StructValidator`实现的底层验证引擎
func (v *DefaultValidator) Engine() interface{} {
v.lazyinit()
return v.validate
}
func (v *DefaultValidator) lazyinit() {
v.once.Do(func() {
v.validate = validator.New()
v.validate.SetTagName("validate")
// //v8版本v8版本使用"binding"
// v.validate.SetTagName("binding")
})
}
func kindOfData(data interface{}) reflect.Kind {
value := reflect.ValueOf(data)
valueType := value.Kind()
if valueType == reflect.Ptr {
valueType = value.Elem().Kind()
}
return valueType
}