base.go
2.6 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package mygin
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"time"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
)
type BaseController struct {
}
func(this *BaseController)JWTMiddleware()gin.HandlerFunc{
return func(c *gin.Context){
token := c.GetHeader("token")
code := http.StatusOK
if token == "" {
code = http.StatusUnauthorized
} else {
claims, err := common.ParseJWTToken(token)
if err != nil {
code = http.StatusUnauthorized
} else if time.Now().Unix() > claims.ExpiresAt {
code = http.StatusUnauthorized
}
}
if code != http.StatusOK {
this.Resp(c,NewMessage(1).SetHttpCode(code))
return
}
c.Next()
}
}
//group.Use(Prepare)
func(this *BaseController)Prepare(c *gin.Context){
this.Secure(c)
this.NoCache(c)
}
// NoCache is a middleware function that appends headers
// to prevent the client from caching the HTTP response.
func (this *BaseController)NoCache(c *gin.Context) {
c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
c.Next()
}
// Secure is a middleware function that appends security
// and resource access headers.
func (this *BaseController)Secure(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("X-Frame-Options", "DENY")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("X-XSS-Protection", "1; mode=block")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
c.Header("Access-Control-Allow-Headers", "uid, token,jwt, deviceid, appid,Content-Type,Authorization,from")
if c.Request.TLS != nil {
c.Header("Strict-Transport-Security", "max-age=31536000")
}
// Also consider adding Content-Security-Policy headers
// c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
}
func(this *BaseController)GetRequestHead(c *gin.Context)*RequestHead{
requestHead := &RequestHead{}
requestHead.Token = c.Query("token")
requestHead.Version = c.Query("version")
requestHead.Os = c.Query("os")
requestHead.From = c.Query("from")
requestHead.Screen = c.Query("screen")
requestHead.Model = c.Query("model")
requestHead.Channel = c.Query("channel")
requestHead.Net = c.Query("net")
requestHead.DeviceId = c.Query("deviceid")
requestHead.Uid, _ = strconv.ParseInt(c.Query("uid"), 10, 64)
requestHead.AppId, _ = strconv.Atoi(c.Query("appid"))
requestHead.LoginIp = c.ClientIP()
requestHead.Jwt = c.Query("jwt")
return requestHead
}
func(this *BaseController)Resp(c *gin.Context,rsp *Message){
c.JSON(rsp.HttpCode,rsp)
c.Abort()
}