diff --git a/config_template.json b/config_template.json index 12d9724..eab1857 100644 --- a/config_template.json +++ b/config_template.json @@ -37,6 +37,11 @@ "firebase_google_analytics_jssdk_apiid": "", "firebase_google_analytics_jssdk_measurementid": "", + "hybeim_projectid": "", + "hybeim_serviceid": "", + "hybeim_acesskey": "", + "hybeim_Endpoint": "", + "maingate_global_admins" : [ "mountain@action2quare.com" ] diff --git a/core/api.go b/core/api.go index 6f9b2d7..95903a0 100644 --- a/core/api.go +++ b/core/api.go @@ -169,7 +169,11 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error { json.NewEncoder(w).Encode(mg.bl.all()) } else if !target.IsZero() { if blocked, ok := mg.bl.get(target); ok && blocked != nil { - json.NewEncoder(w).Encode(blocked) + if !blocked.Expired() { + json.NewEncoder(w).Encode(blocked) + } else { + mg.bl.remove(target) + } } } } else if r.Method == "PUT" { @@ -200,7 +204,6 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error { logger.Println("account is blocked :", meta) bi.Accid = accid - caller.mg.bl.add(&bi) mg.sessionProvider.RevokeAll(accid) } } @@ -226,8 +229,6 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error { if err != nil { return err } - - caller.mg.bl.remove(idobj) } return nil } @@ -386,6 +387,58 @@ func (caller apiCaller) couponAPI(w http.ResponseWriter, r *http.Request) error return nil } +type accountlinkinfo struct { + Uid string `json:"uid"` + Platform string `json:"platform"` +} + +func (caller apiCaller) userinfoAPI(w http.ResponseWriter, r *http.Request) error { + mg := caller.mg + if r.Method == "GET" { + // 계정 조회 + accid, _ := gocommon.ReadObjectIDFormValue(r.Form, "accid") + if len(accid) == 0 { + logger.Println("[userinfoAPI] accid is empty") + w.WriteHeader(http.StatusBadRequest) + return nil + } + + all, err := mg.mongoClient.FindAll(CollectionAccount, bson.M{ + "accid": accid, + }, options.Find().SetProjection(bson.M{"_id": 1, "accid": 1})) + + if err != nil { + return err + } + + var linkinfos []accountlinkinfo + for _, doc := range all { + id := doc["_id"].(primitive.ObjectID) + + link, err := mg.mongoClient.FindOne(CollectionLink, bson.M{ + "_id": id, + }, options.FindOne().SetProjection(bson.M{"_id": 1, "platform": 1, "uid": 1})) + + if err != nil { + logger.Error("link failed. FindOneAndUpdate link err:", err) + w.WriteHeader(http.StatusInternalServerError) + return err + } + + var info accountlinkinfo + info.Platform = link["platform"].(string) + info.Uid = link["uid"].(string) + linkinfos = append(linkinfos, info) + } + + enc := json.NewEncoder(w) + enc.Encode(linkinfos) + + } + + return nil +} + var errApiTokenMissing = errors.New("mg-x-api-token is missing") func (caller apiCaller) configAPI(w http.ResponseWriter, r *http.Request) error { @@ -512,6 +565,8 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) { err = caller.blockAPI(w, r) } else if strings.HasSuffix(r.URL.Path, "/coupon") { err = caller.couponAPI(w, r) + } else if strings.HasSuffix(r.URL.Path, "/userinfo") { + err = caller.userinfoAPI(w, r) } if err != nil { diff --git a/core/maingate.go b/core/maingate.go index 6200238..6ba6aa1 100644 --- a/core/maingate.go +++ b/core/maingate.go @@ -36,6 +36,7 @@ import ( var devflag = flagx.Bool("dev", false, "") var noauth = flagx.Bool("noauth", false, "") +var authtype = flagx.String("auth", "on", "on|off|both") var ( CollectionLink = gocommon.CollectionName("link") @@ -57,6 +58,7 @@ const ( AuthPlatformMicrosoft = "microsoft" AuthPlatformApple = "apple" AuthPlatformTwitter = "twitter" + AuthPlatformHybeim = "hybeim" ) const ( @@ -98,6 +100,11 @@ type maingateConfig struct { SteamAppId string `json:"steam_app_id"` SteamPublisherAuthKey string `json:"steam_publisher_authkey"` GlobalMaingateToken string `json:"maingate_api_token"` + HybeImProjectIdstring string `json:"hybeim_projectid"` + HybeImServiceIdstring string `json:"hybeim_serviceid"` + HybeImAccessKey string `json:"hybeim_acesskey"` + HybeImEndPoint string `json:"hybeim_Endpoint"` + Firebase_Google_Analytics_JS_SDK_Config } @@ -127,6 +134,11 @@ func (ga *globalAdmins) parse() { ga.modtime = gocommon.ConfigModTime() } +type firebaseClient struct { + firebaseAppClient *auth.Client + firebaseAppContext context.Context +} + // Maingate : type Maingate struct { mongoClient gocommon.MongoClient @@ -142,8 +154,8 @@ type Maingate struct { authorizationEndpoints map[string]string userinfoEndpoint map[string]string jwksUri map[string]string - firebaseAppClient *auth.Client - firebaseAppContext context.Context + + firebase *firebaseClient } var config maingateConfig @@ -180,18 +192,29 @@ func New(ctx context.Context) (*Maingate, error) { return nil, err } - if !*noauth { - opt := option.WithCredentialsFile(config.FirebaseAdminSDKCredentialFile) - firebaseApp, err := firebase.NewApp(context.Background(), nil, opt) - if err != nil { - logger.Error("firebase admin error initializing app failed :", err) - return nil, err - } + if len(*authtype) == 0 { + *authtype = "on" + } - mg.firebaseAppContext = ctx - mg.firebaseAppClient, err = firebaseApp.Auth(mg.firebaseAppContext) - if err != nil { - logger.Println("FirebaseAppClient error getting Auth client:", err) + if !*noauth && (*authtype == "on" || *authtype == "both") { + if len(config.FirebaseAdminSDKCredentialFile) > 0 { + opt := option.WithCredentialsFile(config.FirebaseAdminSDKCredentialFile) + firebaseApp, err := firebase.NewApp(context.Background(), nil, opt) + if err != nil { + logger.Error("firebase admin error initializing app failed :", err) + return nil, err + } + + firebaseAppClient, err := firebaseApp.Auth(ctx) + if err != nil { + logger.Println("FirebaseAppClient error getting Auth client:", err) + return nil, err + } + + mg.firebase = &firebaseClient{ + firebaseAppContext: ctx, + firebaseAppClient: firebaseAppClient, + } } } @@ -548,6 +571,8 @@ func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMu serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "authorize_sdk", AuthPlatformSteamSDK), mg.platform_steamsdk_authorize) + serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "authorize_sdk", AuthPlatformHybeim), mg.platform_hybeim_authorize) + go mg.watchServiceCollection(ctx, serveMux, prefix) go mg.watchFileCollection(ctx, serveMux, prefix) // fsx := http.FileServer(http.Dir("console")) @@ -671,6 +696,8 @@ func (mg *Maingate) updateUserinfo(info usertokeninfo) (bool, string, string) { success, userid, email = mg.platform_google_getuserinfo(info) case AuthPlatformSteamSDK: success, userid, email = mg.platform_steamsdk_getuserinfo(info) + case AuthPlatformHybeim: + success, userid, email = mg.platform_hybeim_getuserinfo(info) case AuthPlatformFirebaseAuth: success, userid, email = mg.platform_firebase_getuserinfo(info) } diff --git a/core/platformfirebaseauth.go b/core/platformfirebaseauth.go index 5741818..d7e52db 100644 --- a/core/platformfirebaseauth.go +++ b/core/platformfirebaseauth.go @@ -3,6 +3,7 @@ package core import ( "encoding/json" "errors" + "fmt" "log" "net/http" "net/url" @@ -146,6 +147,11 @@ func (mg *Maingate) platform_firebaseauth_authorize_sdk(w http.ResponseWriter, r } func (mg *Maingate) platform_firebaseauth_authorize_raw(w http.ResponseWriter, brinfo, code, state, cookieSessionKey, memberId, nickname, provider, providerId, email, photourl, phonenumber string) (bool, string) { + if mg.firebase == nil { + logger.Println("mg.firebase is nil. check 'firebase_admin_sdk_credentialfile' config or 'authtype' parameter") + w.WriteHeader(http.StatusBadRequest) + return false, "" + } found, err := mg.mongoClient.FindOne(CollectionPlatformLoginToken, bson.M{ "platform": AuthPlatformFirebaseAuth, @@ -188,7 +194,7 @@ func (mg *Maingate) platform_firebaseauth_authorize_raw(w http.ResponseWriter, b return false, "" } - _, err = mg.firebaseAppClient.VerifyIDToken(mg.firebaseAppContext, code) + _, err = mg.firebase.firebaseAppClient.VerifyIDToken(mg.firebase.firebaseAppContext, code) if err != nil { log.Println("error verifying ID token:", err) return false, "" @@ -242,6 +248,10 @@ func (mg *Maingate) platform_firebaseauth_authorize_raw(w http.ResponseWriter, b } func (mg *Maingate) platform_firebase_getuserinfo(info usertokeninfo) (bool, string, string) { + if mg.firebase == nil { + logger.Println("mg.firebase is nil. check 'firebase_admin_sdk_credentialfile' config or 'authtype' parameter") + return false, "", "" + } found, err := mg.mongoClient.FindOne(CollectionFirebaseUserInfo, bson.M{ "firebaseuserid": info.userid, @@ -256,13 +266,16 @@ func (mg *Maingate) platform_firebase_getuserinfo(info usertokeninfo) (bool, str return false, "", "" } - _, err = mg.firebaseAppClient.VerifyIDToken(mg.firebaseAppContext, info.token) + _, err = mg.firebase.firebaseAppClient.VerifyIDToken(mg.firebase.firebaseAppContext, info.token) if err != nil { log.Println("error verifying ID token:", err) return false, "", "" } tempEmail := found["firebaseemail"].(string) + if found["firebaseprovider"].(string) == "guest" { + tempEmail = fmt.Sprintf("%s@guest.flag", info.userid) + } return true, info.userid, tempEmail diff --git a/core/platformhybeim.go b/core/platformhybeim.go new file mode 100644 index 0000000..a852bb4 --- /dev/null +++ b/core/platformhybeim.go @@ -0,0 +1,159 @@ +package core + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "time" + + "repositories.action2quare.com/ayo/gocommon/logger" +) + +type HybeImSDKAuthInfo struct { + UserHybeimid string `json:"imid"` + UserLoginVerifyToken string `json:"loginVerifyToken"` +} + +type HybeImSDKLoginAuthInfo struct { + ServiceId string `json:"serviceId"` + UserLoginVerifyToken string `json:"loginVerifyToken"` +} + +type Hiveim_LoginVerifyResult struct { + State string `json:"state"` + ImId string `json:"imId"` + Provider string `json:"provider"` + Os string `json:"os"` + AppStore string `json:"appStore"` +} + +type Hiveim_LoginValidationResponse struct { + ResultCode string `json:"resultCode"` + ResultMessage string `json:"resultMessage"` + ResultData Hiveim_LoginVerifyResult `json:"resultData"` +} + +func (mg *Maingate) platform_hybeim_authorize(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + + brinfo, err := mg.GetUserBrowserInfo(r) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + logger.Error(err) + return + } + + var authinfo HybeImSDKAuthInfo + err = json.NewDecoder(r.Body).Decode(&authinfo) + if err != nil { + logger.Println("authinfo decoding fail:", err) + w.WriteHeader(http.StatusBadRequest) + return + } + + if err = authenticateHybeImUser(config.HybeImProjectIdstring, config.HybeImServiceIdstring, config.HybeImAccessKey, config.HybeImEndPoint, authinfo.UserHybeimid, authinfo.UserLoginVerifyToken); err == nil { + acceestoken_expire_time := time.Date(2999, 1, int(time.January), 0, 0, 0, 0, time.UTC).Unix() + + var info usertokeninfo + info.platform = AuthPlatformHybeim + info.userid = authinfo.UserHybeimid + info.token = authinfo.UserLoginVerifyToken + info.brinfo = brinfo + //info.accesstoken = respReferesh.AccessToken + info.accesstoken_expire_time = acceestoken_expire_time + mg.setUserToken(info) + + params := url.Values{} + params.Add("id", authinfo.UserHybeimid) + params.Add("authtype", AuthPlatformHybeim) + w.Write([]byte("?" + params.Encode())) + //http.Redirect(w, r, "actionsquare://login?"+Result, http.StatusSeeOther) + } else { + logger.Println(err) + http.Redirect(w, r, "actionsquare://error", http.StatusSeeOther) + } + +} + +func authenticateHybeImUser(projectid, serviceid, accesskey, endpoint, imid, UserLoginVerifyToken string) error { + + // endpoint + // qa = https://api-qa.pub-dev.hybegames.io + // prod = https://api.hybegames.com + + verifyurl := endpoint + "/member/api-game/v1/auth/login/verify" + + var param HybeImSDKLoginAuthInfo + param.UserLoginVerifyToken = UserLoginVerifyToken + param.ServiceId = serviceid + + dat, err := json.Marshal(param) + if err != nil { + panic(err) + } + + var respReferesh Hiveim_LoginValidationResponse + req, err := http.NewRequest("POST", verifyurl, bytes.NewBuffer(dat)) + if err != nil { + panic(err) + } + + req.Header.Add("X-Auth-Access-Key", accesskey) + req.Header.Add("X-Req-Pjid", projectid) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + panic(err) + } + defer resp.Body.Close() + + defer func() { + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + }() + + body, e := ioutil.ReadAll(resp.Body) + if e != nil { + return e + } + + json.Unmarshal(body, &respReferesh) + + //fmt.Println(string(body)) + + var doc map[string]interface{} + if err := json.Unmarshal(body, &doc); err != nil { + return err + } + + if respReferesh.ResultCode != "SUCCESS" { + return errors.New("higveimSDK: ResultCode is not SUCCESS") + } + + if respReferesh.ResultData.State != "NORMAL" { + return errors.New("higveimSDK: State is not NORMAL") + } + + if respReferesh.ResultData.Provider != "STEAM" { + return errors.New("higveimSDK: Provider is not STEAM") + } + + if respReferesh.ResultData.ImId != imid { + return errors.New("higveimSDK: ImId is not match") + } + + return nil +} + +func (mg *Maingate) platform_hybeim_getuserinfo(info usertokeninfo) (bool, string, string) { + // Hybeim ( Steam )도 이메일 정보를 받을수 없기 때문에 userid로 리턴한다. + dummyEmail := fmt.Sprintf("%s@hibeim.id", info.userid) + return true, info.userid, dummyEmail + +} diff --git a/core/platformsteam.go b/core/platformsteam.go index 4dfc2f7..66e5b5f 100644 --- a/core/platformsteam.go +++ b/core/platformsteam.go @@ -39,11 +39,7 @@ func (mg *Maingate) platform_steamsdk_authorize(w http.ResponseWriter, r *http.R return } - if !*noauth { - err = authenticateSteamUser(config.SteamPublisherAuthKey, config.SteamAppId, authinfo.UserSteamId, authinfo.UserAuthToken) - } - - if err == nil { + if err := authenticateSteamUser(config.SteamPublisherAuthKey, config.SteamAppId, authinfo.UserSteamId, authinfo.UserAuthToken); err == nil { acceestoken_expire_time := time.Date(2999, 1, int(time.January), 0, 0, 0, 0, time.UTC).Unix() var info usertokeninfo diff --git a/core/service.go b/core/service.go index 0fca7d3..30aa1d9 100644 --- a/core/service.go +++ b/core/service.go @@ -296,6 +296,32 @@ func (sh *serviceDescription) link(w http.ResponseWriter, r *http.Request) { return } + bfinfo, err := sh.getUserBrowserInfo(r) + if err != nil { + logger.Error("getUserBrowserInfo failed :", err) + w.WriteHeader(http.StatusBadRequest) + return + } + + guestlink := (oldAuth.Platform == "guest") + if !guestlink { + _, err = sh.readProfile(oldType, oldId, bfinfo) + if err != nil { + logger.Error("readProfile(old) failed :", err) + w.WriteHeader(http.StatusBadRequest) + return + } + } else { + logger.Println("from guest acc to real acc link : ", oldId, bfinfo, newType, newId, bfinfo) + } + + oldType, oldId, err = sh.getProviderInfo(oldType, oldId) + if err != nil { + logger.Error("getProviderInfo failed :", err) + w.WriteHeader(http.StatusBadRequest) + return + } + // fmt.Println("=================") // fmt.Println(oldType) // fmt.Println(oldId) @@ -314,20 +340,6 @@ func (sh *serviceDescription) link(w http.ResponseWriter, r *http.Request) { return } - bfinfo, err := sh.getUserBrowserInfo(r) - if err != nil { - logger.Error("getUserBrowserInfo failed :", err) - w.WriteHeader(http.StatusBadRequest) - return - } - - _, err = sh.readProfile(oldType, oldId, bfinfo) - if err != nil { - logger.Error("readProfile(old) failed :", err) - w.WriteHeader(http.StatusBadRequest) - return - } - email, err := sh.readProfile(newType, newId, bfinfo) if err != nil { logger.Error("readProfile(new) failed :", err) @@ -345,6 +357,19 @@ func (sh *serviceDescription) link(w http.ResponseWriter, r *http.Request) { if err != nil { logger.Error("getProviderInfo failed :", err) w.WriteHeader(http.StatusBadRequest) + return + } + + found, err := sh.mongoClient.FindOne(CollectionLink, bson.M{"platform": newType, "uid": newId}, options.FindOne()) + if err != nil { + logger.Error("link failed. FindOne err:", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + if found != nil { + logger.Println("link failed. already have service account: ", r.URL.Query()) + w.Write([]byte(`{"alreadylink":true}`)) + return } createtime := primitive.NewDateTimeFromTime(time.Now().UTC()) @@ -385,6 +410,20 @@ func (sh *serviceDescription) link(w http.ResponseWriter, r *http.Request) { return } + if guestlink { + //기존 게스트 링크 삭제 + link, err = sh.mongoClient.FindOneAndDelete(CollectionLink, bson.M{ + "platform": oldType, + "uid": oldId, + }, options.FindOneAndDelete().SetProjection(bson.M{"_id": 1})) + + if err == nil { + sh.mongoClient.Delete(CollectionAccount, bson.M{ + "_id": link["_id"].(primitive.ObjectID), + }) + } + } + logger.Println("link success :", r.URL.Query()) } @@ -614,7 +653,7 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) } queryvals := r.URL.Query() - authtype := queryvals.Get("type") + reqauthtype := queryvals.Get("type") uid := queryvals.Get("id") sk := queryvals.Get("sk") @@ -653,9 +692,8 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) } var email string - - if !*noauth { - if len(authtype) > 0 { + if !*noauth && (*authtype == "on" || *authtype == "both") { + if len(reqauthtype) > 0 { //email, err := sh.readProfile(authtype, uid, accesstoken) bfinfo, err := sh.getUserBrowserInfo(r) if err != nil { @@ -664,28 +702,25 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) return } - email, err = sh.readProfile(authtype, uid, bfinfo) + email, err = sh.readProfile(reqauthtype, uid, bfinfo) if err != nil { logger.Error("readProfile failed :", err) w.WriteHeader(http.StatusBadRequest) return } - newType, newId, err := sh.getProviderInfo(authtype, uid) + newType, newId, err := sh.getProviderInfo(reqauthtype, uid) if err != nil { logger.Error("getProviderInfo failed :", err) w.WriteHeader(http.StatusBadRequest) return } - if authtype != newType || uid != newId { - if authtype == "firebase" && newType == "guest" { - email = fmt.Sprintf("%s@guest.flag", uid) - } - authtype = newType + if reqauthtype != newType || uid != newId { + reqauthtype = newType uid = newId } - } else if *devflag { + } else if *authtype == "both" { email = fmt.Sprintf("%s@guest.flag", uid) } else { // authtype이 없으면 입장 불가 @@ -744,7 +779,7 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) sk, err = sh.sessionProvider.New(&session.Authorization{ Account: accid, - Platform: authtype, + Platform: reqauthtype, Uid: uid, Email: email, }) @@ -760,7 +795,7 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) "newAccount": newaccount, "accid": accid.Hex(), } - if *noauth { + if len(reqauthtype) == 0 { output["noauth"] = true }