forked from free-lancers/electricity_bill_calc_service
feat(route):加入安全相关中间件,绑定用户登录路由。
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"electricity_bill_calc/controller"
|
||||
"electricity_bill_calc/response"
|
||||
"log"
|
||||
"runtime/debug"
|
||||
@@ -11,6 +12,9 @@ import (
|
||||
func Router() *gin.Engine {
|
||||
router := gin.Default()
|
||||
router.Use(Recover)
|
||||
router.Use(SessionRecovery)
|
||||
|
||||
controller.InitializeUserController(router)
|
||||
|
||||
return router
|
||||
}
|
||||
|
@@ -2,22 +2,45 @@ package router
|
||||
|
||||
import (
|
||||
"electricity_bill_calc/cache"
|
||||
"electricity_bill_calc/model"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AuthenticatedSession(c *gin.Context) {
|
||||
// 用于解析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.AbortWithStatus(http.StatusForbidden)
|
||||
if err == nil {
|
||||
c.Set("session", session)
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
Reference in New Issue
Block a user