user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. package services
  2. import (
  3. "errors"
  4. "fmt"
  5. "hongze/hongze_api/models"
  6. "hongze/hongze_api/services/go_redis"
  7. "hongze/hongze_api/utils"
  8. "strconv"
  9. "time"
  10. )
  11. var ERR_NO_USER_RECORD = errors.New("用户关系没有入库")
  12. var ERR_USER_NOT_BIND = errors.New("用户没有绑定")
  13. //通过openid获取用户信息
  14. func GetWxUserItemByOpenId(openid string) (item *models.WxUserItem, err error) {
  15. //通过openid获取用户关联信息
  16. userRecord, userRecordErr := models.GetUserRecordByOpenId(openid)
  17. if userRecordErr != nil {
  18. if userRecordErr.Error() == utils.ErrNoRow() {
  19. err = ERR_NO_USER_RECORD
  20. return
  21. } else {
  22. err = userRecordErr
  23. return
  24. }
  25. }
  26. //该openid在系统中没有关联关系
  27. if userRecord == nil {
  28. err = ERR_NO_USER_RECORD
  29. return
  30. }
  31. //该openid没有绑定用户
  32. if userRecord.UserId <= 0 {
  33. err = ERR_USER_NOT_BIND
  34. item = new(models.WxUserItem)
  35. //格式化返回用户数据
  36. formatWxUserAndUserRecord(item, userRecord)
  37. return
  38. }
  39. //获取用户信息
  40. item, wxUserErr := models.GetWxUserItemByUserId(userRecord.UserId)
  41. if wxUserErr != nil {
  42. err = wxUserErr
  43. //如果是找不到数据,那么可能是该用户被删除了,但是user_record没有删除对应的关系
  44. if wxUserErr.Error() == utils.ErrNoRow() {
  45. //用户被删除了,但是user_record没有删除对应的关系,那么去解除绑定
  46. userUnbindErr := models.UnBindUserRecordByOpenid(openid)
  47. if userUnbindErr != nil {
  48. err = userUnbindErr
  49. return
  50. }
  51. //返回状态为 用户未绑定 逻辑代码
  52. err = ERR_USER_NOT_BIND
  53. item = new(models.WxUserItem)
  54. //格式化返回用户数据
  55. formatWxUserAndUserRecord(item, userRecord)
  56. return
  57. }
  58. return
  59. }
  60. //格式化返回用户数据
  61. formatWxUserAndUserRecord(item, userRecord)
  62. return
  63. }
  64. //根据用户id和平台id获取用户信息
  65. func GetWxUserItemByUserId(userId, platform int) (wxUserItem *models.WxUserItem, err error) {
  66. //获取用户信息
  67. wxUserItem, wxUserErr := models.GetWxUserItemByUserId(userId)
  68. if wxUserErr != nil {
  69. err = wxUserErr
  70. return
  71. }
  72. //格式化返回用户数据
  73. formatWxUser(wxUserItem, platform)
  74. return
  75. }
  76. //根据用户邮箱和平台id获取用户信息
  77. func GetWxUserItemByEmail(email string, platform int) (wxUserItem *models.WxUserItem, err error) {
  78. //获取用户信息
  79. wxUserItem, wxUserErr := models.GetWxUserItemByEmail(email)
  80. if wxUserErr != nil {
  81. err = wxUserErr
  82. return
  83. }
  84. //格式化返回用户数据
  85. formatWxUser(wxUserItem, platform)
  86. return
  87. }
  88. //根据用户手机号和平台id获取用户信息
  89. func GetWxUserItemByMobile(mobile string, platform int) (wxUserItem *models.WxUserItem, err error) {
  90. //获取用户信息
  91. wxUserItem, wxUserErr := models.GetWxUserItemByMobile(mobile)
  92. if wxUserErr != nil {
  93. err = wxUserErr
  94. return
  95. }
  96. //格式化返回用户数据
  97. formatWxUser(wxUserItem, platform)
  98. return
  99. }
  100. //根据用户unionid和平台id获取用户信息
  101. func GetWxUserItemByUnionId(unionId string, platform int) (wxUserItem *models.WxUserItem, err error) {
  102. //获取用户信息
  103. wxUserItem, wxUserErr := models.GetWxUserItemByUnionid(unionId)
  104. if wxUserErr != nil {
  105. err = wxUserErr
  106. return
  107. }
  108. //格式化返回用户数据
  109. formatWxUser(wxUserItem, platform)
  110. return
  111. }
  112. //通过用户 关系表记录 和 用户记录 格式化返回 用户数据
  113. func formatWxUserAndUserRecord(wxUser *models.WxUserItem, userRecord *models.UserRecord) {
  114. wxUser.OpenId = userRecord.OpenId
  115. wxUser.UnionId = userRecord.UnionId
  116. wxUser.NickName = userRecord.NickName
  117. //wxUser.RealName = userRecord.RealName
  118. //wxUser.BindAccount = userRecord.BindAccount
  119. wxUser.Headimgurl = userRecord.Headimgurl
  120. }
  121. //通过用户 用户记录 和 来源平台 格式化返回 用户数据
  122. func formatWxUser(wxUser *models.WxUserItem, platform int) {
  123. //根据用户id和平台id获取用户关系
  124. userRecord, userRecordErr := models.GetUserRecordByUserId(wxUser.UserId, platform)
  125. if userRecordErr != nil {
  126. if userRecordErr.Error() != utils.ErrNoRow() {
  127. return
  128. }
  129. if userRecordErr.Error() == utils.ErrNoRow() {
  130. return
  131. }
  132. }
  133. //该openid在系统中没有关联关系
  134. if userRecord == nil {
  135. return
  136. }
  137. wxUser.OpenId = userRecord.OpenId
  138. wxUser.UnionId = userRecord.UnionId
  139. wxUser.NickName = userRecord.NickName
  140. //wxUser.RealName = userRecord.RealName
  141. //wxUser.BindAccount = userRecord.BindAccount
  142. wxUser.Headimgurl = userRecord.Headimgurl
  143. return
  144. }
  145. // BindWxUser 用户绑定
  146. func BindWxUser(openid, mobile, email string, areaNum, registerPlatform int) (wxUser *models.WxUserItem, errMsg string, err error) {
  147. source := 1 //绑定来源,1:微信端,2:pc网页端,3:查研观向小程序,4:每日咨询
  148. if mobile == "" && email == "" {
  149. err = errors.New("手机号或邮箱必填一个")
  150. return
  151. }
  152. var bindAccount string
  153. //根据手机号获取用户信息
  154. if mobile != "" {
  155. tmpWxUser, wxUserErr := models.GetWxUserItemByMobile(mobile)
  156. if wxUserErr != nil && wxUserErr.Error() != utils.ErrNoRow() {
  157. err = wxUserErr
  158. return
  159. }
  160. wxUser = tmpWxUser
  161. bindAccount = mobile
  162. }
  163. //根据邮箱获取用户信息
  164. if wxUser == nil && email != "" {
  165. tmpWxUser, wxUserErr := models.GetWxUserItemByEmail(email)
  166. if wxUserErr != nil && wxUserErr.Error() != utils.ErrNoRow() {
  167. err = wxUserErr
  168. return
  169. }
  170. wxUser = tmpWxUser
  171. bindAccount = email
  172. }
  173. //查询openid的第三方(微信)信息
  174. userRecord, err := models.GetUserRecordByOpenId(openid)
  175. if err != nil {
  176. return
  177. }
  178. var userId int
  179. //如果查询出来的用户是nil,那么需要新增用户
  180. if wxUser == nil {
  181. key := "bind_wx_user:mobile:" + mobile + ":email:" + email
  182. isHas := go_redis.IsExist(key)
  183. if isHas {
  184. err = errors.New("多次提交,请关闭页面重新进入")
  185. return
  186. }
  187. go_redis.SetNX(key, "ok", time.Second*300)
  188. user := &models.WxUser{
  189. CompanyId: 1,
  190. CreatedTime: time.Now(),
  191. FirstLogin: 1,
  192. Enabled: 1,
  193. RegisterPlatform: registerPlatform, //账号注册来源,注册平台,1:微信端,2:PC网页端
  194. RegisterTime: time.Now(),
  195. Mobile: mobile,
  196. Email: email,
  197. IsRegister: 1,
  198. Source: source,
  199. CountryCode: strconv.Itoa(areaNum),
  200. OutboundMobile: mobile,
  201. OutboundCountryCode: strconv.Itoa(areaNum),
  202. }
  203. tmpUserId, addUserErr := models.AddWxUser(user)
  204. //添加完成,清除缓存
  205. _ = go_redis.Delete(key)
  206. if addUserErr != nil {
  207. err = addUserErr
  208. return
  209. }
  210. user.UserId = int(tmpUserId)
  211. userId = int(tmpUserId)
  212. wxUser, err = models.GetWxUserItemByUserId(userId)
  213. } else {
  214. userId = wxUser.UserId
  215. }
  216. //如果存在该手机号/邮箱,那么需要校验
  217. if userRecord.UserId > 0 && userRecord.UserId != userId {
  218. err = errors.New(fmt.Sprint("用户已绑定其他账户,已绑定的用户编号:", userRecord.UserId, ",不允许重复绑定"))
  219. currUser, _ := models.GetWxUserItemByUserId(userRecord.UserId)
  220. if currUser != nil {
  221. currBindAccount := currUser.Mobile
  222. if currBindAccount == `` {
  223. currBindAccount = currUser.Email
  224. }
  225. errMsg = "微信已绑定其它账户:" + currBindAccount
  226. }
  227. return
  228. }
  229. if userRecord.UserId == 0 {
  230. err = models.BindUserRecordByOpenid(userId, openid, bindAccount)
  231. if err != nil {
  232. return
  233. }
  234. userRecord.UserId = userId
  235. }
  236. //如果当前该第三方用户信息的昵称为空串的话,那么需要去查询该用户的第一个绑定信息的数据作为来源做数据修复
  237. if userRecord.NickName == "" {
  238. oldUserRecord, err := models.GetUserThirdRecordByUserId(userId)
  239. if err == nil && oldUserRecord != nil {
  240. //如果该用户绑定的第一条数据的头像信息不为空串,那么就去做新数据的修复
  241. if oldUserRecord.NickName != "" {
  242. _ = models.ModifyUserRecordInfo(userRecord.OpenId, oldUserRecord.NickName, oldUserRecord.Headimgurl, oldUserRecord.City, oldUserRecord.Province, oldUserRecord.Country, oldUserRecord.Sex, userId)
  243. }
  244. }
  245. }
  246. //如果该用户 绑定注册状态 字段处于 未注册 的情况下,那么去修改该数据
  247. if wxUser.IsRegister == 0 {
  248. err = models.ModifyWxUserRegisterStatus(userId, 1, source, time.Now())
  249. if err != nil {
  250. return
  251. }
  252. }
  253. if userRecord.UnionId != `` {
  254. tmpErr := models.ModifyUserIdByUnionId(userRecord.UnionId, userRecord.UserId)
  255. if tmpErr != nil {
  256. utils.FileLog.Info("通过用户unionId修改所有未绑定用户的id失败,Err:" + err.Error())
  257. }
  258. }
  259. //格式化用户数据
  260. formatWxUserAndUserRecord(wxUser, userRecord)
  261. return
  262. }
  263. //微信登录
  264. func WxLogin(wxPlatform int, code string, wxAccessToken *WxAccessToken, wxUserInfo *WxUserInfo) (token string, userId, firstLogin, permission int, err error) {
  265. openId := wxAccessToken.Openid
  266. unionId := wxAccessToken.Unionid
  267. if unionId == "" {
  268. unionId = wxUserInfo.Unionid
  269. }
  270. //firstLogin==1,强制绑定手机号或者邮箱
  271. firstLogin = 1
  272. QUERY_WX_USER:
  273. wxUser, wxUserErr := GetWxUserItemByOpenId(openId)
  274. if wxUserErr == ERR_NO_USER_RECORD { //没有用户openid记录
  275. _, recordErr := AddUserRecord(openId, unionId, wxUserInfo.Nickname, "", wxUserInfo.Province, wxUserInfo.City, wxUserInfo.Country, wxUserInfo.Headimgurl, "", wxPlatform, wxUserInfo.Sex, 0)
  276. //如果插入失败,那么直接将错误信息返回
  277. if recordErr != nil {
  278. err = recordErr
  279. return
  280. }
  281. //插入成功后,需要重新查询该用户,并进入下面的逻辑
  282. goto QUERY_WX_USER
  283. } else if wxUserErr == ERR_USER_NOT_BIND {
  284. //没有用户信息
  285. //wxUser.FirstLogin = 1
  286. } else if wxUserErr != nil {
  287. err = wxUserErr
  288. return
  289. }
  290. //如果已经登录注册绑定的情况下
  291. if wxUser != nil && wxUserErr == nil {
  292. //获取用户权限
  293. firstLogin = wxUser.FirstLogin
  294. userId = wxUser.UserId
  295. permission, permissionErr := CheckUserPermission(userId)
  296. if permissionErr != nil {
  297. //记录日志
  298. utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
  299. }
  300. if wxUserInfo != nil {
  301. go models.ModifyUserRecordInfo(openId, wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
  302. }
  303. {
  304. codeLog := new(models.WxUserCode)
  305. codeLog.WxCode = code
  306. codeLog.UserId = userId
  307. codeLog.Code = 0
  308. codeLog.FirstLogin = firstLogin
  309. codeLog.Authorization = token
  310. codeLog.UserPermission = permission
  311. codeLog.CreateTime = time.Now()
  312. models.AddWxUserCode(codeLog)
  313. }
  314. if wxUser.Mobile == "" && wxUser.Email == "" {
  315. firstLogin = 1
  316. } else {
  317. firstLogin = 0
  318. }
  319. }
  320. //获取登录token
  321. tokenItem, tokenErr := models.GetTokenByOpenId(openId)
  322. if tokenErr != nil && tokenErr.Error() != utils.ErrNoRow() {
  323. err = errors.New("登录失败,获取token失败:" + tokenErr.Error())
  324. return
  325. }
  326. if tokenItem == nil || (tokenErr != nil && tokenErr.Error() == utils.ErrNoRow()) {
  327. timeUnix := time.Now().Unix()
  328. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  329. token = utils.MD5(openId) + utils.MD5(timeUnixStr)
  330. //新增session
  331. {
  332. session := new(models.Session)
  333. session.OpenId = openId
  334. session.UserId = userId
  335. session.CreatedTime = time.Now()
  336. session.LastUpdatedTime = time.Now()
  337. session.ExpireTime = time.Now().AddDate(0, 3, 0)
  338. session.AccessToken = token
  339. sessionErr := models.AddSession(session)
  340. if err != nil {
  341. err = errors.New("登录失败,新增用户session信息失败:" + sessionErr.Error())
  342. return
  343. }
  344. }
  345. } else {
  346. token = tokenItem.AccessToken
  347. //如果联系人编号不为空,且联系人编号与session里面的联系人编号不一致的时候,需要做session变更
  348. if userId > 0 && tokenItem.UserId != userId {
  349. _ = models.UpdateSession(tokenItem.SessionId, userId, time.Now().AddDate(0, 1, 0))
  350. }
  351. }
  352. //新增登录日志
  353. {
  354. loginLog := new(models.WxUserLog)
  355. loginLog.UserId = userId
  356. loginLog.OpenId = openId
  357. loginLog.UnionId = unionId
  358. loginLog.CreateTime = time.Now()
  359. loginLog.Handle = "wechat_login"
  360. loginLog.Remark = token
  361. go models.AddWxUserLog(loginLog)
  362. }
  363. return
  364. }
  365. //添加第三方用户(微信)记录
  366. func AddUserRecord(openId, unionId, nickName, realName, province, city, country, headimgurl, sessionKey string, platform, sex, subscribe int) (userRecord *models.UserRecord, err error) {
  367. find, err := models.GetUserRecordByOpenId(openId)
  368. if err != nil && err.Error() != utils.ErrNoRow() {
  369. return
  370. }
  371. if find != nil {
  372. userRecord = find
  373. return
  374. }
  375. userRecord = &models.UserRecord{
  376. OpenId: openId, //用户open_id
  377. UnionId: unionId, //用户union_id
  378. Subscribe: subscribe,
  379. NickName: nickName, //用户昵称,最大长度:32
  380. RealName: realName, //用户实际名称,最大长度:32
  381. Sex: sex, //普通用户性别,1为男性,2为女性
  382. Province: province, //普通用户个人资料填写的省份,最大长度:30
  383. City: city, //普通用户个人资料填写的城市,最大长度:30
  384. Country: country, //国家,如中国为CN,最大长度:30
  385. Headimgurl: headimgurl, //用户第三方(微信)头像,最大长度:512
  386. CreateTime: time.Now(), //创建时间,关系添加时间、用户授权时间
  387. CreatePlatform: platform, //注册平台,1:日度点评公众号,2:管理后台,3:pc端网站,4:查研观向小程序;默认:1
  388. SessionKey: sessionKey, //微信小程序会话密钥,最大长度:255
  389. }
  390. recordId, err := models.AddUserRecord(userRecord)
  391. if err != nil {
  392. return
  393. }
  394. userRecord.UserRecordId = int(recordId)
  395. return
  396. }