add auth middleware

This commit is contained in:
殷勇 2023-10-27 10:33:26 +08:00
parent 292f6f87e7
commit 8357fbd28f
2 changed files with 26 additions and 14 deletions

View File

@ -1,27 +1,38 @@
package middleware
import (
"f5"
"github.com/gin-gonic/gin"
. "main/global"
"net/http"
"strings"
)
func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Request.Header.Get("Authorization")
strArr := strings.Split(token, "|")
authToken := GetApp().GetSessionAccountId(strArr[0])
if token == "" || token != authToken {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 1,
"message": "未登录或非法访问",
accountID := c.Query("account_id")
sessionID := c.Query("session_id")
if accountID == "" || sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"errcode": http.StatusBadRequest,
"errmsg": "Bad Request: Missing account_id or session_id",
})
/*
response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)*/
f5.GetSysLog().Info("logUnauthorizedAccess, clientIP:%s, requestURL:%s", c.ClientIP(), c.Request.URL.String())
c.Abort()
return
}
if !isValidSession(accountID, sessionID) {
c.JSON(http.StatusUnauthorized, gin.H{
"errcode": http.StatusUnauthorized,
"errmsg": "Unauthorized",
})
c.Abort()
return
}
c.Next()
}
}
func isValidSession(accountID, sessionID string) bool {
return true
}

View File

@ -3,6 +3,7 @@ package router
import (
"f5"
"github.com/gin-gonic/gin"
"main/middleware"
)
type routerMgr struct {
@ -13,9 +14,9 @@ func (rm *routerMgr) Init() {
router := f5.GetApp().GetGinEngine()
router.Use(gin.Logger())
pubRouterGroup := router.Group("api")
rm.mail.InitMailRouter(pubRouterGroup)
authRouterGroup := router.Group("api")
authRouterGroup.Use(middleware.Auth())
rm.mail.InitMailRouter(authRouterGroup)
f5.GetSysLog().Info("routerMgr.init")
}