user_service.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. package service
  2. import (
  3. "crypto/sha1"
  4. "database/sql"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "gopkg.in/guregu/null.v3"
  10. "log"
  11. "strings"
  12. "time"
  13. "gopkg.in/redis.v2"
  14. "xiaoniaokuaiyan.com/xiaoniao/config"
  15. "xiaoniaokuaiyan.com/xiaoniao/constants"
  16. dal "xiaoniaokuaiyan.com/xiaoniao/dal"
  17. "xiaoniaokuaiyan.com/xiaoniao/entity"
  18. server "xiaoniaokuaiyan.com/xiaoniao/server"
  19. util "xiaoniaokuaiyan.com/xiaoniao/util"
  20. )
  21. const PASSWORD_KEY string = "2015bird2015assay2015"
  22. type UserService struct {
  23. server.UserService
  24. dal.IUser
  25. }
  26. /*var USER_NOT_EXISTS_ERROR = errors.New("user account not exists")
  27. var USER_ALREADY_EXISTS_ERROR = errors.New("account already regist")
  28. func getUser(userName string) (*entity.User, error) {
  29. db := util.GetSqlDB()
  30. strSql := "select ID, CUSTOM_MOBILE, CUSTOM_PASSWORD, custom_salt as CUSTOM_SALT from custom where custom_mobile = ? limit 1"
  31. var user entity.User
  32. err := db.Get(&user, strSql, userName)
  33. if err != nil {
  34. return nil, USER_NOT_EXISTS_ERROR
  35. }
  36. return &user, nil
  37. }*/
  38. func (userService *UserService) Login(params map[string]string) (interface{}, error) {
  39. loginType := params["type"]
  40. mobile := params["mobile"]
  41. if loginType != "wx" && loginType != "zfb" && loginType != "trd" {
  42. if ok := util.IsMobile(mobile); !ok {
  43. return nil, errors.New("1::手机号码有误!")
  44. }
  45. }
  46. isNew := true
  47. switch loginType {
  48. case "normal":
  49. user, err := userService.IUser.Get(mobile)
  50. if err != nil {
  51. return nil, errors.New("3::用户不存在,请先注册")
  52. }
  53. password := params["password"]
  54. if password == "" {
  55. return nil, errors.New("2::密码不能为空")
  56. }
  57. dstPwd := encryptPassword(PASSWORD_KEY + password + user.PasswordSalt)
  58. if dstPwd != user.Password {
  59. return nil, errors.New("4::password incorrect")
  60. }
  61. case "vcode":
  62. vcode := params["vcode"]
  63. _, err := dal.DefaultSMSCodeDal.Get(mobile, vcode, int(constants.SMSCODE_LOGIN))
  64. if err != nil {
  65. return nil, errors.New("5::验证码错误")
  66. }
  67. userTemp, err := userService._registUser(mobile, false)
  68. if err != nil {
  69. return nil, errors.New("regist failed")
  70. }
  71. if userTemp != nil {
  72. isNew = userTemp.IsNew
  73. }
  74. go func() {
  75. db := util.GetWriteSqlDB()
  76. db.Exec("update t_sms_code set is_used = 1 where mobile=? and code_type = ? and code=?", mobile, constants.SMSCODE_LOGIN, vcode)
  77. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", mobile)
  78. unionId := params["unionId"]
  79. if len(unionId) > 0 {
  80. db.Exec("update t_custom set unionid = ? where mobile = ?;", unionId, mobile)
  81. }
  82. //20220530 保存三方openid
  83. if openidtrd, ok := params["openid_trd"]; ok && len(strings.TrimSpace(openidtrd)) > 0 {
  84. var extra = map[string]interface{}{}
  85. if userTemp.Extra.Valid {
  86. json.Unmarshal([]byte(userTemp.Extra.String), &extra)
  87. }
  88. var key = "openid_trd"
  89. extra[key] = openidtrd
  90. buf, _ := json.Marshal(extra)
  91. um := entity.User{
  92. Mobile: mobile,
  93. Extra: string(buf),
  94. }
  95. _, err = userService.IUser.Update(&um)
  96. }
  97. }()
  98. case "wx":
  99. unionId := params["unionId"]
  100. user, err := userService.IUser.GetUserByUnionid(unionId)
  101. if err != nil {
  102. return nil, errors.New("3::用户不存在,请先注册")
  103. }
  104. isNew = false
  105. mobile = user.Mobile
  106. case "mp":
  107. //qz add 20201124 小程序注册,
  108. userTemp, err := userService._registUser(mobile, false)
  109. if err != nil {
  110. return nil, errors.New("regist failed")
  111. }
  112. if userTemp != nil {
  113. isNew = userTemp.IsNew
  114. }
  115. param := map[string]interface{}{}
  116. //var openid interface{}
  117. if userTemp.Extra.Valid { //&& userTemp.AccountType == 1
  118. json.Unmarshal([]byte(userTemp.Extra.String), &param)
  119. //openid = param[openidKey]
  120. }
  121. param["openid_mp"] = params["openid_mp"]
  122. extraStr, err := json.Marshal(param)
  123. if err != nil {
  124. return nil, errors.New("7::type mp update extra error :" + err.Error())
  125. }
  126. go func() {
  127. db := util.GetWriteSqlDB()
  128. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", mobile)
  129. unionId := params["unionId"]
  130. if len(unionId) > 0 {
  131. db.Exec("update t_custom set unionid = ?,extra = ? where mobile = ?;", unionId, string(extraStr), mobile)
  132. }
  133. }()
  134. case "zfb": //支付宝小程序登录
  135. zfbUserId := params["user_zfb_id"]
  136. user, err := userService.IUser.GetUserByUserId(zfbUserId)
  137. if err != nil {
  138. return nil, errors.New("3::用户不存在,请先注册")
  139. }
  140. isNew = false
  141. mobile = user.Mobile
  142. case "mini": //支付宝小程序注册
  143. userTemp, err := userService._registUser(mobile, false)
  144. if err != nil {
  145. return nil, errors.New("regist failed")
  146. }
  147. if userTemp != nil {
  148. isNew = userTemp.IsNew
  149. }
  150. param := map[string]interface{}{}
  151. //var openid interface{}
  152. if userTemp.Extra.Valid { //&& userTemp.AccountType == 1
  153. json.Unmarshal([]byte(userTemp.Extra.String), &param)
  154. //openid = param[openidKey]
  155. }
  156. param["user_zfb_id"] = params["user_zfb_id"]
  157. extraStr, err := json.Marshal(param)
  158. if err != nil {
  159. return nil, errors.New("7::type mp update extra error :" + err.Error())
  160. }
  161. go func() {
  162. db := util.GetWriteSqlDB()
  163. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", mobile)
  164. db.Exec("update t_custom set extra = ? where mobile = ?;", string(extraStr), mobile)
  165. }()
  166. case "trd":
  167. //20220530 参照wx 三方openid 登录
  168. if openidtrd, ok := params["openid_trd"]; ok && len(strings.TrimSpace(openidtrd)) > 0 {
  169. user, err := userService.IUser.GetUserByUserId(openidtrd)
  170. if err != nil {
  171. return nil, errors.New("3::用户不存在,请先注册")
  172. }
  173. isNew = false
  174. mobile = user.Mobile
  175. } else {
  176. return nil, errors.New("3::缺少openid_trd")
  177. }
  178. default:
  179. return nil, errors.New("6::unknow login type")
  180. }
  181. /*config := nsq.NewConfig()
  182. producer, _ := nsq.NewProducer("127.0.0.1:4150", config)
  183. producer.Publish("api_logic", []byte("user "+mobile+"logged in"))
  184. */
  185. user, _ := userService.IUser.Get(mobile)
  186. //todo save user login identifier to redis or somewhere else
  187. var client *redis.Client = util.GetRedis()
  188. client.Select(server.REDIS_API_AUTH_DB)
  189. sessionToken := server.GenerateSessionToken(fmt.Sprintf("%d-%s", user.Id, user.Mobile))
  190. tokenBytes, err := json.Marshal(sessionToken)
  191. if err != nil {
  192. return nil, err
  193. }
  194. //sessionId := server.GenerateSessionId(user.Id, source)
  195. statusCmd := client.Set(sessionToken.Token, string(tokenBytes))
  196. if err = statusCmd.Err(); err != nil {
  197. return nil, err
  198. }
  199. /*var exp int64
  200. exp, err = config.IniConf.Section("server").Key("redis_api_session_expire").Int64()
  201. if err != nil || exp < 30 {
  202. exp = 60
  203. }
  204. client.Expire(sessionToken.Token, time.Minute*time.Duration(exp))*/
  205. param := map[string]interface{}{}
  206. var openid interface{}
  207. var openidKey = "openid"
  208. if k, ok := params["wx_type"]; ok && k == "mp" {
  209. openidKey = "openid_mp"
  210. }
  211. if user.Extra.Valid && user.AccountType == 1 {
  212. json.Unmarshal([]byte(user.Extra.String), &param)
  213. openid = param[openidKey]
  214. }
  215. var wxInfo interface{} = nil
  216. if params["openid"] != "" {
  217. wxInfo, err = getUserWxInfo(params["openid"])
  218. if err != nil {
  219. return nil, err
  220. }
  221. }
  222. user.IsNew = isNew
  223. return map[string]interface{}{
  224. "token": sessionToken.Token,
  225. "data": user,
  226. "openid": openid,
  227. "wxinfo": wxInfo,
  228. }, nil
  229. }
  230. func (userService *UserService) LoginV2(params map[string]string) (interface{}, error) {
  231. mobile := params["mobile"]
  232. if ok := util.IsMobile(mobile); !ok {
  233. return nil, errors.New("1::手机号码有误!")
  234. }
  235. vcode := params["vcode"]
  236. _, err := dal.DefaultSMSCodeDal.Get(mobile, vcode, int(constants.SMSCODE_LOGIN))
  237. if err != nil {
  238. //return nil, errors.New("5::验证码错误")
  239. }
  240. isNewCustom, err := userService._registUserV2(params)
  241. if err != nil {
  242. return nil, errors.New("regist failed")
  243. }
  244. go func() {
  245. db := util.GetWriteSqlDB()
  246. db.Exec("update t_sms_code set is_used = 1 where mobile=? and code_type = ? and code=?", mobile, constants.SMSCODE_LOGIN, vcode)
  247. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", mobile)
  248. }()
  249. /*config := nsq.NewConfig()
  250. producer, _ := nsq.NewProducer("127.0.0.1:4150", config)
  251. producer.Publish("api_logic", []byte("user "+mobile+"logged in"))
  252. */
  253. user, _ := userService.IUser.Get(mobile)
  254. //todo save user login identifier to redis or somewhere else
  255. client := util.GetRedis()
  256. client.Select(server.REDIS_API_AUTH_DB)
  257. sessionToken := server.GenerateSessionToken(fmt.Sprintf("%d-%s", user.Id, user.Mobile))
  258. tokenBytes, err := json.Marshal(sessionToken)
  259. if err != nil {
  260. return nil, err
  261. }
  262. //sessionId := server.GenerateSessionId(user.Id, source)
  263. statusCmd := client.Set(sessionToken.Token, string(tokenBytes))
  264. if err = statusCmd.Err(); err != nil {
  265. return nil, err
  266. }
  267. /*var exp int64
  268. exp, err = config.IniConf.Section("server").Key("redis_api_session_expire").Int64()
  269. if err != nil || exp < 30 {
  270. exp = 60
  271. }
  272. client.Expire(sessionToken.Token, time.Minute*time.Duration(exp))*/
  273. param := map[string]interface{}{}
  274. var openid interface{}
  275. var openidKey = "openid"
  276. if k, ok := params["wx_type"]; ok && k == "mp" {
  277. openidKey = "openid_mp"
  278. }
  279. if user.Extra.Valid && user.AccountType == 1 {
  280. json.Unmarshal([]byte(user.Extra.String), &param)
  281. openid = param[openidKey]
  282. }
  283. var wxInfo interface{} = nil
  284. if params["openid"] != "" {
  285. wxInfo, err = getUserWxInfo(params["openid"])
  286. if err != nil {
  287. return nil, err
  288. }
  289. }
  290. return map[string]interface{}{
  291. "token": sessionToken.Token,
  292. "data": user,
  293. "openid": openid,
  294. "wxinfo": wxInfo,
  295. "isNewCustom": isNewCustom,
  296. }, nil
  297. }
  298. func (userService *UserService) LoginCoupons(params map[string]string) (interface{}, error) {
  299. mobile := params["mobile"]
  300. //isNew := true
  301. vcode := params["vcode"]
  302. _, err := dal.DefaultSMSCodeDal.Get(mobile, vcode, int(constants.SMSCODE_LOGIN))
  303. if err != nil {
  304. //return nil, errors.New("5::验证码错误")
  305. }
  306. userTemp, err := userService._registUser(mobile, false)
  307. if err != nil {
  308. return nil, errors.New("regist failed")
  309. }
  310. if userTemp != nil {
  311. //isNew = userTemp.IsNew
  312. }
  313. go func() {
  314. db := util.GetWriteSqlDB()
  315. db.Exec("update t_sms_code set is_used = 1 where mobile=? and code_type = ? and code=?", mobile, constants.SMSCODE_LOGIN, vcode)
  316. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", mobile)
  317. unionId := params["unionId"]
  318. if len(unionId) > 0 {
  319. db.Exec("update t_custom set unionid = ? where mobile = ?;", unionId, mobile)
  320. }
  321. }()
  322. go func() {
  323. //20210304此处逻辑 只能插入一次t_login_coupons
  324. //如果之前下过有效订单发放 99 优惠券;
  325. //如果之前没下过单,或者单据都是在状态(7,9,14) 发放30 优惠券
  326. db := util.GetWriteSqlDB()
  327. //todo 插入 t_login_coupons 只能注册一次
  328. sqlResult := db.MustExec("insert into t_login_coupons (mobile,is_send) SELECT ?, 0 FROM DUAL WHERE NOT EXISTS(SELECT mobile FROM t_login_coupons WHERE mobile = ?)", mobile, mobile)
  329. if re, _ := sqlResult.RowsAffected(); re <= 0 {
  330. return
  331. }
  332. client := util.GetRedis()
  333. client.Select(12)
  334. client.HSet("coupons_unsend", mobile, time.Now().Format("2006-01-02 15:04:05"))
  335. }()
  336. /*config := nsq.NewConfig()
  337. producer, _ := nsq.NewProducer("127.0.0.1:4150", config)
  338. producer.Publish("api_logic", []byte("user "+mobile+"logged in"))
  339. */
  340. user, _ := userService.IUser.Get(mobile)
  341. //todo save user login identifier to redis or somewhere else
  342. var client = util.GetRedis()
  343. client.Select(server.REDIS_API_AUTH_DB)
  344. sessionToken := server.GenerateSessionToken(fmt.Sprintf("%d-%s", user.Id, user.Mobile))
  345. tokenBytes, err := json.Marshal(sessionToken)
  346. if err != nil {
  347. return nil, err
  348. }
  349. //sessionId := server.GenerateSessionId(user.Id, source)
  350. statusCmd := client.Set(sessionToken.Token, string(tokenBytes))
  351. if err = statusCmd.Err(); err != nil {
  352. return nil, err
  353. }
  354. /*var exp int64
  355. exp, err = config.IniConf.Section("server").Key("redis_api_session_expire").Int64()
  356. if err != nil || exp < 30 {
  357. exp = 60
  358. }
  359. client.Expire(sessionToken.Token, time.Minute*time.Duration(exp))*/
  360. return nil, nil
  361. }
  362. func (userService *UserService) GetHomeInvite(params map[string]string) (interface{}, error) {
  363. data, _, err := getHomeInviteByOpenid(params["toopenid"])
  364. if err != nil {
  365. return nil, err
  366. }
  367. return data, nil
  368. }
  369. func getUserWxInfo(openid string) (interface{}, error) {
  370. var wxInfo = struct {
  371. Openid string `db:"openid" json:"openid"`
  372. Nickname string `db:"nickname" json:"nickname"`
  373. Gender int `db:"sex" json:"gender"`
  374. HeadImgUrl string `db:"headimgurl" json:"headimgurl"`
  375. Subscribe int `db:"subscribe" json:"subscribe"`
  376. }{}
  377. db := util.GetSqlDB()
  378. strSql := "select openid, nickname, sex, headimgurl,subscribe from t_wechat_userinfo where openid = ? limit 1;"
  379. err := db.Get(&wxInfo, strSql, openid)
  380. if err == sql.ErrNoRows {
  381. return nil, nil
  382. }
  383. return wxInfo, err
  384. }
  385. func (userService *UserService) GetUserWxInfo(openid string) (interface{}, error) {
  386. return getUserWxInfo(openid)
  387. }
  388. const PASSWORD_SALT_SIZE int = 6
  389. func (userService *UserService) Regist(userName string, password string, vcode string) (interface{}, error) {
  390. if ok := util.IsMobile(userName); !ok {
  391. return nil, errors.New("1::invalid user name")
  392. }
  393. if strings.Trim(password, " ") == "" {
  394. return nil, errors.New("2::password required")
  395. }
  396. _, err := dal.DefaultSMSCodeDal.Get(userName, vcode, int(constants.SMSCODE_REGIST))
  397. if err != nil {
  398. return nil, errors.New("4::验证码错误")
  399. }
  400. user, err := userService._registUser(userName, true)
  401. if err != nil {
  402. //return user, dal.DBRECORD_ALREADY_EXISTS_ERROR
  403. if err == errRecordExsits {
  404. return nil, errors.New("3::手机号已注册")
  405. }
  406. return nil, err
  407. }
  408. go func() {
  409. db := util.GetWriteSqlDB()
  410. db.Exec("update t_sms_code set is_used = 1 where mobile=? and code_type = ? and code=?", userName, constants.SMSCODE_REGIST, vcode)
  411. }()
  412. return user, nil
  413. }
  414. var errRecordExsits = errors.New("record already exists")
  415. func (userService *UserService) _registUser(userName string, toCheckReturn bool) (*entity.UserDB, error) {
  416. //check whether account is already regist
  417. user, err := userService.IUser.Get(userName)
  418. if err != nil && err != dal.DBRECORD_NOT_EXISTS_ERROR {
  419. return nil, err
  420. }
  421. if toCheckReturn {
  422. return nil, errRecordExsits
  423. }
  424. db := util.GetWriteSqlDB()
  425. if user != nil {
  426. if user.IsAcceptProto != "Y" {
  427. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", userName)
  428. }
  429. user.IsNew = false
  430. return user, nil
  431. }
  432. var pwdSalt = util.RandNumString(PASSWORD_SALT_SIZE)
  433. ml := len(userName)
  434. var password = userName[ml-6:]
  435. password = encryptPassword(PASSWORD_KEY + password + pwdSalt)
  436. var fields = map[string]interface{}{
  437. "mobile": userName,
  438. "password": password,
  439. "account": userName,
  440. "password_salt": pwdSalt,
  441. "is_accept_up": "Y",
  442. "status": 1,
  443. "created_at": time.Now().Format("2006-01-02 15:04:05"),
  444. }
  445. var sqlStr = util.GenerateInsertSql("t_custom", fields)
  446. sqlResult, err := db.NamedExec(sqlStr, fields)
  447. if err != nil {
  448. return nil, err
  449. }
  450. uid, _ := sqlResult.LastInsertId()
  451. return &entity.UserDB{
  452. Id: uid,
  453. Mobile: userName,
  454. IsNew: true,
  455. }, nil
  456. }
  457. func (userService *UserService) _registUserV2(params map[string]string) (interface{}, error) {
  458. //check whether account is already regist
  459. user, err := userService.IUser.Get(params["mobile"])
  460. if err != nil && err != dal.DBRECORD_NOT_EXISTS_ERROR {
  461. return nil, err
  462. }
  463. db := util.GetWriteSqlDB()
  464. //已经存在的用户,直接返回
  465. if user != nil {
  466. //20230517 判断修改openid 的逻辑
  467. if params["openid"] != "" {
  468. var extra string
  469. //更新openid
  470. //如果存在 extra 解析 json数据,更新openid
  471. //如果不存在,直接拼json后更新
  472. if user.Extra.Valid && strings.TrimSpace(user.Extra.String) != "" {
  473. var dat map[string]interface{}
  474. if err := json.Unmarshal([]byte(user.Extra.String), &dat); err == nil {
  475. log.Println("loginV2 update exist custom's openid ", dat)
  476. dat["openid"] = params["openid"]
  477. str, err := json.Marshal(dat)
  478. if err != nil {
  479. return nil, errors.New("2::failed to extra openid parse json by loginV2")
  480. }
  481. extra = string(str)
  482. } else {
  483. return nil, errors.New("3::failed to update openid by loginV2")
  484. }
  485. } else {
  486. extra = fmt.Sprintf(`{"openid":"%s"}`, params["openid"])
  487. }
  488. db.Exec("update t_custom set extra = ? where mobile = ?;", extra, params["mobile"])
  489. }
  490. if user.IsAcceptProto != "Y" {
  491. db.Exec("update t_custom set is_accept_up = 'Y' where mobile = ?;", params["mobile"])
  492. }
  493. return "N", nil
  494. }
  495. var pwdSalt = util.RandNumString(PASSWORD_SALT_SIZE)
  496. ml := len(params["mobile"])
  497. var password = params["mobile"][ml-6:]
  498. password = encryptPassword(PASSWORD_KEY + password + pwdSalt)
  499. var fields = map[string]interface{}{
  500. "mobile": params["mobile"],
  501. "password": password,
  502. "account": params["mobile"],
  503. "password_salt": pwdSalt,
  504. "is_accept_up": "Y",
  505. "status": 1,
  506. "extra": fmt.Sprintf(`{"openid":"%s"}`, params["openid"]),
  507. "created_at": time.Now().Format("2006-01-02 15:04:05"),
  508. }
  509. if params["openid"] == "" {
  510. //delete(fields,"extra")
  511. fields["extra"] = ""
  512. }
  513. tx := db.MustBegin()
  514. //1.新建用户数据
  515. var sqlStr = util.GenerateInsertSql("t_custom", fields)
  516. _, err = tx.NamedExec(sqlStr, fields)
  517. if err != nil {
  518. //fmt.Println("split order ", oitem.Id, err)
  519. tx.Tx.Rollback()
  520. return nil, errors.New("4::failed to insert t_custom By loginV2")
  521. }
  522. //如果toopenid 是null 取消后续操作
  523. if params["toopenid"] == "" {
  524. tx.Commit()
  525. return "Y", nil
  526. }
  527. //2.插入t_home_invite 关系
  528. strSql := "insert into t_home_invite(fromopenid, frommobile, fromnickname, fromheadimg, toopenid,create_time) values (?,?,?,?,?,?)"
  529. sqlResult := tx.MustExec(strSql, params["openid"], params["mobile"], params["fromnickname"], params["fromheadimg"], params["toopenid"], time.Now().Format("2006-01-02 15:04:05"))
  530. if ra, _ := sqlResult.RowsAffected(); ra <= 0 {
  531. tx.Tx.Rollback()
  532. return nil, errors.New("5::failed to insert t_home_invite By loginV2")
  533. }
  534. //3.统计已经存在的关系.如果大于10个,就更新t_agent
  535. _, count, err := getHomeInviteByOpenid(params["toopenid"])
  536. if err != nil {
  537. return nil, errors.New("6::failed to insert t_home_invite By loginV2")
  538. }
  539. //
  540. if count >= 9 { //因为是事务,所以第10条数据还没有提交
  541. user, err := userService.IUser.GetUserByOpenid(params["toopenid"])
  542. if err != nil && err != dal.DBRECORD_NOT_EXISTS_ERROR {
  543. tx.Tx.Rollback()
  544. return nil, errors.New("7::failed to get user mobile by toopenid By loginV2")
  545. }
  546. strSql = "update t_agent set redpacket=1000 ,updatetime = ? where openid=? "
  547. updateResult := tx.MustExec(strSql, time.Now().Format("2006-01-02 15:04:05"), params["toopenid"])
  548. if ra, _ := updateResult.RowsAffected(); ra <= 0 {
  549. strSql = "insert into t_agent(openid, mobile, updatetime,redpacket) values(?,?,?,1000)"
  550. insertResult := tx.MustExec(strSql, params["toopenid"], user.Mobile, time.Now().Format("2006-01-02 15:04:05"))
  551. if ra, _ := insertResult.RowsAffected(); ra <= 0 {
  552. tx.Tx.Rollback()
  553. return nil, errors.New("8::failed to insert/update t_agent By loginV2")
  554. }
  555. }
  556. }
  557. tx.Commit()
  558. if err != nil {
  559. return nil, err
  560. }
  561. return "Y", nil
  562. }
  563. func getHomeInviteByOpenid(openid string) (interface{}, int, error) {
  564. var homeInvite []struct {
  565. Fromopenid null.String `db:"fromopenid" json:"fromopenid"`
  566. Frommobile null.String `db:"frommobile" json:"frommobile"`
  567. Fromnickname null.String `db:"fromnickname" json:"fromnickname"`
  568. Fromheadimg null.String `db:"fromheadimg" json:"fromheadimg"`
  569. ToOpenid null.String `db:"toopenid" json:"toopenid"`
  570. CreateTime null.String `db:"create_time" json:"create_time"`
  571. }
  572. db := util.GetSqlDB()
  573. strSql := "select fromopenid, frommobile, fromnickname, fromheadimg,toopenid,create_time from t_home_invite where toopenid = ? order by create_time asc limit 10;"
  574. err := db.Select(&homeInvite, strSql, openid)
  575. if err == sql.ErrNoRows {
  576. return nil, 0, nil
  577. }
  578. return homeInvite, len(homeInvite), err
  579. }
  580. func (userService *UserService) ResetPwd(userName, password, newPassword string) (interface{}, error) {
  581. user, err := userService.IUser.Get(userName)
  582. if err != nil {
  583. return nil, err
  584. }
  585. if user == nil {
  586. return nil, errors.New("找不到用户")
  587. }
  588. password = encryptPassword(PASSWORD_KEY + password + user.PasswordSalt)
  589. if password != user.Password {
  590. return nil, errors.New("密码错误")
  591. }
  592. var pwdSalt = util.RandNumString(PASSWORD_SALT_SIZE)
  593. newPassword = encryptPassword(PASSWORD_KEY + newPassword + pwdSalt)
  594. um := entity.User{
  595. Id: user.Id,
  596. Password: newPassword,
  597. PasswordSalt: pwdSalt,
  598. }
  599. r, err := userService.IUser.Update(&um)
  600. if err != nil {
  601. return nil, err
  602. }
  603. return r, nil
  604. }
  605. func (userService *UserService) ForgetPwd(userName, vcode string, password string) (interface{}, error) {
  606. code, err := dal.DefaultSMSCodeDal.Get(userName, vcode, int(constants.SMSCODE_FORGOT_PASSWORD))
  607. if code == nil || code.Mobile == "" {
  608. return nil, errors.New("1::验证码错误")
  609. }
  610. var pwdSalt = util.RandNumString(PASSWORD_SALT_SIZE)
  611. password = encryptPassword(PASSWORD_KEY + password + pwdSalt)
  612. um := entity.User{
  613. Mobile: userName,
  614. Password: password,
  615. PasswordSalt: pwdSalt,
  616. }
  617. r, err := userService.IUser.Update(&um)
  618. if err != nil {
  619. return nil, err
  620. }
  621. go func() {
  622. db := util.GetWriteSqlDB()
  623. db.Exec("update t_sms_code set is_used = 1 where mobile=? and code_type = ? and code=?", userName, constants.SMSCODE_REGIST, vcode)
  624. }()
  625. return r, nil
  626. }
  627. func (userService *UserService) SetOpenid(mobile string, openid string, wxType string) (interface{}, error) {
  628. if ok := util.IsMobile(mobile); !ok {
  629. return false, errors.New("1::invalid mobile")
  630. }
  631. openid = strings.Trim(openid, " ")
  632. if openid == "" {
  633. return false, errors.New("2::openid is empty")
  634. }
  635. user, err := userService.IUser.Get(mobile)
  636. if err != nil {
  637. return nil, err
  638. }
  639. var extra = map[string]interface{}{}
  640. if user != nil && user.Extra.Valid {
  641. json.Unmarshal([]byte(user.Extra.String), &extra)
  642. }
  643. var key = "openid"
  644. if wxType == "mp" {
  645. key = "openid_mp"
  646. }
  647. extra[key] = openid
  648. buf, _ := json.Marshal(extra)
  649. um := entity.User{
  650. Mobile: mobile,
  651. Extra: string(buf),
  652. }
  653. _, err = userService.IUser.Update(&um)
  654. if err != nil {
  655. return false, err
  656. }
  657. return true, nil
  658. }
  659. func (userService *UserService) UpdateUserinfo(uinfo *entity.User) (interface{}, error) {
  660. toUpUinfo := entity.User{
  661. Id: uinfo.Id,
  662. Avatar: uinfo.Avatar,
  663. }
  664. return userService.IUser.Update(&toUpUinfo)
  665. }
  666. func (userService *UserService) GetQueueNotice(mobile string) (interface{}, error) {
  667. return userService.IUser.GetNotice(mobile)
  668. }
  669. func (userService *UserService) UpdateQueueNotice(notice *entity.QueueNotice) (interface{}, error) {
  670. return userService.IUser.UpdateNotice(notice)
  671. }
  672. func (userService *UserService) GetRelationship() (interface{}, error) {
  673. relationStr := config.IniConf.Section("server").Key("user_relationship").Value()
  674. return strings.Split(relationStr, ","), nil
  675. }
  676. func encryptPassword(source string) string {
  677. dst := sha1.Sum([]byte(source))
  678. dstStr := hex.EncodeToString(dst[0:])
  679. return strings.ToUpper(dstStr)
  680. }
  681. func (userService *UserService) SaveInfo(uinfo *entity.User) (interface{}, error) {
  682. toUpUinfo := entity.User{
  683. Id: uinfo.Id,
  684. Height: uinfo.Height,
  685. Weight: uinfo.Weight,
  686. Gender: uinfo.Gender,
  687. BirthDay: uinfo.BirthDay,
  688. }
  689. return userService.IUser.Update(&toUpUinfo)
  690. }
  691. func (userService *UserService) SaveHobby(uinfo *entity.User) (interface{}, error) {
  692. toUpUinfo := entity.User{
  693. Id: uinfo.Id,
  694. Hobby: uinfo.Hobby,
  695. }
  696. return userService.IUser.Update(&toUpUinfo)
  697. }
  698. func (userService *UserService) GetHobby() (interface{}, error) {
  699. db := util.GetSqlDB()
  700. result := []struct {
  701. Id int `db:"id"`
  702. HobbyName string `db:"hobby_name"`
  703. ImgUrlSelected null.String `db:"img_url_selected"`
  704. ImgUrlUnSelected null.String `db:"img_url_unselected"`
  705. }{}
  706. err := db.Select(&result, "select * from t_custom_hobby ")
  707. if err != nil {
  708. return "", errors.New("1::search hobby error: " + err.Error())
  709. }
  710. return result, nil
  711. }