user_login.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. func ThirdLogin(req map[string]interface{}) (data GetCrmTokenData, err error, errMsg string) {
  229. if utils.BusinessCode == utils.BusinessCodeRelease || utils.BusinessCode == utils.BusinessCodeSandbox {
  230. authCode, ok := req["code"]
  231. if !ok {
  232. errMsg = "参数有误"
  233. err = errors.New("参数缺失, code")
  234. return
  235. }
  236. authCodeStr := fmt.Sprint(authCode)
  237. if authCodeStr == "" {
  238. errMsg = "参数有误"
  239. err = errors.New("参数缺失, AuthCode")
  240. return
  241. }
  242. data, err = CodeLoginFromMiddleServer(authCodeStr)
  243. return
  244. }
  245. data, err = ThirdCodeLoginFromMiddleServer(req)
  246. // 普通的第三方
  247. return
  248. }
  249. // ThirdCodeLoginFromMiddleServer 中间服务-编码登录
  250. func ThirdCodeLoginFromMiddleServer(param map[string]interface{}) (tokenResp GetCrmTokenData, err error) {
  251. data, e := json.Marshal(param)
  252. if e != nil {
  253. err = fmt.Errorf("data json marshal err: %s", e.Error())
  254. return
  255. }
  256. body := io.NopCloser(strings.NewReader(string(data)))
  257. client := &http.Client{}
  258. req, e := http.NewRequest("POST", utils.EtaBridgeLoginUrl, body)
  259. if e != nil {
  260. err = fmt.Errorf("http create request err: %s", e.Error())
  261. return
  262. }
  263. contentType := "application/json;charset=utf-8"
  264. req.Header.Set("Content-Type", contentType)
  265. req.Header.Set("Authorization", utils.CrmEtaAuthorization)
  266. resp, e := client.Do(req)
  267. if e != nil {
  268. err = fmt.Errorf("http client do err: %s", e.Error())
  269. return
  270. }
  271. defer func() {
  272. _ = resp.Body.Close()
  273. }()
  274. b, e := io.ReadAll(resp.Body)
  275. if e != nil {
  276. err = fmt.Errorf("resp body read err: %s", e.Error())
  277. return
  278. }
  279. if len(b) == 0 {
  280. err = fmt.Errorf("resp body is empty")
  281. return
  282. }
  283. // 生产环境解密, 注意有个坑前后的双引号
  284. if utils.RunMode == "release" {
  285. str := string(b)
  286. str = strings.Trim(str, `"`)
  287. b = utils.DesBase64Decrypt([]byte(str), utils.DesKey)
  288. }
  289. result := new(GetCrmTokenDataResp)
  290. if e = json.Unmarshal(b, &result); e != nil {
  291. err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
  292. return
  293. }
  294. if result.Code != 200 {
  295. err = fmt.Errorf("result: %s", string(b))
  296. return
  297. }
  298. tokenResp = result.Data
  299. return
  300. }