user_bind.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. package user
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "hongze/hongze_yb/global"
  7. "hongze/hongze_yb/models/tables/rddp/msg_code"
  8. "hongze/hongze_yb/models/tables/rddp/session"
  9. "hongze/hongze_yb/models/tables/user_record"
  10. "hongze/hongze_yb/models/tables/wx_user"
  11. "hongze/hongze_yb/models/tables/wx_user_log"
  12. "hongze/hongze_yb/utils"
  13. "strconv"
  14. "time"
  15. )
  16. // BindWxUser 用户注册/绑定
  17. func BindWxUser(openid, mobile, email, code string, bindType, areaNum, registerPlatform int) (token string, userInfo UserInfo, err error, errMsg string) {
  18. switch bindType {
  19. case 1: //手机号
  20. _, tmpErr := msg_code.GetMsgCode(mobile, code)
  21. if tmpErr != nil {
  22. if err == utils.ErrNoRow {
  23. err = errors.New("校验验证码失败,Err:" + tmpErr.Error())
  24. errMsg = "校验验证码失败"
  25. return
  26. } else {
  27. err = errors.New("校验验证码失败,Err:" + tmpErr.Error())
  28. errMsg = "验证码错误,请重新输入"
  29. return
  30. }
  31. }
  32. case 2: //邮箱
  33. _, tmpErr := msg_code.GetMsgCode(email, code)
  34. if tmpErr != nil {
  35. if err == utils.ErrNoRow {
  36. err = errors.New("校验验证码失败,Err:" + tmpErr.Error())
  37. errMsg = "校验验证码失败"
  38. return
  39. } else {
  40. err = errors.New("校验验证码失败,Err:" + tmpErr.Error())
  41. errMsg = "验证码错误,请重新输入"
  42. return
  43. }
  44. }
  45. case 3: //微信授权登录(无需校验)
  46. default:
  47. err = errors.New("无效的绑定方式,bindType:" + strconv.Itoa(bindType))
  48. errMsg = "无效的绑定方式"
  49. return
  50. }
  51. userInfo, errMsg, err = bindWxUser(openid, mobile, email, areaNum, registerPlatform)
  52. if err != nil {
  53. if errMsg == `` {
  54. errMsg = "绑定失败:" + err.Error()
  55. }
  56. err = errors.New("BindWxUser绑定失败: " + err.Error())
  57. return
  58. }
  59. sessionItem, err := session.GetTokenByOpenId(userInfo.OpenID)
  60. if err != nil && err != utils.ErrNoRow {
  61. errMsg = "登录失败"
  62. err = errors.New("登录失败,获取token失败:" + err.Error())
  63. return
  64. }
  65. if sessionItem == nil || (err != nil && err == utils.ErrNoRow) {
  66. timeUnix := time.Now().Unix()
  67. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  68. token = utils.MD5(userInfo.OpenID) + utils.MD5(timeUnixStr)
  69. //新增session
  70. {
  71. sessionInfo := &session.Session{
  72. OpenID: userInfo.OpenID,
  73. UserID: int64(userInfo.UserID),
  74. CreatedTime: time.Now(),
  75. LastUpdatedTime: time.Now(),
  76. ExpireTime: time.Now().AddDate(0, 1, 0),
  77. AccessToken: token,
  78. }
  79. tmpErr := sessionInfo.Create()
  80. if tmpErr != nil {
  81. errMsg = "登录失败"
  82. err = errors.New("登录失败,新增用户session信息失败:" + tmpErr.Error())
  83. return
  84. }
  85. }
  86. } else {
  87. token = sessionItem.AccessToken
  88. _ = sessionItem.UpdateSession(int64(userInfo.UserID), time.Now().AddDate(0, 1, 0))
  89. }
  90. err = nil
  91. tmpErr := wx_user.ModifyFirstLogin(userInfo.UserID)
  92. if tmpErr != nil {
  93. fmt.Println("变更联系人是否第一次登录失败,ERR:", tmpErr)
  94. return
  95. }
  96. //新增登录日志
  97. //新增登录日志
  98. {
  99. loginLog := &wx_user_log.WxUserLog{
  100. UserID: int(userInfo.UserID),
  101. OpenID: userInfo.OpenID,
  102. UnionID: userInfo.UnionID,
  103. Email: userInfo.Email,
  104. Mobile: userInfo.Mobile,
  105. CreateTime: time.Now(),
  106. Handle: "yb_login",
  107. Remark: token,
  108. }
  109. go loginLog.Create()
  110. }
  111. return
  112. }
  113. // bindWxUser 用户注册/绑定
  114. func bindWxUser(openid, mobile, email string, areaNum, registerPlatform int) (userInfo UserInfo, errMsg string, err error) {
  115. source := int8(utils.USER_RECORD_PLATFORM_YB) //绑定来源,1:微信端,2:pc网页端,3:查研观向小程序,4:每日咨询
  116. if mobile == "" && email == "" {
  117. err = errors.New("手机号或邮箱必填一个")
  118. return
  119. }
  120. var bindAccount string
  121. var wxUser *wx_user.WxUser
  122. needCreateWxUser := true
  123. //根据手机号获取用户信息
  124. if mobile != "" {
  125. tmpWxUser, wxUserErr := wx_user.GetByMobile(mobile)
  126. if wxUserErr != nil {
  127. if wxUserErr != utils.ErrNoRow {
  128. err = wxUserErr
  129. return
  130. }
  131. } else {
  132. needCreateWxUser = false
  133. wxUser = tmpWxUser
  134. bindAccount = mobile
  135. }
  136. }
  137. //根据邮箱获取用户信息
  138. if needCreateWxUser && email != "" {
  139. tmpWxUser, wxUserErr := wx_user.GetByEmail(email)
  140. if wxUserErr != nil {
  141. if wxUserErr != utils.ErrNoRow {
  142. err = wxUserErr
  143. return
  144. }
  145. } else {
  146. needCreateWxUser = false
  147. wxUser = tmpWxUser
  148. bindAccount = email
  149. }
  150. }
  151. //查询openid的第三方(微信)信息
  152. userRecord, err := user_record.GetByOpenID(openid)
  153. if err != nil {
  154. return
  155. }
  156. var userId int
  157. //如果查询出来的结果是空,那么需要新增用户
  158. if needCreateWxUser {
  159. key := "bind_wx_user:mobile:" + mobile + ":email:" + email
  160. isHas, _ := global.Redis.Exists(context.TODO(), key).Result()
  161. if isHas > 0 {
  162. err = errors.New("多次提交,请关闭页面重新进入")
  163. return
  164. }
  165. global.Redis.SetNX(context.TODO(), key, "ok", time.Second*300)
  166. addwxUser := &wx_user.WxUser{
  167. CompanyID: 1,
  168. CreatedTime: time.Now(),
  169. FirstLogin: 1,
  170. Enabled: 1,
  171. RegisterPlatform: int8(registerPlatform), //账号注册来源,注册平台,1:微信端,2:PC网页端
  172. RegisterTime: time.Now(),
  173. Mobile: mobile,
  174. Email: email,
  175. IsRegister: 1,
  176. Source: source,
  177. CountryCode: strconv.Itoa(areaNum),
  178. OutboundMobile: mobile,
  179. OutboundCountryCode: strconv.Itoa(areaNum),
  180. }
  181. addUserErr := addwxUser.Create()
  182. //添加完成,清除缓存
  183. _ = global.Redis.Del(context.TODO(), key)
  184. if addUserErr != nil {
  185. err = addUserErr
  186. return
  187. }
  188. userId = int(addwxUser.UserID)
  189. tmpWxUser, _ := wx_user.GetByUserId(userId)
  190. wxUser = tmpWxUser
  191. } else {
  192. userId = int(wxUser.UserID)
  193. }
  194. //如果存在该手机号/邮箱,那么需要校验
  195. if userRecord.UserID > 0 && userRecord.UserID != userId {
  196. err = errors.New(fmt.Sprint("用户已绑定其他账户,已绑定的用户编号:", userRecord.UserID, ",不允许重复绑定"))
  197. currUser, tmpErr := wx_user.GetByUserId(userRecord.UserID)
  198. if tmpErr != utils.ErrNoRow {
  199. currBindAccount := currUser.Mobile
  200. if currBindAccount == `` {
  201. currBindAccount = currUser.Email
  202. }
  203. errMsg = "微信已绑定其它账户:" + currBindAccount
  204. }
  205. return
  206. }
  207. // 未绑定
  208. if userRecord.UserID == 0 {
  209. // 校验该手机号/邮箱是否已绑定过微信, 若已绑定过则所有微信均进行解绑, 仅绑定当前微信
  210. repeats, e := user_record.GetRepeatBindAccount(bindAccount, userRecord.UnionID)
  211. if e != nil {
  212. err = fmt.Errorf("获取重复的绑定账号数失败, err: %s", e.Error())
  213. errMsg = "绑定异常"
  214. return
  215. }
  216. if len(repeats) > 0 {
  217. // 清除绑定关系
  218. if e = user_record.ClearRepeatBindAccount(bindAccount, userRecord.UnionID); e != nil {
  219. err = fmt.Errorf("重置重复的绑定账号失败, err: %s", e.Error())
  220. errMsg = "绑定异常"
  221. return
  222. }
  223. // 清除重复账号的session
  224. repeatOpenIds := make([]string, 0)
  225. for _, v := range repeats {
  226. repeatOpenIds = append(repeatOpenIds, v.OpenID)
  227. }
  228. if e = session.ClearRepeatBindAccountToken(repeatOpenIds); e != nil {
  229. err = fmt.Errorf("清除重复绑定账号Token失败, err: %v", e)
  230. errMsg = "绑定异常"
  231. return
  232. }
  233. }
  234. userRecord.BindAccount = bindAccount
  235. userRecord.UserID = userId
  236. var updateCols = []string{"UserID", "BindAccount"}
  237. if e = userRecord.Update(updateCols); e != nil {
  238. err = e
  239. return
  240. }
  241. }
  242. //如果当前该第三方用户信息的昵称为空串的话,那么需要去查询该用户的第一个绑定信息的数据作为来源做数据修复
  243. if userRecord.NickName == "" {
  244. oldUserRecord, err := user_record.GetUserThirdRecordByUserId(userId)
  245. if err == nil && oldUserRecord != nil {
  246. //如果该用户绑定的第一条数据的头像信息不为空串,那么就去做新数据的修复
  247. if oldUserRecord.NickName != "" {
  248. _ = userRecord.ModifyUserRecordInfo(oldUserRecord.NickName, oldUserRecord.Headimgurl, oldUserRecord.City, oldUserRecord.Province, oldUserRecord.Country, oldUserRecord.Sex)
  249. }
  250. }
  251. }
  252. //如果该用户 绑定注册状态 字段处于 未注册 的情况下,那么去修改该数据
  253. if wxUser.IsRegister == 0 {
  254. err = wxUser.ModifyWxUserRegisterStatus(1, source, time.Now())
  255. if err != nil {
  256. return
  257. }
  258. }
  259. //格式化用户数据
  260. userInfo = formatWxUserAndUserRecord(wxUser, userRecord)
  261. return
  262. }