sun-pc-linux 4 months ago
parent
commit
3de2c293ed

+ 2 - 2
pack-cmf/config-service.yaml

@@ -6,9 +6,9 @@ log:
 configer:
   -
     name: cmf-mongo
-    value: mongodb://root:cmf@cmf-mongo:27017/cmf?authSource=admin
+    value: mongodb://root:cmfxxx@cmf-mongo:27017/cmf?authSource=admin
     # devValue: mongodb://root:cmf@192.168.110.180:37037/website?authSource=admin
-    # devValue: mongodb://root:cmf@124.71.139.24:37037/website?authSource=admin
+    devValue: mongodb://root:cmfxxx@192.168.110.131:17019/cmf?authSource=admin
 
 
 

+ 2 - 2
pack-cmf/docker-compose.yaml

@@ -48,7 +48,7 @@ services:
     restart: always
     environment:
       MONGO_INITDB_ROOT_USERNAME: root
-      MONGO_INITDB_ROOT_PASSWORD: cmf
+      MONGO_INITDB_ROOT_PASSWORD: cmfxxx
     volumes:
       - ~/data/packs-cmf/mongo/db:/data/db
       - ~/data/packs-cmf/mongo/log:/var/log/mongodb
@@ -79,7 +79,7 @@ services:
   #     CONFIGER_REDIS: cmf-redis
 
   cmf-srv:
-    image: registry.cn-chengdu.aliyuncs.com/infish/pack-cmf:v1.0.0
+    image: registry.cn-chengdu.aliyuncs.com/infish/pack-cmf:v1.0.1
     restart: always
     depends_on:
       - cmf-bus

+ 9 - 1
src/api/api.go

