common-func-dev.go 13 KB

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