package htfutures import ( "encoding/json" "errors" "eta/eta_bridge/global" "eta/eta_bridge/models/eta" "eta/eta_bridge/models/response" "eta/eta_bridge/services" "eta/eta_bridge/services/xiangyu" "fmt" "gorm.io/gorm" "net/url" "strings" "time" ) const ( token_url = "/frameauth/api/user/getTokenByAuthCode" user_info_url = "/frameauth/api/user/getUserInfoByAccessToken" authCode = "authCode" accessToken = "accessToken" sysType = "systemType" etaAdmin = "etaadmin" etaCrm = "weapp" ) var ( base_url = global.CONFIG.HTFutures.SSOAuthHost clientToken HttpClient[string] = CreateDefault[string]() clientUser HttpClient[UserInfoResp] = CreateDefault[UserInfoResp]() ) type UserInfoResp struct { UserId string `json:"userId"` Status string `json:"status"` WorkStatus string `json:"workStatus"` Username string `json:"username"` Name string `json:"name"` Nickname string `json:"nickname"` LastLogin string `json:"lastLogin"` LastIp string `json:"lastIp"` GivenName string `json:"givenName"` FamilyName string `json:"familyName"` MiddleName string `json:"middleName"` } func ssoLogin(code string, systemType string) (token string, userInfo UserInfoResp, err error) { // 获取ht token token, err = GetToken(code, systemType) if err != nil { global.FILE_LOG.Error("获取token失败" + err.Error()) return } // 获取用户信息 userInfo, err = GetUserInfo(token, systemType) if err != nil { global.FILE_LOG.Error("获取ht域用户信息失败:" + err.Error()) return } return } // LoginCRM // @Description: 获取eta的session // @author: Roc // @datetime 2024-01-23 17:44:15 // @param code string // @return resp response.LoginResp // @return err error // @return errMsg string func LoginCRM(code string) (resp response.LoginResp, err error, errMsg string) { // 获取用户信息 token, userInfo, err := ssoLogin(code, etaCrm) if err != nil { global.FILE_LOG.Error("获取sso用户信息失败:" + err.Error()) errMsg = "获取sso用户信息失败:" + err.Error() return } if userInfo.Username == "" { global.FILE_LOG.Error("sso用户信息不存在") errMsg = "sso用户信息不存在" return } //获取eta用户信息 adminInfo, err := eta.GetSysUserByAdminName(userInfo.Username) if err != nil { global.FILE_LOG.Error("获取eta用户信息失败:" + err.Error()) errMsg = "获取eta用户信息失败:" + err.Error() return } adminInfo.LastLoginTime, err = time.Parse(time.RFC3339, userInfo.LastLogin) if err != nil { adminInfo.LastLoginTime = time.Now() } // 新增登录记录 { record := new(eta.SysUserLoginRecord) record.Uid = adminInfo.AdminId record.UserName = adminInfo.AdminName record.Ip = userInfo.LastIp record.Stage = "login" record.CreateTime = time.Now() go func() { err = eta.AddSysUserLoginRecord(record) if err != nil { global.FILE_LOG.Error("生成登录session失败:" + err.Error()) } }() } // 生成登录session resp, session, err, errMsg := services.CreateEtaSession(adminInfo) if err != nil { global.FILE_LOG.Error("生成登录session失败:" + err.Error()) return } // 记录两方session的绑定信息 thirdSession := &eta.SysThirdSession{ ID: 0, SysUserID: uint64(session.SysUserId), UserName: session.UserName, AccessToken: session.AccessToken, ThirdAccessToken: token, //ThirdRefreshToken: tokenResp.RefreshToken, //ThirdExpiredTime: time.Now().Add(time.Duration(tokenResp.ExpiresIn-100) * time.Second), CreatedTime: time.Now(), LastUpdatedTime: time.Now(), } err = eta.AddSysThirdSession(thirdSession) if err != nil { global.FILE_LOG.Error("记录两方session的绑定信息失败:" + err.Error()) errMsg = "记录两方session的绑定信息失败" return } return } // LoginEta // @Description: 获取eta的session // @author: Roc // @datetime 2024-01-23 17:44:15 // @param code string // @return resp response.LoginResp // @return err error // @return errMsg string func LoginEta(code string) (resp response.LoginResp, err error, errMsg string) { // 获取用户信息 token, userInfo, err := ssoLogin(code, etaAdmin) if err != nil { global.FILE_LOG.Error("获取sso用户信息失败:" + err.Error()) errMsg = "获取sso用户信息失败::" + err.Error() return } if userInfo.Username == "" { global.FILE_LOG.Error("sso用户信息不存在") errMsg = "sso用户信息不存在,获取的用户名为空" return } //获取eta用户信息 adminInfo, err := eta.GetSysUserByAdminName(userInfo.Username) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { global.FILE_LOG.Error("eta用户信息不存在:" + err.Error()) errMsg = "eta用户信息不存在" } else { global.FILE_LOG.Error("获取eta用户信息失败:" + err.Error()) errMsg = "获取eta用户信息失败" + err.Error() } return } adminInfo.LastLoginTime, err = time.Parse(time.RFC3339, userInfo.LastLogin) if err != nil { adminInfo.LastLoginTime = time.Now() } // 新增登录记录 { record := new(eta.SysUserLoginRecord) record.Uid = adminInfo.AdminId record.UserName = adminInfo.AdminName record.Ip = userInfo.LastIp record.Stage = "login" record.CreateTime = time.Now() go func() { err = eta.AddSysUserLoginRecord(record) if err != nil { global.FILE_LOG.Error("生成登录session失败:" + err.Error()) } }() } // 生成登录session resp, session, err, errMsg := services.CreateEtaSession(adminInfo) if err != nil { global.FILE_LOG.Error("生成登录session失败:" + err.Error()) return } str, _ := json.Marshal(resp) global.FILE_LOG.Info(fmt.Sprintf("session json 序列化结果为:%s", str)) // 记录两方session的绑定信息 thirdSession := &eta.SysThirdSession{ ID: 0, SysUserID: uint64(session.SysUserId), UserName: session.UserName, AccessToken: session.AccessToken, ThirdAccessToken: token, //ThirdRefreshToken: tokenResp.RefreshToken, //ThirdExpiredTime: time.Now().Add(time.Duration(tokenResp.ExpiresIn-100) * time.Second), CreatedTime: time.Now(), LastUpdatedTime: time.Now(), } err = eta.AddSysThirdSession(thirdSession) if err != nil { global.FILE_LOG.Error("记录两方session的绑定信息失败:" + err.Error()) errMsg = "记录两方session的绑定信息失败" return } return } 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) { // 判断公司id是否存在,如果不存在,那么就去创建 departmentInfo, ok := departmentMap[xyUserInfo.CompanyId] if !ok { // 没有外部id的部门,那么用名称去匹配 departmentInfo, ok = departmentNameMap[xyUserInfo.CompanyName] if !ok { // 如果没有的话,那么就创建该部门 departmentInfo = &eta.SysDepartment{ DepartmentId: 0, DepartmentName: xyUserInfo.CompanyName, OutID: xyUserInfo.CompanyId, CreateTime: time.Now(), Sort: 0, } err = departmentInfo.Create() if err != nil { return } } else { // 如果通过名称找到了,那么就更新一下外部id departmentInfo.OutID = xyUserInfo.CompanyId err = departmentInfo.Update([]string{"OutID"}) if err != nil { return } delete(departmentNameMap, xyUserInfo.CompanyName) } departmentMap[xyUserInfo.CompanyId] = departmentInfo } // 判断部门id是否存在,如果不存在,那么就去创建 groupInfo, ok := groupMap[xyUserInfo.DepartId] if !ok { groupInfo, ok = groupNameMap[fmt.Sprint(departmentInfo.DepartmentId, "_", xyUserInfo.DepartmentName)] if !ok { // 如果通过名称还是没有找到,那么就创建一个分组 groupInfo = &eta.SysGroup{ GroupId: 0, DepartmentId: departmentInfo.DepartmentId, GroupName: xyUserInfo.DepartmentName, CreateTime: time.Now(), ParentId: 0, Sort: 0, OutID: xyUserInfo.DepartId, } // 如果没有的话,那么就创建该分组 err = groupInfo.Create() if err != nil { return } } else { // 如果通过名称找到了,那么就更新一下外部id groupInfo.OutID = xyUserInfo.DepartId err = groupInfo.Update([]string{"OutID"}) if err != nil { return } delete(groupNameMap, xyUserInfo.DepartmentName) } groupMap[xyUserInfo.DepartId] = groupInfo } enabled := 1 if xyUserInfo.IsDisabled { enabled = 0 } // 判断用户是否存在,如果不存在,那么就去创建 userInfo, ok := userMap[xyUserInfo.Username] if !ok { userInfo = &eta.Admin{ AdminId: 0, AdminName: xyUserInfo.Username, AdminAvatar: "", RealName: xyUserInfo.FullName, Password: xyUserInfo.Password, //LastUpdatedPasswordTime: time.Time{}, Enabled: enabled, Email: "", //LastLoginTime: time.Time{}, CreatedTime: time.Now(), LastUpdatedTime: time.Now(), //Role: roleInfo., Mobile: xyUserInfo.Mobile, RoleType: 0, RoleId: roleInfo.RoleId, RoleName: roleInfo.RoleName, RoleTypeCode: roleInfo.RoleTypeCode, DepartmentId: departmentInfo.DepartmentId, DepartmentName: departmentInfo.DepartmentName, GroupId: groupInfo.GroupId, GroupName: groupInfo.GroupName, Authority: 0, Position: xyUserInfo.PositionName, //DisableTime: time.Time{}, ChartPermission: 0, EdbPermission: 0, MysteelChemicalPermission: 0, OpenId: "", UnionId: "", PredictEdbPermission: 0, Province: "", ProvinceCode: "", City: "", CityCode: "", EmployeeId: xyUserInfo.EmployeeNo, TelAreaCode: "", OutID: xyUserId, } if strings.Contains(roleInfo.RoleTypeCode, "researcher") { userInfo.Role = "researcher" } else if strings.Contains(userInfo.RoleTypeCode, "seller") { userInfo.Role = "sales" } else { userInfo.Role = "admin" } // 如果没有的话,那么就创建该用户 err = userInfo.Create() if err != nil { return } } else { updateColList := make([]string, 0) //状态 if userInfo.Enabled != enabled { updateColList = append(updateColList, "Enabled") userInfo.Enabled = enabled } // 部门 if userInfo.DepartmentId != departmentInfo.DepartmentId { updateColList = append(updateColList, "DepartmentId", "DepartmentName") userInfo.DepartmentId = departmentInfo.DepartmentId userInfo.DepartmentName = departmentInfo.DepartmentName } // 分组 if userInfo.GroupId != groupInfo.GroupId { updateColList = append(updateColList, "GroupId", "GroupName") userInfo.GroupId = groupInfo.GroupId userInfo.GroupName = groupInfo.GroupName } // 职位 if userInfo.Position != xyUserInfo.PositionName { updateColList = append(updateColList, "Position") userInfo.Position = xyUserInfo.PositionName } // 姓名 if userInfo.RealName != xyUserInfo.FullName { updateColList = append(updateColList, "RealName") userInfo.RealName = xyUserInfo.FullName } // 手机号 if userInfo.Mobile != xyUserInfo.Mobile { updateColList = append(updateColList, "Mobile") userInfo.Mobile = xyUserInfo.Mobile } // 外部id if userInfo.OutID == `` { updateColList = append(updateColList, "OutID") userInfo.OutID = xyUserId } // 工号 if userInfo.EmployeeId != xyUserInfo.EmployeeNo { updateColList = append(updateColList, "EmployeeId") userInfo.OutID = xyUserInfo.EmployeeNo } if len(updateColList) > 0 { updateColList = append(updateColList, "LastUpdatedTime") userInfo.LastUpdatedTime = time.Now() err = userInfo.Update(updateColList) if err != nil { return } } } userMap[xyUserInfo.Username] = userInfo return } func GetToken(code string, systemType string) (token string, err error) { urlStr := base_url + token_url params := url.Values{} params.Add(authCode, code) params.Add(sysType, systemType) resp, err := clientToken.PostFromData(urlStr, params) if err != nil { global.FILE_LOG.Error("获取token失败:" + err.Error()) return } if resp.Code != 0 { global.FILE_LOG.Error("请求接口应答异常:" + resp.Message) err = errors.New("接口异常应答:" + resp.Message) return } token = resp.Data return } func GetUserInfo(token string, systemType string) (userinfo UserInfoResp, err error) { urlStr := base_url + user_info_url params := url.Values{} params.Add(accessToken, token) params.Add(sysType, systemType) resp, err := clientUser.PostFromData(urlStr, params) if err != nil { global.FILE_LOG.Error("获取用户信息失败:" + err.Error()) return } if resp.Code != 0 { global.FILE_LOG.Error("请求接口应答异常:" + resp.Message) err = errors.New("接口异常应答:" + resp.Message) return } userinfo = resp.Data //err = json.Unmarshal([]byte(resp.Data), &userinfo) //if err != nil { // global.FILE_LOG.Error("解析用户信息失败:" + err.Error()) // return //} return }