EasyGoAdmin_Gin_EleVue-2

思考并回答以下问题:

middleware

app/middleware/checklogin.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 登录验证中间件
* @File : checkauth
*/
package middleware

import (
"easygoadmin/utils"
"easygoadmin/utils/common"
"easygoadmin/utils/gstr"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)

func CheckLogin() gin.HandlerFunc {
return func(ctx *gin.Context) {
fmt.Println("登录验证中间件")
// 放行设置
urlItem := []string{"/captcha", "/login"}
if !utils.InStringArray(ctx.Request.RequestURI, urlItem) {
// 从请求头中获取Token
token := ctx.GetHeader("Authorization")
// 字符串替换
token = gstr.Replace(token, "Bearer ", "")
claim, err := utils.ParseToken(token)
if err != nil {
fmt.Println("解析token出现错误:", err)
ctx.JSON(http.StatusOK, common.JsonResult{
Code: 401,
Msg: "Token已过期",
})
ctx.Abort()
return
} else if time.Now().Unix() > claim.ExpiresAt {
fmt.Println("时间超时")
ctx.JSON(http.StatusOK, common.JsonResult{
Code: 401,
Msg: "时间超时",
})
ctx.Abort()
return
}
}
// 前置中间件
ctx.Next()
}
}

app/middleware/cros.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 跨域处理中间件
* @File : cros
*/
package middleware

import (
"github.com/gin-gonic/gin"
"net/http"
)

// 处理跨域请求,支持options访问
func Cros() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
if len(origin) == 0 {
c.Next()
return
}

// 同源直接过
host := c.GetHeader("Host")
if origin == "http://"+host || origin == "https://"+host {
c.Next()
return
}

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, PUT, PATCH, DELETE")
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 过
method := c.Request.Method
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
c.Abort()
}
c.Next()
}
}
0%