reface to openteam
This commit is contained in:
53
internal/controller/team/middleware.go
Normal file
53
internal/controller/team/middleware.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"opencatd-open/internal/consts"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (h *Team) AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.URL.Path == "/1/users/init" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
authtoken := c.GetHeader("Authorization")
|
||||
if authtoken == "" || len(authtoken) <= 7 || authtoken[:7] != "Bearer " {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
authtoken = authtoken[7:]
|
||||
token, err := h.tokenService.GetByKey(c, authtoken)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
if token.Name != "default" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "only default token can access"})
|
||||
c.Abort()
|
||||
}
|
||||
if token.User.Status != consts.StatusEnabled {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "user is disabled"})
|
||||
c.Abort()
|
||||
}
|
||||
c.Set("local_user", true)
|
||||
c.Set("token", token)
|
||||
|
||||
// 可以在这里对 token 进行验证并检查权限
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func CORS() gin.HandlerFunc {
|
||||
config := cors.DefaultConfig()
|
||||
config.AllowAllOrigins = true
|
||||
config.AllowCredentials = true
|
||||
config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
|
||||
config.AllowHeaders = []string{"*"}
|
||||
return cors.New(config)
|
||||
}
|
||||
Reference in New Issue
Block a user