Compare commits
71 Commits
kd-live
...
dbd22fe285
| Author | SHA1 | Date | |
|---|---|---|---|
| dbd22fe285 | |||
| 894663ed38 | |||
| ec3edbd8d5 | |||
| 938f80b460 | |||
| 843ac3340c | |||
| 97e0effc61 | |||
| 8f9b9cf402 | |||
| 53d4d4536d | |||
| f2afeac3da | |||
| cf9c4d57c7 | |||
| ddf88501a1 | |||
| 681927911c | |||
| e862ff3717 | |||
| d3e72a2e4b | |||
| 8956ba03d5 | |||
| 048ffa00b6 | |||
| ba19cc0006 | |||
| f8557078cc | |||
| eace5933a1 | |||
| e38e8a91e5 | |||
| 2076fb1b81 | |||
| f734ef099b | |||
| c0e1e229cd | |||
| b5114b5224 | |||
| a3b4ac47b8 | |||
| 45e7169c3a | |||
| 3444c17026 | |||
| 98340db8df | |||
| e7b3f59dd0 | |||
| bc82cb123c | |||
| 2165a4400b | |||
| 6ca3905fed | |||
| d5708a964f | |||
| bb9b3a9735 | |||
| da68071e97 | |||
| 2e60fac840 | |||
| dab5a35870 | |||
| a35512e327 | |||
| 8a8bd50e28 | |||
| db90ce931f | |||
| 7639c749dc | |||
| 63461676f4 | |||
| eebd3fb746 | |||
| ba4b4eea94 | |||
| e583904693 | |||
| a2def0af79 | |||
| 6ccf76d1b2 | |||
| bc58249483 | |||
| 95a7972835 | |||
| e37aaff9cb | |||
| 77cffbbe9a | |||
| d623196c10 | |||
| 06e40853ad | |||
| d873965d37 | |||
| 275b9b12e3 | |||
| 81689f7512 | |||
| e3ad826826 | |||
| 9e98b581e4 | |||
| 41641b88e9 | |||
| a4d297a944 | |||
| 418713b0c7 | |||
| 087743453c | |||
| caed2b5925 | |||
| e18dc74dc2 | |||
| 9afa1d87e7 | |||
| 3cf9466cdb | |||
| 6c73e9990e | |||
| e8aa6189be | |||
| 47284a79c2 | |||
| 0121310941 | |||
| 76a4818a66 |
@ -1,7 +1,9 @@
|
|||||||
{
|
{
|
||||||
"maingate_mongodb_url": "mongodb://...",
|
"maingate_mongodb_url": "mongodb://...",
|
||||||
|
"session_storage": "",
|
||||||
|
"session_ttl" : 3600,
|
||||||
|
|
||||||
"autologin_ttl": 604800,
|
"autologin_ttl": 604800,
|
||||||
"acc_del_ttl": 7776000,
|
|
||||||
"maximum_num_link_account": 10,
|
"maximum_num_link_account": 10,
|
||||||
"redirect_base_url": "",
|
"redirect_base_url": "",
|
||||||
"google_client_id" : "",
|
"google_client_id" : "",
|
||||||
|
|||||||
243
core/api.go
243
core/api.go
@ -160,37 +160,49 @@ func (caller apiCaller) uploadAPI(w http.ResponseWriter, r *http.Request) error
|
|||||||
|
|
||||||
func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error {
|
func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error {
|
||||||
mg := caller.mg
|
mg := caller.mg
|
||||||
|
logger.Println("blockAPI :", r.Method)
|
||||||
if r.Method == "GET" {
|
if r.Method == "GET" {
|
||||||
json.NewEncoder(w).Encode(mg.bl.all())
|
target, ok := gocommon.ReadObjectIDFormValue(r.Form, "accid")
|
||||||
|
logger.Println("Get :", target, ok)
|
||||||
|
if !ok {
|
||||||
|
// 페이지네이션 해야할 듯
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if r.Method == "PUT" {
|
} else if r.Method == "PUT" {
|
||||||
body, _ := io.ReadAll(r.Body)
|
var targets struct {
|
||||||
|
Start primitive.DateTime
|
||||||
var bipl blockinfoWithStringId
|
End primitive.DateTime
|
||||||
if err := json.Unmarshal(body, &bipl); err != nil {
|
Accounts map[primitive.ObjectID]primitive.M // accid->meta
|
||||||
|
}
|
||||||
|
if err := gocommon.MakeDecoder(r).Decode(&targets); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
accid, err := primitive.ObjectIDFromHex(bipl.StrId)
|
for accid, meta := range targets.Accounts {
|
||||||
if err != nil {
|
bi := blockinfo{
|
||||||
return err
|
Start: targets.Start,
|
||||||
}
|
End: targets.End,
|
||||||
|
Meta: meta,
|
||||||
|
}
|
||||||
|
|
||||||
bi := blockinfo{
|
_, _, err := mg.mongoClient.Update(CollectionBlock, bson.M{
|
||||||
Start: primitive.NewDateTimeFromTime(time.Unix(bipl.StartUnix, 0)),
|
"_id": accid,
|
||||||
End: primitive.NewDateTimeFromTime(time.Unix(bipl.EndUnix, 0)),
|
}, bson.M{
|
||||||
Reason: bipl.Reason,
|
"$set": &bi,
|
||||||
}
|
}, options.Update().SetUpsert(true))
|
||||||
|
if err != nil {
|
||||||
|
logger.Println("account is not blocked. err :", err)
|
||||||
|
} else {
|
||||||
|
logger.Println("account is blocked :", meta)
|
||||||
|
|
||||||
logger.Println("bi :", accid, bi)
|
bi.Accid = accid
|
||||||
|
caller.mg.bl.add(&bi)
|
||||||
_, _, err = mg.mongoClient.Update(CollectionBlock, bson.M{
|
mg.sessionProvider.RevokeAll(accid)
|
||||||
"_id": accid,
|
}
|
||||||
}, bson.M{
|
|
||||||
"$set": &bi,
|
|
||||||
}, options.Update().SetUpsert(true))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
} else if r.Method == "DELETE" {
|
} else if r.Method == "DELETE" {
|
||||||
id := r.URL.Query().Get("id")
|
id := r.URL.Query().Get("id")
|
||||||
@ -215,7 +227,7 @@ func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
mg.mongoClient.Delete(CollectionAuth, bson.M{"_id": idobj})
|
caller.mg.bl.remove(idobj)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@ -232,9 +244,9 @@ func (caller apiCaller) whitelistAPI(w http.ResponseWriter, r *http.Request) err
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
member.ExpiredAt = 0
|
member.ExpiredAt = 0
|
||||||
member.Id = primitive.NilObjectID
|
member.Id = primitive.NewObjectID()
|
||||||
_, _, err := mg.mongoClient.Update(CollectionWhitelist, bson.M{
|
_, _, err := mg.mongoClient.Update(CollectionWhitelist, bson.M{
|
||||||
"_id": primitive.NewObjectID(),
|
"_id": member.Id,
|
||||||
}, bson.M{
|
}, bson.M{
|
||||||
"$set": &member,
|
"$set": &member,
|
||||||
}, options.Update().SetUpsert(true))
|
}, options.Update().SetUpsert(true))
|
||||||
@ -274,9 +286,7 @@ func (caller apiCaller) serviceAPI(w http.ResponseWriter, r *http.Request) error
|
|||||||
if mg.service().Id.IsZero() {
|
if mg.service().Id.IsZero() {
|
||||||
logger.Println(" id is zero")
|
logger.Println(" id is zero")
|
||||||
newService := serviceDescription{
|
newService := serviceDescription{
|
||||||
ServiceDescriptionSummary: ServiceDescriptionSummary{
|
Id: primitive.NewObjectID(),
|
||||||
Id: primitive.NewObjectID(),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
if err := newService.prepare(caller.mg); err != nil {
|
if err := newService.prepare(caller.mg); err != nil {
|
||||||
logger.Println(" prepare failed :", err)
|
logger.Println(" prepare failed :", err)
|
||||||
@ -372,15 +382,62 @@ func (caller apiCaller) couponAPI(w http.ResponseWriter, r *http.Request) error
|
|||||||
logger.Println("begin listAllCouponNames")
|
logger.Println("begin listAllCouponNames")
|
||||||
listAllCouponNames(caller.mg.mongoClient, w, r)
|
listAllCouponNames(caller.mg.mongoClient, w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
case "DELETE":
|
|
||||||
// 쿠폰 삭제
|
|
||||||
logger.Println("begin deleteCoupon")
|
|
||||||
deleteCoupon(caller.mg.mongoClient, w, r)
|
|
||||||
}
|
}
|
||||||
return nil
|
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")
|
var errApiTokenMissing = errors.New("mg-x-api-token is missing")
|
||||||
|
|
||||||
func (caller apiCaller) configAPI(w http.ResponseWriter, r *http.Request) error {
|
func (caller apiCaller) configAPI(w http.ResponseWriter, r *http.Request) error {
|
||||||
@ -401,40 +458,6 @@ func (caller apiCaller) configAPI(w http.ResponseWriter, r *http.Request) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (caller apiCaller) lockcreatecharAPI(w http.ResponseWriter, r *http.Request) error {
|
|
||||||
mg, err := caller.mg.mongoClient.FindAll(CollectionService, bson.M{})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
haschr, _ := gocommon.ReadStringFormValue(r.Form, "haschr")
|
|
||||||
|
|
||||||
locked := make(map[string]any)
|
|
||||||
if haschr == "true" {
|
|
||||||
locked["lock"] = false
|
|
||||||
} else {
|
|
||||||
curregion, _ := gocommon.ReadStringFormValue(r.Form, "region")
|
|
||||||
|
|
||||||
for _, regioninfo := range mg {
|
|
||||||
region := regioninfo["divisions"].(primitive.M)
|
|
||||||
for idx, rl := range region {
|
|
||||||
if idx == curregion {
|
|
||||||
if rl.(primitive.M)["lockcreatechar"].(bool) {
|
|
||||||
locked["lock"] = true
|
|
||||||
} else {
|
|
||||||
locked["lock"] = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
create, _ := json.Marshal(locked)
|
|
||||||
w.Write(create)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type apiCaller struct {
|
type apiCaller struct {
|
||||||
userinfo map[string]any
|
userinfo map[string]any
|
||||||
globalAdmins map[string]bool
|
globalAdmins map[string]bool
|
||||||
@ -459,52 +482,34 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
var userinfo map[string]any
|
var userinfo map[string]any
|
||||||
|
|
||||||
var apiTokenObj primitive.ObjectID
|
|
||||||
if !*devflag {
|
if !*devflag {
|
||||||
apiToken := r.Header.Get("MG-X-API-TOKEN")
|
authheader := r.Header.Get("Authorization")
|
||||||
if len(apiToken) > 0 {
|
if len(authheader) == 0 {
|
||||||
if apiToken != mg.maingateConfig.ApiToken {
|
logger.Println("Authorization header is not valid :", authheader)
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
obj, err := primitive.ObjectIDFromHex(apiToken)
|
req, _ := http.NewRequest("GET", "https://graph.microsoft.com/oidc/userinfo", nil)
|
||||||
if err != nil {
|
req.Header.Add("Authorization", authheader)
|
||||||
logger.Error(err)
|
client := &http.Client{}
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apiTokenObj = obj
|
resp, err := client.Do(req)
|
||||||
} else {
|
if err != nil {
|
||||||
authheader := r.Header.Get("Authorization")
|
logger.Println("graph microsoft api call failed :", err)
|
||||||
if len(authheader) == 0 {
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
logger.Println("Authorization header is not valid :", authheader)
|
return
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
}
|
||||||
return
|
defer resp.Body.Close()
|
||||||
}
|
|
||||||
|
|
||||||
req, _ := http.NewRequest("GET", "https://graph.microsoft.com/oidc/userinfo", nil)
|
raw, _ := io.ReadAll(resp.Body)
|
||||||
req.Header.Add("Authorization", authheader)
|
if err = json.Unmarshal(raw, &userinfo); err != nil {
|
||||||
client := &http.Client{}
|
return
|
||||||
|
}
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
if _, expired := userinfo["error"]; expired {
|
||||||
if err != nil {
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
logger.Println("graph microsoft api call failed :", err)
|
return
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
raw, _ := io.ReadAll(resp.Body)
|
|
||||||
if err = json.Unmarshal(raw, &userinfo); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, expired := userinfo["error"]; expired {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -520,6 +525,20 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var apiTokenObj primitive.ObjectID
|
||||||
|
if !*devflag {
|
||||||
|
apiToken := r.Header.Get("MG-X-API-TOKEN")
|
||||||
|
if len(apiToken) > 0 {
|
||||||
|
obj, err := primitive.ObjectIDFromHex(apiToken)
|
||||||
|
if err != nil {
|
||||||
|
logger.Error(err)
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiTokenObj = obj
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logger.Println("api call :", r.URL.Path, r.Method, r.URL.Query(), userinfo)
|
logger.Println("api call :", r.URL.Path, r.Method, r.URL.Query(), userinfo)
|
||||||
caller := apiCaller{
|
caller := apiCaller{
|
||||||
userinfo: userinfo,
|
userinfo: userinfo,
|
||||||
@ -545,8 +564,8 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) {
|
|||||||
err = caller.blockAPI(w, r)
|
err = caller.blockAPI(w, r)
|
||||||
} else if strings.HasSuffix(r.URL.Path, "/coupon") {
|
} else if strings.HasSuffix(r.URL.Path, "/coupon") {
|
||||||
err = caller.couponAPI(w, r)
|
err = caller.couponAPI(w, r)
|
||||||
} else if strings.HasSuffix(r.URL.Path, "/lockcreatechar") {
|
} else if strings.HasSuffix(r.URL.Path, "/userinfo") {
|
||||||
err = caller.lockcreatecharAPI(w, r)
|
err = caller.userinfoAPI(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@ -30,7 +30,6 @@ type couponDoc struct {
|
|||||||
Total int64 `json:"total" bson:"total"`
|
Total int64 `json:"total" bson:"total"`
|
||||||
Remains []string `json:"remains,omitempty" bson:"remains,omitempty"`
|
Remains []string `json:"remains,omitempty" bson:"remains,omitempty"`
|
||||||
Used []string `json:"used,omitempty" bson:"used,omitempty"`
|
Used []string `json:"used,omitempty" bson:"used,omitempty"`
|
||||||
Expire int64 `json:"expire" bson:"expire"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeCouponKey(roundnum uint32, uid []byte) string {
|
func makeCouponKey(roundnum uint32, uid []byte) string {
|
||||||
@ -45,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]))
|
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) {
|
func makeCouponCodes(name string, count int) (string, map[string]string) {
|
||||||
checkunique := make(map[string]bool)
|
checkunique := make(map[string]bool)
|
||||||
keys := make(map[string]string)
|
keys := make(map[string]string)
|
||||||
uid := make([]byte, 4)
|
uid := make([]byte, 4)
|
||||||
|
|
||||||
roundHash, roundnum := coupon.MakeCouponRoundHash(name)
|
roundHash, roundnum := coupon.MakeCouponRoundHash(name)
|
||||||
seed := time.Now().UnixNano()
|
|
||||||
|
|
||||||
for len(keys) < count {
|
for len(keys) < count {
|
||||||
rand.Seed(seed)
|
r.Read(uid)
|
||||||
rand.Read(uid)
|
|
||||||
|
|
||||||
code := makeCouponKey(roundnum, uid)
|
code := makeCouponKey(roundnum, uid)
|
||||||
|
|
||||||
@ -63,7 +62,6 @@ func makeCouponCodes(name string, count int) (string, map[string]string) {
|
|||||||
checkunique[code] = true
|
checkunique[code] = true
|
||||||
keys[hex.EncodeToString(uid)] = code
|
keys[hex.EncodeToString(uid)] = code
|
||||||
}
|
}
|
||||||
seed = int64(binary.BigEndian.Uint32(uid))
|
|
||||||
}
|
}
|
||||||
return roundHash, keys
|
return roundHash, keys
|
||||||
}
|
}
|
||||||
@ -73,7 +71,6 @@ func generateCoupons(mongoClient gocommon.MongoClient, w http.ResponseWriter, r
|
|||||||
effect, _ := gocommon.ReadStringFormValue(r.Form, "effect")
|
effect, _ := gocommon.ReadStringFormValue(r.Form, "effect")
|
||||||
count, _ := gocommon.ReadIntegerFormValue(r.Form, "count")
|
count, _ := gocommon.ReadIntegerFormValue(r.Form, "count")
|
||||||
desc, _ := gocommon.ReadStringFormValue(r.Form, "desc")
|
desc, _ := gocommon.ReadStringFormValue(r.Form, "desc")
|
||||||
expire, _ := gocommon.ReadIntegerFormValue(r.Form, "expire")
|
|
||||||
|
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
logger.Println("[generateCoupons] count == 0")
|
logger.Println("[generateCoupons] count == 0")
|
||||||
@ -94,7 +91,6 @@ func generateCoupons(mongoClient gocommon.MongoClient, w http.ResponseWriter, r
|
|||||||
Effect: effect,
|
Effect: effect,
|
||||||
Desc: desc,
|
Desc: desc,
|
||||||
Total: -1,
|
Total: -1,
|
||||||
Expire: expire,
|
|
||||||
},
|
},
|
||||||
}, options.Update().SetUpsert(true)); err != nil {
|
}, options.Update().SetUpsert(true)); err != nil {
|
||||||
logger.Println("[generateCoupons] Update failed :", err)
|
logger.Println("[generateCoupons] Update failed :", err)
|
||||||
@ -157,7 +153,6 @@ func generateCoupons(mongoClient gocommon.MongoClient, w http.ResponseWriter, r
|
|||||||
Effect: effect,
|
Effect: effect,
|
||||||
Desc: desc,
|
Desc: desc,
|
||||||
Total: count,
|
Total: count,
|
||||||
Expire: expire,
|
|
||||||
},
|
},
|
||||||
}, options.Update().SetUpsert(true))
|
}, options.Update().SetUpsert(true))
|
||||||
}
|
}
|
||||||
@ -240,7 +235,7 @@ func queryCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *htt
|
|||||||
var coupon couponDoc
|
var coupon couponDoc
|
||||||
if err := mongoClient.FindOneAs(CollectionCoupon, bson.M{
|
if err := mongoClient.FindOneAs(CollectionCoupon, bson.M{
|
||||||
"_id": roundObj,
|
"_id": roundObj,
|
||||||
}, &coupon, options.FindOne().SetProjection(bson.M{"effect": 1, "name": 1, "reason": 1, "total": 1, "desc": 1, "expire": 1}).SetReturnKey(false)); err != nil {
|
}, &coupon, options.FindOne().SetProjection(bson.M{"effect": 1, "name": 1, "reason": 1, "total": 1, "desc": 1}).SetReturnKey(false)); err != nil {
|
||||||
logger.Println("[queryCoupon] FindOneAs failed :", err)
|
logger.Println("[queryCoupon] FindOneAs failed :", err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@ -307,7 +302,7 @@ func useCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *http.
|
|||||||
// 무한 쿠폰일 수 있으므로 존재하는지 확인
|
// 무한 쿠폰일 수 있으므로 존재하는지 확인
|
||||||
if err := mongoClient.FindOneAs(CollectionCoupon, bson.M{
|
if err := mongoClient.FindOneAs(CollectionCoupon, bson.M{
|
||||||
"_id": roundObj,
|
"_id": roundObj,
|
||||||
}, &coupon, options.FindOne().SetProjection(bson.M{"_id": 0, "effect": 1, "name": 1, "total": 1, "expire": 1})); err != nil {
|
}, &coupon, options.FindOne().SetProjection(bson.M{"_id": 0, "effect": 1, "name": 1, "reason": 1, "total": 1})); err != nil {
|
||||||
logger.Println(err)
|
logger.Println(err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
@ -319,7 +314,7 @@ func useCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *http.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 쿠폰을 하나 꺼냄
|
// 2. 쿠폰을 하나 꺼냄
|
||||||
matched, _, err := mongoClient.Update(CollectionCoupon, bson.M{
|
matched, _, err := mongoClient.Update(CollectionCoupon, bson.M{
|
||||||
"_id": roundObj,
|
"_id": roundObj,
|
||||||
"remains": key,
|
"remains": key,
|
||||||
@ -338,24 +333,18 @@ func useCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *http.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// round의 효과 읽기
|
// 3. round의 효과 읽기
|
||||||
if err := mongoClient.FindOneAndUpdateAs(CollectionCoupon, bson.M{
|
if err := mongoClient.FindOneAndUpdateAs(CollectionCoupon, bson.M{
|
||||||
"_id": roundObj,
|
"_id": roundObj,
|
||||||
}, bson.M{
|
}, bson.M{
|
||||||
"$push": bson.M{"used": key},
|
"$push": bson.M{"used": key},
|
||||||
}, &coupon, options.FindOneAndUpdate().SetProjection(bson.M{"effect": 1, "expire": 1})); err != nil {
|
}, &coupon, options.FindOneAndUpdate().SetProjection(bson.M{"effect": 1})); err != nil {
|
||||||
logger.Println(err)
|
logger.Println(err)
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if coupon.Expire < time.Now().Unix() {
|
|
||||||
// 쿠폰 만료시간 경과
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(coupon.Effect) == 0 {
|
if len(coupon.Effect) == 0 {
|
||||||
// 쿠폰이 없네?
|
// 쿠폰이 없네?
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
@ -386,22 +375,3 @@ func useCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *http.
|
|||||||
|
|
||||||
w.Write([]byte(coupon.Effect))
|
w.Write([]byte(coupon.Effect))
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteCoupon(mongoClient gocommon.MongoClient, w http.ResponseWriter, r *http.Request) {
|
|
||||||
code, _ := gocommon.ReadStringFormValue(r.Form, "name")
|
|
||||||
if len(code) == 0 {
|
|
||||||
logger.Println("coupon delete code error")
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := mongoClient.Delete(CollectionCoupon, bson.M{
|
|
||||||
"name": code,
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Println("coupon delete error")
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,39 +1,9 @@
|
|||||||
package core
|
package core
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
|
||||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
|
||||||
"repositories.action2quare.com/ayo/gocommon"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMakeLocalUniqueId(t *testing.T) {
|
func TestMakeLocalUniqueId(t *testing.T) {
|
||||||
ts := int64(1690815600)
|
|
||||||
start := primitive.NewDateTimeFromTime(time.Unix(ts, 0))
|
|
||||||
ts = int64(1693493999)
|
|
||||||
end := primitive.NewDateTimeFromTime(time.Unix(ts, 0))
|
|
||||||
|
|
||||||
fmt.Println(start.Time().Format(time.RFC3339))
|
|
||||||
fmt.Println(end.Time().Format(time.RFC3339))
|
|
||||||
|
|
||||||
mongoClient, err := gocommon.NewMongoClient(context.Background(), "mongodb://121.134.91.160:27018/mountain-maingate?replicaSet=rs0&retrywrites=true", "maingate")
|
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
bi := blockinfo{
|
|
||||||
Start: start,
|
|
||||||
End: end,
|
|
||||||
Reason: "test",
|
|
||||||
}
|
|
||||||
mongoClient.Update(CollectionBlock, bson.M{
|
|
||||||
"_id": primitive.NewObjectID(),
|
|
||||||
}, bson.M{
|
|
||||||
"$set": &bi,
|
|
||||||
}, options.Update().SetUpsert(true))
|
|
||||||
}
|
}
|
||||||
|
|||||||
336
core/maingate.go
336
core/maingate.go
@ -9,11 +9,9 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"math/big"
|
"math/big"
|
||||||
"math/rand"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"runtime/debug"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"text/template"
|
"text/template"
|
||||||
@ -23,6 +21,7 @@ import (
|
|||||||
"repositories.action2quare.com/ayo/gocommon"
|
"repositories.action2quare.com/ayo/gocommon"
|
||||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||||
|
"repositories.action2quare.com/ayo/gocommon/session"
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt"
|
"github.com/golang-jwt/jwt"
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
@ -37,10 +36,10 @@ import (
|
|||||||
|
|
||||||
var devflag = flagx.Bool("dev", false, "")
|
var devflag = flagx.Bool("dev", false, "")
|
||||||
var noauth = flagx.Bool("noauth", false, "")
|
var noauth = flagx.Bool("noauth", false, "")
|
||||||
|
var authtype = flagx.String("auth", "on", "on|off|both")
|
||||||
|
|
||||||
var (
|
var (
|
||||||
CollectionLink = gocommon.CollectionName("link")
|
CollectionLink = gocommon.CollectionName("link")
|
||||||
CollectionAuth = gocommon.CollectionName("auth")
|
|
||||||
CollectionWhitelist = gocommon.CollectionName("whitelist")
|
CollectionWhitelist = gocommon.CollectionName("whitelist")
|
||||||
CollectionService = gocommon.CollectionName("service")
|
CollectionService = gocommon.CollectionName("service")
|
||||||
CollectionAccount = gocommon.CollectionName("account")
|
CollectionAccount = gocommon.CollectionName("account")
|
||||||
@ -59,6 +58,7 @@ const (
|
|||||||
AuthPlatformMicrosoft = "microsoft"
|
AuthPlatformMicrosoft = "microsoft"
|
||||||
AuthPlatformApple = "apple"
|
AuthPlatformApple = "apple"
|
||||||
AuthPlatformTwitter = "twitter"
|
AuthPlatformTwitter = "twitter"
|
||||||
|
AuthPlatformHybeim = "hybeim"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -74,56 +74,10 @@ func SessionTTL() time.Duration {
|
|||||||
return sessionTTL
|
return sessionTTL
|
||||||
}
|
}
|
||||||
|
|
||||||
type mongoAuthCell struct {
|
|
||||||
src *gocommon.Authinfo
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ac *mongoAuthCell) ToAuthinfo() *gocommon.Authinfo {
|
|
||||||
if ac.src == nil {
|
|
||||||
logger.Error("mongoAuthCell ToAuthinfo failed. ac.src is nil")
|
|
||||||
}
|
|
||||||
return ac.src
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ac *mongoAuthCell) ToBytes() []byte {
|
|
||||||
bt, _ := json.Marshal(ac.src)
|
|
||||||
return bt
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeAuthCollection(mongoClient gocommon.MongoClient, sessionTTL time.Duration) *gocommon.AuthCollection {
|
|
||||||
authcoll := gocommon.MakeAuthCollection(sessionTTL)
|
|
||||||
authcoll.SessionRemoved = func(sk string) {
|
|
||||||
skid, _ := primitive.ObjectIDFromHex(sk)
|
|
||||||
mongoClient.Delete(CollectionAuth, bson.M{
|
|
||||||
"sk": skid,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
authcoll.QuerySession = func(sk string, token string) gocommon.AuthinfoCell {
|
|
||||||
skid, _ := primitive.ObjectIDFromHex(sk)
|
|
||||||
var outcell mongoAuthCell
|
|
||||||
err := mongoClient.FindOneAs(CollectionAuth, bson.M{
|
|
||||||
"sk": skid,
|
|
||||||
}, &outcell.src, options.FindOne().SetHint("skonly"))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("QuerySession failed :", err)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if outcell.src == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return &outcell
|
|
||||||
}
|
|
||||||
|
|
||||||
return authcoll
|
|
||||||
}
|
|
||||||
|
|
||||||
type maingateConfig struct {
|
type maingateConfig struct {
|
||||||
|
session.SessionConfig `json:",inline"`
|
||||||
|
MustUseChecksum bool `json:"maingate_must_checksum"`
|
||||||
Mongo string `json:"maingate_mongodb_url"`
|
Mongo string `json:"maingate_mongodb_url"`
|
||||||
SessionTTL int64 `json:"maingate_session_ttl"`
|
|
||||||
ApiToken string `json:"maingate_api_token"`
|
|
||||||
Autologin_ttl int64 `json:"autologin_ttl"`
|
Autologin_ttl int64 `json:"autologin_ttl"`
|
||||||
AccDelTTL int64 `json:"acc_del_ttl"`
|
AccDelTTL int64 `json:"acc_del_ttl"`
|
||||||
MaximumNumLinkAccount int64 `json:"maximum_num_link_account"`
|
MaximumNumLinkAccount int64 `json:"maximum_num_link_account"`
|
||||||
@ -146,6 +100,12 @@ type maingateConfig struct {
|
|||||||
FirebaseAdminSDKCredentialFile string `json:"firebase_admin_sdk_credentialfile"`
|
FirebaseAdminSDKCredentialFile string `json:"firebase_admin_sdk_credentialfile"`
|
||||||
SteamAppId string `json:"steam_app_id"`
|
SteamAppId string `json:"steam_app_id"`
|
||||||
SteamPublisherAuthKey string `json:"steam_publisher_authkey"`
|
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
|
Firebase_Google_Analytics_JS_SDK_Config
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,13 +135,16 @@ func (ga *globalAdmins) parse() {
|
|||||||
ga.modtime = gocommon.ConfigModTime()
|
ga.modtime = gocommon.ConfigModTime()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type firebaseClient struct {
|
||||||
|
firebaseAppClient *auth.Client
|
||||||
|
firebaseAppContext context.Context
|
||||||
|
}
|
||||||
|
|
||||||
// Maingate :
|
// Maingate :
|
||||||
type Maingate struct {
|
type Maingate struct {
|
||||||
maingateConfig
|
|
||||||
|
|
||||||
mongoClient gocommon.MongoClient
|
mongoClient gocommon.MongoClient
|
||||||
|
|
||||||
auths *gocommon.AuthCollection
|
sessionProvider session.Provider
|
||||||
//services servicelist
|
//services servicelist
|
||||||
serviceptr unsafe.Pointer
|
serviceptr unsafe.Pointer
|
||||||
admins unsafe.Pointer
|
admins unsafe.Pointer
|
||||||
@ -192,13 +155,14 @@ type Maingate struct {
|
|||||||
authorizationEndpoints map[string]string
|
authorizationEndpoints map[string]string
|
||||||
userinfoEndpoint map[string]string
|
userinfoEndpoint map[string]string
|
||||||
jwksUri map[string]string
|
jwksUri map[string]string
|
||||||
firebaseAppClient *auth.Client
|
|
||||||
firebaseAppContext context.Context
|
firebase *firebaseClient
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var config maingateConfig
|
||||||
|
|
||||||
// New :
|
// New :
|
||||||
func New(ctx context.Context) (*Maingate, error) {
|
func New(ctx context.Context) (*Maingate, error) {
|
||||||
var config maingateConfig
|
|
||||||
if err := gocommon.LoadConfig(&config); err != nil {
|
if err := gocommon.LoadConfig(&config); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -208,12 +172,15 @@ func New(ctx context.Context) (*Maingate, error) {
|
|||||||
admins.parse()
|
admins.parse()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(config.SessionStorage) == 0 {
|
||||||
|
return nil, errors.New("maingate_session_storage is missing")
|
||||||
|
}
|
||||||
|
|
||||||
if config.SessionTTL == 0 {
|
if config.SessionTTL == 0 {
|
||||||
config.SessionTTL = 3600
|
config.SessionTTL = 3600
|
||||||
}
|
}
|
||||||
|
|
||||||
mg := Maingate{
|
mg := Maingate{
|
||||||
maingateConfig: config,
|
|
||||||
admins: unsafe.Pointer(&admins),
|
admins: unsafe.Pointer(&admins),
|
||||||
tokenEndpoints: make(map[string]string),
|
tokenEndpoints: make(map[string]string),
|
||||||
authorizationEndpoints: make(map[string]string),
|
authorizationEndpoints: make(map[string]string),
|
||||||
@ -226,18 +193,29 @@ func New(ctx context.Context) (*Maingate, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !*noauth {
|
if len(*authtype) == 0 {
|
||||||
opt := option.WithCredentialsFile(mg.FirebaseAdminSDKCredentialFile)
|
*authtype = "on"
|
||||||
firebaseApp, err := firebase.NewApp(context.Background(), nil, opt)
|
}
|
||||||
if err != nil {
|
|
||||||
logger.Error("firebase admin error initializing app failed :", err)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
mg.firebaseAppContext = ctx
|
if !*noauth && (*authtype == "on" || *authtype == "both") {
|
||||||
mg.firebaseAppClient, err = firebaseApp.Auth(mg.firebaseAppContext)
|
if len(config.FirebaseAdminSDKCredentialFile) > 0 {
|
||||||
if err != nil {
|
opt := option.WithCredentialsFile(config.FirebaseAdminSDKCredentialFile)
|
||||||
logger.Println("FirebaseAppClient error getting Auth client:", err)
|
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,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -302,110 +280,104 @@ func (mg *Maingate) discoverOpenIdConfiguration(name string, url string) error {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeErrorWithStack(err error) error {
|
|
||||||
return fmt.Errorf("%s\n%s", err.Error(), string(debug.Stack()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mg *Maingate) prepare(context context.Context) (err error) {
|
func (mg *Maingate) prepare(context context.Context) (err error) {
|
||||||
if err := mg.discoverOpenIdConfiguration(AuthPlatformMicrosoft, "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"); err != nil {
|
if err := mg.discoverOpenIdConfiguration(AuthPlatformMicrosoft, "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
if err := mg.discoverOpenIdConfiguration("google", "https://accounts.google.com/.well-known/openid-configuration"); err != nil {
|
if err := mg.discoverOpenIdConfiguration("google", "https://accounts.google.com/.well-known/openid-configuration"); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// redis에서 env를 가져온 후에
|
// redis에서 env를 가져온 후에
|
||||||
mg.mongoClient, err = gocommon.NewMongoClient(context, mg.Mongo, "maingate")
|
mg.mongoClient, err = gocommon.NewMongoClient(context, config.Mongo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionCouponUse, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionCouponUse, map[string]bson.D{
|
||||||
"idrounds": {{Key: "_id", Value: 1}, {Key: "rounds", Value: 1}},
|
"idrounds": {{Key: "_id", Value: 1}, {Key: "rounds", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return err
|
return logger.ErrorWithCallStack(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{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionLink, map[string]bson.D{
|
||||||
"platformuid": {{Key: "platform", Value: 1}, {Key: "uid", Value: 1}},
|
"platformuid": {{Key: "platform", Value: 1}, {Key: "uid", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionLink, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionLink, map[string]bson.D{
|
||||||
"emailplatform": {{Key: "email", Value: 1}, {Key: "platform", Value: 1}},
|
"emailplatform": {{Key: "email", Value: 1}, {Key: "platform", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeIndices(CollectionAccount, map[string]bson.D{
|
if err = mg.mongoClient.MakeIndices(CollectionAccount, map[string]bson.D{
|
||||||
"accid": {{Key: "accid", Value: 1}},
|
"accid": {{Key: "accid", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionFile, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionFile, map[string]bson.D{
|
||||||
"keyonly": {{Key: "key", Value: 1}},
|
"keyonly": {{Key: "key", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionAccount, int32(mg.AccDelTTL)); err != nil {
|
if err = mg.mongoClient.MakeExpireIndex(CollectionAccount, int32(config.AccDelTTL)); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionLink, int32(mg.AccDelTTL)); err != nil {
|
if err = mg.mongoClient.MakeExpireIndex(CollectionLink, int32(config.AccDelTTL)); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete대신 _ts로 expire시킴. pipeline에 삭제 알려주기 위함
|
// Delete대신 _ts로 expire시킴. pipeline에 삭제 알려주기 위함
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionWhitelist, 10); err != nil {
|
if err = mg.mongoClient.MakeExpireIndex(CollectionWhitelist, 10); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionAuth, int32(mg.SessionTTL+300)); err != nil {
|
if *devflag {
|
||||||
return makeErrorWithStack(err)
|
// 에러 체크하지 말것
|
||||||
|
mg.mongoClient.DropIndex(CollectionBlock, "codeaccid")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionBlock, int32(3)); err != nil {
|
if err = mg.mongoClient.MakeExpireIndex(CollectionBlock, int32(3)); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionPlatformLoginToken, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionPlatformLoginToken, map[string]bson.D{
|
||||||
"platformauthtoken": {{Key: "platform", Value: 1}, {Key: "key", Value: 1}},
|
"platformauthtoken": {{Key: "platform", Value: 1}, {Key: "key", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeExpireIndex(CollectionPlatformLoginToken, int32(mg.SessionTTL+300)); err != nil {
|
if err = mg.mongoClient.MakeExpireIndex(CollectionPlatformLoginToken, int32(config.SessionTTL+300)); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionUserToken, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionUserToken, map[string]bson.D{
|
||||||
"platformusertoken": {{Key: "platform", Value: 1}, {Key: "userid", Value: 1}},
|
"platformusertoken": {{Key: "platform", Value: 1}, {Key: "userid", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionGamepotUserInfo, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionGamepotUserInfo, map[string]bson.D{
|
||||||
"gamepotuserid": {{Key: "gamepotuserid", Value: 1}},
|
"gamepotuserid": {{Key: "gamepotuserid", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = mg.mongoClient.MakeUniqueIndices(CollectionFirebaseUserInfo, map[string]bson.D{
|
if err = mg.mongoClient.MakeUniqueIndices(CollectionFirebaseUserInfo, map[string]bson.D{
|
||||||
"firebaseuserid": {{Key: "firebaseuserid", Value: 1}},
|
"firebaseuserid": {{Key: "firebaseuserid", Value: 1}},
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
mg.auths = makeAuthCollection(mg.mongoClient, time.Duration(mg.SessionTTL*int64(time.Second)))
|
mg.sessionProvider, err = session.NewProviderWithConfig(context, config.SessionConfig)
|
||||||
|
if err != nil {
|
||||||
|
return logger.ErrorWithCallStack(err)
|
||||||
|
}
|
||||||
|
|
||||||
var preall []struct {
|
var preall []struct {
|
||||||
Link string `bson:"link"`
|
Link string `bson:"link"`
|
||||||
@ -414,7 +386,7 @@ func (mg *Maingate) prepare(context context.Context) (err error) {
|
|||||||
if err = mg.mongoClient.FindAllAs(CollectionFile, nil, &preall, options.Find().SetProjection(bson.M{
|
if err = mg.mongoClient.FindAllAs(CollectionFile, nil, &preall, options.Find().SetProjection(bson.M{
|
||||||
"link": 1,
|
"link": 1,
|
||||||
})); err != nil {
|
})); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, pre := range preall {
|
for _, pre := range preall {
|
||||||
@ -429,56 +401,57 @@ func (mg *Maingate) prepare(context context.Context) (err error) {
|
|||||||
"_id": pre.Id,
|
"_id": pre.Id,
|
||||||
}, &fulldoc)
|
}, &fulldoc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
err = fulldoc.Save()
|
err = fulldoc.Save()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var whites []*whitelistmember
|
var whites []*whitelistmember
|
||||||
if err := mg.mongoClient.AllAs(CollectionWhitelist, &whites, options.Find().SetReturnKey(false)); err != nil {
|
if err := mg.mongoClient.AllAs(CollectionWhitelist, &whites, options.Find().SetReturnKey(false)); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
mg.wl.init(whites)
|
mg.wl.init(whites)
|
||||||
|
|
||||||
var blocks []*blockinfo
|
var blocks []*blockinfo
|
||||||
if err := mg.mongoClient.AllAs(CollectionBlock, &blocks); err != nil {
|
if err := mg.mongoClient.AllAs(CollectionBlock, &blocks); err != nil {
|
||||||
return makeErrorWithStack(err)
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.Println("allblocks :", blocks)
|
||||||
mg.bl.init(blocks)
|
mg.bl.init(blocks)
|
||||||
|
|
||||||
go watchAuthCollection(context, mg.auths, mg.mongoClient)
|
|
||||||
go mg.wl.watchCollection(context, CollectionWhitelist, mg.mongoClient)
|
go mg.wl.watchCollection(context, CollectionWhitelist, mg.mongoClient)
|
||||||
go mg.bl.watchCollection(context, CollectionBlock, mg.mongoClient)
|
go mg.bl.watchCollection(context, CollectionBlock, mg.mongoClient)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var portptr = flagx.Int("port", 80, "")
|
||||||
|
|
||||||
func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMux, prefix string) error {
|
func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMux, prefix string) error {
|
||||||
var allServices []*serviceDescription
|
var allServices []*serviceDescription
|
||||||
if err := mg.mongoClient.AllAs(CollectionService, &allServices, options.Find().SetReturnKey(false)); err != nil {
|
if err := mg.mongoClient.AllAs(CollectionService, &allServices, options.Find().SetReturnKey(false)); err != nil {
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(allServices) > 0 {
|
if len(allServices) > 0 {
|
||||||
only := allServices[0]
|
only := allServices[0]
|
||||||
only.prepare(mg)
|
only.prepare(mg)
|
||||||
|
only.mustUseChecksum = config.MustUseChecksum
|
||||||
|
|
||||||
atomic.StorePointer(&mg.serviceptr, unsafe.Pointer(only))
|
atomic.StorePointer(&mg.serviceptr, unsafe.Pointer(only))
|
||||||
} else {
|
} else {
|
||||||
empty := serviceDescription{
|
empty := serviceDescription{
|
||||||
ServiceDescriptionSummary: ServiceDescriptionSummary{
|
Id: primitive.NewObjectID(),
|
||||||
Id: primitive.NewObjectID(),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if *devflag {
|
if *devflag {
|
||||||
host, _ := os.Hostname()
|
|
||||||
addrs, err := net.InterfaceAddrs()
|
addrs, err := net.InterfaceAddrs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
ipaddr := "127.0.0.1"
|
ipaddr := "127.0.0.1"
|
||||||
for _, addr := range addrs {
|
for _, addr := range addrs {
|
||||||
@ -490,14 +463,13 @@ func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMu
|
|||||||
}
|
}
|
||||||
|
|
||||||
empty.Divisions = map[string]*Division{
|
empty.Divisions = map[string]*Division{
|
||||||
host: {
|
"default": {
|
||||||
DivisionForUser: DivisionForUser{
|
DivisionForUser: DivisionForUser{
|
||||||
Priority: 0,
|
Priority: 0,
|
||||||
State: DivisionState_FullOpen,
|
State: DivisionState_FullOpen,
|
||||||
LockCreateChar: false,
|
|
||||||
},
|
},
|
||||||
|
|
||||||
Url: fmt.Sprintf("http://%s/warehouse", ipaddr),
|
Url: fmt.Sprintf("http://%s:%d/warehouse", ipaddr, *portptr),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -511,21 +483,29 @@ func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMu
|
|||||||
}, options.Update().SetUpsert(true))
|
}, options.Update().SetUpsert(true))
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Println("Service is registered :", mg.service().ServiceCode)
|
if *devflag {
|
||||||
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, mg.service().ServiceCode, "/"), func(w http.ResponseWriter, r *http.Request) {
|
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "/"), func(w http.ResponseWriter, r *http.Request) {
|
||||||
mg.service().serveHTTP(w, r)
|
// mg.service()를 요청마다 불러야 함
|
||||||
})
|
mg.service().serveHTTP_dev(w, r)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
pattern := gocommon.MakeHttpHandlerPattern(prefix, "/")
|
||||||
|
logger.Println("pattern registered :", pattern)
|
||||||
|
serveMux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// mg.service()를 요청마다 불러야 함
|
||||||
|
mg.service().serveHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "api/"), mg.api)
|
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "api/"), mg.api)
|
||||||
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "query/"), mg.query)
|
|
||||||
|
|
||||||
configraw, _ := json.Marshal(mg.maingateConfig)
|
configraw, _ := json.Marshal(config)
|
||||||
var convertedConfig map[string]any
|
var convertedConfig map[string]any
|
||||||
if err := json.Unmarshal(configraw, &convertedConfig); err != nil {
|
if err := json.Unmarshal(configraw, &convertedConfig); err != nil {
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "config"), func(w http.ResponseWriter, r *http.Request) {
|
serveMux.HandleFunc(gocommon.MakeHttpHandlerPattern(prefix, "config"), func(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -558,7 +538,7 @@ func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMu
|
|||||||
|
|
||||||
if err := os.MkdirAll("static", os.ModePerm); err != nil {
|
if err := os.MkdirAll("static", os.ModePerm); err != nil {
|
||||||
// 일반 엔드유저한테 오픈할 static 페이지
|
// 일반 엔드유저한테 오픈할 static 페이지
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfsx := http.FileServer(http.Dir("console"))
|
cfsx := http.FileServer(http.Dir("console"))
|
||||||
@ -600,6 +580,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", 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.watchServiceCollection(ctx, serveMux, prefix)
|
||||||
go mg.watchFileCollection(ctx, serveMux, prefix)
|
go mg.watchFileCollection(ctx, serveMux, prefix)
|
||||||
// fsx := http.FileServer(http.Dir("console"))
|
// fsx := http.FileServer(http.Dir("console"))
|
||||||
@ -609,59 +591,11 @@ func (mg *Maingate) RegisterHandlers(ctx context.Context, serveMux *http.ServeMu
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) query(w http.ResponseWriter, r *http.Request) {
|
|
||||||
defer func() {
|
|
||||||
s := recover()
|
|
||||||
if s != nil {
|
|
||||||
logger.Error(s)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
io.Copy(io.Discard, r.Body)
|
|
||||||
r.Body.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
queryvals := r.URL.Query()
|
|
||||||
sk := queryvals.Get("sk")
|
|
||||||
|
|
||||||
if len(sk) == 0 {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
info := mg.auths.Find(sk)
|
|
||||||
if info == nil {
|
|
||||||
logger.Println("session key is not valid :", sk)
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !*devflag {
|
|
||||||
apitoken := r.Header.Get("MG-X-API-TOKEN")
|
|
||||||
if len(apitoken) == 0 {
|
|
||||||
logger.Println("MG-X-API-TOKEN is missing")
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apitokenObj, _ := primitive.ObjectIDFromHex(apitoken)
|
|
||||||
if !mg.service().isValidToken(apitokenObj) {
|
|
||||||
logger.Println("MG-X-API-TOKEN is invalid :", apitoken)
|
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bt, _ := json.Marshal(info)
|
|
||||||
w.Write(bt)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mg *Maingate) GeneratePlatformLoginNonceKey() string {
|
func (mg *Maingate) GeneratePlatformLoginNonceKey() string {
|
||||||
const allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
const allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
b := make([]byte, 52)
|
b := make([]byte, 52)
|
||||||
for i := range b {
|
for i := range b {
|
||||||
b[i] = allowed[rand.Intn(len(allowed))]
|
b[i] = allowed[r.Intn(len(allowed))]
|
||||||
}
|
}
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
@ -675,7 +609,7 @@ func (mg *Maingate) GetUserBrowserInfo(r *http.Request) (string, error) {
|
|||||||
|
|
||||||
cookie, err := r.Cookie("ActionSquareSessionExtraInfo")
|
cookie, err := r.Cookie("ActionSquareSessionExtraInfo")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
//requestinfo := fmt.Sprintf("%s_%s", cookie.Value, host) //-- RemoteAddr체크는 로드밸런서 IP 찍히는 문제 때문에 제외한다.
|
//requestinfo := fmt.Sprintf("%s_%s", cookie.Value, host) //-- RemoteAddr체크는 로드밸런서 IP 찍히는 문제 때문에 제외한다.
|
||||||
@ -697,7 +631,7 @@ func (mg *Maingate) setUserToken(info usertokeninfo) error {
|
|||||||
"accesstoken_expire_time": info.accesstoken_expire_time,
|
"accesstoken_expire_time": info.accesstoken_expire_time,
|
||||||
},
|
},
|
||||||
}, options.Update().SetUpsert(true))
|
}, options.Update().SetUpsert(true))
|
||||||
return err
|
return logger.ErrorWithCallStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) getUserTokenWithCheck(platform string, userid string, brinfo string) (usertokeninfo, error) {
|
func (mg *Maingate) getUserTokenWithCheck(platform string, userid string, brinfo string) (usertokeninfo, error) {
|
||||||
@ -722,7 +656,7 @@ func (mg *Maingate) getUserTokenWithCheck(platform string, userid string, brinfo
|
|||||||
|
|
||||||
updatetime, ok := found["lastupdate"].(int64)
|
updatetime, ok := found["lastupdate"].(int64)
|
||||||
|
|
||||||
if !ok || time.Now().Unix()-updatetime < mg.maingateConfig.Autologin_ttl {
|
if !ok || time.Now().Unix()-updatetime < config.Autologin_ttl {
|
||||||
info.platform = platform
|
info.platform = platform
|
||||||
info.userid = userid
|
info.userid = userid
|
||||||
info.brinfo = brinfo
|
info.brinfo = brinfo
|
||||||
@ -771,6 +705,8 @@ func (mg *Maingate) updateUserinfo(info usertokeninfo) (bool, string, string) {
|
|||||||
success, userid, email = mg.platform_google_getuserinfo(info)
|
success, userid, email = mg.platform_google_getuserinfo(info)
|
||||||
case AuthPlatformSteamSDK:
|
case AuthPlatformSteamSDK:
|
||||||
success, userid, email = mg.platform_steamsdk_getuserinfo(info)
|
success, userid, email = mg.platform_steamsdk_getuserinfo(info)
|
||||||
|
case AuthPlatformHybeim:
|
||||||
|
success, userid, email = mg.platform_hybeim_getuserinfo(info)
|
||||||
case AuthPlatformFirebaseAuth:
|
case AuthPlatformFirebaseAuth:
|
||||||
success, userid, email = mg.platform_firebase_getuserinfo(info)
|
success, userid, email = mg.platform_firebase_getuserinfo(info)
|
||||||
}
|
}
|
||||||
@ -811,18 +747,13 @@ func (mg *Maingate) getProviderInfo(platform string, uid string) (string, string
|
|||||||
if provider == "" || providerid == "" {
|
if provider == "" || providerid == "" {
|
||||||
return "", "", errors.New("getProviderInfo - firebase info not found: " + provider + " / " + providerid)
|
return "", "", errors.New("getProviderInfo - firebase info not found: " + provider + " / " + providerid)
|
||||||
}
|
}
|
||||||
case "":
|
|
||||||
//guest auth
|
|
||||||
providerid = uid
|
|
||||||
if providerid == "" {
|
|
||||||
return "", "", errors.New("getProviderInfo - guest provider id not found: " + provider + " / " + providerid)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
provider = platform
|
provider = platform
|
||||||
providerid = uid
|
providerid = uid
|
||||||
if provider == "" || providerid == "" {
|
}
|
||||||
return "", "", errors.New("getProviderInfo - provider info not found: " + provider + " / " + providerid)
|
|
||||||
}
|
if provider == "" || providerid == "" {
|
||||||
|
return "", "", errors.New("getProviderInfo - provider info not found: " + provider + " / " + providerid)
|
||||||
}
|
}
|
||||||
|
|
||||||
return provider, providerid, nil
|
return provider, providerid, nil
|
||||||
@ -986,25 +917,16 @@ func JWTparseCode(keyurl string, code string) (string, string, string) {
|
|||||||
return claims["sub"].(string), email, nonce
|
return claims["sub"].(string), email, nonce
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) google_analytics_html(w http.ResponseWriter, r *http.Request) {
|
|
||||||
parsedTemplate, _ := template.ParseFiles("template/track-event.html")
|
|
||||||
err := parsedTemplate.Execute(w, nil)
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("Error executing template :", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (mg *Maingate) google_analytics_js(w http.ResponseWriter, r *http.Request) {
|
func (mg *Maingate) google_analytics_js(w http.ResponseWriter, r *http.Request) {
|
||||||
fgaconfig := Firebase_Google_Analytics_JS_SDK_Config{
|
fgaconfig := Firebase_Google_Analytics_JS_SDK_Config{
|
||||||
FGA_apiKey: mg.FGA_apiKey,
|
FGA_apiKey: config.FGA_apiKey,
|
||||||
FGA_authDomain: mg.FGA_authDomain,
|
FGA_authDomain: config.FGA_authDomain,
|
||||||
FGA_databaseURL: mg.FGA_databaseURL,
|
FGA_databaseURL: config.FGA_databaseURL,
|
||||||
FGA_projectId: mg.FGA_projectId,
|
FGA_projectId: config.FGA_projectId,
|
||||||
FGA_storageBucket: mg.FGA_storageBucket,
|
FGA_storageBucket: config.FGA_storageBucket,
|
||||||
FGA_messagingSenderId: mg.FGA_messagingSenderId,
|
FGA_messagingSenderId: config.FGA_messagingSenderId,
|
||||||
FGA_appId: mg.FGA_appId,
|
FGA_appId: config.FGA_appId,
|
||||||
FGA_measurementId: mg.FGA_measurementId,
|
FGA_measurementId: config.FGA_measurementId,
|
||||||
}
|
}
|
||||||
parsedTemplate, _ := template.ParseFiles("template/fb-ga.min.js")
|
parsedTemplate, _ := template.ParseFiles("template/fb-ga.min.js")
|
||||||
err := parsedTemplate.Execute(w, fgaconfig)
|
err := parsedTemplate.Execute(w, fgaconfig)
|
||||||
|
|||||||
@ -84,24 +84,6 @@ func (p *memberContainerPtr[K, T]) all() []T {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *memberContainerPtr[K, T]) contains(key K, out *T) bool {
|
|
||||||
ptr := atomic.LoadPointer(&p.ptr)
|
|
||||||
src := (*map[K]T)(ptr)
|
|
||||||
|
|
||||||
found, exists := (*src)[key]
|
|
||||||
if exists {
|
|
||||||
if found.Expired() {
|
|
||||||
p.remove(key)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if out != nil {
|
|
||||||
*out = found
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *memberContainerPtr[K, T]) watchCollection(parentctx context.Context, coll gocommon.CollectionName, mc gocommon.MongoClient) {
|
func (p *memberContainerPtr[K, T]) watchCollection(parentctx context.Context, coll gocommon.CollectionName, mc gocommon.MongoClient) {
|
||||||
defer func() {
|
defer func() {
|
||||||
s := recover()
|
s := recover()
|
||||||
|
|||||||
@ -95,8 +95,8 @@ func (mg *Maingate) platform_apple_get_login_url(w http.ResponseWriter, r *http.
|
|||||||
}
|
}
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.AppleCientId)
|
params.Add("client_id", config.AppleCientId)
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformApple)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformApple)
|
||||||
|
|
||||||
params.Add("response_type", "code id_token")
|
params.Add("response_type", "code id_token")
|
||||||
params.Add("scope", "name email")
|
params.Add("scope", "name email")
|
||||||
@ -146,7 +146,7 @@ func (mg *Maingate) platform_apple_authorize(w http.ResponseWriter, r *http.Requ
|
|||||||
}
|
}
|
||||||
http.SetCookie(w, &cookie)
|
http.SetCookie(w, &cookie)
|
||||||
|
|
||||||
http.Redirect(w, r, mg.RedirectBaseUrl+"/authorize_result/"+AuthPlatformApple, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
http.Redirect(w, r, config.RedirectBaseUrl+"/authorize_result/"+AuthPlatformApple, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) platform_apple_authorize_result(w http.ResponseWriter, r *http.Request) {
|
func (mg *Maingate) platform_apple_authorize_result(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -208,17 +208,17 @@ func (mg *Maingate) platform_apple_authorize_result(w http.ResponseWriter, r *ht
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generate the client secret used to authenticate with Apple's validation servers
|
// Generate the client secret used to authenticate with Apple's validation servers
|
||||||
secret, err := generateClientSecret(mg.ApplePrivateKey, mg.AppleTeamId, mg.AppleServiceId, mg.AppleKeyId)
|
secret, err := generateClientSecret(config.ApplePrivateKey, config.AppleTeamId, config.AppleServiceId, config.AppleKeyId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("error generating secret: ", err)
|
logger.Error("error generating secret: ", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
vReq := Apple_WebValidationTokenRequest{
|
vReq := Apple_WebValidationTokenRequest{
|
||||||
ClientID: mg.AppleServiceId,
|
ClientID: config.AppleServiceId,
|
||||||
ClientSecret: secret,
|
ClientSecret: secret,
|
||||||
Code: code,
|
Code: code,
|
||||||
RedirectURI: mg.RedirectBaseUrl + "/authorize/" + AuthPlatformApple, // This URL must be validated with apple in your service
|
RedirectURI: config.RedirectBaseUrl + "/authorize/" + AuthPlatformApple, // This URL must be validated with apple in your service
|
||||||
}
|
}
|
||||||
|
|
||||||
var resp Apple_ValidationResponse
|
var resp Apple_ValidationResponse
|
||||||
@ -268,14 +268,14 @@ func (mg *Maingate) platform_apple_authorize_result(w http.ResponseWriter, r *ht
|
|||||||
|
|
||||||
func (mg *Maingate) platform_apple_getuserinfo(refreshToken string) (bool, string, string) {
|
func (mg *Maingate) platform_apple_getuserinfo(refreshToken string) (bool, string, string) {
|
||||||
//=================================RefreshToken을 사용해서 정보 가져 온다. 이미 인증된 사용자의 업데이트 목적
|
//=================================RefreshToken을 사용해서 정보 가져 온다. 이미 인증된 사용자의 업데이트 목적
|
||||||
secret, err := generateClientSecret(mg.ApplePrivateKey, mg.AppleTeamId, mg.AppleServiceId, mg.AppleKeyId)
|
secret, err := generateClientSecret(config.ApplePrivateKey, config.AppleTeamId, config.AppleServiceId, config.AppleKeyId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("error generating secret: ", err)
|
logger.Error("error generating secret: ", err)
|
||||||
return false, "", ""
|
return false, "", ""
|
||||||
}
|
}
|
||||||
|
|
||||||
vReqRefreshToken := Apple_WebRefreshTokenRequest{
|
vReqRefreshToken := Apple_WebRefreshTokenRequest{
|
||||||
ClientID: mg.AppleServiceId,
|
ClientID: config.AppleServiceId,
|
||||||
ClientSecret: secret,
|
ClientSecret: secret,
|
||||||
RefreshToken: refreshToken,
|
RefreshToken: refreshToken,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,6 +3,7 @@ package core
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"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) {
|
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{
|
found, err := mg.mongoClient.FindOne(CollectionPlatformLoginToken, bson.M{
|
||||||
"platform": AuthPlatformFirebaseAuth,
|
"platform": AuthPlatformFirebaseAuth,
|
||||||
@ -188,7 +194,7 @@ func (mg *Maingate) platform_firebaseauth_authorize_raw(w http.ResponseWriter, b
|
|||||||
return false, ""
|
return false, ""
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = mg.firebaseAppClient.VerifyIDToken(mg.firebaseAppContext, code)
|
_, err = mg.firebase.firebaseAppClient.VerifyIDToken(mg.firebase.firebaseAppContext, code)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("error verifying ID token:", err)
|
log.Println("error verifying ID token:", err)
|
||||||
return false, ""
|
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) {
|
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{
|
found, err := mg.mongoClient.FindOne(CollectionFirebaseUserInfo, bson.M{
|
||||||
"firebaseuserid": info.userid,
|
"firebaseuserid": info.userid,
|
||||||
@ -256,13 +266,16 @@ func (mg *Maingate) platform_firebase_getuserinfo(info usertokeninfo) (bool, str
|
|||||||
return false, "", ""
|
return false, "", ""
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = mg.firebaseAppClient.VerifyIDToken(mg.firebaseAppContext, info.token)
|
_, err = mg.firebase.firebaseAppClient.VerifyIDToken(mg.firebase.firebaseAppContext, info.token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("error verifying ID token:", err)
|
log.Println("error verifying ID token:", err)
|
||||||
return false, "", ""
|
return false, "", ""
|
||||||
}
|
}
|
||||||
|
|
||||||
tempEmail := found["firebaseemail"].(string)
|
tempEmail := found["firebaseemail"].(string)
|
||||||
|
if found["firebaseprovider"].(string) == "guest" {
|
||||||
|
tempEmail = fmt.Sprintf("%s@guest.flag", info.userid)
|
||||||
|
}
|
||||||
|
|
||||||
return true, info.userid, tempEmail
|
return true, info.userid, tempEmail
|
||||||
|
|
||||||
|
|||||||
@ -84,9 +84,9 @@ func (mg *Maingate) platform_google_get_login_url(w http.ResponseWriter, r *http
|
|||||||
}
|
}
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.GoogleClientId)
|
params.Add("client_id", config.GoogleClientId)
|
||||||
params.Add("response_type", "code")
|
params.Add("response_type", "code")
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
||||||
params.Add("scope", "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
|
params.Add("scope", "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
|
||||||
params.Add("access_type", "offline")
|
params.Add("access_type", "offline")
|
||||||
params.Add("prompt", "consent")
|
params.Add("prompt", "consent")
|
||||||
@ -140,7 +140,7 @@ func (mg *Maingate) platform_google_authorize(w http.ResponseWriter, r *http.Req
|
|||||||
}
|
}
|
||||||
http.SetCookie(w, &cookie2)
|
http.SetCookie(w, &cookie2)
|
||||||
|
|
||||||
http.Redirect(w, r, mg.RedirectBaseUrl+"/authorize_result/"+AuthPlatformGoogle, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
http.Redirect(w, r, config.RedirectBaseUrl+"/authorize_result/"+AuthPlatformGoogle, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) platform_google_authorize_result(w http.ResponseWriter, r *http.Request) {
|
func (mg *Maingate) platform_google_authorize_result(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -211,9 +211,9 @@ func (mg *Maingate) platform_google_authorize_result(w http.ResponseWriter, r *h
|
|||||||
|
|
||||||
//=================
|
//=================
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.GoogleClientId)
|
params.Add("client_id", config.GoogleClientId)
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
||||||
params.Add("client_secret", mg.GoogleClientSecret)
|
params.Add("client_secret", config.GoogleClientSecret)
|
||||||
params.Add("code", code)
|
params.Add("code", code)
|
||||||
params.Add("grant_type", "authorization_code")
|
params.Add("grant_type", "authorization_code")
|
||||||
|
|
||||||
@ -285,9 +285,9 @@ func (mg *Maingate) platform_google_getuserinfo(info usertokeninfo) (bool, strin
|
|||||||
if time.Now().Unix() > info.accesstoken_expire_time {
|
if time.Now().Unix() > info.accesstoken_expire_time {
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.GoogleClientId)
|
params.Add("client_id", config.GoogleClientId)
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformGoogle)
|
||||||
params.Add("client_secret", mg.GoogleClientSecret)
|
params.Add("client_secret", config.GoogleClientSecret)
|
||||||
params.Add("scope", "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
|
params.Add("scope", "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email")
|
||||||
params.Add("refresh_token", info.token)
|
params.Add("refresh_token", info.token)
|
||||||
params.Add("grant_type", "refresh_token")
|
params.Add("grant_type", "refresh_token")
|
||||||
|
|||||||
159
core/platformhybeim.go
Normal file
159
core/platformhybeim.go
Normal file
@ -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
|
||||||
|
|
||||||
|
}
|
||||||
@ -83,9 +83,9 @@ func (mg *Maingate) platform_microsoft_get_login_url(w http.ResponseWriter, r *h
|
|||||||
}
|
}
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.MicrosoftClientId)
|
params.Add("client_id", config.MicrosoftClientId)
|
||||||
params.Add("response_type", "code")
|
params.Add("response_type", "code")
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
||||||
params.Add("response_mode", "query")
|
params.Add("response_mode", "query")
|
||||||
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
||||||
|
|
||||||
@ -127,7 +127,7 @@ func (mg *Maingate) platform_microsoft_authorize(w http.ResponseWriter, r *http.
|
|||||||
}
|
}
|
||||||
http.SetCookie(w, &cookie)
|
http.SetCookie(w, &cookie)
|
||||||
|
|
||||||
http.Redirect(w, r, mg.RedirectBaseUrl+"/authorize_result/"+AuthPlatformMicrosoft, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
http.Redirect(w, r, config.RedirectBaseUrl+"/authorize_result/"+AuthPlatformMicrosoft, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) platform_microsoft_authorize_result(w http.ResponseWriter, r *http.Request) {
|
func (mg *Maingate) platform_microsoft_authorize_result(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -191,13 +191,13 @@ func (mg *Maingate) platform_microsoft_authorize_result(w http.ResponseWriter, r
|
|||||||
//=================
|
//=================
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.MicrosoftClientId)
|
params.Add("client_id", config.MicrosoftClientId)
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
||||||
params.Add("code", code)
|
params.Add("code", code)
|
||||||
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
||||||
params.Add("grant_type", "authorization_code")
|
params.Add("grant_type", "authorization_code")
|
||||||
|
|
||||||
params.Add("client_secret", mg.MicrosoftClientSecret)
|
params.Add("client_secret", config.MicrosoftClientSecret)
|
||||||
|
|
||||||
var respReferesh Microsoft_ValidationResponse
|
var respReferesh Microsoft_ValidationResponse
|
||||||
acceestoken_expire_time := time.Now().Unix()
|
acceestoken_expire_time := time.Now().Unix()
|
||||||
@ -263,13 +263,13 @@ func (mg *Maingate) platform_microsoft_getuserinfo(info usertokeninfo) (bool, st
|
|||||||
if time.Now().Unix() > info.accesstoken_expire_time {
|
if time.Now().Unix() > info.accesstoken_expire_time {
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("client_id", mg.MicrosoftClientId)
|
params.Add("client_id", config.MicrosoftClientId)
|
||||||
params.Add("redirect_uri", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
params.Add("redirect_uri", config.RedirectBaseUrl+"/authorize/"+AuthPlatformMicrosoft)
|
||||||
params.Add("refresh_token", info.token)
|
params.Add("refresh_token", info.token)
|
||||||
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
params.Add("scope", "openid offline_access https://graph.microsoft.com/mail.read")
|
||||||
params.Add("grant_type", "refresh_token")
|
params.Add("grant_type", "refresh_token")
|
||||||
|
|
||||||
params.Add("client_secret", mg.MicrosoftClientSecret)
|
params.Add("client_secret", config.MicrosoftClientSecret)
|
||||||
|
|
||||||
var respReferesh Microsoft_ValidationResponse
|
var respReferesh Microsoft_ValidationResponse
|
||||||
acceestoken_expire_time := time.Now().Unix()
|
acceestoken_expire_time := time.Now().Unix()
|
||||||
|
|||||||
@ -39,11 +39,7 @@ func (mg *Maingate) platform_steamsdk_authorize(w http.ResponseWriter, r *http.R
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !*noauth {
|
if err := authenticateSteamUser(config.SteamPublisherAuthKey, config.SteamAppId, authinfo.UserSteamId, authinfo.UserAuthToken); err == nil {
|
||||||
err = authenticateSteamUser(mg.SteamPublisherAuthKey, mg.SteamAppId, authinfo.UserSteamId, authinfo.UserAuthToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err == nil {
|
|
||||||
acceestoken_expire_time := time.Date(2999, 1, int(time.January), 0, 0, 0, 0, time.UTC).Unix()
|
acceestoken_expire_time := time.Date(2999, 1, int(time.January), 0, 0, 0, 0, time.UTC).Unix()
|
||||||
|
|
||||||
var info usertokeninfo
|
var info usertokeninfo
|
||||||
@ -118,9 +114,8 @@ func authenticateSteamUser(pubkey, appid, playerid, ticket string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) platform_steamsdk_getuserinfo(info usertokeninfo) (bool, string, string) {
|
func (mg *Maingate) platform_steamsdk_getuserinfo(info usertokeninfo) (bool, string, string) {
|
||||||
|
// Steam은 이메일 정보를 받을수 없기 때문에 userid로 리턴한다.
|
||||||
// Steam은 이메일 정보를 받을수 없기 때문에 dummy임시 주소 할당하여 리턴한다.
|
dummyEmail := fmt.Sprintf("%s@steam.id", info.userid)
|
||||||
dummyEmail := fmt.Sprintf("__dummy_%s@steamtemp__", info.userid)
|
|
||||||
return true, info.userid, dummyEmail
|
return true, info.userid, dummyEmail
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -123,7 +123,7 @@ func (mg *Maingate) platform_twitter_authorize(w http.ResponseWriter, r *http.Re
|
|||||||
}
|
}
|
||||||
http.SetCookie(w, &cookie)
|
http.SetCookie(w, &cookie)
|
||||||
|
|
||||||
http.Redirect(w, r, mg.RedirectBaseUrl+"/authorize_result/"+AuthPlatformTwitter, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
http.Redirect(w, r, config.RedirectBaseUrl+"/authorize_result/"+AuthPlatformTwitter, http.StatusSeeOther) //-- 바로 받으니까 쿠키 안와서 한번 더 Redirect 시킨다.
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) platform_twitter_authorize_result(w http.ResponseWriter, r *http.Request) {
|
func (mg *Maingate) platform_twitter_authorize_result(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -249,7 +249,7 @@ func (mg *Maingate) platform_twitter_getuserinfo(token, secret string) (bool, st
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) CallTwitterAPI_WithAPPKey(requesturl, method, nonce string) string {
|
func (mg *Maingate) CallTwitterAPI_WithAPPKey(requesturl, method, nonce string) string {
|
||||||
return mg.CallTwitterAPI(requesturl, method, mg.TwitterOAuthKey, mg.TwitterOAuthSecret, nonce)
|
return mg.CallTwitterAPI(requesturl, method, config.TwitterOAuthKey, config.TwitterOAuthSecret, nonce)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Maingate) CallTwitterAPI(requesturl, method, oauth_token, oauth_secret, nonce string) string {
|
func (mg *Maingate) CallTwitterAPI(requesturl, method, oauth_token, oauth_secret, nonce string) string {
|
||||||
@ -272,8 +272,8 @@ func (mg *Maingate) CallTwitterAPI(requesturl, method, oauth_token, oauth_secret
|
|||||||
//vals.Add("oauth_callback", "actionclient://callback")
|
//vals.Add("oauth_callback", "actionclient://callback")
|
||||||
//vals.Add("oauth_callback", "http://127.0.0.1:7770/auth")
|
//vals.Add("oauth_callback", "http://127.0.0.1:7770/auth")
|
||||||
|
|
||||||
vals.Add("oauth_callback", mg.RedirectBaseUrl+"/authorize/"+AuthPlatformTwitter)
|
vals.Add("oauth_callback", config.RedirectBaseUrl+"/authorize/"+AuthPlatformTwitter)
|
||||||
vals.Add("oauth_consumer_key", mg.TwitterCustomerKey)
|
vals.Add("oauth_consumer_key", config.TwitterCustomerKey)
|
||||||
vals.Add("oauth_token", oauth_token)
|
vals.Add("oauth_token", oauth_token)
|
||||||
vals.Add("oauth_signature_method", "HMAC-SHA1")
|
vals.Add("oauth_signature_method", "HMAC-SHA1")
|
||||||
vals.Add("oauth_timestamp", strconv.Itoa(int(time.Now().Unix())))
|
vals.Add("oauth_timestamp", strconv.Itoa(int(time.Now().Unix())))
|
||||||
@ -282,7 +282,7 @@ func (mg *Maingate) CallTwitterAPI(requesturl, method, oauth_token, oauth_secret
|
|||||||
|
|
||||||
parameterString := strings.Replace(vals.Encode(), "+", "%20", -1)
|
parameterString := strings.Replace(vals.Encode(), "+", "%20", -1)
|
||||||
signatureBase := strings.ToUpper(method) + "&" + url.QueryEscape(strings.Split(requesturl, "?")[0]) + "&" + url.QueryEscape(parameterString)
|
signatureBase := strings.ToUpper(method) + "&" + url.QueryEscape(strings.Split(requesturl, "?")[0]) + "&" + url.QueryEscape(parameterString)
|
||||||
signingKey := url.QueryEscape(mg.TwitterCustomerSecret) + "&" + url.QueryEscape(oauth_secret)
|
signingKey := url.QueryEscape(config.TwitterCustomerSecret) + "&" + url.QueryEscape(oauth_secret)
|
||||||
signature := calculateTwitterSignature(signatureBase, signingKey)
|
signature := calculateTwitterSignature(signatureBase, signingKey)
|
||||||
|
|
||||||
headerString := "OAuth oauth_callback=\"" + url.QueryEscape(vals.Get("oauth_callback")) + "\", oauth_consumer_key=\"" + url.QueryEscape(vals.Get("oauth_consumer_key")) + "\", oauth_nonce=\"" + url.QueryEscape(vals.Get("oauth_nonce")) +
|
headerString := "OAuth oauth_callback=\"" + url.QueryEscape(vals.Get("oauth_callback")) + "\", oauth_consumer_key=\"" + url.QueryEscape(vals.Get("oauth_consumer_key")) + "\", oauth_nonce=\"" + url.QueryEscape(vals.Get("oauth_nonce")) +
|
||||||
|
|||||||
724
core/service.go
724
core/service.go
File diff suppressed because it is too large
Load Diff
@ -10,7 +10,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"repositories.action2quare.com/ayo/gocommon"
|
|
||||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||||
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
@ -19,14 +18,6 @@ import (
|
|||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
)
|
)
|
||||||
|
|
||||||
type authPipelineDocument struct {
|
|
||||||
OperationType string `bson:"operationType"`
|
|
||||||
DocumentKey struct {
|
|
||||||
Id primitive.ObjectID `bson:"_id"`
|
|
||||||
} `bson:"documentKey"`
|
|
||||||
Authinfo *gocommon.Authinfo `bson:"fullDocument"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type servicePipelineDocument struct {
|
type servicePipelineDocument struct {
|
||||||
OperationType string `bson:"operationType"`
|
OperationType string `bson:"operationType"`
|
||||||
DocumentKey struct {
|
DocumentKey struct {
|
||||||
@ -222,87 +213,3 @@ func (mg *Maingate) watchServiceCollection(parentctx context.Context, serveMux *
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func watchAuthCollection(parentctx context.Context, ac *gocommon.AuthCollection, mongoClient gocommon.MongoClient) {
|
|
||||||
defer func() {
|
|
||||||
s := recover()
|
|
||||||
if s != nil {
|
|
||||||
logger.Error(s)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
matchStage := bson.D{
|
|
||||||
{
|
|
||||||
Key: "$match", Value: bson.D{
|
|
||||||
{Key: "operationType", Value: bson.D{
|
|
||||||
{Key: "$in", Value: bson.A{
|
|
||||||
"delete",
|
|
||||||
"insert",
|
|
||||||
"update",
|
|
||||||
}},
|
|
||||||
}},
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
projectStage := bson.D{
|
|
||||||
{
|
|
||||||
Key: "$project", Value: bson.D{
|
|
||||||
{Key: "documentKey", Value: 1},
|
|
||||||
{Key: "operationType", Value: 1},
|
|
||||||
{Key: "fullDocument", Value: 1},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var stream *mongo.ChangeStream
|
|
||||||
var err error
|
|
||||||
var ctx context.Context
|
|
||||||
|
|
||||||
for {
|
|
||||||
if stream == nil {
|
|
||||||
stream, err = mongoClient.Watch(CollectionAuth, mongo.Pipeline{matchStage, projectStage})
|
|
||||||
if err != nil {
|
|
||||||
logger.Error("watchAuthCollection watch failed :", err)
|
|
||||||
time.Sleep(time.Minute)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ctx = context.TODO()
|
|
||||||
}
|
|
||||||
|
|
||||||
changed := stream.TryNext(ctx)
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
logger.Error("watchAuthCollection stream.TryNext failed. process should be restarted! :", ctx.Err().Error())
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
if changed {
|
|
||||||
var data authPipelineDocument
|
|
||||||
if err := stream.Decode(&data); err == nil {
|
|
||||||
ot := data.OperationType
|
|
||||||
switch ot {
|
|
||||||
case "insert":
|
|
||||||
ac.AddRaw(&mongoAuthCell{src: data.Authinfo})
|
|
||||||
case "update":
|
|
||||||
ac.AddRaw(&mongoAuthCell{src: data.Authinfo})
|
|
||||||
case "delete":
|
|
||||||
ac.RemoveByAccId(data.DocumentKey.Id)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.Error("watchAuthCollection stream.Decode failed :", err)
|
|
||||||
}
|
|
||||||
} else if stream.Err() != nil || stream.ID() == 0 {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
logger.Println("watchAuthCollection is done")
|
|
||||||
stream.Close(ctx)
|
|
||||||
return
|
|
||||||
|
|
||||||
case <-time.After(time.Second):
|
|
||||||
logger.Error("watchAuthCollection stream error :", stream.Err())
|
|
||||||
stream.Close(ctx)
|
|
||||||
stream = nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
time.Sleep(time.Second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
10
go.mod
10
go.mod
@ -1,13 +1,13 @@
|
|||||||
module repositories.action2quare.com/ayo/maingate
|
module repositories.action2quare.com/ayo/maingate
|
||||||
|
|
||||||
go 1.18
|
go 1.19
|
||||||
|
|
||||||
require (
|
require (
|
||||||
firebase.google.com/go v3.13.0+incompatible
|
firebase.google.com/go v3.13.0+incompatible
|
||||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||||
go.mongodb.org/mongo-driver v1.11.7
|
go.mongodb.org/mongo-driver v1.11.7
|
||||||
google.golang.org/api v0.128.0
|
google.golang.org/api v0.128.0
|
||||||
repositories.action2quare.com/ayo/gocommon v0.0.0-20240205060841-c31f838ba8a9
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240517005942-6a98802e24e5
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@ -42,7 +42,7 @@ require (
|
|||||||
golang.org/x/net v0.11.0 // indirect
|
golang.org/x/net v0.11.0 // indirect
|
||||||
golang.org/x/oauth2 v0.9.0 // indirect
|
golang.org/x/oauth2 v0.9.0 // indirect
|
||||||
golang.org/x/sync v0.3.0 // indirect
|
golang.org/x/sync v0.3.0 // indirect
|
||||||
golang.org/x/sys v0.9.0 // indirect
|
golang.org/x/sys v0.11.0 // indirect
|
||||||
golang.org/x/text v0.10.0 // indirect
|
golang.org/x/text v0.10.0 // indirect
|
||||||
golang.org/x/time v0.3.0 // indirect
|
golang.org/x/time v0.3.0 // indirect
|
||||||
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
|
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
|
||||||
@ -51,7 +51,5 @@ require (
|
|||||||
google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect
|
||||||
google.golang.org/grpc v1.56.0 // indirect
|
google.golang.org/grpc v1.56.0 // indirect
|
||||||
google.golang.org/protobuf v1.30.0 // indirect
|
google.golang.org/protobuf v1.31.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
replace repositories.action2quare.com/ayo/maingate => ./
|
|
||||||
|
|||||||
18
go.sum
18
go.sum
@ -192,8 +192,8 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
|
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
|
||||||
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
@ -255,8 +255,8 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD
|
|||||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||||
@ -268,7 +268,9 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
repositories.action2quare.com/ayo/gocommon v0.0.0-20230912075917-f9a146321cdb h1:Rdf6uhBIWunRLZ2LIT1hSovYXxZoOzx9mdSK5bjWpos=
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240425023707-60c95c2e0edf h1:V2L6UlyKwzzKudU940AowVjGwzBhNBAQirYdPa13JhE=
|
||||||
repositories.action2quare.com/ayo/gocommon v0.0.0-20230912075917-f9a146321cdb/go.mod h1:rn6NA28Mej+qgLNx/Bu2wsdGyIycmacqlNP6gUXX2a0=
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240425023707-60c95c2e0edf/go.mod h1:Gb418rT96M3K7L/XMPzp8IJj4UXVunq7dZzrxsMBz/8=
|
||||||
repositories.action2quare.com/ayo/gocommon v0.0.0-20240205060841-c31f838ba8a9 h1:5cQ60XjlI7k0qld0rIpd6gy7+a9csv3ijz1EVKTzsy8=
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240517005227-40d025ad4d78 h1:1chjh1LkfxQBjBt0MDVKp/EFq+PhXDEDRnrgOaL6NAU=
|
||||||
repositories.action2quare.com/ayo/gocommon v0.0.0-20240205060841-c31f838ba8a9/go.mod h1:rn6NA28Mej+qgLNx/Bu2wsdGyIycmacqlNP6gUXX2a0=
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240517005227-40d025ad4d78/go.mod h1:Gb418rT96M3K7L/XMPzp8IJj4UXVunq7dZzrxsMBz/8=
|
||||||
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240517005942-6a98802e24e5 h1:XF1JdiBshuGmCtNIcJ9Vqt1CsfWBO+IakP5jJWutL58=
|
||||||
|
repositories.action2quare.com/ayo/gocommon v0.0.0-20240517005942-6a98802e24e5/go.mod h1:Gb418rT96M3K7L/XMPzp8IJj4UXVunq7dZzrxsMBz/8=
|
||||||
|
|||||||
15
main.go
15
main.go
@ -2,9 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
|
||||||
|
|
||||||
"repositories.action2quare.com/ayo/gocommon"
|
"repositories.action2quare.com/ayo/gocommon"
|
||||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||||
@ -21,26 +19,29 @@ func main() {
|
|||||||
flagx.Parse()
|
flagx.Parse()
|
||||||
|
|
||||||
logger.Println("build revision =", revision)
|
logger.Println("build revision =", revision)
|
||||||
rand.Seed(time.Now().UnixNano())
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
mg, err := core.New(ctx)
|
mg, err := core.New(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("core.New failed :", err)
|
logger.Error("core.New failed :", err)
|
||||||
panic(err)
|
return
|
||||||
}
|
}
|
||||||
|
defer mg.Destructor()
|
||||||
|
|
||||||
serveMux := http.NewServeMux()
|
serveMux := http.NewServeMux()
|
||||||
if err := mg.RegisterHandlers(ctx, serveMux, *prefix); err != nil {
|
if err := mg.RegisterHandlers(ctx, serveMux, *prefix); err != nil {
|
||||||
logger.Error("RegisterHandlers failed :", err)
|
logger.Error("RegisterHandlers failed :", err)
|
||||||
panic(err)
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
server := gocommon.NewHTTPServer(serveMux)
|
server := gocommon.NewHTTPServer(serveMux)
|
||||||
logger.Println("maingate is started")
|
logger.Println("maingate is started")
|
||||||
|
|
||||||
if err := server.Start(); err != nil {
|
if err := server.Start(); err != nil {
|
||||||
logger.Error("maingate is stopped with error :", err)
|
logger.Error("maingate is stopped with error :", err)
|
||||||
}
|
}
|
||||||
cancel()
|
|
||||||
mg.Destructor()
|
logger.Println("maingate is terminated")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,14 +0,0 @@
|
|||||||
# $ErrorActionPreference = 'SilentlyContinue'
|
|
||||||
|
|
||||||
$CurBranch = git branch --show-current
|
|
||||||
|
|
||||||
Remove-Item maingate.zip -Force -Recurse -ErrorAction SilentlyContinue
|
|
||||||
|
|
||||||
$Env:GOOS="linux"
|
|
||||||
$Env:GOARCH="amd64"
|
|
||||||
go build -ldflags="-s -w" .
|
|
||||||
|
|
||||||
Compress-Archive -Path maingate -Update -DestinationPath maingate.zip
|
|
||||||
Compress-Archive -Path *-firebase-*.json -Update -DestinationPath maingate.zip
|
|
||||||
Compress-Archive -Path fba -Update -DestinationPath maingate.zip
|
|
||||||
Compress-Archive -Path template -Update -DestinationPath maingate.zip
|
|
||||||
Reference in New Issue
Block a user