99 lines
2.2 KiB
Go
99 lines
2.2 KiB
Go
package router
|
||
|
||
import (
|
||
"SciencesServer/app/logic"
|
||
"SciencesServer/app/service"
|
||
"SciencesServer/app/session"
|
||
"SciencesServer/config"
|
||
"SciencesServer/utils"
|
||
"fmt"
|
||
"github.com/gin-gonic/gin"
|
||
"net/http"
|
||
)
|
||
|
||
// SkipperURL 跳过验证
|
||
type SkipperURL func(*gin.Context) bool
|
||
|
||
// PermissionHandle 权限验证
|
||
type PermissionHandle func(key string) gin.HandlerFunc
|
||
|
||
// AddSkipperURL 添加路由
|
||
func AddSkipperURL(url ...string) SkipperURL {
|
||
return func(c *gin.Context) bool {
|
||
path := c.Request.URL.Path
|
||
return utils.InArray(path, url)
|
||
}
|
||
}
|
||
|
||
// NeedLogin 需要登录
|
||
func NeedLogin(key string, session logic.ISession, skipperURL ...SkipperURL) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
if len(skipperURL) > 0 && skipperURL[0](c) {
|
||
c.Next()
|
||
return
|
||
}
|
||
token := c.GetHeader(config.APIRequestToken)
|
||
|
||
if token == "" {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"message": "Token异常"})
|
||
c.Abort()
|
||
return
|
||
}
|
||
err := service.NewAuthToken(token).Auth(key, session)
|
||
|
||
if err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{"message": err.Error()})
|
||
c.Abort()
|
||
return
|
||
}
|
||
c.Set(config.TokenForSession, session)
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// NeedPermission 需要权限验证
|
||
func NeedPermission(skipperURL ...SkipperURL) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
if len(skipperURL) > 0 && skipperURL[0](c) {
|
||
c.Next()
|
||
return
|
||
}
|
||
value, _ := c.Get(config.TokenForSession)
|
||
_session := value.(*session.Admin)
|
||
|
||
if _session.IsAdmin || _session.IsSystemAdmin {
|
||
c.Next()
|
||
return
|
||
}
|
||
pass, err := service.NewPermission(
|
||
service.WithAuthTenant(_session.TenantIDFormat()),
|
||
service.WithAuthUser(_session.GetStringUID()),
|
||
service.WithAuthRequest([]*service.AuthRequest{
|
||
&service.AuthRequest{
|
||
Url: c.Request.URL.Path,
|
||
Method: c.Request.Method,
|
||
},
|
||
}),
|
||
).Enforce()
|
||
|
||
if err != nil {
|
||
c.JSON(http.StatusUnauthorized, gin.H{
|
||
"message": fmt.Sprintf("权限验证错误【%v】,请联系管理员!", err),
|
||
})
|
||
c.Abort()
|
||
return
|
||
} else if !pass {
|
||
c.JSON(http.StatusForbidden, gin.H{"message": "无权限访问!"})
|
||
c.Abort()
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
func NeedAuthIdentity() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
c.Next()
|
||
}
|
||
}
|