93 lines
2.1 KiB
Go
93 lines
2.1 KiB
Go
package casdoor_middleware
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"autolibrary.top/webserver/config"
|
|
|
|
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func CasdoorAuth() gin.HandlerFunc {
|
|
cfg := config.GetConfig()
|
|
|
|
return func(c *gin.Context) {
|
|
// If Casdoor is not configured, return 501 Not Implemented
|
|
if cfg.Backend.Casdoor.Endpoint == "" || cfg.Backend.Casdoor.ClientID == "" {
|
|
c.JSON(http.StatusNotImplemented, gin.H{
|
|
"code": http.StatusNotImplemented,
|
|
"msg": "AUTH > Casdoor authentication is not configured on this server",
|
|
"data": nil,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"msg": "AUTH > missing Authorization header",
|
|
"data": nil,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
token := strings.TrimPrefix(authHeader, "Bearer ")
|
|
if token == authHeader {
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"msg": "AUTH > Authorization header must be Bearer <token>",
|
|
"data": nil,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
claims, err := casdoorsdk.ParseJwtToken(token)
|
|
if err != nil {
|
|
log.Printf("[W] AUTH > invalid JWT token: %v", err)
|
|
c.JSON(http.StatusUnauthorized, gin.H{
|
|
"code": http.StatusUnauthorized,
|
|
"msg": "AUTH > invalid or expired token",
|
|
"data": nil,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("user_id", claims.User.Id)
|
|
c.Set("user_name", claims.User.Name)
|
|
c.Set("display_name", claims.User.DisplayName)
|
|
c.Set("is_admin", claims.User.IsAdmin)
|
|
c.Set("user_tag", claims.User.Tag)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// CasdoorAdminAuth requires both valid Casdoor JWT and admin privileges
|
|
func CasdoorAdminAuth() gin.HandlerFunc {
|
|
auth := CasdoorAuth()
|
|
return func(c *gin.Context) {
|
|
auth(c)
|
|
if c.IsAborted() {
|
|
return
|
|
}
|
|
isAdmin, _ := c.Get("is_admin")
|
|
if isAdmin == nil || !isAdmin.(bool) {
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"code": http.StatusForbidden,
|
|
"msg": "AUTH > admin privileges required",
|
|
"data": nil,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|