From d8b2d89366ef6a9f3ae85b484879810e767e5783 Mon Sep 17 00:00:00 2001 From: xun Date: Sat, 27 Jul 2024 14:13:14 +0800 Subject: [PATCH] fix: Fix the issue where the oauth client module could't store JSONB in PostgreSQL In PostgreSQL, _jsonb represents a JSONB array rather than a JSONB object :(. --- sql/oauth2_info.sql | 2 +- src/api/v1/oauth_client_lark.go | 61 +++++++++++++++++---------------- src/api/v1/user.go | 12 ++++--- src/go.mod | 4 --- src/go.sum | 16 --------- src/model/oauth.go | 19 ++++++---- src/model/oauth_test.go | 27 +++++++-------- src/service/oauth.go | 27 ++++++++++++--- 8 files changed, 87 insertions(+), 81 deletions(-) diff --git a/sql/oauth2_info.sql b/sql/oauth2_info.sql index bf5380a..ff6e7af 100644 --- a/sql/oauth2_info.sql +++ b/sql/oauth2_info.sql @@ -27,7 +27,7 @@ SET default_table_access_method = heap; CREATE TABLE public.oauth2_info ( id integer NOT NULL, client character varying NOT NULL, - info jsonb[], + info jsonb DEFAULT '{}', oauth_user_id character varying NOT NULL, user_id character varying NOT NULL ); diff --git a/src/api/v1/oauth_client_lark.go b/src/api/v1/oauth_client_lark.go index e0f9a6b..4f610fa 100644 --- a/src/api/v1/oauth_client_lark.go +++ b/src/api/v1/oauth_client_lark.go @@ -37,16 +37,16 @@ var ( // OauthLarkLogin redirect url to lark auth page. func OauthLarkLogin(c *gin.Context) { redirectURL := c.Query("redirect_url") - log.Log.Debugf("redirectURL ::: %s\n", redirectURL) + log.Debugf("redirectURL ::: %s\n", redirectURL) larkConf.RedirectURL = redirectURL // Create oauthState cookie oauthState := GenerateStateOauthCookie(c.Writer) - log.Log.Debugf("oauthState ::: %s\n", redirectURL) + log.Debugf("oauthState ::: %s\n", redirectURL) url := larkConf.AuthCodeURL(oauthState) - log.Log.Warnln("ClientID: ", larkConf.ClientID) - log.Log.Warnln("ClientSecret: ", larkConf.ClientSecret) + log.Debug("ClientID: ", larkConf.ClientID) + log.Debug("ClientSecret: ", larkConf.ClientSecret) log.Log.Warnf("Visit the URL for the auth dialog: %v\n", url) @@ -59,7 +59,7 @@ func OauthLarkLogin(c *gin.Context) { // at last request user info func OauthLarkCallback(c *gin.Context) { oauthState, _ := c.Request.Cookie("oauthstate") - log.Log.Debugf("oauthState ::: %v\n", oauthState) + log.Debugf("oauthState ::: %v\n", oauthState) if c.Request.FormValue("state") != oauthState.Value { fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthState.Value, c.Request.FormValue("state")) c.Redirect(http.StatusFound, "/") @@ -67,18 +67,18 @@ func OauthLarkCallback(c *gin.Context) { } code := c.Query("code") - log.Log.Debugf("\ncode ::: %s\n", code) + log.Debugf("\ncode ::: %s\n", code) accessToken, err := larkAppAccessToken() if err != nil { - log.Log.Errorln("larkAppAccessToken ::: ", err) + log.Error("larkAppAccessToken ::: ", err) c.JSON(http.StatusOK, result.Failed(result.HandleError(err))) return } userAccessTokenBody, err := larkUserAccessToken(code, accessToken) if err != nil { - log.Log.Errorln("larkUserAccessToken ::: ", err) + log.Error("larkUserAccessToken ::: ", err) c.JSON(http.StatusOK, result.Failed(result.HandleError(err))) return } @@ -87,30 +87,33 @@ func OauthLarkCallback(c *gin.Context) { userInfoBody, err := larkUserInfo(userAccessToken) if err != nil { - log.Log.Errorln("larkUserInfo ::: ", err) + log.Error("larkUserInfo ::: ", err) c.JSON(http.StatusOK, result.Failed(result.HandleError(err))) return } unionId := gjson.Get(userInfoBody, "data.union_id").Str // save user info in redis (then retrive in login) - userInfo := gjson.Get(userInfoBody, "data") - model.Rdb.Set(model.RedisCtx, unionId, - userInfo, time.Duration(model.OAUTH_USER_INFO_EXP)) + userInfo := gjson.Get(userInfoBody, "data").String() + if err := model.Rdb.Set(c, unionId, + userInfo, time.Duration(model.OAUTH_USER_INFO_EXP)).Err(); err != nil { + log.Error("model.Rdb.Set ::: ", err) + c.JSON(http.StatusOK, result.Failed(result.InternalErr)) + return + } - // FIXME: Use OauthInfoByUID to get user - user, err := service.UserByLarkUnionID(unionId) + userLarkInfo, err := service.OauthInfoByLarkID(unionId) if err != nil { c.JSON(http.StatusOK, result.Failed(result.InternalErr)) - log.Log.Errorln("service.UserByLarkUnionID ::: ", err) + log.Error("service.UserByLarkUnionID ::: ", err) return - } else if user == nil { + } else if userLarkInfo == nil { // return with oauth lark ticket, which contains "union_id" oauthToken, err := util.GenerateTokenWithExp(c, model.OauthSubKey(unionId, model.OAUTH_LARK_SUB), model.OAUTH_TICKET_EXP) if err != nil { c.JSON(http.StatusOK, result.Failed(result.GenerateToken)) - log.Log.Errorln("util.GenerateTokenWithExp ::: ", err) + log.Error("util.GenerateTokenWithExp ::: ", err) return } c.JSON(http.StatusOK, result.Response{ @@ -125,7 +128,8 @@ func OauthLarkCallback(c *gin.Context) { } else { // User already registered and bounded lark, // directly return token - uid := *user.Uid + uid := userLarkInfo.UserID + log.Debugf("User already registered and bounded lark: %s", uid) token, err := util.GenerateTokenWithExp(c, model.LoginJWTSubKey(uid), model.LOGIN_TOKEN_EXP) if err != nil { c.JSON(http.StatusOK, result.Failed(result.GenerateToken)) @@ -150,27 +154,24 @@ func larkAppAccessToken() (string, error) { res, error := http.PostForm(AppAccessTokenURL, params) if error != nil { - log.Log.Errorln("http.PostForm ::: ", error) + log.Error("http.PostForm ::: ", error) return "", error } - log.LogRes(res) + // log.LogRes(res) body, error := io.ReadAll(res.Body) defer res.Body.Close() if error != nil { - log.Log.Errorln("io.ReadAll ::: ", error) + log.Error("io.ReadAll ::: ", error) return "", error } if code := gjson.Get(string(body), "code").Int(); code != 0 { - log.Log.Errorln("gjson.Get ::: code:", code) + log.Error("gjson.Get ::: code:", code) return "", result.InternalErr } acceToken := gjson.Get(string(body), "app_access_token").String() - expire := gjson.Get(string(body), "expire").Int() - - model.Rdb.Set(model.RedisCtx, "lark_app_access_token", acceToken, time.Duration(expire)) return acceToken, nil } @@ -195,11 +196,11 @@ func larkUserAccessToken(code string, accessToken string) (string, error) { body, err := io.ReadAll(res.Body) defer res.Body.Close() if err != nil { - log.Log.Errorln("io.ReadAll ::: ", err) + log.Error("io.ReadAll ::: ", err) return "", result.InternalErr } if resCode := gjson.Get(string(body), "code").Int(); resCode != 0 { - log.Log.Errorf("larkUserAccessToken ::: gjson.Get ::: response code: %d\n", resCode) + log.Errorf("larkUserAccessToken ::: gjson.Get ::: response code: %d\n", resCode) return "", fmt.Errorf("OauthLarkCallback resCode: %d", resCode) } return string(body), nil @@ -212,18 +213,18 @@ func larkUserInfo(userAccessToken string) (string, error) { } res, err := util.GetWithHeader(UserInfoURL, header) if err != nil { - log.Log.Errorln("util.GetWithHeader ::: ", err) + log.Error("util.GetWithHeader ::: ", err) return "", result.AccessTokenErr } body, err := io.ReadAll(res.Body) defer res.Body.Close() if err != nil { - log.Log.Errorln("io.ReadAll ::: ", err) + log.Error("io.ReadAll ::: ", err) return "", result.InternalErr } if resCode := gjson.Get(string(body), "code").Int(); resCode != 0 { - log.Log.Errorf("larkUserInfo ::: gjson.Get ::: response code: %d\n", resCode) + log.Errorf("larkUserInfo ::: gjson.Get ::: response code: %d\n", resCode) return "", fmt.Errorf("OauthLarkCallback resCode: %d", resCode) } return string(body), nil diff --git a/src/api/v1/user.go b/src/api/v1/user.go index c8379be..8c4cdeb 100644 --- a/src/api/v1/user.go +++ b/src/api/v1/user.go @@ -12,8 +12,6 @@ import ( "github.com/NJUPT-SAST/sast-link-backend/service" "github.com/NJUPT-SAST/sast-link-backend/util" "github.com/gin-gonic/gin" - - "gorm.io/datatypes" ) var controllerLogger = log.Log @@ -235,9 +233,13 @@ func Login(ctx *gin.Context) { return } - // TODO: save oauth user info oauthLarkUserInfo, _ := model.Rdb.Get(ctx, unionID).Result() - service.UpsetOauthInfo(username, model.LARK_CLIENT_TYPE, unionID, datatypes.JSON(oauthLarkUserInfo)) + + log.Debugf("Login ::: Oauth ::: unionID ::: %v", unionID) + log.Debugf("Login ::: Oauth ::: lark info ::: %v", oauthLarkUserInfo) + + service.UpsetOauthInfo(username, model.LARK_CLIENT_TYPE, unionID, oauthLarkUserInfo) + case model.OAUTH_GITHUB_SUB: unionID, err := util.IdentityFromToken(oauthTicket, model.OAUTH_GITHUB_SUB) if err != nil { @@ -250,7 +252,7 @@ func Login(ctx *gin.Context) { log.Debugf("Login ::: Oauth ::: github info ::: %v", oauthGithubUserInfo) - service.UpsetOauthInfo(username, model.GITHUB_CLIENT_TYPE, unionID, datatypes.JSON(oauthGithubUserInfo)) + service.UpsetOauthInfo(username, model.GITHUB_CLIENT_TYPE, unionID, oauthGithubUserInfo) default: log.Errorf("Login ::: Oauth ::: flagIn ::: %v", flagIn) ctx.JSON(http.StatusOK, result.Failed(result.OauthTokenError)) diff --git a/src/go.mod b/src/go.mod index 683b6d1..ef5bacf 100644 --- a/src/go.mod +++ b/src/go.mod @@ -28,7 +28,6 @@ require ( github.com/vgarvardt/go-oauth2-pg/v4 v4.4.3 github.com/vgarvardt/go-pg-adapter v1.0.0 golang.org/x/oauth2 v0.12.0 - gorm.io/datatypes v1.2.1 ) require ( @@ -41,7 +40,6 @@ require ( ) require ( - filippo.io/edwards25519 v1.1.0 // indirect github.com/bytedance/sonic v1.9.2 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect @@ -56,7 +54,6 @@ require ( github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.14.1 // indirect github.com/go-redis/redis/v8 v8.11.4 // indirect - github.com/go-sql-driver/mysql v1.8.1 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/golang-jwt/jwt v3.2.1+incompatible // indirect github.com/golang/protobuf v1.5.3 // indirect @@ -104,5 +101,4 @@ require ( google.golang.org/protobuf v1.31.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - gorm.io/driver/mysql v1.5.6 // indirect ) diff --git a/src/go.sum b/src/go.sum index 91decf0..0148703 100644 --- a/src/go.sum +++ b/src/go.sum @@ -37,8 +37,6 @@ cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RX cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= -filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= @@ -146,9 +144,6 @@ github.com/go-session/session/v3 v3.1.5 h1:G44Qx6wts5IA2jNLWYOVYxip/0LH5FTg8/Tde github.com/go-session/session/v3 v3.1.5/go.mod h1:sWg9Nca0XsmPHUnPypN+yl6zV/OSilR69vFBnkJgNjY= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= -github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= -github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= @@ -160,8 +155,6 @@ github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfE github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE= github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= -github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -380,8 +373,6 @@ github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APP github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= -github.com/mattn/go-sqlite3 v1.14.15 h1:vfoHhTN1af61xCRSWzFIWzx2YskyMTwHLrExkBOjvxI= -github.com/microsoft/go-mssqldb v0.17.0 h1:Fto83dMZPnYv1Zwx5vHHxpNraeEaUlQ/hhHLgZiaenE= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= @@ -946,16 +937,9 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/datatypes v1.2.1 h1:r+g0bk4LPCW2v4+Ls7aeNgGme7JYdNDQ2VtvlNUfBh0= -gorm.io/datatypes v1.2.1/go.mod h1:hYK6OTb/1x+m96PgoZZq10UXJ6RvEBb9kRDQ2yyhzGs= -gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8= -gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= gorm.io/driver/postgres v1.5.0 h1:u2FXTy14l45qc3UeCJ7QaAXZmZfDDv0YrthvmRq1l0U= gorm.io/driver/postgres v1.5.0/go.mod h1:FUZXzO+5Uqg5zzwzv4KK49R8lvGIyscBOqYrtI1Ce9A= -gorm.io/driver/sqlite v1.4.3 h1:HBBcZSDnWi5BW3B3rwvVTc510KGkBkexlOg0QrmLUuU= -gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0= gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= -gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= gorm.io/gorm v1.25.9 h1:wct0gxZIELDk8+ZqF/MVnHLkA1rvYlBWUMv2EdsK1g8= gorm.io/gorm v1.25.9/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= diff --git a/src/model/oauth.go b/src/model/oauth.go index 036cc3d..98dc805 100644 --- a/src/model/oauth.go +++ b/src/model/oauth.go @@ -2,21 +2,28 @@ package model import ( // "encoding/json" + + "encoding/json" "errors" + "fmt" "github.com/NJUPT-SAST/sast-link-backend/log" "github.com/NJUPT-SAST/sast-link-backend/model/result" - "gorm.io/datatypes" "gorm.io/gorm" ) // OAuth2Info struct type OAuth2Info struct { - ID uint `gorm:"primaryKey"` - Client string `gorm:"not null"` - Info datatypes.JSON `gorm:"default:'[]'"` - OauthID string `gorm:"not null"` - UserID string `gorm:"not null"` + ID uint + Client string + Info json.RawMessage + OauthID string `json:"oauth_user_id"` + UserID string +} + +// String return string of OAuth2Info +func (o OAuth2Info) String() string { + return fmt.Sprintf("OAuth2Info{Client: %s, Info: %s, OauthID: %s, UserID: %s}", o.Client, o.Info, o.OauthID, o.UserID) } func UpdateLarkUserInfo(info OAuth2Info) error { diff --git a/src/model/oauth_test.go b/src/model/oauth_test.go index e33dcb3..c9919a5 100644 --- a/src/model/oauth_test.go +++ b/src/model/oauth_test.go @@ -1,27 +1,26 @@ package model import ( - "database/sql" - "log" + "encoding/json" + "fmt" "testing" - - "gorm.io/datatypes" ) func TestInsertOAuth2Info(t *testing.T) { - db, err := sql.Open("postgres", "your-database-connection-string") - if err != nil { - log.Fatal(err) - } - defer db.Close() - - info := `{"login":"user","id":123,"node_id":"node_id","avatar_url":"url","gravatar_id":"","url":"url","html_url":"url","followers_url":"url","following_url":"url","gists_url":"url","starred_url":"url","subscriptions_url":"https://api.github.com/users/user/subscriptions","organizations_url":"https://api.github.com/users/user/orgs","repos_url":"https://api.github.com/users/user/repos","events_url":"https://api.github.com/users/user/events{/privacy}","received_events_url":"https://api.github.com/users/user/received_events","type":"User","site_admin":false,"name":"max","company":"@Xiaomi @sast @GreenPomelo","blog":"blog_url","location":"Nanjing","email":null,"hireable":null,"bio":"From Nanjing University of Posts and Telecommunications, member of @SAST. Working on 👀 visualization & 🌐 web dev\\r\\n","twitter_username":null,"public_repos":48,"public_gists":3,"followers":65,"following":148,"created_at":"2020-02-07T09:21:13Z","updated_at":"2024-07-19T12:26:27Z"}` + info := `{"login":"user","id":123,"node_id":"node_id","avatar_url":"url","gravatar_id":"","url":"url","html_url":"url","followers_url":"url","following_url":"url","gists_url":"url","starred_url":"url","subscriptions_url":"https://api.github.com/users/user/subscriptions","organizations_url":"https://api.github.com/users/user/orgs","repos_url":"https://api.github.com/users/user/repos","events_url":"https://api.github.com/users/user/events{/privacy}","received_events_url":"https://api.github.com/users/user/received_events","type":"User","site_admin":false,"name":"max","company":"@sast","blog":"blog_url","location":"Nanjing","email":null,"hireable":null,"bio":"From Nanjing University of Posts and Telecommunications, member of @SAST. Working on 👀 visualization & 🌐 web dev\\r\\n","twitter_username":null,"public_repos":48,"public_gists":3,"followers":65,"following":148,"created_at":"2020-02-07T09:21:13Z","updated_at":"2024-07-19T12:26:27Z"}` testData := OAuth2Info{ Client: "github", - Info: datatypes.JSON(info), - OauthID: "60775796", - UserID: "b21041313", + Info: json.RawMessage(info), + OauthID: "oauthid", + UserID: "userid", } UpsetOauthInfo(testData) + res, err := OauthInfoByUID("github", "oauthid") + if err != nil { + t.Errorf("InsertOAuth2Info failed: %s", err) + } + + fmt.Println("jsonStr: ", string(res.Info)) + t.Log("InsertOAuth2Info test passed") } diff --git a/src/service/oauth.go b/src/service/oauth.go index a99be5e..3799575 100644 --- a/src/service/oauth.go +++ b/src/service/oauth.go @@ -1,10 +1,10 @@ package service import ( + "encoding/json" "fmt" "github.com/NJUPT-SAST/sast-link-backend/model" - "gorm.io/datatypes" ) // Oauth Github @@ -28,10 +28,10 @@ func GetUserInfoFromGithub(username, githubId string) (*model.User, error) { return nil, nil } -func UpsetOauthInfo(username, clientType, oauthID string, OAuth2Info datatypes.JSON) { +func UpsetOauthInfo(username, clientType, oauthID, OAuth2Info string) { var oauthInfo = model.OAuth2Info{ Client: clientType, - Info: OAuth2Info, + Info: json.RawMessage(OAuth2Info), OauthID: oauthID, UserID: username, } @@ -39,8 +39,25 @@ func UpsetOauthInfo(username, clientType, oauthID string, OAuth2Info datatypes.J } // Oauth Lark -func UserByLarkUnionID(unionID string) (*model.User, error) { - return model.UserByField("lark_id", unionID) +func OauthInfoByLarkID(unionID string) (*model.OAuth2Info, error) { + return model.OauthInfoByUID(model.LARK_CLIENT_TYPE, unionID) +} + +func UserByLarkID(username, unionID string) (*model.User, error) { + // FIXME: replace union_id with "real" field name in db + user, err := model.UserByField("lark_id", unionID) + if err != nil { + return nil, err + } + + if user == nil { + return nil, fmt.Errorf("user not found") + } + + if user.Uid != &username { + return nil, fmt.Errorf("user not match") + } + return nil, nil } // Oauth server