92 lines
2.9 KiB
Go
92 lines
2.9 KiB
Go
package security
|
||
|
||
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 && session != nil {
|
||
c.Set("session", session)
|
||
}
|
||
}
|
||
c.Next()
|
||
}
|
||
|
||
// 用于强制确定用户已经登录了系统,即具有有效的用户会话
|
||
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
||
func MustAuthenticated(c *gin.Context) {
|
||
session, exists := c.Get("session")
|
||
if !exists || session == nil {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
if _, ok := session.(*model.Session); !ok {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
c.Next()
|
||
}
|
||
|
||
// 用于对用户会话进行是否企业用户的判断
|
||
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
||
func EnterpriseAuthorize(c *gin.Context) {
|
||
session, exists := c.Get("session")
|
||
if !exists || session == nil {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
if sess, ok := session.(*model.Session); !ok || sess.Type != model.USER_TYPE_ENT {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
c.Next()
|
||
}
|
||
|
||
// 用于对用户会话进行是否监管用户或运维用户的判断
|
||
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
||
func ManagementAuthorize(c *gin.Context) {
|
||
session, exists := c.Get("session")
|
||
if !exists || session == nil {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
if sess, ok := session.(*model.Session); !ok || (sess.Type != model.USER_TYPE_SUP && sess.Type != model.USER_TYPE_OPS) {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
c.Next()
|
||
}
|
||
|
||
// 用于对用户会话进行是否运维用户的判断
|
||
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
||
func OPSAuthorize(c *gin.Context) {
|
||
session, exists := c.Get("session")
|
||
if !exists {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
if sess, ok := session.(*model.Session); !ok || sess.Type != model.USER_TYPE_OPS {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
c.Next()
|
||
}
|
||
|
||
// 用于对用户会话进行是否核心运维用户的判断
|
||
// ! 通过该中间件以后,是可以保证上下文中一定具有用户会话信息的。
|
||
func SingularityAuthorize(c *gin.Context) {
|
||
session, exists := c.Get("session")
|
||
if !exists {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
if sess, ok := session.(*model.Session); !ok || sess.Type != model.USER_TYPE_OPS || sess.Uid != "000" {
|
||
c.AbortWithStatus(http.StatusForbidden)
|
||
}
|
||
c.Next()
|
||
}
|