common-func-dev.go- 13 KB

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