sso_auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package htfutures
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_bridge/global"
  6. "eta/eta_bridge/models/eta"
  7. "eta/eta_bridge/models/response"
  8. "eta/eta_bridge/services"
  9. "eta/eta_bridge/services/xiangyu"
  10. "fmt"
  11. "gorm.io/gorm"
  12. "net/url"
  13. "strings"
  14. "time"
  15. )
  16. const (
  17. token_url = "/frameauth/api/user/getTokenByAuthCode"
  18. user_info_url = "/frameauth/api/user/getUserInfoByAccessToken"
  19. authCode = "authCode"
  20. accessToken = "accessToken"
  21. sysType = "systemType"
  22. etaAdmin = "etaadmin"
  23. etaCrm = "weapp"
  24. CACHE_ABNORMAL_LOGIN = "pc_eta_admin:login:abnormal:" //管理后台登录-异常登录
  25. CACHE_LOGIN_ERR_PASS = "pc_eta_admin:login:errPass:" //管理后台登录-输入错误密码次数
  26. )
  27. var (
  28. base_url = global.CONFIG.HTFutures.SSOAuthHost
  29. clientToken HttpClient[string] = CreateDefault[string]()
  30. clientUser HttpClient[UserInfoResp] = CreateDefault[UserInfoResp]()
  31. )
  32. type UserInfoResp struct {
  33. UserId string `json:"userId"`
  34. Status string `json:"status"`
  35. WorkStatus string `json:"workStatus"`
  36. Username string `json:"username"`
  37. Name string `json:"name"`
  38. Nickname string `json:"nickname"`
  39. LastLogin string `json:"lastLogin"`
  40. LastIp string `json:"lastIp"`
  41. GivenName string `json:"givenName"`
  42. FamilyName string `json:"familyName"`
  43. MiddleName string `json:"middleName"`
  44. }
  45. func ssoLogin(code string, systemType string) (token string, userInfo UserInfoResp, err error) {
  46. // 获取ht token
  47. token, err = GetToken(code, systemType)
  48. if err != nil {
  49. global.FILE_LOG.Error("获取token失败" + err.Error())
  50. return
  51. }
  52. // 获取用户信息
  53. userInfo, err = GetUserInfo(token, systemType)
  54. if err != nil {
  55. global.FILE_LOG.Error("获取ht域用户信息失败:" + err.Error())
  56. return
  57. }
  58. return
  59. }
  60. // LoginCRM
  61. // @Description: 获取eta的session
  62. // @author: Roc
  63. // @datetime 2024-01-23 17:44:15
  64. // @param code string
  65. // @return resp response.LoginResp
  66. // @return err error
  67. // @return errMsg string
  68. func LoginCRM(code string) (resp response.LoginResp, err error, errMsg string) {
  69. // 获取用户信息
  70. token, userInfo, err := ssoLogin(code, etaCrm)
  71. if err != nil {
  72. global.FILE_LOG.Error("获取sso用户信息失败:" + err.Error())
  73. errMsg = "获取sso用户信息失败:" + err.Error()
  74. return
  75. }
  76. if userInfo.Username == "" {
  77. global.FILE_LOG.Error("sso用户信息不存在")
  78. errMsg = "sso用户信息不存在"
  79. return
  80. }
  81. //获取eta用户信息
  82. adminInfo, err := eta.GetSysUserByAdminName(userInfo.Username)
  83. if err != nil {
  84. global.FILE_LOG.Error("获取eta用户信息失败:" + err.Error())
  85. errMsg = "获取eta用户信息失败:" + err.Error()
  86. return
  87. }
  88. adminInfo.LastLoginTime, err = time.Parse(time.RFC3339, userInfo.LastLogin)
  89. if err != nil {
  90. adminInfo.LastLoginTime = time.Now()
  91. }
  92. // 新增登录记录
  93. {
  94. record := new(eta.SysUserLoginRecord)
  95. record.Uid = adminInfo.AdminId
  96. record.UserName = adminInfo.AdminName
  97. record.Ip = userInfo.LastIp
  98. record.Stage = "login"
  99. record.CreateTime = time.Now()
  100. go func() {
  101. err = eta.AddSysUserLoginRecord(record)
  102. if err != nil {
  103. global.FILE_LOG.Error("生成登录session失败:" + err.Error())
  104. }
  105. }()
  106. }
  107. // 生成登录session
  108. resp, session, err, errMsg := services.CreateEtaSession(adminInfo)
  109. if err != nil {
  110. global.FILE_LOG.Error("生成登录session失败:" + err.Error())
  111. return
  112. }
  113. // 记录两方session的绑定信息
  114. thirdSession := &eta.SysThirdSession{
  115. ID: 0,
  116. SysUserID: uint64(session.SysUserId),
  117. UserName: session.UserName,
  118. AccessToken: session.AccessToken,
  119. ThirdAccessToken: token,
  120. //ThirdRefreshToken: tokenResp.RefreshToken,
  121. //ThirdExpiredTime: time.Now().Add(time.Duration(tokenResp.ExpiresIn-100) * time.Second),
  122. CreatedTime: time.Now(),
  123. LastUpdatedTime: time.Now(),
  124. }
  125. err = eta.AddSysThirdSession(thirdSession)
  126. if err != nil {
  127. global.FILE_LOG.Error("记录两方session的绑定信息失败:" + err.Error())
  128. errMsg = "记录两方session的绑定信息失败"
  129. return
  130. }
  131. return
  132. }
  133. // LoginEta
  134. // @Description: 获取eta的session
  135. // @author: Roc
  136. // @datetime 2024-01-23 17:44:15
  137. // @param code string
  138. // @return resp response.LoginResp
  139. // @return err error
  140. // @return errMsg string
  141. func LoginEta(code string) (resp response.LoginResp, err error, errMsg string) {
  142. // 获取用户信息
  143. token, userInfo, err := ssoLogin(code, etaAdmin)
  144. if err != nil {
  145. global.FILE_LOG.Error("获取sso用户信息失败:" + err.Error())
  146. errMsg = "获取sso用户信息失败::" + err.Error()
  147. return
  148. }
  149. if userInfo.Username == "" {
  150. global.FILE_LOG.Error("sso用户信息不存在")
  151. errMsg = "sso用户信息不存在,获取的用户名为空"
  152. return
  153. }
  154. //获取eta用户信息
  155. adminInfo, err := eta.GetSysUserByAdminName(userInfo.Username)
  156. if err != nil {
  157. if errors.Is(err, gorm.ErrRecordNotFound) {
  158. global.FILE_LOG.Error("eta用户信息不存在:" + err.Error())
  159. errMsg = "eta用户信息不存在"
  160. } else {
  161. global.FILE_LOG.Error("获取eta用户信息失败:" + err.Error())
  162. errMsg = "获取eta用户信息失败" + err.Error()
  163. }
  164. return
  165. }
  166. adminInfo.LastLoginTime, err = time.Parse(time.RFC3339, userInfo.LastLogin)
  167. if err != nil {
  168. adminInfo.LastLoginTime = time.Now()
  169. }
  170. // 新增登录记录
  171. {
  172. record := new(eta.SysUserLoginRecord)
  173. record.Uid = adminInfo.AdminId
  174. record.UserName = adminInfo.AdminName
  175. record.Ip = userInfo.LastIp
  176. record.Stage = "login"
  177. record.CreateTime = time.Now()
  178. go func() {
  179. err = eta.AddSysUserLoginRecord(record)
  180. if err != nil {
  181. global.FILE_LOG.Error("生成登录session失败:" + err.Error())
  182. }
  183. }()
  184. go func() {
  185. err = adminInfo.Update([]string{"last_login_time"})
  186. if err != nil {
  187. global.FILE_LOG.Error("更新用户最近登录时间失败:" + err.Error())
  188. }
  189. //删除用户redis信息
  190. abnormalKey := fmt.Sprint(CACHE_ABNORMAL_LOGIN, adminInfo.AdminName)
  191. errPassKey := fmt.Sprint(CACHE_LOGIN_ERR_PASS, adminInfo.AdminName)
  192. _ = global.Rc.Delete(abnormalKey)
  193. _ = global.Rc.Delete(errPassKey)
  194. }()
  195. }
  196. // 生成登录session
  197. resp, session, err, errMsg := services.CreateEtaSession(adminInfo)
  198. if err != nil {
  199. global.FILE_LOG.Error("生成登录session失败:" + err.Error())
  200. return
  201. }
  202. str, _ := json.Marshal(resp)
  203. global.FILE_LOG.Info(fmt.Sprintf("session json 序列化结果为:%s", str))
  204. // 记录两方session的绑定信息
  205. thirdSession := &eta.SysThirdSession{
  206. ID: 0,
  207. SysUserID: uint64(session.SysUserId),
  208. UserName: session.UserName,
  209. AccessToken: session.AccessToken,
  210. ThirdAccessToken: token,
  211. //ThirdRefreshToken: tokenResp.RefreshToken,
  212. //ThirdExpiredTime: time.Now().Add(time.Duration(tokenResp.ExpiresIn-100) * time.Second),
  213. CreatedTime: time.Now(),
  214. LastUpdatedTime: time.Now(),
  215. }
  216. err = eta.AddSysThirdSession(thirdSession)
  217. if err != nil {
  218. global.FILE_LOG.Error("记录两方session的绑定信息失败:" + err.Error())
  219. errMsg = "记录两方session的绑定信息失败"
  220. return
  221. }
  222. return
  223. }
  224. func handleUser(xyUserInfo xiangyu.UserData, xyUserId string, departmentMap, departmentNameMap map[string]*eta.SysDepartment, groupMap, groupNameMap map[string]*eta.SysGroup, userMap map[string]*eta.Admin, roleInfo *eta.SysRole) (err error) {
  225. // 判断公司id是否存在,如果不存在,那么就去创建
  226. departmentInfo, ok := departmentMap[xyUserInfo.CompanyId]
  227. if !ok {
  228. // 没有外部id的部门,那么用名称去匹配
  229. departmentInfo, ok = departmentNameMap[xyUserInfo.CompanyName]
  230. if !ok {
  231. // 如果没有的话,那么就创建该部门
  232. departmentInfo = &eta.SysDepartment{
  233. DepartmentId: 0,
  234. DepartmentName: xyUserInfo.CompanyName,
  235. OutID: xyUserInfo.CompanyId,
  236. CreateTime: time.Now(),
  237. Sort: 0,
  238. }
  239. err = departmentInfo.Create()
  240. if err != nil {
  241. return
  242. }
  243. } else {
  244. // 如果通过名称找到了,那么就更新一下外部id
  245. departmentInfo.OutID = xyUserInfo.CompanyId
  246. err = departmentInfo.Update([]string{"OutID"})
  247. if err != nil {
  248. return
  249. }
  250. delete(departmentNameMap, xyUserInfo.CompanyName)
  251. }
  252. departmentMap[xyUserInfo.CompanyId] = departmentInfo
  253. }
  254. // 判断部门id是否存在,如果不存在,那么就去创建
  255. groupInfo, ok := groupMap[xyUserInfo.DepartId]
  256. if !ok {
  257. groupInfo, ok = groupNameMap[fmt.Sprint(departmentInfo.DepartmentId, "_", xyUserInfo.DepartmentName)]
  258. if !ok {
  259. // 如果通过名称还是没有找到,那么就创建一个分组
  260. groupInfo = &eta.SysGroup{
  261. GroupId: 0,
  262. DepartmentId: departmentInfo.DepartmentId,
  263. GroupName: xyUserInfo.DepartmentName,
  264. CreateTime: time.Now(),
  265. ParentId: 0,
  266. Sort: 0,
  267. OutID: xyUserInfo.DepartId,
  268. }
  269. // 如果没有的话,那么就创建该分组
  270. err = groupInfo.Create()
  271. if err != nil {
  272. return
  273. }
  274. } else {
  275. // 如果通过名称找到了,那么就更新一下外部id
  276. groupInfo.OutID = xyUserInfo.DepartId
  277. err = groupInfo.Update([]string{"OutID"})
  278. if err != nil {
  279. return
  280. }
  281. delete(groupNameMap, xyUserInfo.DepartmentName)
  282. }
  283. groupMap[xyUserInfo.DepartId] = groupInfo
  284. }
  285. enabled := 1
  286. if xyUserInfo.IsDisabled {
  287. enabled = 0
  288. }
  289. // 判断用户是否存在,如果不存在,那么就去创建
  290. userInfo, ok := userMap[xyUserInfo.Username]
  291. if !ok {
  292. userInfo = &eta.Admin{
  293. AdminId: 0,
  294. AdminName: xyUserInfo.Username,
  295. AdminAvatar: "",
  296. RealName: xyUserInfo.FullName,
  297. Password: xyUserInfo.Password,
  298. //LastUpdatedPasswordTime: time.Time{},
  299. Enabled: enabled,
  300. Email: "",
  301. //LastLoginTime: time.Time{},
  302. CreatedTime: time.Now(),
  303. LastUpdatedTime: time.Now(),
  304. //Role: roleInfo.,
  305. Mobile: xyUserInfo.Mobile,
  306. RoleType: 0,
  307. RoleId: roleInfo.RoleId,
  308. RoleName: roleInfo.RoleName,
  309. RoleTypeCode: roleInfo.RoleTypeCode,
  310. DepartmentId: departmentInfo.DepartmentId,
  311. DepartmentName: departmentInfo.DepartmentName,
  312. GroupId: groupInfo.GroupId,
  313. GroupName: groupInfo.GroupName,
  314. Authority: 0,
  315. Position: xyUserInfo.PositionName,
  316. //DisableTime: time.Time{},
  317. ChartPermission: 0,
  318. EdbPermission: 0,
  319. MysteelChemicalPermission: 0,
  320. OpenId: "",
  321. UnionId: "",
  322. PredictEdbPermission: 0,
  323. Province: "",
  324. ProvinceCode: "",
  325. City: "",
  326. CityCode: "",
  327. EmployeeId: xyUserInfo.EmployeeNo,
  328. TelAreaCode: "",
  329. OutID: xyUserId,
  330. }
  331. if strings.Contains(roleInfo.RoleTypeCode, "researcher") {
  332. userInfo.Role = "researcher"
  333. } else if strings.Contains(userInfo.RoleTypeCode, "seller") {
  334. userInfo.Role = "sales"
  335. } else {
  336. userInfo.Role = "admin"
  337. }
  338. // 如果没有的话,那么就创建该用户
  339. err = userInfo.Create()
  340. if err != nil {
  341. return
  342. }
  343. } else {
  344. updateColList := make([]string, 0)
  345. //状态
  346. if userInfo.Enabled != enabled {
  347. updateColList = append(updateColList, "Enabled")
  348. userInfo.Enabled = enabled
  349. }
  350. // 部门
  351. if userInfo.DepartmentId != departmentInfo.DepartmentId {
  352. updateColList = append(updateColList, "DepartmentId", "DepartmentName")
  353. userInfo.DepartmentId = departmentInfo.DepartmentId
  354. userInfo.DepartmentName = departmentInfo.DepartmentName
  355. }
  356. // 分组
  357. if userInfo.GroupId != groupInfo.GroupId {
  358. updateColList = append(updateColList, "GroupId", "GroupName")
  359. userInfo.GroupId = groupInfo.GroupId
  360. userInfo.GroupName = groupInfo.GroupName
  361. }
  362. // 职位
  363. if userInfo.Position != xyUserInfo.PositionName {
  364. updateColList = append(updateColList, "Position")
  365. userInfo.Position = xyUserInfo.PositionName
  366. }
  367. // 姓名
  368. if userInfo.RealName != xyUserInfo.FullName {
  369. updateColList = append(updateColList, "RealName")
  370. userInfo.RealName = xyUserInfo.FullName
  371. }
  372. // 手机号
  373. if userInfo.Mobile != xyUserInfo.Mobile {
  374. updateColList = append(updateColList, "Mobile")
  375. userInfo.Mobile = xyUserInfo.Mobile
  376. }
  377. // 外部id
  378. if userInfo.OutID == `` {
  379. updateColList = append(updateColList, "OutID")
  380. userInfo.OutID = xyUserId
  381. }
  382. // 工号
  383. if userInfo.EmployeeId != xyUserInfo.EmployeeNo {
  384. updateColList = append(updateColList, "EmployeeId")
  385. userInfo.OutID = xyUserInfo.EmployeeNo
  386. }
  387. if len(updateColList) > 0 {
  388. updateColList = append(updateColList, "LastUpdatedTime")
  389. userInfo.LastUpdatedTime = time.Now()
  390. err = userInfo.Update(updateColList)
  391. if err != nil {
  392. return
  393. }
  394. }
  395. }
  396. userMap[xyUserInfo.Username] = userInfo
  397. return
  398. }
  399. func GetToken(code string, systemType string) (token string, err error) {
  400. urlStr := base_url + token_url
  401. params := url.Values{}
  402. params.Add(authCode, code)
  403. params.Add(sysType, systemType)
  404. resp, err := clientToken.PostFromData(urlStr, params)
  405. if err != nil {
  406. global.FILE_LOG.Error("获取token失败:" + err.Error())
  407. return
  408. }
  409. if resp.Code != 0 {
  410. global.FILE_LOG.Error("请求接口应答异常:" + resp.Message)
  411. err = errors.New("接口异常应答:" + resp.Message)
  412. return
  413. }
  414. token = resp.Data
  415. return
  416. }
  417. func GetUserInfo(token string, systemType string) (userinfo UserInfoResp, err error) {
  418. urlStr := base_url + user_info_url
  419. params := url.Values{}
  420. params.Add(accessToken, token)
  421. params.Add(sysType, systemType)
  422. resp, err := clientUser.PostFromData(urlStr, params)
  423. if err != nil {
  424. global.FILE_LOG.Error("获取用户信息失败:" + err.Error())
  425. return
  426. }
  427. if resp.Code != 0 {
  428. global.FILE_LOG.Error("请求接口应答异常:" + resp.Message)
  429. err = errors.New("接口异常应答:" + resp.Message)
  430. return
  431. }
  432. userinfo = resp.Data
  433. //err = json.Unmarshal([]byte(resp.Data), &userinfo)
  434. //if err != nil {
  435. // global.FILE_LOG.Error("解析用户信息失败:" + err.Error())
  436. // return
  437. //}
  438. return
  439. }