common-func-dev.go-- 13 KB

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