gin-vue-admin 2.0代码重构

This commit is contained in:
QM303176530
2020-04-04 21:39:07 +08:00
parent 5ed41ddd8c
commit 1b9adea284
202 changed files with 1240 additions and 1299 deletions
+30
View File
@@ -0,0 +1,30 @@
package middleware
import (
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"github.com/gin-gonic/gin"
)
//拦截器
func CasbinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
claims, _ := c.Get("claims")
waitUse := claims.(*CustomClaims)
//获取请求的URI
obj := c.Request.URL.RequestURI()
//获取请求方法
act := c.Request.Method
//获取用户的角色
sub := waitUse.AuthorityId
e := model.Casbin()
//判断策略中是否存在
if e.Enforce(sub, obj, act) {
c.Next()
} else {
response.Result(response.ERROR, gin.H{}, "权限不足", c)
c.Abort()
return
}
}
}
+25
View File
@@ -0,0 +1,25 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}
+137
View File
@@ -0,0 +1,137 @@
package middleware
import (
"errors"
"gin-vue-admin/global"
"gin-vue-admin/global/response"
"gin-vue-admin/model"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"time"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localSstorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
token := c.Request.Header.Get("x-token")
ModelToken := model.JwtBlacklist{
Jwt: token,
}
if token == "" {
response.Result(response.ERROR, gin.H{
"reload": true,
}, "未登录或非法访问", c)
c.Abort()
return
}
if ModelToken.IsBlacklist(token) {
response.Result(response.ERROR, gin.H{
"reload": true,
}, "您的帐户异地登陆或令牌失效", c)
c.Abort()
return
}
j := NewJWT()
// parseToken 解析token包含的信息
claims, err := j.ParseToken(token)
if err != nil {
if err == TokenExpired {
response.Result(response.ERROR, gin.H{
"reload": true,
}, "授权已过期", c)
c.Abort()
return
}
response.Result(response.ERROR, gin.H{
"reload": true,
}, err.Error(), c)
c.Abort()
return
}
c.Set("claims", claims)
c.Next()
}
}
type JWT struct {
SigningKey []byte
}
var (
TokenExpired error = errors.New("Token is expired")
TokenNotValidYet error = errors.New("Token not active yet")
TokenMalformed error = errors.New("That's not even a token")
TokenInvalid error = errors.New("Couldn't handle this token:")
)
type CustomClaims struct {
UUID uuid.UUID
ID uint
NickName string
AuthorityId string
jwt.StandardClaims
}
func NewJWT() *JWT {
return &JWT{
[]byte(global.GVA_CONFIG.JWT.SigningKey),
}
}
//创建一个token
func (j *JWT) CreateToken(claims CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
//解析 token
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
} else {
return nil, TokenInvalid
}
}
// 更新token
func (j *JWT) RefreshToken(tokenString string) (string, error) {
jwt.TimeFunc = func() time.Time {
return time.Unix(0, 0)
}
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return j.SigningKey, nil
})
if err != nil {
return "", err
}
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
jwt.TimeFunc = time.Now
claims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()
return j.CreateToken(*claims)
}
return "", TokenInvalid
}
+26
View File
@@ -0,0 +1,26 @@
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
// 用https把这个中间件在router里面use一下就好
func LoadTls() gin.HandlerFunc {
return func(c *gin.Context) {
middleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: "localhost:443",
})
err := middleware.Process(c.Writer, c.Request)
if err != nil {
//如果出现错误,请不要继续。
fmt.Println(err)
return
}
// 继续往下处理
c.Next()
}
}
+64
View File
@@ -0,0 +1,64 @@
package middleware
import (
"bytes"
"gin-vue-admin/init"
"net/http/httputil"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
// request time
start := time.Now()
// request path
path := c.Request.URL.Path
logFlag := true
if strings.Contains(path, "swagger") {
logFlag = false
}
// request ip
clientIP := c.ClientIP()
// method
method := c.Request.Method
// copy request content
req, _ := httputil.DumpRequest(c.Request, true)
if logFlag {
init.L.Debug(
"Request:", method, clientIP, path, string(req))
}
// replace writer
cusWriter := &responseBodyWriter{
ResponseWriter: c.Writer,
body: bytes.NewBufferString(""),
}
c.Writer = cusWriter
// handle request
c.Next()
// ending time
end := time.Now()
//execute time
latency := end.Sub(start)
statusCode := c.Writer.Status()
if logFlag {
init.L.Debug(
"Response:",
statusCode,
latency,
cusWriter.body.String())
}
}
}
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w responseBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}