user_login.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_api/models"
  6. "eta_gn/eta_api/models/system"
  7. "eta_gn/eta_api/utils"
  8. "fmt"
  9. "github.com/go-ldap/ldap"
  10. "io"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. // SendAdminMobileVerifyCode 发送用户手机验证码
  17. func SendAdminMobileVerifyCode(source int, mobile, areaCode string) (ok bool, err error) {
  18. defer func() {
  19. if err != nil {
  20. tips := fmt.Sprintf("SendAdminMobileVerifyCode ErrMsg: %s", err.Error())
  21. utils.FileLog.Info(tips)
  22. fmt.Println(tips)
  23. }
  24. }()
  25. smsClient, e := NewSmsClient()
  26. if e != nil {
  27. err = fmt.Errorf("NewSmsClient err: %s", e.Error())
  28. return
  29. }
  30. verifyCode := utils.GetRandDigit(6)
  31. record := new(system.AdminVerifyCodeRecord)
  32. record.VerifyType = system.AdminVerifyCodeRecordTypeMobile
  33. record.Mobile = mobile
  34. record.Source = source
  35. record.Code = verifyCode
  36. record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
  37. record.CreateTime = time.Now().Local()
  38. record.ModifyTime = time.Now().Local()
  39. if e := record.Create(); e != nil {
  40. err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
  41. return
  42. }
  43. var smsReq UserLoginSmsCodeReq
  44. smsReq.Mobile = mobile
  45. smsReq.TelAreaCode = areaCode
  46. smsReq.VerifyCode = verifyCode
  47. smsResult, e := smsClient.SendUserLoginCode(smsReq)
  48. if e != nil {
  49. err = fmt.Errorf("SendUserLoginCode err: %s", e.Error())
  50. return
  51. }
  52. ok = smsResult.Success
  53. record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
  54. if !ok {
  55. record.SendStatus = system.AdminVerifyCodeRecordStatusFail
  56. }
  57. record.RequestId = smsResult.RequestId
  58. cols := []string{"SendStatus", "RequestId"}
  59. if e := record.Update(cols); e != nil {
  60. err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
  61. }
  62. return
  63. }
  64. // SendAdminEmailVerifyCode 发送用户邮箱验证码
  65. func SendAdminEmailVerifyCode(source int, email string) (ok bool, err error) {
  66. defer func() {
  67. if err != nil {
  68. tips := fmt.Sprintf("SendAdminEmailVerifyCode ErrMsg: %s", err.Error())
  69. utils.FileLog.Info(tips)
  70. fmt.Println(tips)
  71. }
  72. }()
  73. // 读取配置
  74. confMap, e := models.GetBusinessConf()
  75. if e != nil {
  76. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  77. return
  78. }
  79. subjectConf := confMap[models.BusinessConfLoginEmailTemplateSubject]
  80. contentConf := confMap[models.BusinessConfLoginEmailTemplateContent]
  81. if subjectConf == "" {
  82. err = fmt.Errorf("请先配置邮件模版主题")
  83. return
  84. }
  85. if contentConf == "" {
  86. err = fmt.Errorf("请先配置邮件模版内容")
  87. return
  88. }
  89. verifyCode := utils.GetRandDigit(6)
  90. t := time.Now().Format("2006年01月02日")
  91. emailContent := contentConf
  92. emailContent = strings.Replace(emailContent, "{{VERIFY_CODE}}", verifyCode, 1)
  93. emailContent = strings.Replace(emailContent, "{{EXPIRED_MINUTE}}", strconv.Itoa(utils.VerifyCodeExpireMinute), 1)
  94. emailContent = strings.Replace(emailContent, "{{DATE_TIME}}", t, 1)
  95. // 验证码记录
  96. record := new(system.AdminVerifyCodeRecord)
  97. record.VerifyType = system.AdminVerifyCodeRecordTypeEmail
  98. record.Email = email
  99. record.Source = source
  100. record.Code = verifyCode
  101. record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
  102. record.CreateTime = time.Now().Local()
  103. record.ModifyTime = time.Now().Local()
  104. if e := record.Create(); e != nil {
  105. err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
  106. return
  107. }
  108. var result string
  109. // 普通邮箱
  110. var emailReq SendEmailReq
  111. emailReq.Title = subjectConf
  112. emailReq.Content = emailContent
  113. emailReq.ToUser = append(emailReq.ToUser, email)
  114. ok, e = SendEmail(emailReq)
  115. if e != nil {
  116. err = fmt.Errorf("邮箱推送失败, Err: %s", e.Error())
  117. return
  118. }
  119. record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
  120. if !ok {
  121. record.SendStatus = system.AdminVerifyCodeRecordStatusFail
  122. }
  123. record.SendResult = result
  124. cols := []string{"SendStatus", "SendResult"}
  125. if e = record.Update(cols); e != nil {
  126. err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
  127. }
  128. return
  129. }
  130. // LdapUserCheck AD域用户校验
  131. func LdapUserCheck(userName, password string) (pass bool, err error) {
  132. defer func() {
  133. if err != nil {
  134. tips := fmt.Sprintf("LdapUserCheck ErrMsg: %s", err.Error())
  135. utils.FileLog.Info(tips)
  136. fmt.Println(tips)
  137. }
  138. }()
  139. if userName == "" || password == "" {
  140. err = fmt.Errorf("账号密码有误")
  141. return
  142. }
  143. confMap, e := models.GetBusinessConf()
  144. if e != nil {
  145. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  146. return
  147. }
  148. if confMap[models.BusinessConfLdapHost] == "" || confMap[models.BusinessConfLdapBase] == "" {
  149. err = fmt.Errorf("AD域配置有误")
  150. return
  151. }
  152. ldapPort, _ := strconv.Atoi(confMap[models.BusinessConfLdapPort])
  153. if ldapPort <= 0 {
  154. err = fmt.Errorf("AD域端口号有误, Port: %d", ldapPort)
  155. return
  156. }
  157. // 连接ldap
  158. addr := fmt.Sprintf("%s:%d", confMap[models.BusinessConfLdapHost], ldapPort)
  159. conn, e := ldap.Dial("tcp", addr)
  160. if e != nil {
  161. err = fmt.Errorf("ldap Dial err: %s", e.Error())
  162. return
  163. }
  164. defer conn.Close()
  165. // 绑定用户
  166. bindUserName := fmt.Sprintf("%s%s", userName, confMap[models.BusinessConfLdapBindUserSuffix])
  167. if e = conn.Bind(bindUserName, password); e != nil {
  168. err = fmt.Errorf("ldap Bind err: %s", e.Error())
  169. return
  170. }
  171. // 鉴权操作
  172. searchRequest := ldap.NewSearchRequest(
  173. confMap[models.BusinessConfLdapBase],
  174. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  175. fmt.Sprintf(confMap[models.BusinessConfLdapUserFilter], userName),
  176. []string{"dn"},
  177. nil,
  178. )
  179. //b, _ := json.Marshal(searchRequest)
  180. //fmt.Println("searchRequest: ", string(b))
  181. sr, e := conn.Search(searchRequest)
  182. if e != nil {
  183. err = fmt.Errorf("ldap Search err: %s", e.Error())
  184. return
  185. }
  186. // 验证结果
  187. if len(sr.Entries) != 1 {
  188. utils.FileLog.Info("ldap check fail: user does not exist or too many entries returned")
  189. return
  190. }
  191. pass = true
  192. return
  193. }
  194. // ThirdLogin
  195. // @Description: 第三方登录(换取token)
  196. // @author: Roc
  197. // @datetime 2024-01-30 16:09:18
  198. // @param req map[string]interface{}
  199. // @return data GetCrmTokenData
  200. // @return err error
  201. // @return errMsg string
  202. func ThirdLogin(req map[string]interface{}) (data GetCrmTokenData, err error, errMsg string) {
  203. // 普通的第三方
  204. data, err, errMsg = ThirdCodeLoginFromMiddleServer(req)
  205. return
  206. }
  207. // ThirdCodeLoginFromMiddleServer
  208. // @Description: 第三方登录(向桥接服务换取token)
  209. // @author: Roc
  210. // @datetime 2024-01-30 16:09:35
  211. // @param param map[string]interface{}
  212. // @return tokenResp GetCrmTokenData
  213. // @return err error
  214. func ThirdCodeLoginFromMiddleServer(param map[string]interface{}) (tokenResp GetCrmTokenData, err error, errMsg string) {
  215. if utils.EtaBridgeUrl == `` || utils.EtaBridgeLoginUrl == "" {
  216. errMsg = `未配置第三方登录的桥接服务地址`
  217. err = errors.New(errMsg)
  218. return
  219. }
  220. data, e := json.Marshal(param)
  221. if e != nil {
  222. err = fmt.Errorf("data json marshal err: %s", e.Error())
  223. return
  224. }
  225. body := io.NopCloser(strings.NewReader(string(data)))
  226. client := &http.Client{}
  227. req, e := http.NewRequest("POST", utils.EtaBridgeUrl+utils.EtaBridgeLoginUrl, body)
  228. if e != nil {
  229. err = fmt.Errorf("http create request err: %s", e.Error())
  230. return
  231. }
  232. contentType := "application/json;charset=utf-8"
  233. req.Header.Set("Content-Type", contentType)
  234. checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
  235. req.Header.Set("Authorization", checkToken)
  236. resp, e := client.Do(req)
  237. if e != nil {
  238. err = fmt.Errorf("http client do err: %s", e.Error())
  239. return
  240. }
  241. defer func() {
  242. _ = resp.Body.Close()
  243. }()
  244. b, e := io.ReadAll(resp.Body)
  245. if e != nil {
  246. err = fmt.Errorf("resp body read err: %s", e.Error())
  247. return
  248. }
  249. if len(b) == 0 {
  250. err = fmt.Errorf("resp body is empty")
  251. return
  252. }
  253. // 生产环境解密, 注意有个坑前后的双引号
  254. if utils.RunMode == "release" {
  255. str := string(b)
  256. str = strings.Trim(str, `"`)
  257. b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
  258. }
  259. result := new(GetCrmTokenDataResp)
  260. if e = json.Unmarshal(b, &result); e != nil {
  261. err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
  262. utils.FileLog.Info("第三方登录(向桥接服务换取token):\n" + string(b))
  263. return
  264. }
  265. if result.Code != 200 {
  266. errMsg = result.Msg
  267. err = fmt.Errorf("result: %s", string(b))
  268. return
  269. }
  270. tokenResp = result.Data
  271. return
  272. }
  273. // ThirdLogout
  274. // @Description: 第三方登出
  275. // @author: Roc
  276. // @datetime 2024-01-30 16:09:18
  277. // @param req map[string]interface{}
  278. // @return data GetCrmTokenData
  279. // @return err error
  280. func ThirdLogout(accessToken string) (err error) {
  281. if utils.EtaBridgeUrl == "" || utils.EtaBridgeLogoutUrl == "" {
  282. // 未配置第三方登出的桥接服务地址
  283. return
  284. }
  285. params := map[string]interface{}{
  286. "access_token": accessToken,
  287. }
  288. data, e := json.Marshal(params)
  289. if e != nil {
  290. err = fmt.Errorf("data json marshal err: %s", e.Error())
  291. return
  292. }
  293. body := io.NopCloser(strings.NewReader(string(data)))
  294. client := &http.Client{}
  295. req, e := http.NewRequest("POST", utils.EtaBridgeUrl+utils.EtaBridgeLogoutUrl, body)
  296. if e != nil {
  297. err = fmt.Errorf("http create request err: %s", e.Error())
  298. return
  299. }
  300. contentType := "application/json;charset=utf-8"
  301. req.Header.Set("Content-Type", contentType)
  302. checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
  303. req.Header.Set("Authorization", checkToken)
  304. resp, e := client.Do(req)
  305. if e != nil {
  306. err = fmt.Errorf("http client do err: %s", e.Error())
  307. return
  308. }
  309. defer func() {
  310. _ = resp.Body.Close()
  311. }()
  312. b, e := io.ReadAll(resp.Body)
  313. if e != nil {
  314. err = fmt.Errorf("resp body read err: %s", e.Error())
  315. return
  316. }
  317. if len(b) == 0 {
  318. err = fmt.Errorf("resp body is empty")
  319. return
  320. }
  321. // 生产环境解密, 注意有个坑前后的双引号
  322. if utils.RunMode == "release" {
  323. str := string(b)
  324. str = strings.Trim(str, `"`)
  325. b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
  326. }
  327. result := new(GetCrmTokenDataResp)
  328. if e = json.Unmarshal(b, &result); e != nil {
  329. err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
  330. return
  331. }
  332. if result.Code != 200 {
  333. err = fmt.Errorf("result: %s", string(b))
  334. return
  335. }
  336. return
  337. }
  338. // UserLoginChange 切换用户
  339. func UserLoginChange(adminName string) (resp *system.LoginResp, err error) {
  340. sysUser, e := system.GetSysUserByAdminName(adminName)
  341. if e != nil {
  342. if utils.IsErrNoRow(e) {
  343. err = fmt.Errorf("用户不存在: %s", adminName)
  344. return
  345. }
  346. err = fmt.Errorf("获取用户失败, %v", e)
  347. return
  348. }
  349. // 生成token
  350. account := utils.MD5(sysUser.AdminName)
  351. token := utils.GenToken(account)
  352. sysSession := new(system.SysSession)
  353. sysSession.UserName = sysUser.AdminName
  354. sysSession.SysUserId = sysUser.AdminId
  355. sysSession.ExpiredTime = time.Now().AddDate(0, 0, 90)
  356. sysSession.IsRemember = 0 // 均需要做过期校验
  357. sysSession.CreatedTime = time.Now()
  358. sysSession.LastUpdatedTime = time.Now()
  359. sysSession.AccessToken = token
  360. if e := system.AddSysSession(sysSession); e != nil {
  361. err = fmt.Errorf("新增session失败, %v", e)
  362. return
  363. }
  364. // 修改最后登录时间
  365. {
  366. sysUser.LastLoginTime = time.Now().Format(utils.FormatDateTime)
  367. sysUser.LastUpdatedTime = time.Now().Format(utils.FormatDateTime)
  368. _ = sysUser.Update([]string{"LastLoginTime", "LastUpdatedTime"})
  369. }
  370. resp = new(system.LoginResp)
  371. resp.Authorization = token
  372. resp.Authorization = "authorization=" + token
  373. resp.RealName = sysUser.RealName
  374. resp.AdminName = sysUser.AdminName
  375. resp.RoleName = sysUser.RoleName
  376. resp.SysRoleTypeCode = sysUser.RoleTypeCode //系统角色编码
  377. resp.RoleTypeCode = sysUser.RoleTypeCode
  378. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  379. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
  380. }
  381. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
  382. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
  383. }
  384. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_DEPARTMENT {
  385. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
  386. }
  387. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  388. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_RAI_SELLER
  389. }
  390. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_DEPARTMENT {
  391. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_RAI_SELLER
  392. }
  393. if sysUser.RoleName == utils.ROLE_NAME_FICC_DIRECTOR {
  394. resp.RoleTypeCode = utils.ROLE_TYPE_CODE_FICC_SELLER
  395. }
  396. resp.AdminId = sysUser.AdminId
  397. var productName string
  398. productId := GetProductId(sysUser.RoleTypeCode)
  399. if productId == 1 {
  400. productName = utils.COMPANY_PRODUCT_FICC_NAME
  401. } else if productId == 2 {
  402. productName = utils.COMPANY_PRODUCT_RAI_NAME
  403. } else {
  404. productName = "admin"
  405. }
  406. resp.ProductName = productName
  407. resp.Authority = sysUser.Authority
  408. // 设置redis缓存
  409. {
  410. // 获取不可信的登录态,并将该登录态重置掉,不允许多次登录
  411. noTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN_NO_TRUST, sysUser.AdminId)
  412. noTrustLoginId, _ := utils.Rc.RedisString(noTrustLoginKey)
  413. if noTrustLoginId != `` { // 如果存在不可信设备,那么将其下架
  414. oldNoTrustLoginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, noTrustLoginId)
  415. _ = utils.Rc.Put(oldNoTrustLoginKey, "0", utils.LoginCacheTime*time.Minute)
  416. }
  417. // 如果当前是不可信设备,那么将其加入到不可信名单
  418. loginKey := fmt.Sprint(utils.CACHE_ACCESS_TOKEN_LOGIN, sysSession.Id)
  419. _ = utils.Rc.Put(loginKey, "1", utils.LoginCacheTime*time.Minute)
  420. _ = utils.Rc.Put(noTrustLoginKey, sysSession.Id, utils.LoginCacheTime*time.Minute)
  421. }
  422. // 新增登录记录
  423. go func() {
  424. record := new(system.SysUserLoginRecord)
  425. record.Uid = sysUser.AdminId
  426. record.UserName = adminName
  427. //record.Ip = this.Ctx.Input.IP()
  428. record.Stage = "login"
  429. record.CreateTime = time.Now()
  430. _ = system.AddSysUserLoginRecord(record)
  431. }()
  432. return
  433. }