整理架构,初次提交

This commit is contained in:
马宝龙
2026-06-24 19:24:47 +08:00
parent a4c719f9a5
commit ac7e4e9088
338 changed files with 147 additions and 29066 deletions

View File

@@ -1,374 +0,0 @@
package com.ruoyi.framework.web.service;
import com.ruoyi.cms.service.CompanyContactService;
import com.ruoyi.cms.service.IAppUserService;
import com.ruoyi.cms.service.ICompanyService;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.cms.util.oauth.OauthClient;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.common.core.domain.entity.CompanyContact;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.tymh.nwToken.PortalTokenCacheDTO;
import com.ruoyi.common.core.domain.entity.tymh.wwToken.WwTokenResult;
import com.ruoyi.common.core.domain.entity.tymh.wwToken.WwTyInfo;
import com.ruoyi.common.core.domain.entity.tymh.wwToken.WwUserLogin;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class OauthLoginHlwService {
@Autowired
private OauthClient oauthClient;
@Autowired
private TokenService tokenService;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysUserService sysUserService;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private ICompanyService companyService;
@Autowired
private CompanyContactService companyContactService;
@Autowired
private IAppUserService appUserService;
// Redis缓存门户UserID → 若依本地用户名(避免重复匹配数据库)
private static final String REDIS_KEY_PORTAL_USER_MAPPING = "hlw:user:mapping:";
// 门户 Token 存储前缀Redis 键:门户 userId → 门户 Token 信息)
private static final String REDIS_KEY_PORTAL_TOKEN = "hlw:token:";
final private int expireTime=30;
protected static final long MILLIS_SECOND = 1000;
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
/**
* OAuth 登录流程:通过授权码获取系统令牌
* @return 系统内部令牌(供前端后续使用)
*/
public String getWwTjmhToken(WwUserLogin wwUserLogin){
try {
//获取门户token
WwTokenResult wwTokenResult = oauthClient.wwGetToken(wwUserLogin);
String wwToken=wwTokenResult.getAccessToken();
System.out.println("wwToken======================="+wwToken);
if (StringUtils.isBlank(wwToken)) {
throw new ServiceException("获取门户 Token 失败:" + wwToken);
}
//获取门户userInfo
WwTyInfo portalUser = oauthClient.wwGetUserInfo(wwTokenResult);
//匹配/创建本地用户
String localUsername = getOrCreateLocalUser(portalUser);
//执行原来的登录流程
Authentication authentication = authenticateLocalUser(localUsername);
AsyncManager.me().execute(AsyncFactory.recordLogininfor(localUsername, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
storePortalToken(loginUser.getUserId(), wwToken);
recordLoginInfo(loginUser.getUserId());
return tokenService.createToken(loginUser);
} catch (Exception e) {
throw new ServiceException("OAuth 登录失败:" + e.getMessage());
}
}
/**
* 匹配/创建本地用户,返回若依本地用户名
*/
private String getOrCreateLocalUser(WwTyInfo wwTyInfo) {
String idCard="";
switch (wwTyInfo.getUsertype()){
case "1"://个人
idCard=wwTyInfo.getIdno();
break;
default:
idCard=wwTyInfo.getEnterprisecode();
}
// 先从Redis查询缓存的本地用户名
String cacheKey = REDIS_KEY_PORTAL_USER_MAPPING + idCard;
String localUsername = redisCache.getCacheObject(cacheKey);
if (StringUtils.isNotBlank(localUsername)) {
if ("hlw_".equals(localUsername)) {
localUsername = String.format("%s%s", localUsername, idCard);
}
updateUserInfo(wwTyInfo);
return localUsername;
}
SysUser localUser=sysUserService.selectUserByIdCard(wwTyInfo.getIdno());
if (localUser == null) {
// 本地无用户,自动创建
localUser = createLocalUser(wwTyInfo);
// 缓存门户UserID与本地用户名的映射有效期1天可调整
redisCache.setCacheObject(cacheKey, localUser.getUserName(), 1, TimeUnit.DAYS);
return localUser.getUserName();
}
// 缓存映射关系(更新有效期)
redisCache.setCacheObject(cacheKey, localUser.getUserName(), 1, TimeUnit.DAYS);
return localUser.getUserName();
}
/**
* 门户UserID字符串转Long
*/
private Long parseStringToLoing(String portalUserIdStr) {
try {
return Long.parseLong(portalUserIdStr);
} catch (NumberFormatException e) {
throw new ServiceException("门户用户ID格式错误" + portalUserIdStr);
}
}
/**
* 自动创建本地用户
*/
private SysUser createLocalUser(WwTyInfo wwTyInfo) {
//移动端用户
AppUser appUserParm=new AppUser();
appUserParm.setIsRecommend(1);
//pc端
SysUser newUser = new SysUser();
String localUsername=StringUtil.USER_KEY+wwTyInfo.getIdno();
switch (wwTyInfo.getUsertype()) {
case "1"://个人
newUser.setNickName(wwTyInfo.getName());
newUser.setIdCard(wwTyInfo.getIdno());
newUser.setRoleIds(new Long[]{parseStringToLoing(StringUtil.SYS_QZZ)});
//移动端
appUserParm.setPhone(wwTyInfo.getPhone());
appUserParm.setIdCard(wwTyInfo.getIdno());
appUserParm.setName(wwTyInfo.getName());
break;
default://单位
newUser.setNickName(wwTyInfo.getEnterprisename());
newUser.setIdCard(wwTyInfo.getEnterprisecode());
newUser.setRoleIds(new Long[]{parseStringToLoing(StringUtil.SYS_QY)});
//修改企业和企业联系人
updateCompanyContact(wwTyInfo);
//移动端
appUserParm.setPhone(wwTyInfo.getPhone());
appUserParm.setIdCard(wwTyInfo.getEnterprisecode());
appUserParm.setName(wwTyInfo.getEnterprisename());
}
newUser.setPassword(SecurityUtils.encryptPassword("123456"));
newUser.setDelFlag("0");
newUser.setUserName(localUsername);
sysUserService.insertUser(newUser);
//插入app_user
AppUser appUser=appUserService.selectAppuserByIdcard(wwTyInfo.getIdno());
if(appUser!=null){
appUserParm.setUserId(appUser.getUserId());
appUserService.updateAppUser(appUserParm);
}else{
appUserService.insertAppUser(appUserParm);
}
return newUser;
}
/**
* 复用若依认证机制,触发 UserDetailsService 加载 LoginUser
* (关键:用本地用户名构建认证令牌,无需密码,因为门户已完成身份校验)
*/
private Authentication authenticateLocalUser(String localUsername) {
Authentication authentication = null;
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(localUsername);
authentication = new UsernamePasswordAuthenticationToken(
userDetails,
null, // 密码为 null彻底绕过 Spring Security 的密码校验
userDetails.getAuthorities()
);
AuthenticationContextHolder.setContext(authentication);
} catch (Exception e) {
throw new ServiceException("本地用户认证失败:" + e.getMessage());
} finally {
AuthenticationContextHolder.clearContext();
}
return authentication;
}
/**
* 存储门户 Token 到 Redis结构化存储含过期时间
*/
private void storePortalToken(Long portalUserId, String accessToken) {
String redisKey = REDIS_KEY_PORTAL_TOKEN + portalUserId;
PortalTokenCacheDTO tokenCache = new PortalTokenCacheDTO();
tokenCache.setAccessToken(accessToken);
tokenCache.setExpireTimestamp(System.currentTimeMillis() + expireTime * MILLIS_MINUTE);
redisCache.setCacheObject(redisKey, tokenCache, expireTime, TimeUnit.SECONDS);
}
/**
* 记录登录信息(复用若依原生逻辑,直接复制过来)
*/
private void recordLoginInfo(Long userId) {
SysUser sysUser = new SysUser();
sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysUser.setLoginDate(new Date());
sysUserService.updateUserProfile(sysUser);
}
/**
* 获取互联网token
* @param wwTokenResult
* @return
*/
public String getWwTjmHlwToken(WwTokenResult wwTokenResult){
try {
//获取门户userInfo
WwTyInfo portalUser = oauthClient.wwGetUserInfo(wwTokenResult);
//匹配/创建本地用户
String localUsername = getOrCreateLocalUser(portalUser);
//执行原来的登录流程
Authentication authentication = authenticateLocalUser(localUsername);
AsyncManager.me().execute(AsyncFactory.recordLogininfor(localUsername, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
storePortalToken(loginUser.getUserId(), wwTokenResult.getAccessToken());
recordLoginInfo(loginUser.getUserId());
return tokenService.createToken(loginUser);
} catch (Exception e) {
throw new ServiceException("OAuth 登录失败:" + e.getMessage());
}
}
/**
* 修改个人信息
* @param wwTyInfo
*/
private void updateUserInfo(WwTyInfo wwTyInfo){
//移动端用户
AppUser appUserParm=new AppUser();
appUserParm.setIsRecommend(1);
//pc端
String code="";
SysUser sysUser=new SysUser();
switch (wwTyInfo.getUsertype()){
case "1":
sysUser.setNickName(wwTyInfo.getName());
sysUser.setIdCard(wwTyInfo.getIdno());
sysUser.setRoleIds(new Long[]{parseStringToLoing(StringUtil.SYS_QZZ)});
//移动端
appUserParm.setPhone(wwTyInfo.getPhone());
appUserParm.setIdCard(wwTyInfo.getIdno());
appUserParm.setName(wwTyInfo.getName());
appUserParm.setIsCompanyUser(StringUtil.IS_JOB_REQUEST_USER);
code=wwTyInfo.getIdno();
break;
default:
sysUser.setNickName(wwTyInfo.getEnterprisename());
sysUser.setIdCard(wwTyInfo.getEnterprisecode());
sysUser.setRoleIds(new Long[]{parseStringToLoing(StringUtil.SYS_QY)});
//企业联系人->现根据社会信用代码查询企业信息
updateCompanyContact(wwTyInfo);
//移动端
String phone = StringUtils.isNotBlank(wwTyInfo.getPhone()) ? wwTyInfo.getPhone() : wwTyInfo.getContactphone();
appUserParm.setPhone(phone);
appUserParm.setIdCard(wwTyInfo.getEnterprisecode());
appUserParm.setName(wwTyInfo.getEnterprisename());
appUserParm.setIsCompanyUser(StringUtil.IS_COMPANY_USER);
code=wwTyInfo.getEnterprisecode();
}
String localUsername=StringUtil.USER_KEY+code;
//查询用户角色
sysUser.setUserName(localUsername);
//查询用户id
SysUser parmUser=sysUserService.selectUserByIdCard(code);
sysUser.setUserId(parmUser.getUserId());
sysUserService.updateUser(sysUser);
//插入app_user
AppUser appUser=appUserService.selectAppuserByIdcard(code);
if(appUser!=null){
appUserParm.setUserId(appUser.getUserId());
appUserService.updateAppUser(appUserParm);
}else{
appUserService.insertAppUser(appUserParm);
}
}
/**
* 修改联系人信息
* @param wwTyInfo
*/
public void updateCompanyContact(WwTyInfo wwTyInfo) {
if (wwTyInfo == null) {
throw new IllegalArgumentException("参数WwTyInfo不能为空");
}
String enterpriseCode = wwTyInfo.getEnterprisecode();
String enterpriseName = wwTyInfo.getEnterprisename();
String contactPerson = wwTyInfo.getContactperson();
String contactPhone = wwTyInfo.getContactphone();
Company company = companyService.queryCodeCompany(enterpriseCode);
CompanyContact contact = new CompanyContact();
contact.setContactPerson(contactPerson);
contact.setContactPersonPhone(contactPhone);
if (Objects.nonNull(company)) {
Company updateCompany = new Company();
updateCompany.setCompanyId(company.getCompanyId());
updateCompany.setCode(enterpriseCode);
updateCompany.setName(enterpriseName);
companyService.updateCompany(updateCompany);
contact.setCompanyId(company.getCompanyId());
List<CompanyContact> existingContacts = companyContactService.getSelectList(contact);
List<CompanyContact> contactList = new ArrayList<>();
if (!CollectionUtils.isEmpty(existingContacts)) {
contact.setId(existingContacts.get(0).getId());
contactList.add(contact);
companyContactService.insertUpadteCompanyContact(contactList);
} else {
companyContactService.insertContact(contact);
}
} else {
Company newCompany = new Company();
newCompany.setCode(enterpriseCode);
newCompany.setName(enterpriseName);
companyService.insertCompany(newCompany);
if (Objects.nonNull(newCompany.getCompanyId())) {
contact.setCompanyId(newCompany.getCompanyId());
companyContactService.insertContact(contact);
} else {
throw new RuntimeException("新增企业失败:社会信用代码=" + enterpriseCode + "未返回有效企业ID");
}
}
}
}

View File

@@ -1,586 +0,0 @@
package com.ruoyi.framework.web.service;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.cms.service.ICompanyService;
import com.ruoyi.cms.service.impl.AppUserServiceImpl;
import com.ruoyi.cms.util.StringUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.Company;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginSiteUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.encrypt.EncryptUtil;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
/**
* @Author: chenyanchang
* @Date: 2026/5/19 下午6:03
*/
@Service
public class SsoService {
@Autowired
RedisCache redisCache;
@Autowired
AppUserServiceImpl appUserService;
@Autowired
SysUserServiceImpl sysUserService;
@Autowired
private TokenSiteService tokenSiteService;
@Autowired
private TokenService tokenService;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private ICompanyService companyService;
//一体机pc个人企业
@Value("${lc_web_auth.appId}")
String webAppId;
@Value("${lc_web_auth.appSecret}")
String webAppSecret;
@Value("${lc_web_auth.getTokenUrl}")
String WEB_GET_TOKEN_URL;
@Value("${lc_web_auth.getUserInfoUrl}")
String WEB_GET_USER_INFO;
//pc监管
@Value("${lc_cms_auth.appId}")
String cmsAppId;
@Value("${lc_cms_auth.appSecret}")
String cmsAppSecret;
@Value("${lc_cms_auth.getTokenUrl}")
String CMS_GET_TOKEN_URL;
@Value("${lc_cms_auth.getUserInfoUrl}")
String CMS_GET_USER_INFO;
/**
* 一体机单点登录-code
* @param param
* @return
*/
public JSONObject ssoCodeLogin(JSONObject param) {
if (ObjectUtils.isEmpty(param)) {
throw new RuntimeException("请求参数不能为空");
}
String code = param.getString("code");
//通过code获取token
JSONObject json = new JSONObject();
json.put("code", code);
String lcToken = getToken(WEB_GET_TOKEN_URL, null, json.toJSONString());
if (StringUtils.isEmpty(lcToken)) {
throw new RuntimeException("获取token失败");
}
//获取用户信息
JSONObject pJson = new JSONObject();
pJson.put("appId", webAppId);
pJson.put("appSecret", webAppSecret);
JSONObject userJson = getUserInfo(WEB_GET_USER_INFO, lcToken, pJson.toJSONString());
System.out.println("userJson=============" + JSONObject.toJSONString(userJson));
if (ObjectUtils.isEmpty(userJson)) {
throw new RuntimeException("获取用户信息失败");
}
//获取身份证号
String personCardNo = null;
JSONObject info = null;
if (userJson.containsKey("info")) {
info = userJson.getJSONObject("info");
if (ObjectUtils.isNotEmpty(info) && info.containsKey("personCardNo")) {
personCardNo = info.getString("personCardNo");
//解密处理
if (StringUtils.isEmpty(personCardNo)) {
throw new RuntimeException("获取用户证件信息失败");
}
personCardNo = EncryptUtil.decryptByAppIdAndSecret(personCardNo, webAppId, webAppSecret);
}
}
//用身份证号查询用户 用户类型01个人02企业
// 转换成本地app角色0企业1求职者2网格员 3内部政府人员 4其他浪潮用
String isCompanyUser = userJson.getString("userType");
isCompanyUser = "01".equals(isCompanyUser) ? "1" : "0";
AppUser appUser = saveAppUser(userJson, isCompanyUser);
//用户存在生成本系统用户的token
String token = loginAppUser(appUser, userJson.getString("userName"));
JSONObject backJson = new JSONObject();
backJson.put("token", token);
backJson.put("lcToken", lcToken);
return backJson;
}
/**
* 一体机单点登录-token(浪潮token)
* @param param
* @return
*/
public JSONObject ssoTokenLogin(JSONObject param) {
if (ObjectUtils.isEmpty(param)) {
throw new RuntimeException("请求参数不能为空");
}
//浪潮token
String lcToken = param.getString("lcToken");
//获取用户信息
JSONObject pJson = new JSONObject();
pJson.put("appId", webAppId);
pJson.put("appSecret", webAppSecret);
JSONObject userJson = getUserInfo(WEB_GET_USER_INFO, lcToken, pJson.toJSONString());
if (ObjectUtils.isEmpty(userJson)) {
throw new RuntimeException("获取用户信息失败");
}
//获取身份证号
String personCardNo = null;
JSONObject info = null;
if (userJson.containsKey("info")) {
info = userJson.getJSONObject("info");
if (ObjectUtils.isNotEmpty(info) && info.containsKey("personCardNo")) {
personCardNo = info.getString("personCardNo");
//解密处理
if (StringUtils.isEmpty(personCardNo)) {
throw new RuntimeException("获取用户证件信息失败");
}
personCardNo = EncryptUtil.decryptByAppIdAndSecret(personCardNo, webAppId, webAppSecret);
}
}
//用身份证号查询用户 用户类型01个人02企业
// 转换成本地app角色0企业1求职者2网格员 3内部政府人员 4其他浪潮用
String isCompanyUser = userJson.getString("userType");
isCompanyUser = "01".equals(isCompanyUser) ? "1" : "0";
AppUser appUser = saveAppUser(userJson, isCompanyUser);
//用户存在生成本系统用户的token
String token = loginAppUser(appUser, userJson.getString("userName"));
JSONObject backJson = new JSONObject();
backJson.put("token", token);
backJson.put("lcToken", lcToken);
return backJson;
}
/**
* pc端个人、企业单点登录-code
* @param param
* @return
*/
public JSONObject ssoPcodeLogin(JSONObject param) {
if (ObjectUtils.isEmpty(param)) {
throw new RuntimeException("请求参数不能为空");
}
//浪潮code
String code = param.getString("code");
//用户类型
//通过code获取token
JSONObject json = new JSONObject();
json.put("code", code);
String lcToken = getToken(WEB_GET_TOKEN_URL, null, json.toJSONString());
if (StringUtils.isEmpty(lcToken)) {
throw new RuntimeException("获取token失败");
}
//获取用户信息
JSONObject pJson = new JSONObject();
pJson.put("appId", webAppId);
pJson.put("appSecret", webAppSecret);
JSONObject userJson = getUserInfo(WEB_GET_USER_INFO, lcToken, pJson.toJSONString());
if (ObjectUtils.isEmpty(userJson)) {
throw new RuntimeException("获取用户信息失败");
}
//用身份证号查询用户 用户类型01个人02企业
// 转换成本地app角色0企业1求职者2网格员 3内部政府人员 4其他浪潮用
//userType对应appuser的isCompanyUser
String isCompanyUser = userJson.getString("userType");
isCompanyUser = "01".equals(isCompanyUser) ? "1" : "0";
//获取身份证号
String personCardNo = null;
JSONObject info = userJson.getJSONObject("info");;
//判断是否是企业
boolean hasRecruitRole = Optional.ofNullable(userJson.getJSONArray("roles"))
.filter(arr -> !arr.isEmpty())
.map(JSONArray::stream)
.orElse(Stream.empty())
.anyMatch(obj -> {
JSONObject role = (JSONObject) obj;
Long roleCode = role.getLong("roleCode");
return roleCode != null && roleCode == 1102L;
});
//保存企业信息
if("0".equals(isCompanyUser) && hasRecruitRole){
personCardNo=info.getString("entCreditCode");
if (personCardNo != null) {
Company company=companyService.queryCodeCompany(personCardNo);
if(company==null){
JSONObject infoJson = userJson.getJSONObject("info");
saveCompany(infoJson);
}
}
}
//1.先查appuser,不存在,则新增
AppUser appUser = saveAppUser(userJson, isCompanyUser);
//2.再查sysuser,不存在,则新增
SysUser sysUser = saveSysUser(userJson, appUser.getUserId(), isCompanyUser);
//用户存在生成本系统用户的token
String token = loginSysUser(sysUser, userJson.getString("userName"));
JSONObject backJson = new JSONObject();
backJson.put("token", token);
backJson.put("lcToken", lcToken);
return backJson;
}
/**
* 保存企业信息
* @param object
*/
public void saveCompany(JSONObject object){
Company company=new Company();
company.setCode(object.getString("entCreditCode"));
company.setName(object.getString("entName"));
company.setLegalPerson(object.getString("entLegalPersonName"));
company.setLegalIdCard(object.getString("entLegalPersonCardNo"));
company.setLegalPhone(object.getString("entLegalPersonPhone"));
company.setIndustry(object.getString("entIndustry"));
company.setRegisteredAddress(object.getString("entRegisteredAddress"));
companyService.insertCompany(company);
}
/**
* pc端监管端单点登录-code
* @param param
* @return
*/
public JSONObject ssoPcmsCodeLogin(JSONObject param) {
if (ObjectUtils.isEmpty(param)) {
throw new RuntimeException("请求参数不能为空");
}
//浪潮code
String code = param.getString("code");
//通过code获取token
JSONObject json = new JSONObject();
json.put("code", code);
String lcToken = getToken(CMS_GET_TOKEN_URL, null, json.toJSONString());
if (StringUtils.isEmpty(lcToken)) {
throw new RuntimeException("获取token失败");
}
//获取用户信息
JSONObject pJson = new JSONObject();
pJson.put("appId", cmsAppId);
pJson.put("appSecret", cmsAppSecret);
JSONObject userJson = getUserInfo(CMS_GET_USER_INFO, lcToken, pJson.toJSONString());
if (ObjectUtils.isEmpty(userJson)) {
throw new RuntimeException("获取用户信息失败");
}
//用身份证号查询用户 用户类型01个人02企业
// 转换成本地app角色0企业1求职者2网格员 3内部政府人员 4其他浪潮用
//取角色判断是网格员2还是内部工作者3
String isCompanyUser = null;
if(userJson.containsKey("roles")) {
JSONObject role = userJson.getJSONArray("roles").getJSONObject(0);
if (role != null && role.containsKey("roleId")) {
/*1101(求职者)、1102(招聘者)、1103(网格员)、1104(内部工作者)*/
Long roleId = role.getLong("roleId");
if (roleId != null && roleId.equals(1103L)) {
isCompanyUser = "2";//2网格员
}
}
}
Long appUserId = null;
if (StringUtils.isNotEmpty(isCompanyUser) && "2".equals(isCompanyUser)) {
//1.先查appuser,不存在,则新增
AppUser appUser = saveAppUser(userJson, isCompanyUser);
appUserId = appUser.getUserId();
} /*else {
throw new RuntimeException("非网格员不允许执行此操作");
}*/
//2.再查sysuser,不存在,则新增
//身份证为空则查userId
SysUser sysUser = saveSysUser(userJson, appUserId, isCompanyUser);
//用户存在生成本系统用户的token
String token = loginSysUser(sysUser, userJson.getString("userName"));
JSONObject backJson = new JSONObject();
backJson.put("token", token);
backJson.put("lcToken", lcToken);
return backJson;
}
//获取token
private String getToken(String url, String token, String params) {
String result = sendHttpPost(url, token, params);
if (StringUtils.isEmpty(result)) {
throw new RuntimeException("获取token失败");
}
JSONObject json = JSONObject.parseObject(result);
if (json.getInteger("code") == 200) {
return json.getString("token");
} else if (json.getInteger("code") == 401) {
throw new RuntimeException("认证过期");
} else {
throw new RuntimeException("获取token失败");
}
}
//模拟登录appuser
public String loginAppUser(AppUser appUser, String userName){
LoginSiteUser loginSiteUser = new LoginSiteUser();
loginSiteUser.setUserId(appUser.getUserId());
loginSiteUser.setUser(appUser);
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
// 生成token
return tokenSiteService.createTokenHourTwo(loginSiteUser);
}
//模拟登录sysuser
public String loginSysUser(SysUser sysUser, String userName){
Authentication authentication = authenticateLocalUser(userName);
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
// 生成token
return tokenService.createTokenHourTwo(loginUser);
}
/**
* 获取用户权限
* @param localUsername
* @return
*/
private Authentication authenticateLocalUser(String localUsername) {
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(localUsername);
return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
} catch (Exception e) {
throw new ServiceException("本地用户认证失败:" + e.getMessage());
}
}
//获取用户信息
private JSONObject getUserInfo(String url, String token, String params) {
try {
String result = sendHttpPost(url, token, params);
if (StringUtils.isEmpty(result)) {
throw new RuntimeException("获取用户信息失败");
}
JSONObject json = JSONObject.parseObject(result);
if (json.getInteger("code") == 200) {
return json.getJSONObject("sysUser");
} else if (json.getInteger("code") == 401) {
throw new RuntimeException("认证过期");
} else {
throw new RuntimeException("获取用户信息失败");
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
//保存appuser用户
private AppUser saveAppUser(JSONObject userJson, String isCompanyUser) {
JSONObject info = userJson.containsKey("info") ? userJson.getJSONObject("info") : null;
System.out.println("userId===========" + userJson.getLong("userId"));
System.out.println("userJson===========" + JSONObject.toJSONString(userJson));
AppUser appUser = new AppUser();
//app角色0企业1求职者2网格员 3内部政府人员 4其他浪潮用
appUser.setIsCompanyUser(isCompanyUser);
// appUser.setUserId(userJson.getLong("userId"));
String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
appUser.setCreateTime(date);
appUser.setUpdateTime(date);
appUser.setLoginDate(new Date());
appUser.setCreateBy("system");
appUser.setLoginIp(IpUtils.getIpAddr());
//获取身份证,再获取年龄
String personCardNo = null;
//1.求职者 2.网格员
if ("0".equals(isCompanyUser)) {
appUser.setName(userJson.getString("nickName"));
appUser.setAddress(info.getString("entRegisteredAddress"));
appUser.setDomicileAddress(info.getString("entRegisteredAddress"));
personCardNo = info.getString("entCreditCode");
appUser.setAddress(info.getString("entRegisteredAddress"));
String phone = info.getString("entAdminPhone");
//解密电话号码
if (StringUtils.isNotEmpty(phone)) {
phone = EncryptUtil.decryptByAppIdAndSecret(phone, cmsAppId, cmsAppSecret);
appUser.setPhone(phone);
}
} else {
appUser.setName(info != null ? info.getString("personName") : userJson.getString("nickName"));
appUser.setSex(info != null ? info.getString("personSex") : userJson.getString("sex"));
appUser.setBirthDate(info.getString("personBirthday"));
appUser.setEducation(StringUtil.convertEducation(info.getString("personEducation")));
appUser.setPoliticalAffiliation(info.getString("personPolitical"));
appUser.setAddress(info.getString("liveAddress"));
appUser.setWorkExperience(StringUtil.convertExp(info.getInteger("personYearsWorking")));
appUser.setNation(info.getString("personNation"));
appUser.setDomicileAddress(info.getString("householdAddress"));
//证件号
personCardNo = info != null && info.containsKey("personCardNo") ? info.getString("personCardNo") : userJson.getString("idCardNo");
personCardNo = EncryptUtil.decryptByAppIdAndSecret(personCardNo, webAppId, webAppSecret);
appUser.setAge(StringUtil.getAgeByIdNumber(personCardNo));
String phone = info != null ? info.getString("personPhone") : userJson.getString("phonenumber");
//解密电话号码
if (StringUtils.isNotEmpty(phone)) {
phone = EncryptUtil.decryptByAppIdAndSecret(phone, webAppId, webAppSecret);
appUser.setPhone(phone);
}
}
appUser.setIdCard(personCardNo);
AppUser checkUser = appUserService.selectAppuserByIdcardAndUserType(personCardNo, isCompanyUser);
if (checkUser != null) {
appUser.setUserId(checkUser.getUserId());
appUserService.updateAppUser(appUser);
} else {
appUserService.insertAppUser(appUser);
}
return appUser;
}
/**
* 保存sysuser
* @param userJson
* @return
*/
private SysUser saveSysUser(JSONObject userJson, Long appUserId, String isCompanyUser) {
JSONObject info = userJson.containsKey("info") ? userJson.getJSONObject("info") : null;
System.out.println("sysuserId==========" + userJson.getLong("userId"));
System.out.println("userJson==========" + JSONObject.toJSONString(userJson));
SysUser sysUser = new SysUser();
sysUser.setAppUserId(appUserId);
sysUser.setUserId(userJson.getLong("userId"));
sysUser.setUserName(userJson.getString("userName"));
sysUser.setNickName(userJson.getString("nickName"));
sysUser.setEmail(userJson.getString("email"));
sysUser.setSex(userJson.getString("sex"));
sysUser.setStatus("0");
sysUser.setDelFlag("0");
String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
sysUser.setCreateTime(date);
sysUser.setUpdateTime(date);
sysUser.setLoginDate(new Date());
sysUser.setCreateBy("system");
sysUser.setLoginIp(IpUtils.getIpAddr());
//获取身份证
String personCardNo="";
//0.企业 1.求职者 2.风格员
if("0".equals(isCompanyUser)){
personCardNo = info.getString("entCreditCode");
String phone = info.getString("entAdminPhone");
//解密电话号码
if (StringUtils.isNotEmpty(phone)) {
phone = EncryptUtil.decryptByAppIdAndSecret(phone, cmsAppId, cmsAppSecret);
sysUser.setPhonenumber(phone);
}
} else {
personCardNo = info != null && info.containsKey("personCardNo") ? info.getString("personCardNo") : userJson.getString("idCardNo");
personCardNo = EncryptUtil.decryptByAppIdAndSecret(personCardNo, webAppId, webAppSecret);
String phone = info != null && info.containsKey("personPhone") ? info.getString("personPhone") : userJson.getString("phonenumber");
//解密电话号码
if (StringUtils.isNotEmpty(phone)) {
phone = EncryptUtil.decryptByAppIdAndSecret(phone, webAppId, webAppSecret);
sysUser.setPhonenumber(phone);
}
}
//解密处理
if (StringUtils.isNotEmpty(personCardNo)) {
sysUser.setIdCard(personCardNo);
}
//部门
if (userJson.containsKey("dept")) {
JSONObject dept = userJson.getJSONObject("dept");
Long deptId = dept != null && dept.containsKey("deptId") ? dept.getLong("deptId") : null;
sysUser.setDeptId(deptId);
}
SysUser checkUser = sysUserService.selectUserById(userJson.getLong("userId"));
if (checkUser != null) {
sysUserService.updateUser(sysUser);
} else {
sysUserService.insertUser(sysUser);
}
//添加权限
JSONArray roles = userJson.getJSONArray("roles");
if (CollectionUtils.isNotEmpty(roles) && roles.size() != 0) {
List<SysUserRole> list = new ArrayList<>();
sysUserRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
for (int i = 0; i < roles.size(); i++) {
JSONObject json = roles.getJSONObject(i);
SysUserRole sysUserRole = new SysUserRole();
sysUserRole.setRoleId(json.getLong("roleId"));
sysUserRole.setUserId(sysUser.getUserId());
list.add(sysUserRole);
}
//新增角色
sysUserRoleMapper.batchUserRole(list);
}
return sysUser;
}
//发送请求
private String sendHttpPost(String url, String token, String params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (StringUtils.isNotEmpty(token)) {
httpPost.setHeader("Authorization", "Bearer " + token);
}
httpPost.setEntity(new StringEntity(params, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
return responseBody;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}