-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
61 lines (59 loc) · 1.49 KB
/
auth.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
51
52
53
54
55
56
57
58
59
60
61
package middleware
import (
"encoding/base64"
"encoding/gob"
"encoding/json"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
sl "github.com/irellik/gblog/service/local"
"github.com/irellik/gblog/utils"
"net/http"
"strconv"
"time"
)
func AuthMiddleware(c *gin.Context) {
gob.Register(map[string]string{})
globalConfig := sl.GetConfig()
session := sessions.Default(c)
user_info := session.Get("user_info")
if user_info == nil {
user := make(map[string]string, 0)
// get cookie
cookieBase64Encode, err := c.Cookie("g_u")
if err != nil {
utils.Failed(c, http.StatusUnauthorized, err.Error(), nil)
return
}
// base64 decode
cookieBase64Decode, err := base64.StdEncoding.DecodeString(cookieBase64Encode)
if err != nil {
utils.Failed(c, http.StatusUnauthorized, err.Error(), nil)
return
}
// decrypt cookie
cookieByte, err := sl.Decrypt(cookieBase64Decode)
if err != nil {
utils.Failed(c, http.StatusUnauthorized, err.Error(), nil)
return
}
// json to map
err = json.Unmarshal(cookieByte, &user)
if err != nil {
utils.Failed(c, http.StatusUnauthorized, err.Error(), nil)
return
}
// if cookie is valid,set session
expired, _ := strconv.Atoi(user["expired"])
if int(time.Now().Unix()) < expired {
session.Set("user_info", user)
session.Options(sessions.Options{
MaxAge: globalConfig.Session.MaxAge,
})
session.Save()
} else {
utils.Failed(c, http.StatusUnauthorized, "unauthorized", nil)
return
}
}
c.Next()
}