123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- // Copyright 2020 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package middleware
- import (
- "git.getensh.com/common/gopkgs/jwtwrapper"
- "github.com/dgrijalva/jwt-go"
- "github.com/gin-gonic/gin"
- "github.com/tidwall/gjson"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "net/http"
- "strings"
- "time"
- "xingjia-management-gateway/errors"
- )
- // 响应数据
- type Response struct {
- Code codes.Code `json:"code" default:"1"`
- Message string `json:"message" default:"success"`
- }
- // JWT is jwt middleware
- func Jwt() gin.HandlerFunc {
- return func(c *gin.Context) {
- s := status.New(1, "内部服务错误")
- token := c.GetHeader("token")
- if token == "" {
- if v, ok := status.FromError(errors.NoTokenError); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- // 解析token
- claims, err := jwtwrapper.ParseToken(token)
- if err != nil {
- switch err.(*jwt.ValidationError).Errors {
- case jwt.ValidationErrorExpired:
- if v, ok := status.FromError(errors.TokenExpiredError); ok {
- s = v
- }
- default:
- if v, ok := status.FromError(errors.TokenFailedError); ok {
- s = v
- }
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- // 将claims信息保存到上下文,为后续使用
- c.Set("claims", claims)
- /*
- supper := gjson.GetBytes(utils.StrToBytes(claims.Subject), "supper").Bool()
- if c.Request.Method == "PUT" || c.Request.Method == "POST" || c.Request.Method == "DELETE" {
- if supper == false && strings.Contains(c.Request.RequestURI, "/user") == false {
- c.JSON(http.StatusOK, Response{10008, "权限不足"})
- }
- }
- */
- userType := gjson.GetBytes([]byte(claims.Subject), "user_type").Int()
- userEnd := gjson.GetBytes([]byte(claims.Subject), "effective_end").Int()
- userStart := gjson.GetBytes([]byte(claims.Subject), "effective_start").Int()
- if userType != 1 && userType != 2 && userType != 3 {
- if v, ok := status.FromError(errors.UserWrong); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- if userType == 3 && (userEnd < time.Now().Unix() || userStart > time.Now().Unix()) {
- if v, ok := status.FromError(errors.UserNotEffective); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- if userType != 1 {
- // 非超级管理员不能账号管理和日志查看
- if !strings.Contains(c.Request.RequestURI, "/jt/") {
- if v, ok := status.FromError(errors.PermissionError); ok {
- s = v
- }
- c.JSON(http.StatusOK, Response{s.Code(), s.Message()})
- c.Abort()
- return
- }
- }
- // 进行下一次处理
- if gjson.GetBytes([]byte(claims.Subject), "tmp_token").Bool() {
- c.JSON(http.StatusOK, Response{10008, "无效凭据"})
- c.Abort()
- }
- c.Next()
- }
- }
|