diff --git a/core/api.go b/core/api.go index 6aeda99..08fe704 100644 --- a/core/api.go +++ b/core/api.go @@ -193,6 +193,8 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error { if err != nil { return err } + + mg.sessionProvider.Delete(accid) } else if r.Method == "DELETE" { id := r.URL.Query().Get("id") @@ -215,8 +217,6 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error { if err != nil { return err } - - mg.mongoClient.Delete(CollectionAuth, bson.M{"_id": idobj}) } return nil } @@ -271,13 +271,16 @@ func (caller apiCaller) whitelistAPI(w http.ResponseWriter, r *http.Request) err func (caller apiCaller) serviceAPI(w http.ResponseWriter, r *http.Request) error { mg := caller.mg if r.Method == "GET" { + logger.Println("serviceAPI :", r.URL.Path) if mg.service().Id.IsZero() { + logger.Println(" id is zero") newService := serviceDescription{ ServiceDescriptionSummary: ServiceDescriptionSummary{ Id: primitive.NewObjectID(), }, } if err := newService.prepare(caller.mg); err != nil { + logger.Println(" prepare failed :", err) return err } atomic.StorePointer(&mg.serviceptr, unsafe.Pointer(&newService)) diff --git a/core/api_coupon.go b/core/api_coupon.go index 8e788f6..1d1f4a8 100644 --- a/core/api_coupon.go +++ b/core/api_coupon.go @@ -44,17 +44,17 @@ func makeCouponKey(roundnum uint32, uid []byte) string { return fmt.Sprintf("%s-%s-%s-%s", hex.EncodeToString(final[0:2]), hex.EncodeToString(final[2:4]), hex.EncodeToString(final[4:6]), hex.EncodeToString(final[6:8])) } +var r = rand.New(rand.NewSource(time.Now().UnixNano())) + func makeCouponCodes(name string, count int) (string, map[string]string) { checkunique := make(map[string]bool) keys := make(map[string]string) uid := make([]byte, 4) roundHash, roundnum := coupon.MakeCouponRoundHash(name) - seed := time.Now().UnixNano() for len(keys) < count { - rand.Seed(seed) - rand.Read(uid) + r.Read(uid) code := makeCouponKey(roundnum, uid) @@ -62,7 +62,6 @@ func makeCouponCodes(name string, count int) (string, map[string]string) { checkunique[code] = true keys[hex.EncodeToString(uid)] = code } - seed = int64(binary.BigEndian.Uint32(uid)) } return roundHash, keys } diff --git a/core/maingate.go b/core/maingate.go index 48870f5..fda15d8 100644 --- a/core/maingate.go +++ b/core/maingate.go @@ -9,7 +9,6 @@ import ( "fmt" "io" "math/big" - "math/rand" "net" "net/http" "os" @@ -40,7 +39,6 @@ var noauth = flagx.Bool("noauth", false, "") var ( CollectionLink = gocommon.CollectionName("link") - CollectionAuth = gocommon.CollectionName("auth") CollectionWhitelist = gocommon.CollectionName("whitelist") CollectionService = gocommon.CollectionName("service") CollectionAccount = gocommon.CollectionName("account") @@ -267,12 +265,6 @@ func (mg *Maingate) prepare(context context.Context) (err error) { return err } - if err = mg.mongoClient.MakeUniqueIndices(CollectionAuth, map[string]bson.D{ - "skonly": {{Key: "sk", Value: 1}}, - }); err != nil { - return makeErrorWithStack(err) - } - if err = mg.mongoClient.MakeUniqueIndices(CollectionLink, map[string]bson.D{ "platformuid": {{Key: "platform", Value: 1}, {Key: "uid", Value: 1}}, }); err != nil { @@ -302,10 +294,6 @@ func (mg *Maingate) prepare(context context.Context) (err error) { return makeErrorWithStack(err) } - if err = mg.mongoClient.MakeExpireIndex(CollectionAuth, int32(mg.SessionTTL+300)); err != nil { - return makeErrorWithStack(err) - } - if *devflag { // 에러 체크하지 말것 mg.mongoClient.DropIndex(CollectionBlock, "codeaccid") @@ -554,7 +542,7 @@ func (mg *Maingate) GeneratePlatformLoginNonceKey() string { const allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" b := make([]byte, 52) for i := range b { - b[i] = allowed[rand.Intn(len(allowed))] + b[i] = allowed[r.Intn(len(allowed))] } return string(b) } diff --git a/core/service.go b/core/service.go index 608141f..24c481f 100644 --- a/core/service.go +++ b/core/service.go @@ -554,8 +554,7 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) queryvals := r.URL.Query() authtype := queryvals.Get("type") uid := queryvals.Get("id") - //accesstoken := queryvals.Get("token") //-- 이거 이제 받지마라 - session := queryvals.Get("sk") + var email string if !*noauth { @@ -584,7 +583,6 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) if authtype != newType || uid != newId { authtype = newType uid = newId - logger.Println("auth success ( redirect ) :", authtype, uid, email, session) } } else { email = fmt.Sprintf("%s@guest.flag", uid) @@ -593,128 +591,79 @@ func (sh *serviceDescription) authorize(w http.ResponseWriter, r *http.Request) email = fmt.Sprintf("%s@noauth.flag", uid) } - //if len(session) == 0 && len(email) > 0 { - if len(session) == 0 { - // platform + id -> account id - createtime := primitive.NewDateTimeFromTime(time.Now().UTC()) - link, err := sh.mongoClient.FindOneAndUpdate(CollectionLink, bson.M{ - "platform": authtype, - "uid": uid, - }, bson.M{ - "$setOnInsert": bson.M{ - "create": createtime, - "email": email, - }, - }, options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true).SetProjection(bson.M{"_id": 1})) - if err != nil { - logger.Error("authorize failed :", err) - w.WriteHeader(http.StatusInternalServerError) - return - } - - linkid := link["_id"].(primitive.ObjectID) - newaccid := primitive.NewObjectID() - for i := 0; i < len(sh.serviceCodeBytes); i++ { - newaccid[i] ^= sh.serviceCodeBytes[i] - } - account, err := sh.mongoClient.FindOneAndUpdate(CollectionAccount, bson.M{ - "_id": linkid, - }, bson.M{ - "$setOnInsert": bson.M{ - "accid": newaccid, - "create": createtime, - }, - }, options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true).SetProjection(bson.M{"accid": 1, "create": 1})) - if err != nil { - logger.Error("authorize failed. Update sh.ServiceName err:", err) - w.WriteHeader(http.StatusInternalServerError) - return - } - - accid := account["accid"].(primitive.ObjectID) - oldcreate := account["create"].(primitive.DateTime) - newaccount := oldcreate == createtime - - var bi *blockinfo - if sh.bl.contains(accid, &bi) { - // 블럭된 계정. 블락 정보를 알려준다. - w.Header().Add("MG-ACCOUNTBLOCK-START", strconv.FormatInt(bi.Start.Time().Unix(), 10)) - w.Header().Add("MG-ACCOUNTBLOCK-END", strconv.FormatInt(bi.End.Time().Unix(), 10)) - w.Header().Add("MG-ACCOUNTBLOCK-REASON", bi.Reason) - w.WriteHeader(http.StatusUnauthorized) - return - } - - newsession := primitive.NewObjectID() - expired := primitive.NewDateTimeFromTime(time.Now().UTC().Add(sh.sessionTTL)) - newauth := gocommon.Authinfo{ - Accid: accid, - ServiceCode: sh.ServiceCode, - Platform: authtype, - Uid: uid, - Email: email, - Sk: newsession, - Expired: expired, - //RefreshToken: queryvals.Get("rt"), - } - - _, _, err = sh.mongoClient.UpsertOne(CollectionAuth, bson.M{"_id": newauth.Accid}, &newauth) - if err != nil { - logger.Error("authorize failed :", err) - w.WriteHeader(http.StatusInternalServerError) - return - } - - output := map[string]any{ - "sk": newsession.Hex(), - "expirein": sh.sessionTTL.Seconds(), - "newAccount": newaccount, - "accid": newauth.Accid.Hex(), - } - if *noauth { - output["noauth"] = true - } - bt, _ := json.Marshal(output) - w.Write(bt) - } else if len(session) > 0 { - sessionobj, _ := primitive.ObjectIDFromHex(session) - if !sessionobj.IsZero() { - updated, _, err := sh.mongoClient.Update(CollectionAuth, - bson.M{ - "sk": sessionobj, - }, - bson.M{ - "$currentDate": bson.M{ - "_ts": bson.M{"$type": "date"}, - }, - }, options.Update().SetUpsert(false)) - if err != nil { - logger.Error("update auth collection failed") - logger.Error(err) - return - } - - if !updated { - // 세션이 없네? - logger.Println("authorize failed. session not exists in database :", session) - w.WriteHeader(http.StatusUnauthorized) - return - } - - output := map[string]any{ - "sk": session, - "expirein": sh.sessionTTL.Seconds(), - } - bt, _ := json.Marshal(output) - w.Write(bt) - } else { - logger.Println("authorize failed. sk is not valid hex :", session) - w.WriteHeader(http.StatusBadRequest) - return - } - } else { - logger.Println("authorize failed. id empty :", queryvals) + // platform + id -> account id + createtime := primitive.NewDateTimeFromTime(time.Now().UTC()) + link, err := sh.mongoClient.FindOneAndUpdate(CollectionLink, bson.M{ + "platform": authtype, + "uid": uid, + }, bson.M{ + "$setOnInsert": bson.M{ + "create": createtime, + "email": email, + }, + }, options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true).SetProjection(bson.M{"_id": 1})) + if err != nil { + logger.Error("authorize failed :", err) + w.WriteHeader(http.StatusInternalServerError) + return } + + linkid := link["_id"].(primitive.ObjectID) + newaccid := primitive.NewObjectID() + for i := 0; i < len(sh.serviceCodeBytes); i++ { + newaccid[i] ^= sh.serviceCodeBytes[i] + } + account, err := sh.mongoClient.FindOneAndUpdate(CollectionAccount, bson.M{ + "_id": linkid, + }, bson.M{ + "$setOnInsert": bson.M{ + "accid": newaccid, + "create": createtime, + }, + }, options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true).SetProjection(bson.M{"accid": 1, "create": 1})) + if err != nil { + logger.Error("authorize failed. Update sh.ServiceName err:", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + accid := account["accid"].(primitive.ObjectID) + oldcreate := account["create"].(primitive.DateTime) + newaccount := oldcreate == createtime + + var bi *blockinfo + if sh.bl.contains(accid, &bi) { + // 블럭된 계정. 블락 정보를 알려준다. + w.Header().Add("MG-ACCOUNTBLOCK-START", strconv.FormatInt(bi.Start.Time().Unix(), 10)) + w.Header().Add("MG-ACCOUNTBLOCK-END", strconv.FormatInt(bi.End.Time().Unix(), 10)) + w.Header().Add("MG-ACCOUNTBLOCK-REASON", bi.Reason) + w.WriteHeader(http.StatusUnauthorized) + return + } + + sk, err := sh.sessionProvider.New(&session.Authorization{ + Account: accid, + Platform: authtype, + Uid: uid, + Email: email, + }) + if err != nil { + logger.Error("authorize failed. sessionProvider.New err:", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + output := map[string]any{ + "sk": sk, + "expirein": sh.sessionTTL.Seconds(), + "newAccount": newaccount, + "accid": accid.Hex(), + } + if *noauth { + output["noauth"] = true + } + bt, _ := json.Marshal(output) + w.Write(bt) } func (sh *serviceDescription) findVersionSplit(version string) []byte { diff --git a/go.mod b/go.mod index c2d4eb3..2c78c65 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/golang-jwt/jwt v3.2.2+incompatible go.mongodb.org/mongo-driver v1.11.7 google.golang.org/api v0.128.0 - repositories.action2quare.com/ayo/gocommon v0.0.0-20230830073522-021f18315726 + repositories.action2quare.com/ayo/gocommon v0.0.0-20230831053308-cde46e6a5fdb ) require ( diff --git a/go.sum b/go.sum index a407328..25893b0 100644 --- a/go.sum +++ b/go.sum @@ -339,3 +339,5 @@ repositories.action2quare.com/ayo/gocommon v0.0.0-20230830064326-66a191f4944f h1 repositories.action2quare.com/ayo/gocommon v0.0.0-20230830064326-66a191f4944f/go.mod h1:PdpZ16O1czKKxCxn+0AFNaEX/0kssYwC3G8jR0V7ybw= repositories.action2quare.com/ayo/gocommon v0.0.0-20230830073522-021f18315726 h1:HB13+b19K56B5Uih0hWCwCs5x4CvzHxZlq5ARtpe/CE= repositories.action2quare.com/ayo/gocommon v0.0.0-20230830073522-021f18315726/go.mod h1:PdpZ16O1czKKxCxn+0AFNaEX/0kssYwC3G8jR0V7ybw= +repositories.action2quare.com/ayo/gocommon v0.0.0-20230831053308-cde46e6a5fdb h1:F7BxLeUeJoBnE+5VCMuKimceSYmhdH2dQSzmyBzc4+M= +repositories.action2quare.com/ayo/gocommon v0.0.0-20230831053308-cde46e6a5fdb/go.mod h1:PdpZ16O1czKKxCxn+0AFNaEX/0kssYwC3G8jR0V7ybw= diff --git a/main.go b/main.go index 7de2944..c7effe8 100644 --- a/main.go +++ b/main.go @@ -2,9 +2,7 @@ package main import ( "context" - "math/rand" "net/http" - "time" "repositories.action2quare.com/ayo/gocommon" "repositories.action2quare.com/ayo/gocommon/flagx" @@ -21,7 +19,6 @@ func main() { flagx.Parse() logger.Println("build revision =", revision) - rand.Seed(time.Now().UnixNano()) ctx, cancel := context.WithCancel(context.Background()) mg, err := core.New(ctx)