sun-pc-linux 4 months ago
parent
commit
5e6d6aad9d
6 changed files with 86 additions and 175 deletions
  1. 21 46
      src/api/api.go
  2. 1 1
      src/api/callback.go
  3. 4 125
      src/api/controller.go
  4. 1 1
      src/api/utils.go
  5. 2 2
      src/build.sh
  6. 57 0
      src/middleware/auth.go

+ 21 - 46
src/api/api.go

@@ -4,26 +4,26 @@ import (
 	"cmf/conf"
 	"cmf/db"
 	"cmf/db/repo"
+	"cmf/middleware"
 	"context"
 	"fmt"
 
+	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
 	"github.com/gin-contrib/cors"
-	"github.com/gin-contrib/sessions"
-	"github.com/gin-contrib/sessions/cookie"
 	"github.com/gin-gonic/gin"
 	"github.com/go-redis/redis/v8"
 )
 
 type Service struct {
-	Gin            *gin.Engine
-	Mongo          *db.MongoDB
-	Redis          *redis.Client
-	Port           int32
-	DebugUserId    string
-	DebugUserPhone string
-	DebugUserRole  string
-	JWT            *UtilsJwt
-	Conf           *conf.AppConf
+	Gin   *gin.Engine
+	Mongo *db.MongoDB
+	Redis *redis.Client
+	Port  int32
+	// DebugUserId    string
+	// DebugUserPhone string
+	// DebugUserRole  string
+	// JWT            *UtilsJwt
+	Conf *conf.AppConf
 }
 
 func (svc *Service) Run() {
@@ -31,8 +31,9 @@ func (svc *Service) Run() {
 }
 
 type ApiSession struct {
-	Svc  *Service
-	User *JWTUser
+	Svc *Service
+	// User *JWTUser
+	User *casdoorsdk.User
 }
 
 func (api *ApiSession) CreateRepoCtx() *repo.RepoSession {
@@ -46,18 +47,16 @@ func NewHttpService(app *conf.AppConf, dbMongo *db.MongoDB) *Service {
 
 	engine := gin.Default()
 
-	store := cookie.NewStore([]byte("spu3d-server"))
-	engine.Use(sessions.Sessions("dcsession", store))
-	engine.Static("/public", "static")
+	// store := cookie.NewStore([]byte("spu3d-server"))
+	// engine.Use(sessions.Sessions("dcsession", store))
+	// engine.Static("/public", "static")
 	config := cors.DefaultConfig()
 	// config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}
 	config.AllowAllOrigins = true
 	config.AllowHeaders = append(config.AllowHeaders, "authorization")
 	engine.Use(cors.New(config))
 
-	jwt := NewUitlsJwt(app)
-
-	s := &Service{Conf: app, JWT: jwt, Gin: engine, Mongo: dbMongo, Port: app.Port, DebugUserId: app.Debug.UserId, DebugUserPhone: app.Debug.UserPhone, DebugUserRole: app.Debug.UserRole}
+	s := &Service{Conf: app, Gin: engine, Mongo: dbMongo, Port: app.Port}
 
 	RegRouters(s)
 
@@ -92,39 +91,15 @@ func (g GinRouter) POST(path string, httpHandler Handler) {
 
 // GETJWT http Get 请求
 func (g GinRouter) GETJWT(path string, httpHandler JWTHander) {
-	g.group.GET(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
-}
-
-// GETJWTTest http Get 请求
-func (g GinRouter) GETJWTTest(path string, httpHandler JWTHander) {
-	g.group.GET(path, ResultJWTTestWrapper(httpHandler, g.svc))
+	g.group.GET(path, middleware.CasdoorAuthMiddleware(), ResultJWTWrapper(httpHandler, g.svc))
 }
 
 // POSTJWT http POST 请求
 func (g GinRouter) POSTJWT(path string, httpHandler JWTHander) {
-	g.group.POST(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
+	g.group.POST(path, middleware.CasdoorAuthMiddleware(), ResultJWTWrapper(httpHandler, g.svc))
 }
 
 // DeleteJWT http POST 请求
 func (g GinRouter) DeleteJWT(path string, httpHandler JWTHander) {
-	g.group.DELETE(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapper(httpHandler, g.svc))
-}
-
-// DeleteJWT http POST 请求
-func (g GinRouter) DeleteJWTTEST(path string, httpHandler JWTHander) {
-	g.group.DELETE(path, ResultJWTTestWrapper(httpHandler, g.svc))
-}
-
-// POSTJWTTest 测试
-func (g GinRouter) POSTJWTTest(path string, httpHandler JWTHander) {
-	g.group.POST(path, ResultJWTTestWrapper(httpHandler, g.svc))
-}
-
-// 代参数判断权限
-func (g GinRouter) GETJWTKEY(path string, httpHandler JWTHander, keys ...string) {
-	g.group.GET(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapperKey(httpHandler, g.svc, keys))
-}
-
-func (g GinRouter) POSTJWTKEY(path string, httpHandler JWTHander, keys ...string) {
-	g.group.POST(path, g.svc.JWT.MiddleFunc(), ResultJWTWrapperKey(httpHandler, g.svc, keys))
+	g.group.DELETE(path, middleware.CasdoorAuthMiddleware(), ResultJWTWrapper(httpHandler, g.svc))
 }

+ 1 - 1
src/api/callback.go

@@ -32,5 +32,5 @@ func callback(c *gin.Context, apictx *ApiSession) (interface{}, error) {
 	c.Redirect(http.StatusFound, "https://auth.3dqueen.cloud")
 
 	// claims.AccessToken = token.AccessToken
-	return nil, nil
+	return token.AccessToken, nil
 }

+ 4 - 125
src/api/controller.go

@@ -11,7 +11,7 @@ import (
 	"strconv"
 	"strings"
 
-	jwt "github.com/appleboy/gin-jwt/v2"
+	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
 	"github.com/gin-gonic/gin"
 )
 
@@ -75,135 +75,14 @@ func ResultJWTWrapper(handle JWTHander, svc *Service) gin.HandlerFunc {
 			}
 		}()
 
-		claims := jwt.ExtractClaims(c)
+		claims, _ := c.Get("casdoor_user")
 
-		var usr *JWTUser
+		user := claims.(*casdoorsdk.User)
 
-		if claims["id"] != nil {
-			fmt.Printf("%#v\n", claims)
-			id := claims["id"].(string)
-			name := claims["name"].(string)
-			phone := claims["phone"].(string)
-			parent := claims["parent"].(string)
-			state := int32(claims["state"].(float64))
-
-			usr = &JWTUser{ID: id, Phone: phone, Name: name, Parent: parent, State: state}
-		}
 		var apis = &ApiSession{
 			Svc:  svc,
-			User: usr,
-		}
-		data, err := handle(c, apis)
-
-		if err != nil {
-			fmt.Println(err)
-			httpErr, ok := err.(HTTPError)
-			if ok {
-				c.JSON(http.StatusOK, NewFailResultWithCode(httpErr.Error(), httpErr.Code))
-				return
-			}
-
-			c.JSON(http.StatusOK, NewFailResult(err.Error()))
-			return
+			User: user,
 		}
-		if data != nil {
-			c.JSON(http.StatusOK, NewOkResult(data))
-		}
-	}
-}
-
-// ResultJWTTestWrapper test 默认一个测试用户 JWT授权处理handler
-func ResultJWTTestWrapper(handle JWTHander, svc *Service) gin.HandlerFunc {
-
-	return func(c *gin.Context) {
-
-		defer func() {
-			if r := recover(); r != nil {
-
-				fmt.Println("recover success.")
-				fmt.Println(r)
-
-				buf := make([]byte, 1<<16)
-				runtime.Stack(buf, true)
-				fmt.Println("buf", string(buf))
-
-				c.JSON(http.StatusOK, NewFailResultWithData("error", r))
-			}
-		}()
-
-		var usr *JWTUser = &JWTUser{ID: svc.DebugUserId, Phone: svc.DebugUserPhone, Parent: svc.DebugUserId, Role: svc.DebugUserRole}
-
-		data, err := handle(c, &ApiSession{Svc: svc, User: usr})
-
-		if err != nil {
-			fmt.Println(err)
-			httpErr, ok := err.(HTTPError)
-			if ok {
-				c.JSON(http.StatusOK, NewFailResultWithCode(httpErr.Error(), httpErr.Code))
-				return
-			}
-
-			c.JSON(http.StatusOK, NewFailResult(err.Error()))
-			return
-		}
-		c.JSON(http.StatusOK, NewOkResult(data))
-	}
-}
-
-// ResultJWTWrapper JWT授权处理handler
-func ResultJWTWrapperKey(handle JWTHander, svc *Service, keys []string) gin.HandlerFunc {
-
-	return func(c *gin.Context) {
-
-		defer func() {
-			if r := recover(); r != nil {
-				fmt.Println("recover success.")
-				fmt.Println(r)
-
-				buf := make([]byte, 1<<16)
-				runtime.Stack(buf, true)
-				fmt.Println("buf", string(buf))
-
-				c.JSON(http.StatusOK, NewFailResultWithData("系统异常", r))
-			}
-		}()
-
-		claims := jwt.ExtractClaims(c)
-
-		var usr *JWTUser
-
-		if claims["id"] != nil {
-			id := claims["id"].(string)
-			phone := claims["phone"].(string)
-			name := claims["name"].(string)
-			parent := claims["parent"].(string)
-			state := int32(claims["state"].(float64))
-			key := ""
-			if claims["key"] != nil {
-				key = claims["key"].(string)
-			}
-
-			usr = &JWTUser{ID: id, Name: name, Phone: phone, Parent: parent, State: state, Key: key}
-		}
-
-		var apis = &ApiSession{
-			Svc:  svc,
-			User: usr,
-		}
-
-		flag := false
-		for _, key := range keys {
-			if usr.Key == key {
-				flag = true
-				break
-			}
-		}
-		if !flag {
-			c.JSON(http.StatusForbidden, NewFailResult("您没有权限"))
-			c.Abort()
-			return
-		}
-
 		data, err := handle(c, apis)
 
 		if err != nil {

+ 1 - 1
src/api/utils.go

@@ -15,7 +15,7 @@ import (
 // 这里需要nats获取通用用户信息,因为spu3d中功能聚合了lancher的功能
 func getUserRole(_ *gin.Context, apictx *ApiSession) ([]string, error) {
 	if apictx.User != nil {
-		userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
+		userId, _ := primitive.ObjectIDFromHex(apictx.User.Id)
 		var searchUser model.UserSmaple
 		ok, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
 			Db:          "usercenter",

+ 2 - 2
src/build.sh

@@ -5,8 +5,8 @@ echo "building..."
 go build -o cmf
 
 # 命名镜像
-local_imge="pack-cmf:v1.0.0"
-repository_image="registry.cn-chengdu.aliyuncs.com/infish/pack-cmf:v1.0.0"
+local_imge="pack-cmf:v1.0.1"
+repository_image="registry.cn-chengdu.aliyuncs.com/infish/pack-cmf:v1.0.1"
 
 # 删除本地已存在的镜像
 docker rmi $repository_image

+ 57 - 0
src/middleware/auth.go

@@ -0,0 +1,57 @@
+package middleware
+
+import (
+	"cmf/conf"
+	"net/http"
+	"os"
+	"strings"
+
+	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
+	"github.com/gin-gonic/gin"
+)
+
+// Casdoor 中间件,用于验证请求中的 token
+func CasdoorAuthMiddleware() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		// 从请求头中获取 Authorization token
+		authHeader := c.GetHeader("Authorization")
+		if authHeader == "" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is missing"})
+			return
+		}
+
+		// 提取 token,格式一般为 "Bearer <token>"
+		parts := strings.SplitN(authHeader, " ", 2)
+		if len(parts) != 2 || parts[0] != "Bearer" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization header format"})
+			return
+		}
+
+		token := parts[1]
+		if token == "" {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is missing"})
+			return
+		}
+
+		authConf := conf.AppConfig.Auth
+		pemByte, err := os.ReadFile(authConf.Certificate)
+		if err != nil {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "config error"})
+			return
+		}
+		casdoorsdk.InitConfig(authConf.Endpoint, authConf.ClientId, authConf.ClientSecret, string(pemByte), authConf.OrganizationName, authConf.ApplicationName)
+
+		// 验证 token
+		user, err := casdoorsdk.ParseJwtToken(token)
+		if err != nil {
+			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token: " + err.Error()})
+			return
+		}
+
+		// 将用户信息存储在上下文中,以便后续使用
+		c.Set("casdoor_user", user)
+
+		// 继续处理请求
+		c.Next()
+	}
+}