sso_auth.go 13 KB

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