47 lines
1.4 KiB
Go
47 lines
1.4 KiB
Go
package router
|
|
|
|
import (
|
|
"electricity_bill_calc/cache"
|
|
"electricity_bill_calc/model"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 用于解析Authorization头,并从缓存中获取用户会话信息注入上下文的中间件。
|
|
// 如果没有获取到用户会话信息,将直接跳过会话信息注入。
|
|
// ! 仅通过该中间件是不能保证上下文中一定保存有用户会话信息的。
|
|
func SessionRecovery(c *gin.Context) {
|
|
auth := c.Request.Header.Get("Authorization")
|
|
if len(auth) > 0 {
|
|
token := strings.Fields(auth)[1]
|
|
session, err := cache.RetreiveSession(token)
|
|
|
|
if err == nil {
|
|
c.Set("session", session)
|
|
}
|
|
}
|
|
c.Next()
|
|
}
|
|
|
|
// 用于对用户会话进行是否企业用户的判断
|
|
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
|
func EnterpriseAuthorize(c *gin.Context) {
|
|
session, exists := c.Get("session")
|
|
if !exists || session.(*model.Session).Type != 0 {
|
|
c.AbortWithStatus(http.StatusForbidden)
|
|
}
|
|
c.Next()
|
|
}
|
|
|
|
// 用于对用户会话进行是否监管用户或运维用户的判断
|
|
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
|
func ManagementAuthorize(c *gin.Context) {
|
|
session, exists := c.Get("session")
|
|
if !exists || (session.(*model.Session).Type != 1 && session.(*model.Session).Type != 2) {
|
|
c.AbortWithStatus(http.StatusForbidden)
|
|
}
|
|
c.Next()
|
|
}
|