@@ -7,6 +7,7 @@ import (
 	"cmf/middleware"
 	"context"
 	"fmt"
+	"os"
 
 	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
 	"github.com/gin-contrib/cors"
@@ -33,7 +34,7 @@ func (svc *Service) Run() {
 type ApiSession struct {
 	Svc *Service
 	// User *JWTUser
-	User *casdoorsdk.User
+	User *casdoorsdk.Claims
 }
 
 func (api *ApiSession) CreateRepoCtx() *repo.RepoSession {
@@ -45,6 +46,13 @@ func (api *ApiSession) CreateRepoCtx() *repo.RepoSession {
 
 func NewHttpService(app *conf.AppConf, dbMongo *db.MongoDB) *Service {
 
+	authConf := app.Auth
+	pemByte, err := os.ReadFile(authConf.Certificate)
+	if err != nil {
+		panic(err)
+	}
+	casdoorsdk.InitConfig(authConf.Endpoint, authConf.ClientId, authConf.ClientSecret, string(pemByte), authConf.OrganizationName, authConf.ApplicationName)
+
 	engine := gin.Default()
 
 	// store := cookie.NewStore([]byte("spu3d-server"))

File diff suppressed because it is too large
+ 5 - 0
src/api/api.http


+ 4 - 10
src/api/callback.go

@@ -2,21 +2,15 @@ package api
 
 import (
 	"fmt"
-	"os"
 
 	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
 	"github.com/gin-gonic/gin"
 )
 
-// https://auth.3dqueen.cloud/login/oauth/authorize?client_id=d372dce9cd00805db7e0&redirect_uri=https://www.3dqueen.cloud/box/v1/boxcost/callback&response_type=code&scope=openid&state=STATE
+// https://auth.3dqueen.cloud/login/oauth/authorize?client_id=d372dce9cd00805db7e0&redirect_uri=http://localhost:9999/cmf/login/callback&response_type=code&scope=openid&state=STATE
 // 需要在第三方提供商配置回调 https://auth.3dqueen.cloud/callback
 func callback(c *gin.Context, apictx *ApiSession) (interface{}, error) {
-	authConf := apictx.Svc.Conf.Auth
-	pemByte, err := os.ReadFile(authConf.Certificate)
-	if err != nil {
-		return nil, err
-	}
-	casdoorsdk.InitConfig(authConf.Endpoint, authConf.ClientId, authConf.ClientSecret, string(pemByte), authConf.OrganizationName, authConf.ApplicationName)
+
 	token, err := casdoorsdk.GetOAuthToken(c.Query("code"), c.Query("state"))
 	if err != nil {
 		fmt.Println(err)
@@ -30,6 +24,6 @@ func callback(c *gin.Context, apictx *ApiSession) (interface{}, error) {
 	fmt.Println(claims)
 	// c.Redirect(http.StatusFound, "https://auth.3dqueen.cloud")
 
-	// claims.AccessToken = token.AccessToken
-	return token.AccessToken, nil
+	claims.AccessToken = token.AccessToken
+	return claims, nil
 }

+ 1 - 1
src/api/controller.go

@@ -77,7 +77,7 @@ func ResultJWTWrapper(handle JWTHander, svc *Service) gin.HandlerFunc {
 
 		claims, _ := c.Get("casdoor_user")
 
-		user := claims.(*casdoorsdk.User)
+		user := claims.(*casdoorsdk.Claims)
 
 		var apis = &ApiSession{
 			Svc:  svc,

+ 0 - 158
src/api/jwt.go

@@ -1,158 +0,0 @@
-package api
-
-import (
-	"cmf/conf"
-	"fmt"
-	"log"
-	"time"
-
-	jwt "github.com/appleboy/gin-jwt/v2"
-	"github.com/gin-gonic/gin"
-)
-
-var identityKey = "id"
-
-type UtilsJwt struct {
-	jwt *jwt.GinJWTMiddleware
-}
-
-func (j *UtilsJwt) MiddleFunc() gin.HandlerFunc {
-	return j.jwt.MiddlewareFunc()
-}
-
-func (j *UtilsJwt) JwtCreateToken(data interface{}) (string, time.Time, error) {
-	return j.jwt.TokenGenerator(data)
-}
-
-func NewUitlsJwt(app *conf.AppConf) *UtilsJwt {
-
-	var utils = &UtilsJwt{
-		jwt: nil,
-	}
-
-	var jwtImpl *jwt.GinJWTMiddleware
-
-	jwtImpl, err := jwt.New(&jwt.GinJWTMiddleware{
-		Realm:       app.Jwt.Realm,
-		Key:         []byte(app.Jwt.Key),
-		Timeout:     time.Hour * time.Duration(app.Jwt.TimeoutHour),
-		MaxRefresh:  time.Hour * time.Duration(app.Jwt.TimeoutHour),
-		IdentityKey: identityKey,
-		PayloadFunc: func(data interface{}) jwt.MapClaims {
-			if v, ok := data.(*JWTUser); ok {
-				return jwt.MapClaims{
-					"id":       v.ID,
-					"name":     v.Name,
-					"phone":    v.Phone,
-					"parent":   v.Parent,
-					"state":    v.State,
-					"key":      v.Key,
-					"userType": v.UserType,
-				}
-			}
-			return jwt.MapClaims{}
-		},
-		IdentityHandler: func(c *gin.Context) interface{} {
-			claims := jwt.ExtractClaims(c)
-			// lg.Debug().Msgf("token: %v\n", claims)
-
-			u := &JWTUser{
-				ID:     claims["id"].(string), //uint32(claims["id"].(float64)),
-				Phone:  claims["phone"].(string),
-				Parent: claims["parent"].(string),
-			}
-			if claims["state"] != nil {
-				u.State = int32(claims["state"].(float64))
-			}
-
-			return u
-		},
-
-		Authenticator: func(c *gin.Context) (interface{}, error) {
-			return &JWTUser{Phone: "empty"}, nil
-		},
-
-		Authorizator: func(data interface{}, _ *gin.Context) bool {
-			u := data.(*JWTUser)
-			return u.State > 0
-		},
-
-		LoginResponse: func(c *gin.Context, status int, token string, expire time.Time) {
-
-			t, _ := jwtImpl.ParseTokenString(token)
-			fmt.Println("LoginResponse==>", status, token)
-
-			ResultSuc(c, map[string]interface{}{
-				"user":   t.Claims,
-				"token":  token,
-				"expire": expire.Format(time.RFC3339),
-			})
-		},
-
-		LogoutResponse: func(c *gin.Context, _ int) {
-			ResultSuc(c, true)
-		},
-
-		RefreshResponse: func(c *gin.Context, status int, token string, expire time.Time) {
-
-			ResultSuc(c, map[string]interface{}{
-				"status": status,
-				"token":  token,
-				"expire": expire.Format(time.RFC3339),
-			})
-		},
-
-		Unauthorized: func(c *gin.Context, status int, token string) {
-			if token == "用户名/密码 不正确" {
-				ResultFail401(c, "账号密码不对", map[string]interface{}{
-					"status": -1,
-					"token":  token,
-				})
-				return
-			}
-
-			fmt.Println("xxxxx")
-			fmt.Println(token, status)
-
-			ResultFail401(c, token, map[string]interface{}{
-				"status": status,
-				"token":  token,
-			})
-		},
-
-		HTTPStatusMessageFunc: func(e error, _ *gin.Context) string {
-
-			// if e == jwt.ErrFailedAuthentication {
-			// 	return "用户名/密码 不正确"
-			// }
-			fmt.Println("HTTPStatusMessageFunc", e)
-			return e.Error()
-		},
-
-		// TokenLookup is a string in the form of "<source>:<name>" that is used
-		// to extract token from the request.
-		// Optional. Default value "header:Authorization".
-		// Possible values:
-		// - "header:<name>"
-		// - "query:<name>"
-		// - "cookie:<name>"
-		// - "param:<name>"
-		TokenLookup: "header: Authorization, query: token, cookie: jwt",
-		// TokenLookup: "query:token",
-		// TokenLookup: "cookie:token",
-
-		// TokenHeadName is a string in the header. Default value is "Bearer"
-		TokenHeadName: "Bearer",
-
-		// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
-		TimeFunc: time.Now,
-	})
-
-	if err != nil {
-		log.Fatal("JWT Error:" + err.Error())
-	}
-
-	utils.jwt = jwtImpl
-
-	return utils
-}

+ 4 - 1
src/api/router.go

@@ -30,7 +30,10 @@ func RegRouters(svc *Service) {
 	// r.POSTJWT("/gallery/update", UpdateGallery)
 
 	// category
-	r.GET("/callback", callback)
+	r.GET("/getToken", callback)
+	r.GETJWT("/r1", func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
+		return apictx.User, nil
+	})
 
 	CreateCategoryRouter(r)
 	// Asset(r)

+ 2 - 2
src/app.yaml

@@ -18,8 +18,8 @@ debug:
   UserRole: string
 
 nats:
-  url: nats://124.71.139.24:14309
-  # url: nats://127.0.0.1:14309
+  # url: nats://124.71.139.24:14309
+  url: nats://127.0.0.1:14224
   maxReconnect: 1000
   reconnDelaySecond: 5
 

+ 2 - 12
src/middleware/auth.go

@@ -1,9 +1,7 @@
 package middleware
 
 import (
-	"cmf/conf"
 	"net/http"
-	"os"
 	"strings"
 
 	"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
@@ -33,23 +31,15 @@ func CasdoorAuthMiddleware() gin.HandlerFunc {
 			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)
+		claims, 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.Set("casdoor_user", claims)
 
 		// 继续处理请求
 		c.Next()

+ 157 - 0
src/readme.json

@@ -0,0 +1,157 @@
+{
+    "errorNo": 200,
+    "result": {
+        "owner": "cmf",
+        "name": "admin",
+        "createdTime": "2024-11-27T15:26:12+08:00",
+        "updatedTime": "2024-11-27T07:40:34Z",
+        "id": "50ed8707-cafc-4760-8d84-6669fd8d1214",
+        "externalId": "",
+        "type": "normal-user",
+        "password": "",
+        "passwordSalt": "",
+        "passwordType": "plain",
+        "displayName": "admin",
+        "firstName": "",
+        "lastName": "",
+        "avatar": "https://cdn.casbin.org/img/casbin.svg",
+        "avatarType": "",
+        "permanentAvatar": "",
+        "email": "1oqm1c@example.com",
+        "emailVerified": false,
+        "phone": "29205187214",
+        "countryCode": "CN",
+        "region": "",
+        "location": "",
+        "address": [],
+        "affiliation": "Example Inc.",
+        "title": "",
+        "idCardType": "",
+        "idCard": "",
+        "homepage": "",
+        "bio": "",
+        "tag": "staff",
+        "language": "",
+        "gender": "",
+        "birthday": "",
+        "education": "",
+        "score": 2000,
+        "karma": 0,
+        "ranking": 2,
+        "isDefaultAvatar": false,
+        "isOnline": false,
+        "isAdmin": true,
+        "isForbidden": false,
+        "isDeleted": false,
+        "signupApplication": "cmf-editor-admin",
+        "hash": "",
+        "preHash": "",
+        "accessKey": "",
+        "accessSecret": "",
+        "createdIp": "",
+        "lastSigninTime": "",
+        "lastSigninIp": "",
+        "github": "",
+        "google": "",
+        "qq": "",
+        "wechat": "",
+        "facebook": "",
+        "dingtalk": "",
+        "weibo": "",
+        "gitee": "",
+        "linkedin": "",
+        "wecom": "",
+        "lark": "",
+        "gitlab": "",
+        "adfs": "",
+        "baidu": "",
+        "alipay": "",
+        "casdoor": "",
+        "infoflow": "",
+        "apple": "",
+        "azuread": "",
+        "slack": "",
+        "steam": "",
+        "bilibili": "",
+        "okta": "",
+        "douyin": "",
+        "line": "",
+        "amazon": "",
+        "auth0": "",
+        "battlenet": "",
+        "bitbucket": "",
+        "box": "",
+        "cloudfoundry": "",
+        "dailymotion": "",
+        "deezer": "",
+        "digitalocean": "",
+        "discord": "",
+        "dropbox": "",
+        "eveonline": "",
+        "fitbit": "",
+        "gitea": "",
+        "heroku": "",
+        "influxcloud": "",
+        "instagram": "",
+        "intercom": "",
+        "kakao": "",
+        "lastfm": "",
+        "mailru": "",
+        "meetup": "",
+        "microsoftonline": "",
+        "naver": "",
+        "nextcloud": "",
+        "onedrive": "",
+        "oura": "",
+        "patreon": "",
+        "paypal": "",
+        "salesforce": "",
+        "shopify": "",
+        "soundcloud": "",
+        "spotify": "",
+        "strava": "",
+        "stripe": "",
+        "tiktok": "",
+        "tumblr": "",
+        "twitch": "",
+        "twitter": "",
+        "typetalk": "",
+        "uber": "",
+        "vk": "",
+        "wepay": "",
+        "xero": "",
+        "yahoo": "",
+        "yammer": "",
+        "yandex": "",
+        "zoom": "",
+        "metamask": "",
+        "web3onboard": "",
+        "custom": "",
+        "preferredMfaType": "",
+        "recoveryCodes": null,
+        "totpSecret": "",
+        "mfaPhoneEnabled": false,
+        "mfaEmailEnabled": false,
+        "ldap": "",
+        "properties": {},
+        "roles": [],
+        "permissions": [],
+        "groups": [],
+        "lastSigninWrongTime": "",
+        "signinWrongTimes": 0,
+        "managedAccounts": null,
+        "accessToken": "",
+        "iss": "https://auth.3dqueen.cloud",
+        "sub": "50ed8707-cafc-4760-8d84-6669fd8d1214",
+        "aud": [
+            "d372dce9cd00805db7e0"
+        ],
+        "exp": 1733298034,
+        "nbf": 1732693234,
+        "iat": 1732693234,
+        "jti": "admin/4b3ff91f-f0e1-4bd7-b50d-20542968ab3d",
+        "tokenType": "access-token",
+        "TokenType": ""
+    },
+    "errorDesc": ""
+}

Some files were not shown because too many files changed in this diff