user_login.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models"
  6. "eta/eta_api/models/company"
  7. "eta/eta_api/models/system"
  8. "eta/eta_api/utils"
  9. "fmt"
  10. "github.com/go-ldap/ldap"
  11. "io"
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. // SendAdminMobileVerifyCode 发送用户手机验证码
  18. func SendAdminMobileVerifyCode(source int, mobile, areaCode string) (ok bool, err error) {
  19. defer func() {
  20. if err != nil {
  21. tips := fmt.Sprintf("SendAdminMobileVerifyCode ErrMsg: %s", err.Error())
  22. utils.FileLog.Info(tips)
  23. fmt.Println(tips)
  24. }
  25. }()
  26. smsClient, e := NewSmsClient()
  27. if e != nil {
  28. err = fmt.Errorf("NewSmsClient err: %s", e.Error())
  29. return
  30. }
  31. verifyCode := utils.GetRandDigit(6)
  32. record := new(system.AdminVerifyCodeRecord)
  33. record.VerifyType = system.AdminVerifyCodeRecordTypeMobile
  34. record.Mobile = mobile
  35. record.Source = source
  36. record.Code = verifyCode
  37. record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
  38. record.CreateTime = time.Now().Local()
  39. record.ModifyTime = time.Now().Local()
  40. if e := record.Create(); e != nil {
  41. err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
  42. return
  43. }
  44. var smsReq UserLoginSmsCodeReq
  45. smsReq.Mobile = mobile
  46. smsReq.TelAreaCode = areaCode
  47. smsReq.VerifyCode = verifyCode
  48. smsResult, e := smsClient.SendUserLoginCode(smsReq)
  49. if e != nil {
  50. err = fmt.Errorf("SendUserLoginCode err: %s", e.Error())
  51. return
  52. }
  53. ok = smsResult.Success
  54. record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
  55. if !ok {
  56. record.SendStatus = system.AdminVerifyCodeRecordStatusFail
  57. }
  58. record.RequestId = smsResult.RequestId
  59. cols := []string{"SendStatus", "RequestId"}
  60. if e := record.Update(cols); e != nil {
  61. err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
  62. }
  63. return
  64. }
  65. // SendAdminEmailVerifyCode 发送用户邮箱验证码
  66. func SendAdminEmailVerifyCode(source int, email string) (ok bool, err error) {
  67. defer func() {
  68. if err != nil {
  69. tips := fmt.Sprintf("SendAdminEmailVerifyCode ErrMsg: %s", err.Error())
  70. utils.FileLog.Info(tips)
  71. fmt.Println(tips)
  72. }
  73. }()
  74. // 读取配置
  75. confMap, e := models.GetBusinessConf()
  76. if e != nil {
  77. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  78. return
  79. }
  80. subjectConf := confMap[models.BusinessConfLoginEmailTemplateSubject]
  81. contentConf := confMap[models.BusinessConfLoginEmailTemplateContent]
  82. if subjectConf == "" {
  83. err = fmt.Errorf("请先配置邮件模版主题")
  84. return
  85. }
  86. if contentConf == "" {
  87. err = fmt.Errorf("请先配置邮件模版内容")
  88. return
  89. }
  90. verifyCode := utils.GetRandDigit(6)
  91. t := time.Now().Format("2006年01月02日")
  92. emailContent := contentConf
  93. emailContent = strings.Replace(emailContent, "{{VERIFY_CODE}}", verifyCode, 1)
  94. emailContent = strings.Replace(emailContent, "{{EXPIRED_MINUTE}}", strconv.Itoa(utils.VerifyCodeExpireMinute), 1)
  95. emailContent = strings.Replace(emailContent, "{{DATE_TIME}}", t, 1)
  96. // 验证码记录
  97. record := new(system.AdminVerifyCodeRecord)
  98. record.VerifyType = system.AdminVerifyCodeRecordTypeEmail
  99. record.Email = email
  100. record.Source = source
  101. record.Code = verifyCode
  102. record.ExpiredTime = time.Now().Add(utils.VerifyCodeExpireMinute * time.Minute)
  103. record.CreateTime = time.Now().Local()
  104. record.ModifyTime = time.Now().Local()
  105. if e := record.Create(); e != nil {
  106. err = fmt.Errorf("新增验证码记录失败, Err: %s", e.Error())
  107. return
  108. }
  109. var result string
  110. if confMap[models.BusinessConfEmailClient] == models.BusinessConfEmailClientSmtp {
  111. // 普通邮箱
  112. var emailReq SendEmailReq
  113. emailReq.Title = subjectConf
  114. emailReq.Content = emailContent
  115. emailReq.ToUser = append(emailReq.ToUser, email)
  116. ok, e = SendEmail(emailReq)
  117. if e != nil {
  118. err = fmt.Errorf("邮箱推送失败, Err: %s", e.Error())
  119. return
  120. }
  121. } else {
  122. // 默认阿里云邮箱
  123. // 读取发信人昵称配置...后面可以优化一下
  124. authKey := "english_report_email_conf"
  125. emailConf, e := company.GetConfigDetailByCode(authKey)
  126. if e != nil {
  127. err = fmt.Errorf("获取群发邮件权限失败, Err: %s", e.Error())
  128. return
  129. }
  130. if emailConf.ConfigValue == "" {
  131. err = fmt.Errorf("邮件配置为空, 不可推送")
  132. return
  133. }
  134. conf := new(models.EnglishReportEmailConf)
  135. if e = json.Unmarshal([]byte(emailConf.ConfigValue), &conf); e != nil {
  136. err = fmt.Errorf("邮件配置有误, 不可推送")
  137. return
  138. }
  139. req := new(EnglishReportSendEmailRequest)
  140. req.Subject = subjectConf
  141. req.Email = email
  142. req.FromAlias = conf.FromAlias // 发信人昵称
  143. req.HtmlBody = emailContent
  144. aliEmail := new(AliyunEmail)
  145. o, r, e := aliEmail.SendEmail(req)
  146. if e != nil {
  147. err = fmt.Errorf("阿里云邮箱推送失败, Err: %s", e.Error())
  148. return
  149. }
  150. ok = o
  151. result = r
  152. }
  153. record.SendStatus = system.AdminVerifyCodeRecordStatusSuccess
  154. if !ok {
  155. record.SendStatus = system.AdminVerifyCodeRecordStatusFail
  156. }
  157. record.SendResult = result
  158. cols := []string{"SendStatus", "SendResult"}
  159. if e = record.Update(cols); e != nil {
  160. err = fmt.Errorf("更新验证码记录失败, Err: %s", e.Error())
  161. }
  162. return
  163. }
  164. // LdapUserCheck AD域用户校验
  165. func LdapUserCheck(userName, password string) (pass bool, err error) {
  166. defer func() {
  167. if err != nil {
  168. tips := fmt.Sprintf("LdapUserCheck ErrMsg: %s", err.Error())
  169. utils.FileLog.Info(tips)
  170. fmt.Println(tips)
  171. }
  172. }()
  173. if userName == "" || password == "" {
  174. err = fmt.Errorf("账号密码有误")
  175. return
  176. }
  177. confMap, e := models.GetBusinessConf()
  178. if e != nil {
  179. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  180. return
  181. }
  182. if confMap[models.BusinessConfLdapHost] == "" || confMap[models.BusinessConfLdapBase] == "" {
  183. err = fmt.Errorf("AD域配置有误")
  184. return
  185. }
  186. ldapPort, _ := strconv.Atoi(confMap[models.BusinessConfLdapPort])
  187. if ldapPort <= 0 {
  188. err = fmt.Errorf("AD域端口号有误, Port: %d", ldapPort)
  189. return
  190. }
  191. // 连接ldap
  192. addr := fmt.Sprintf("%s:%d", confMap[models.BusinessConfLdapHost], ldapPort)
  193. conn, e := ldap.Dial("tcp", addr)
  194. if e != nil {
  195. err = fmt.Errorf("ldap Dial err: %s", e.Error())
  196. return
  197. }
  198. defer conn.Close()
  199. // 绑定用户
  200. bindUserName := fmt.Sprintf("%s%s", userName, confMap[models.BusinessConfLdapBindUserSuffix])
  201. if e = conn.Bind(bindUserName, password); e != nil {
  202. err = fmt.Errorf("ldap Bind err: %s", e.Error())
  203. return
  204. }
  205. // 鉴权操作
  206. searchRequest := ldap.NewSearchRequest(
  207. confMap[models.BusinessConfLdapBase],
  208. ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
  209. fmt.Sprintf(confMap[models.BusinessConfLdapUserFilter], userName),
  210. []string{"dn"},
  211. nil,
  212. )
  213. //b, _ := json.Marshal(searchRequest)
  214. //fmt.Println("searchRequest: ", string(b))
  215. sr, e := conn.Search(searchRequest)
  216. if e != nil {
  217. err = fmt.Errorf("ldap Search err: %s", e.Error())
  218. return
  219. }
  220. // 验证结果
  221. if len(sr.Entries) != 1 {
  222. utils.FileLog.Info("ldap check fail: user does not exist or too many entries returned")
  223. return
  224. }
  225. pass = true
  226. return
  227. }
  228. // ThirdLogin
  229. // @Description: 第三方登录(换取token)
  230. // @author: Roc
  231. // @datetime 2024-01-30 16:09:18
  232. // @param req map[string]interface{}
  233. // @return data GetCrmTokenData
  234. // @return err error
  235. // @return errMsg string
  236. func ThirdLogin(req map[string]interface{}) (data GetCrmTokenData, err error, errMsg string) {
  237. if utils.BusinessCode == utils.BusinessCodeRelease || utils.BusinessCode == utils.BusinessCodeSandbox {
  238. authCode, ok := req["code"]
  239. if !ok {
  240. errMsg = "参数有误"
  241. err = errors.New("参数缺失, code")
  242. return
  243. }
  244. authCodeStr := fmt.Sprint(authCode)
  245. if authCodeStr == "" {
  246. errMsg = "参数有误"
  247. err = errors.New("参数缺失, AuthCode")
  248. return
  249. }
  250. data, err = CodeLoginFromMiddleServer(authCodeStr)
  251. return
  252. }
  253. data, err, errMsg = ThirdCodeLoginFromMiddleServer(req)
  254. // 普通的第三方
  255. return
  256. }
  257. // ThirdCodeLoginFromMiddleServer
  258. // @Description: 第三方登录(向桥接服务换取token)
  259. // @author: Roc
  260. // @datetime 2024-01-30 16:09:35
  261. // @param param map[string]interface{}
  262. // @return tokenResp GetCrmTokenData
  263. // @return err error
  264. func ThirdCodeLoginFromMiddleServer(param map[string]interface{}) (tokenResp GetCrmTokenData, err error, errMsg string) {
  265. if utils.EtaBridgeUrl == `` || utils.EtaBridgeLoginUrl == "" {
  266. errMsg = `未配置第三方登录的桥接服务地址`
  267. err = errors.New(errMsg)
  268. return
  269. }
  270. data, e := json.Marshal(param)
  271. if e != nil {
  272. err = fmt.Errorf("data json marshal err: %s", e.Error())
  273. return
  274. }
  275. body := io.NopCloser(strings.NewReader(string(data)))
  276. client := &http.Client{}
  277. req, e := http.NewRequest("POST", utils.EtaBridgeUrl+utils.EtaBridgeLoginUrl, body)
  278. if e != nil {
  279. err = fmt.Errorf("http create request err: %s", e.Error())
  280. return
  281. }
  282. contentType := "application/json;charset=utf-8"
  283. req.Header.Set("Content-Type", contentType)
  284. checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
  285. req.Header.Set("Authorization", checkToken)
  286. resp, e := client.Do(req)
  287. if e != nil {
  288. err = fmt.Errorf("http client do err: %s", e.Error())
  289. return
  290. }
  291. defer func() {
  292. _ = resp.Body.Close()
  293. }()
  294. b, e := io.ReadAll(resp.Body)
  295. if e != nil {
  296. err = fmt.Errorf("resp body read err: %s", e.Error())
  297. return
  298. }
  299. if len(b) == 0 {
  300. err = fmt.Errorf("resp body is empty")
  301. return
  302. }
  303. // 生产环境解密, 注意有个坑前后的双引号
  304. if utils.RunMode == "release" {
  305. str := string(b)
  306. str = strings.Trim(str, `"`)
  307. b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
  308. }
  309. result := new(GetCrmTokenDataResp)
  310. if e = json.Unmarshal(b, &result); e != nil {
  311. err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
  312. utils.FileLog.Info("第三方登录(向桥接服务换取token):\n" + string(b))
  313. return
  314. }
  315. if result.Code != 200 {
  316. errMsg = result.Msg
  317. err = fmt.Errorf("result: %s", string(b))
  318. return
  319. }
  320. tokenResp = result.Data
  321. return
  322. }
  323. // ThirdLogout
  324. // @Description: 第三方登出
  325. // @author: Roc
  326. // @datetime 2024-01-30 16:09:18
  327. // @param req map[string]interface{}
  328. // @return data GetCrmTokenData
  329. // @return err error
  330. func ThirdLogout(accessToken string) (err error) {
  331. if utils.EtaBridgeUrl == "" || utils.EtaBridgeLogoutUrl == "" {
  332. // 未配置第三方登出的桥接服务地址
  333. return
  334. }
  335. params := map[string]interface{}{
  336. "access_token": accessToken,
  337. }
  338. data, e := json.Marshal(params)
  339. if e != nil {
  340. err = fmt.Errorf("data json marshal err: %s", e.Error())
  341. return
  342. }
  343. body := io.NopCloser(strings.NewReader(string(data)))
  344. client := &http.Client{}
  345. req, e := http.NewRequest("POST", utils.EtaBridgeUrl+utils.EtaBridgeLogoutUrl, body)
  346. if e != nil {
  347. err = fmt.Errorf("http create request err: %s", e.Error())
  348. return
  349. }
  350. contentType := "application/json;charset=utf-8"
  351. req.Header.Set("Content-Type", contentType)
  352. checkToken := utils.MD5(utils.EtaBridgeAppNameEn + utils.EtaBridgeMd5Key)
  353. req.Header.Set("Authorization", checkToken)
  354. resp, e := client.Do(req)
  355. if e != nil {
  356. err = fmt.Errorf("http client do err: %s", e.Error())
  357. return
  358. }
  359. defer func() {
  360. _ = resp.Body.Close()
  361. }()
  362. b, e := io.ReadAll(resp.Body)
  363. if e != nil {
  364. err = fmt.Errorf("resp body read err: %s", e.Error())
  365. return
  366. }
  367. if len(b) == 0 {
  368. err = fmt.Errorf("resp body is empty")
  369. return
  370. }
  371. // 生产环境解密, 注意有个坑前后的双引号
  372. if utils.RunMode == "release" {
  373. str := string(b)
  374. str = strings.Trim(str, `"`)
  375. b = utils.DesBase64Decrypt([]byte(str), utils.EtaBridgeDesKey)
  376. }
  377. result := new(GetCrmTokenDataResp)
  378. if e = json.Unmarshal(b, &result); e != nil {
  379. err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
  380. return
  381. }
  382. if result.Code != 200 {
  383. err = fmt.Errorf("result: %s", string(b))
  384. return
  385. }
  386. return
  387. }