common-func.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. //go:build !dev
  2. // +build !dev
  3. package locals
  4. import (
  5. "bytes"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "kkscrap-go/locals/gosodium/cryptobox"
  13. "net/http"
  14. "strings"
  15. "time"
  16. "github.com/dabory/abango-rest"
  17. e "github.com/dabory/abango-rest/etc"
  18. "github.com/go-xorm/xorm"
  19. "github.com/microcosm-cc/bluemonday"
  20. )
  21. const (
  22. // Tpf string = "dbr_" // TablePrefix
  23. //QueryComment
  24. QcWhere string = "-- @where"
  25. QcSubWhere string = "-- @subwhere"
  26. QcHaving string = "-- @having"
  27. QcOrder string = "-- @order"
  28. QcLimitOffset string = "-- @limitoffset"
  29. QcExtract string = "-- @extract:"
  30. QcClosed string = "-- @closed:"
  31. QcDelivery string = "-- @delivery:"
  32. QcBetweenDates string = "-- @between_dates"
  33. QcEnd string = "--" //QueryComment
  34. //QueryKeyword
  35. QkWhere string = "\nwhere true "
  36. // QkWhere string = "\nwhere 1 "
  37. QkHaving string = "\nhaving true "
  38. QkOrder string = "\norder by "
  39. QkLimit string = "\nlimit "
  40. QkOffset string = " offset "
  41. QkTmpOrder string = " order by is_sum desc, t_id asc "
  42. )
  43. type AppApi struct {
  44. ApiUrl string
  45. GateToken string
  46. }
  47. // 0:Sso, 1:Dbu 매우 중요하다.
  48. var gAppApis [2]AppApi
  49. var (
  50. SQL_DEBUG bool
  51. NORMAL_DEBUG bool
  52. )
  53. var BlockNoCnt int
  54. // type GateTokenGetReq struct {
  55. // ClientId string
  56. // BeforeBase64 string
  57. // AppBase64 string
  58. // }
  59. func (y *SyncController) Init() error {
  60. var kPairStr string
  61. if abango.XConfig["IsLocalKeyPair"] != "Yes" {
  62. keypair, err := GuestKeyPairGet(abango.XConfig["SyncClientId"])
  63. if err != nil {
  64. return e.ErrLog(e.FuncRun("03joau0u3qd", e.CurrFuncName()), err)
  65. }
  66. kPairStr = keypair
  67. fmt.Println("RemoteKeypair:", kPairStr)
  68. } else {
  69. kPairStr = abango.XConfig["LocalKeyPair"]
  70. fmt.Println("LocalKeyPair:", kPairStr)
  71. }
  72. keyPair, err := base64.StdEncoding.DecodeString(kPairStr)
  73. if err != nil {
  74. return e.ErrLog(e.FuncRun("joiuejcsoe: Decryption Failure-1 ", e.CurrFuncName()), err)
  75. }
  76. sKey, pKey, err := cryptobox.CryptoBoxGetSecretPublicKeyFrom(keyPair)
  77. if err != nil {
  78. return e.ErrLog(e.FuncRun("joiuejcsoe: Decryption Failure-2 ", e.CurrFuncName()), err)
  79. }
  80. decodedBytes, err := base64.StdEncoding.DecodeString(abango.XConfig["SyncBB64"])
  81. if err != nil {
  82. return e.ErrLog(e.FuncRun("joiuejcsoe: Decryption Failure-3 ", e.CurrFuncName()), err)
  83. }
  84. //decrypt 문제는 여기서 memory error 가 난다.
  85. decryptedBytes, boxRet := cryptobox.CryptoBoxSealOpen(decodedBytes, pKey, sKey)
  86. if boxRet != 0 {
  87. return e.ErrLog(e.FuncRun("joiuejcsoe: Decryption Failure-4(Wrong BB64Key) ", e.CurrFuncName()), err)
  88. }
  89. vmc := &struct {
  90. Driver string
  91. Host string
  92. Port int
  93. Username string
  94. Database string
  95. Password string
  96. }{}
  97. if err := json.Unmarshal(decryptedBytes, vmc); err != nil {
  98. return e.ErrLog(e.FuncRun("joiuejcsoe: Decryption Failure-5 ", e.CurrFuncName()), err)
  99. }
  100. connStr := vmc.Username + ":" + vmc.Password + "@tcp(" + vmc.Host + ":" + e.NumToStr(vmc.Port) + ")/" + vmc.Database
  101. fmt.Println("connStr:", connStr)
  102. y.Scb.ConnString = connStr
  103. if y.Db, err = xorm.NewEngine(abango.XConfig["DbType"], connStr); err != nil {
  104. return e.ErrLog(e.FuncRun("309upajs3w: DBEngine Open Error ", e.CurrFuncName()), err)
  105. }
  106. var connHint string
  107. strArr := strings.Split(connStr, "@tcp")
  108. if len(strArr) == 2 {
  109. connHint = strArr[1]
  110. } else {
  111. return e.ErrLog(e.FuncRun("309upajs3w: connString format mismatch: "+strArr[1], e.CurrFuncName()), err)
  112. }
  113. y.Db.ShowSQL(false)
  114. y.Db.SetMaxOpenConns(100)
  115. y.Db.SetMaxIdleConns(20)
  116. y.Db.SetConnMaxLifetime(60 * time.Second)
  117. if _, err := y.Db.IsTableExist("aaa"); err == nil {
  118. e.OkLog("SyncDB connection in " + connHint)
  119. return nil
  120. } else {
  121. return e.ErrLog(e.FuncRun("93haoy93d: SyncDB connection Fail in "+connHint+": ", e.CurrFuncName()), err)
  122. }
  123. }
  124. func (t *PageVars) ChkPageVars(chk string) {
  125. if t.Query == "" {
  126. e.ChkLog(chk, "Query is empty")
  127. }
  128. if t.Fields == "" {
  129. e.ChkLog(chk, "Fields is empty")
  130. }
  131. if t.Asc == "" {
  132. e.ChkLog(chk, "Asc is empty")
  133. }
  134. if t.Desc == "" {
  135. e.ChkLog(chk, "Desc is empty")
  136. }
  137. if t.Limit == 0 {
  138. e.ChkLog(chk, "Limit is zero")
  139. }
  140. if t.Offset == 0 {
  141. e.ChkLog(chk, "Offset is zero")
  142. }
  143. e.ChkLog(chk+", PageVars value is", *t)
  144. return
  145. }
  146. type (
  147. MemoryMap map[string]interface{}
  148. MapStore struct {
  149. store MemoryMap
  150. }
  151. )
  152. func (c *MapStore) Get(key string) interface{} {
  153. return c.store[key]
  154. }
  155. func (c *MapStore) Set(key string, val interface{}) {
  156. if c.store == nil {
  157. c.store = make(MemoryMap)
  158. }
  159. c.store[key] = val
  160. }
  161. func DbrPasswd(password string, salt string) string {
  162. salt16 := DbrSaltBase(salt, 16)
  163. var passwordBytes = []byte(password)
  164. var sha256Hasher = sha256.New()
  165. passwordBytes = append(passwordBytes, salt16...)
  166. sha256Hasher.Write(passwordBytes)
  167. var hashedPasswordBytes = sha256Hasher.Sum(nil)
  168. var base64EncodedPasswordHash = base64.URLEncoding.EncodeToString(hashedPasswordBytes)
  169. return base64EncodedPasswordHash
  170. }
  171. func DbrHashedIndex(target string) string {
  172. //!!중요: salt는 16char에서만 작동된다. hash 값은 44 char나오지만 32char로 잘라서 쓴다.
  173. fmt.Println("hash_full_length:", DbrPasswd(target, "$$hashed_index$$"))
  174. return DbrPasswd(target, "$$hashed_index$$")[0:32]
  175. }
  176. func DbrCompare(hashedPassword, currPassword string, salt string) bool {
  177. // fmt.Println("salt:", salt)
  178. // fmt.Println("currPassword:", currPassword)
  179. var currPasswordHash = DbrPasswd(currPassword, salt)
  180. // fmt.Println("currPasswordHash:", currPasswordHash)
  181. // fmt.Println("hashedPassword:", hashedPassword)
  182. return hashedPassword == currPasswordHash
  183. }
  184. func DbrSaltBase(salt string, saltSize int) []byte { //어떤 사이즈라도 16byte의 Base64로 변경
  185. tmp := []byte(salt)
  186. salt64 := base64.StdEncoding.EncodeToString(tmp)
  187. return []byte(salt64[4 : saltSize+4])
  188. }
  189. func HasPickActPage(uri string, table string) bool {
  190. if table == "member" {
  191. if uri == "/"+table+"-pick" || uri == "/"+table+"-act" || uri == "/"+table+"-page" || uri == "/"+table+"-secured-pick" || uri == "/"+table+"-secured-page" || uri == "/"+table+"-secured-act" {
  192. return true
  193. } else {
  194. return false
  195. }
  196. } else {
  197. if uri == "/"+table+"-pick" || uri == "/"+table+"-act" || uri == "/"+table+"-page" {
  198. return true
  199. } else {
  200. return false
  201. }
  202. }
  203. }
  204. // func ByteIndex(ba *[]byte, bt byte, opt int) int {
  205. // if opt == 0 { //normal
  206. // for i := 0; i < len(*ba); i++ {
  207. // if (*ba)[i] == bt {
  208. // return i
  209. // }
  210. // }
  211. // } else if opt == 1 { //rerverse
  212. // for i := len(*ba) - 1; i > 0; i-- {
  213. // if (*ba)[i] == bt {
  214. // return i
  215. // }
  216. // }
  217. // }
  218. // return -1
  219. // }
  220. func LastQry(qry xorm.Session) string {
  221. ret, _ := qry.LastSQL()
  222. fmt.Println("\n" + ret + "\n")
  223. return ret
  224. }
  225. func ShowQry(qry xorm.Session, qryName string) string {
  226. if SQL_DEBUG {
  227. ret, _ := qry.LastSQL()
  228. return e.LogStr("", "ShowQry===["+qryName+"]==="+"\n[ "+ret+" ]\n")
  229. }
  230. return ""
  231. }
  232. func ShowSql(sqlStr string, qryName string) string {
  233. if SQL_DEBUG {
  234. return e.LogStr("", "ShowSql===["+qryName+"]==="+"\n[ "+sqlStr+" ]\n")
  235. }
  236. return ""
  237. }
  238. // func ShowDebug(debugStr string, index string) string {
  239. // if NORMAL_DEBUG {
  240. // return e.LogStr("", "ShowDebug===["+index+"]==="+"\n[ "+debugStr+" ]\n")
  241. // }
  242. // return ""
  243. // }
  244. func QryDirName(qryName string) (string, string) {
  245. if !strings.Contains(qryName, "::") {
  246. return "queries/", qryName
  247. } else {
  248. q := strings.Split(qryName, "::")
  249. return "queries/themes/" + q[0] + "/", q[1]
  250. }
  251. }
  252. func StripHtml(cont string, max int) string {
  253. p := bluemonday.StripTagsPolicy()
  254. s := p.Sanitize(cont)
  255. if len(s) > max {
  256. return string([]rune(s)[:max])
  257. } else {
  258. return s
  259. }
  260. }
  261. func Sanitize(cont string) string {
  262. p := bluemonday.UGCPolicy()
  263. return p.Sanitize(cont)
  264. }
  265. func AddStrIfNotExist(s *string, target string) {
  266. if !strings.Contains(*s, target) {
  267. *s += target
  268. }
  269. }
  270. func HttpResponseSimplePost(method string, apiurl string, jsBytes []byte) (retbody []byte, retsta int, reterr error) {
  271. response, err := http.Post(apiurl, "application/json", bytes.NewBuffer(jsBytes))
  272. if err != nil {
  273. return nil, 0, errors.New(e.FuncRunErr("65rfg0csdew", "The HTTP request failed with error "+e.CurrFuncName()+err.Error()))
  274. } else {
  275. retbody, err = ioutil.ReadAll(response.Body)
  276. if err != nil {
  277. return nil, 0, errors.New(e.FuncRunErr("kjda89382", "ReadAll error "+e.CurrFuncName()+err.Error()))
  278. }
  279. }
  280. return retbody, response.StatusCode, nil
  281. }
  282. func HttpResponseWithGt(method string, apiurl string, jsBytes []byte, gateToken string) (retbody []byte, retsta int, reterr error) {
  283. reader := bytes.NewBuffer(jsBytes)
  284. req, err := http.NewRequest(method, apiurl, reader)
  285. if err != nil {
  286. return nil, 909, e.ErrLog(e.FuncRun("xcawrq3276fa-http.NewRequest "+apiurl, e.CurrFuncName()), err)
  287. }
  288. req.Header.Add("RemoteIp", "localhost")
  289. req.Header.Add("Referer", "http://localhost")
  290. req.Header.Add("GateToken", gateToken)
  291. req.Body = ioutil.NopCloser(bytes.NewReader(jsBytes))
  292. // Client객체에서 Request 실행
  293. client := &http.Client{
  294. Timeout: time.Second * 20, //Otherwirse, it can cause crash without this line. Must Must.
  295. } // Normal is 10 but extend 20 on 1 Dec 2018
  296. // fmt.Println(reflect.TypeOf(respo))
  297. resp, err := client.Do(req)
  298. if err != nil {
  299. return nil, 909, e.ErrLog(e.FuncRun("wewer2354e-client.Do "+apiurl, e.CurrFuncName()), err)
  300. }
  301. defer resp.Body.Close()
  302. byteRtn, _ := ioutil.ReadAll(resp.Body)
  303. return byteRtn, resp.StatusCode, nil
  304. }
  305. func GuestGateTokenGet(appType int, pivotUrl string, ab64 string) (string, string, error) {
  306. if gAppApis[appType].GateToken == "" {
  307. req := &struct {
  308. AppType string
  309. AppBase64 string
  310. }{
  311. AppType: "Main",
  312. AppBase64: ab64,
  313. }
  314. bodyBytes, _ := json.Marshal(req)
  315. apiUrl := pivotUrl + "/gate-token-get"
  316. msgBytes, staInt, err := HttpResponseSimplePost("POST", apiUrl, bodyBytes)
  317. // fmt.Println("apiUrl:", apiUrl)
  318. // fmt.Println("bodyBytes:", string(bodyBytes))
  319. if err != nil {
  320. return "", "", e.ErrLog(e.FuncRun("45425fd34sd-The HTTP request "+apiUrl, e.CurrFuncName()), err)
  321. }
  322. if staInt != 200 {
  323. return "", "", errors.New(e.FuncRun("87ty344ra3-Request Fail "+string(msgBytes), e.CurrFuncName()))
  324. }
  325. ret := &struct {
  326. ApiUrl string
  327. GateToken string
  328. }{}
  329. if err := json.Unmarshal(msgBytes, ret); err != nil {
  330. return "", "", e.ErrLog(e.FuncRun("45425fd34sd-Json Format "+apiUrl, e.CurrFuncName()), err)
  331. }
  332. gAppApis[appType].ApiUrl = ret.ApiUrl
  333. gAppApis[appType].GateToken = ret.GateToken
  334. } else {
  335. fmt.Println("GateToken already is in the ARRAY")
  336. }
  337. // fmt.Println("gSsoApiUrl:", gSsoApiUrl)
  338. // fmt.Println("gSsoGateToken:", gSsoGateToken)
  339. return gAppApis[appType].ApiUrl, gAppApis[appType].GateToken, nil
  340. }
  341. func GuestEncryptGet(code string) (string, string, error) {
  342. appType := 1 //Dbupdate
  343. req := &struct {
  344. EncryptCode string
  345. }{
  346. EncryptCode: code,
  347. }
  348. // 0:Sso, 1:Dbu
  349. pivotUrl, gateToken, err := GuestGateTokenGet(appType, abango.XConfig["DbuConnString"], abango.XConfig["DbuAppBase64"])
  350. if err != nil {
  351. return "", "", e.ErrLog(e.FuncRun("23rfsr3qrase", e.CurrFuncName()), err)
  352. }
  353. ret := &struct {
  354. EncrypteKey string
  355. SaltKey string
  356. }{}
  357. bodyBytes, _ := json.Marshal(req)
  358. apiUrl := pivotUrl + "/encrypt-get"
  359. msgBytes, staInt, err := HttpResponseWithGt("POST", apiUrl, bodyBytes, gateToken)
  360. if err != nil {
  361. return "", "", e.ErrLog(e.FuncRun("1eadwrq34dxc-The HTTP request "+apiUrl, e.CurrFuncName()), err)
  362. }
  363. if staInt != 200 {
  364. gAppApis[appType].GateToken = "" // GateToke Expired 경우 Clear 한다.
  365. return "", "", errors.New(e.FuncRun("45faw3rfw-Request Fail "+string(msgBytes), e.CurrFuncName()))
  366. }
  367. if err := json.Unmarshal(msgBytes, ret); err != nil {
  368. return "", "", e.ErrLog(e.FuncRun("6756er345r3", e.CurrFuncName()), err)
  369. }
  370. return ret.EncrypteKey, ret.SaltKey, nil
  371. }
  372. func GuestAvailDbupdateGet(lastno string, isskipup string) ([]byte, error) {
  373. appType := 1 //Dbupdate
  374. req := &struct {
  375. DbupdateNo string
  376. IsSkipUpdate string
  377. }{
  378. DbupdateNo: lastno,
  379. IsSkipUpdate: isskipup,
  380. }
  381. // 0:Sso, 1:Dbu
  382. pivotUrl, gateToken, err := GuestGateTokenGet(appType, abango.XConfig["DbuConnString"], abango.XConfig["DbuAppBase64"])
  383. if err != nil {
  384. return nil, e.ErrLog(e.FuncRun("23rfsr3qrase", e.CurrFuncName()), err)
  385. }
  386. bodyBytes, _ := json.Marshal(req)
  387. apiUrl := pivotUrl + "/avail-dbupdate-get"
  388. msgBytes, staInt, err := HttpResponseWithGt("POST", apiUrl, bodyBytes, gateToken)
  389. if err != nil {
  390. return nil, e.ErrLog(e.FuncRun("1eadwrq34dxc-The HTTP request "+apiUrl, e.CurrFuncName()), err)
  391. }
  392. if staInt != 200 {
  393. gAppApis[appType].GateToken = "" // GateToke Expired 경우 Clear 한다.
  394. return nil, errors.New(e.FuncRun("0asfweijcvs-Request Fail "+string(msgBytes), e.CurrFuncName()))
  395. }
  396. return msgBytes, nil
  397. }
  398. func GuestKeyPairGet(clientId string) (string, error) {
  399. appType := 0 //Dbupdate
  400. req := &struct {
  401. ClientId string
  402. }{
  403. ClientId: clientId,
  404. }
  405. // fmt.Println("clientId:", clientId)
  406. // 0:Sso, 1:Dbu
  407. pivotUrl, gateToken, err := GuestGateTokenGet(appType, abango.XConfig["SsoConnString"], abango.XConfig["SsoAppBase64"])
  408. if err != nil {
  409. return "", e.ErrLog(e.FuncRun("23rfsr3qrase", e.CurrFuncName()), err)
  410. }
  411. ret := &struct {
  412. KeyPair string
  413. }{}
  414. bodyBytes, _ := json.Marshal(req)
  415. apiUrl := pivotUrl + "/key-pair-get"
  416. msgBytes, staInt, err := HttpResponseWithGt("POST", apiUrl, bodyBytes, gateToken)
  417. if err != nil {
  418. return "", e.ErrLog(e.FuncRun("1eadwrq34dxc-The HTTP request "+apiUrl, e.CurrFuncName()), err)
  419. }
  420. if staInt != 200 {
  421. gAppApis[appType].GateToken = "" // GateToke Expired 경우 Clear 한다.
  422. return "", errors.New(e.FuncRun("09665gsre3-Request Fail "+string(msgBytes), e.CurrFuncName()))
  423. }
  424. if err := json.Unmarshal(msgBytes, ret); err != nil {
  425. return "", e.ErrLog(e.FuncRun("9074tf32de", e.CurrFuncName()), err)
  426. }
  427. return ret.KeyPair, nil
  428. }
  429. func OneRowQuery(y *abango.Controller, sql string) (c1 string, c2 string, c3 string, err error) {
  430. page, err := y.Db.Query(sql)
  431. if err != nil {
  432. return "", "", "", errors.New(e.FuncRunErr("0hjnboisqow", e.CurrFuncName()+err.Error()))
  433. }
  434. if len(page) > 1 {
  435. return "", "", "", errors.New(e.FuncRunErr("0k1dt6j3d", e.CurrFuncName()+"Row Count > 1 "))
  436. }
  437. for _, row := range page {
  438. c1 = string(row["c1"])
  439. c2 = string(row["c2"])
  440. c3 = string(row["c3"])
  441. }
  442. return
  443. }
  444. func IsFirstOrderGet(y *abango.Controller, buyerId int) string {
  445. qry := fmt.Sprintf("select count(*) as c1 from dbr_sorder where buyer_id = %d ", buyerId)
  446. ordCnt, _, _, _ := OneRowQuery(y, qry)
  447. if ordCnt == "1" {
  448. return "1"
  449. } else {
  450. return "0"
  451. }
  452. }
  453. func TimeFormatGet(format string) string {
  454. rtn := ""
  455. if format == "" {
  456. rtn = "060102"
  457. } else if format == "YYMMDD" {
  458. rtn = "060102"
  459. } else if format == "YYYYMMDD" {
  460. rtn = "20060102"
  461. } else if format == "YY-MM-DD" {
  462. rtn = "06-01-02"
  463. } else if format == "YY.MM.DD" {
  464. rtn = "06.01.02"
  465. } else if format == "YYMM" {
  466. rtn = "0601"
  467. } else if format == "YY" {
  468. rtn = "06"
  469. }
  470. return rtn
  471. }