Commit d1366289 authored by 李健华's avatar 李健华

Merge branch 'KA-29' into 'master'

Ka 29

See merge request !15
parents 8ace2dbe 994ec947
# Created by https://www.gitignore.io
### log ###
.log
### svn ###
.svn/
......
##KA-29/2021-11-12
###ToB积分时代-电商saas产研开发专项-用户中心
```
package cn.quantgroup.xyqb.controller.internal.user.InnerController
修改 findUserDetailByUserId 方法增加 Integer tenantId(租户Id)参数,并修改逻辑判断。
修改 修改findByUuid 方法为findByUuidInfo 方法增加 Integer tenantId(租户Id)参数,并修改逻辑判断。
修改 findByPhoneNo 方法增加 Integer tenantId(租户Id)参数,并修改逻辑判断。
修改 findUserDetailByPhone 方法增加 Integer tenantId(租户Id)参数,并修改逻辑判断。
修改 findUserDetailByUserId 方法增加 Integer tenantId(租户Id)参数,并修改逻辑判断。
package cn.quantgroup.xyqb.controller.external.UserController;
修改 userCenterIndex 方法增加 头部信息qg-tenant-id (租户Id)参数,并修改逻辑判断。
新增 package cn.quantgroup.xyqb.controller.tenant.TenantController
新增接口方法 findTenantByUserId;通过userId (Long) 获取租户id列表
```
##KA-28/2021-11-02
###修改日志格式
##KA-27/2021-11-01
......
package cn.quantgroup.xyqb;
import cn.quantgroup.xyqb.config.SequencerProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
......@@ -25,6 +27,7 @@ import cn.quantgroup.tech.db.EnableDynamicDataSource;
@EnableAspectJAutoProxy
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDynamicDataSource
@EnableConfigurationProperties({SequencerProperties.class})
public class Bootstrap {
public static void main(String[] args) {
......
......@@ -33,6 +33,7 @@ public interface Constants {
Long VERIFICATION_CODE_FINITE_COUNT_NEW = 2L;
String X_AUTH_TOKEN = "x-auth-token";
String X_AUTH_TENANT = "qg-tenant-id";
int VERIFICATION_LEN = 2;
int SMS_CODE_LEN_4 = 4;
int SMS_CODE_LEN_6 = 6;
......
......@@ -7,8 +7,6 @@ import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
......@@ -37,6 +35,8 @@ public class IpValidateAdvisor {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 客户端IP
String clientIp = IpUtil.getRemoteIP(request);
log.error("Lock_ipv4-success: don't match white ip access:{}", clientIp);
// 白名单
if (IpUtil.whiteOf(clientIp)) {
return pjp.proceed();
......
......@@ -3,22 +3,20 @@ package cn.quantgroup.xyqb.aspect.captcha;
import cn.qg.ec.model.base.BusinessEventBaseInfo;
import cn.qg.ec.model.user.UserLoginRegEvent;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.risk.entity.CountDevice;
import cn.quantgroup.xyqb.entity.enums.Device;
import cn.quantgroup.xyqb.entity.enums.KeyType;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.LoginRefuseResult;
import cn.quantgroup.xyqb.risk.entity.CountDevice;
import cn.quantgroup.xyqb.risk.entity.LoginInfo;
import cn.quantgroup.xyqb.risk.repository.LoginInfoRepository;
import cn.quantgroup.xyqb.risk.repository.WhiteListRepository;
import cn.quantgroup.xyqb.risk.uereventcollecting.UserEventCollectingUtil;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.user.impl.UserServiceImpl;
import cn.quantgroup.xyqb.util.TenantUtil;
import cn.quantgroup.xyqb.util.encrypt.Md5Util;
import com.amazonaws.util.Md5Utils;
import com.google.common.collect.Maps;
import com.qiniu.util.Md5;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
......@@ -89,6 +87,23 @@ public class LoginInterceptorAspect {
private Object around(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Integer tenantId = null;
String tenId = request.getParameter("tenantId");
if (null != tenId) {
tenantId = Integer.parseInt(tenId);
}
// if (null == tenId) {
// byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
//
// String body = new String(bodyBytes, request.getCharacterEncoding());
// if (!"".equals(body)) {
// HashMap hashMap = JSON.parseObject(body, HashMap.class);
// tenantId = Integer.parseInt(hashMap.get("tenantId").toString());
// }
// } else {
// tenantId = Integer.parseInt(tenId);
// }
/**
* 拿参数
*/
......@@ -115,9 +130,9 @@ public class LoginInterceptorAspect {
/**
* 尝试登录发一下
*/
sendEvent(UserLoginRegEvent.SubEventType.user_attempt_login, device, phone, deviceId, realIp, null);
sendEvent(UserLoginRegEvent.SubEventType.user_attempt_login, device, phone, deviceId, realIp, null, tenantId);
LoginRefuseResult result = verification(scDeviceId, phone, device);
LoginRefuseResult result = verification(scDeviceId, phone, device, tenantId);
Object loginResult = null;
try {
......@@ -133,7 +148,7 @@ public class LoginInterceptorAspect {
/**
* 保存登录信息
*/
saveLoginInfo(phone, device, deviceId, realIp, result, loginResult);
saveLoginInfo(phone, device, deviceId, realIp, result, loginResult, tenantId);
}
return loginResult;
}
......@@ -143,7 +158,7 @@ public class LoginInterceptorAspect {
* @param phone
* @return
*/
private LoginRefuseResult verification(String deviceId, String phone, Device device) {
private LoginRefuseResult verification(String deviceId, String phone, Device device, Integer tenantId) {
try {
/**
* 默认code不需要
......@@ -160,6 +175,12 @@ public class LoginInterceptorAspect {
return LoginRefuseResult.builder()
.isPass(Boolean.TRUE).build();
}
// 如果租户非羊小咩放过
if (!tenantId.equals(TenantUtil.TENANT_DEFAULT) || null == tenantId) {
return LoginRefuseResult.builder()
.isPass(Boolean.TRUE).build();
}
/**
* 阈值
*/
......@@ -226,7 +247,7 @@ public class LoginInterceptorAspect {
* @param deviceId
* @param ip
*/
private void saveLoginInfo(String phone, Device device, String deviceId, String ip, LoginRefuseResult refuseResult, Object loginResult) {
private void saveLoginInfo(String phone, Device device, String deviceId, String ip, LoginRefuseResult refuseResult, Object loginResult, Integer tenantId) {
try {
/**
* 默认code不需要
......@@ -269,7 +290,7 @@ public class LoginInterceptorAspect {
if (loginResult instanceof JsonResult) {
if (((JsonResult) loginResult).isSuccess()) {
info.setIsLogin(Boolean.TRUE);
sendEvent(UserLoginRegEvent.SubEventType.user_only_login, device, phone, deviceId, ip, loginResult);
sendEvent(UserLoginRegEvent.SubEventType.user_only_login, device, phone, deviceId, ip, loginResult, tenantId);
} else {
info.setIsLogin(Boolean.FALSE);
info.setLoginFailMsg(((JsonResult) loginResult)
......@@ -307,7 +328,7 @@ public class LoginInterceptorAspect {
* @param ip
* @param loginResult
*/
private void sendEvent(UserLoginRegEvent.SubEventType type, Device device, String phone, String deviceId, String ip, Object loginResult) {
private void sendEvent(UserLoginRegEvent.SubEventType type, Device device, String phone, String deviceId, String ip, Object loginResult, Integer tenantId) {
try {
if (null == phone) {
......@@ -349,7 +370,9 @@ public class LoginInterceptorAspect {
baseInfoBuilder.deviceType(device.getCode());
builder.businessEventBaseInfo(baseInfoBuilder.build());
UserEventCollectingUtil.addEvent(builder.build());
if (tenantId == null || tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
UserEventCollectingUtil.addEvent(builder.build());
}
} catch (Exception e) {
log.error("发送用户登录事件异常phone:{}", phone);
}
......
......@@ -3,17 +3,17 @@ package cn.quantgroup.xyqb.aspect.limit;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.session.XyqbSessionContextHolder;
import cn.quantgroup.xyqb.util.IpUtil;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
......@@ -85,12 +85,41 @@ public class PasswordFreeAccessValidateAdvisor {
log.info("非法请求 - 无效token, token={}, phoneNo={}, userId={}, clientIp={}", token, phoneNo, userId, clientIp);
return false;
}
// 当前session
SessionStruct session = XyqbSessionContextHolder.getXSessionFromRedis(token);
if (Objects.isNull(session) || Objects.isNull(session.getValues()) || Objects.isNull(session.getValues().getUser())) {
log.info("非法请求 - 未登录, token={}, phoneNo={}, userId={}, clientIp={}", token, phoneNo, userId, clientIp);
return false;
}
// 获取头部qg-tenant-id
String tenantId = request.getHeader(Constants.X_AUTH_TENANT);
LoginProperties loginProperties = session.getValues().getLoginProperties();
// 如果token Session tenantId 不为空
if (!Objects.isNull(loginProperties.getTenantId())) {
// 如果头部没有tenantId参数
if (StringUtils.isBlank(tenantId)) {
// 如果 token Session tenantId 不是默认羊小咩, 那么拒绝登陆
if (!loginProperties.getTenantId().equals(TenantUtil.TENANT_DEFAULT)) {
log.info("非法请求 - 错误租户, token={}, phoneNo={}, userId={}, clientIp={}, tenantId={}, loginTenantId={}", token, phoneNo, userId, clientIp, tenantId, loginProperties.getTenantId().toString());
return false;
}
} else {
//如果头部有tenantId参数,判断是否相等,并且是否是默认羊小咩
if (!loginProperties.getTenantId().toString().equals(tenantId) && !TenantUtil.TENANT_DEFAULT.toString().equals(tenantId)) {
log.info("非法请求 - 错误租户, token={}, phoneNo={}, userId={}, clientIp={}, tenantId={}, loginTenantId={}", token, phoneNo, userId, clientIp, tenantId, loginProperties.getTenantId().toString());
return false;
}
}
} else {
// 如果token seesion tenantId 为空, tenantId不为空,并且不是默认羊小咩
if(!StringUtils.isBlank(tenantId) && !TenantUtil.TENANT_DEFAULT.toString().equals(tenantId)) {
log.info("非法请求 - 错误租户, token={}, phoneNo={}, userId={}, clientIp={}, tenantId={}", token, phoneNo, userId, clientIp, tenantId);
return false;
}
}
// 当前用户
User user = session.getValues().getUser();
if (Objects.isNull(user.getId()) && StringUtils.isBlank(user.getPhoneNo())) {
......
package cn.quantgroup.xyqb.config;
import cn.quantgroup.xyqb.util.DefaultSequencer;
import cn.quantgroup.xyqb.util.IdentitySequencer;
import cn.quantgroup.xyqb.util.ServerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Created by hechao on 2020/1/22.
*/
@Configuration
@EnableConfigurationProperties
public class AutoConfiguration {
@Autowired
private Environment environment;
@EnableConfigurationProperties
class Sequencer {
@Bean
@ConditionalOnMissingBean
public IdentitySequencer identitySequencer(SequencerProperties sequencerProperties) throws Exception {
Integer integerPort = ServerUtils.getIntegerPort(environment);
Long workId = null;
if (integerPort != null) {
workId = integerPort.longValue();
}
if (workId == null) {
throw new IllegalArgumentException("server port is null.");
}
workId = ServerUtils.getLongHostAddress() ^ integerPort;
return new DefaultSequencer(workId, sequencerProperties);
}
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Created by hechao on 2020/1/22.
*/
@ConfigurationProperties(prefix = "cn.quantgroup.sequencer")
public class SequencerProperties {
private String operator = "TWEPOCH_XOR";
private Integer sequenceBits = 8;
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public Integer getSequenceBits() {
return sequenceBits;
}
public void setSequenceBits(Integer sequenceBits) {
this.sequenceBits = sequenceBits;
}
@Override
public String toString() {
return "SnowflakepProperties{" +
", sequenceBits=" + sequenceBits +
'}';
}
}
......@@ -15,6 +15,7 @@ import java.util.Objects;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSession;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSessionFromRedis;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSessionFromTenantRedis;
/**
* Created by Miraculous on 15/7/5.
......@@ -43,6 +44,14 @@ public interface IBaseController {
return session.getValues().getUser();
}
default String getCurrentTenantIdRedis() {
String tenantId = getXSessionFromTenantRedis();
if (tenantId == null) {
return null;
}
return tenantId;
}
default SessionStruct getCurrentSessionFromRedis() {
return getXSessionFromRedis();
}
......
......@@ -19,14 +19,12 @@ import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.ILockIpv4Service;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.user.UserCenterService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.session.XyqbSessionContextHolder;
import cn.quantgroup.xyqb.util.IpUtil;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.TenantUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
......@@ -81,6 +79,9 @@ public class UserController implements IBaseController {
@Autowired
private IUserRegisterService userRegisterService;
@Autowired
private ITenantService tenantService;
/**
* 登录(账号 + 密码)
......@@ -161,9 +162,10 @@ public class UserController implements IBaseController {
@RequestParam(required = false) Long btRegisterChannelId,
@RequestParam(required = false) String dimension,
@RequestParam(name = "click_id", required = false) String clickId,
@RequestParam(required = false) Integer tenantId,
HttpServletRequest request) {
log.info("login/fastV1 -> channelId:{},ZappChennel:{},createdFrom:{},key:{},btRegisterChannelId:{},dimension:{},clickId:{}", channelId, appChannel, createdFrom, key, btRegisterChannelId, dimension, clickId);
return loginFast(channelId, appChannel, createdFrom, key, btRegisterChannelId, dimension, clickId, request);
return loginFast(channelId, appChannel, createdFrom, key, btRegisterChannelId, dimension, clickId, tenantId, request);
}
/**
......@@ -180,6 +182,7 @@ public class UserController implements IBaseController {
@RequestParam(required = false) Long btRegisterChannelId,
@RequestParam(required = false) String dimension,
@RequestParam(name = "click_id", required = false) String clickId,
@RequestParam(required = false) Integer tenantId,
HttpServletRequest request) {
Map<String, JsonResult> validMap = getHeaderParam(request);
log.info("login/fast -> channelId:{},appChannel:{},createdFrom:{},btRegisterChannelId:{},key:{},dimension:{},clickId:{}", channelId, appChannel, createdFrom, btRegisterChannelId, key, dimension, clickId);
......@@ -200,7 +203,11 @@ public class UserController implements IBaseController {
String verificationCode = successResult.getMsg();
// 执行短信验证码检查
verifyPhoneAndCodeForOnce(phoneNo, verificationCode);
return userService.loginFast(channelId, appChannel, createdFrom, btRegisterChannelId, dimension, clickId, request, merchant, phoneNo);
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
return userService.loginFast(channelId, appChannel, createdFrom, btRegisterChannelId, dimension, clickId, request, merchant, phoneNo, tenantId);
}
/**
......@@ -434,7 +441,8 @@ public class UserController implements IBaseController {
* @yapi http://yapi.quantgroups.com/project/17/interface/api/9191
*/
@RequestMapping("/token")
public JsonResult token(@RequestParam String token) {
public JsonResult token(@RequestParam String token, @RequestParam(required = false) Integer tenantId) {
Map<String, Object> result = new HashMap<>();
result.put("exist", false);
if (StringUtils.isEmpty(token)) {
......@@ -448,6 +456,22 @@ public class UserController implements IBaseController {
return JsonResult.buildSuccessResult(null, result);
}
User user = sessionStruct.getValues().getUser();
Integer sessionTenantId = sessionStruct.getValues().getLoginProperties().getTenantId();
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(sessionTenantId)) {
sessionTenantId = TenantUtil.TENANT_DEFAULT;
}
//校验非羊小咩租户
if (!sessionTenantId.equals(TenantUtil.TENANT_DEFAULT)) {
if (sessionTenantId.equals(tenantId)) {
user = tenantService.getTenantUser(user, tenantId);
if (user == null) {
return JsonResult.buildSuccessResult(null, result);
}
}else {
return JsonResult.buildSuccessResult(null, result);
}
}
String phoneNo = user.getPhoneNo();
result.put("phoneNo", phoneNo);
result.put("userId", user.getId());
......@@ -479,6 +503,13 @@ public class UserController implements IBaseController {
brief.setName(userDetail.getName());
brief.setSex(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).ordinal() + "");
brief.setPhoneNo(userDetail.getPhoneNo().substring(0, 3) + "****" + userDetail.getPhoneNo().substring(7, 11));
} else {
return JsonResult.buildSuccessResult("", brief);
}
String tenantId = getCurrentTenantIdRedis();
if (tenantId != null && !TenantUtil.TENANT_DEFAULT.equals(Integer.parseInt(tenantId))) {
brief = tenantService.getTenantCustomerInfo(userDetail, Integer.parseInt(tenantId));
}
return JsonResult.buildSuccessResult(null, brief);
}
......@@ -531,7 +562,7 @@ public class UserController implements IBaseController {
} else if (!wechatRelateUserIfNecessary(user, request)) {
return JsonResult.buildErrorStateResult("登录时微信关联失败", null);
}
LoginProperties loginProperties = new LoginProperties("", 1, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 1, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName(), null);
AuthBean authBean=sessionService.createSession(user, loginProperties);
if(authBean!=null){
authBean.setRegister(false);
......@@ -596,7 +627,7 @@ public class UserController implements IBaseController {
} else if (!wechatRelateUserIfNecessary(user, request)) {
return JsonResult.buildErrorStateResult("登录时微信关联失败", null);
}
LoginProperties loginProperties = new LoginProperties("", 4, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 4, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName(), null);
//尝试解锁
lockIpv4Service.unLockPhone(user.getPhoneNo());
//更新session
......
......@@ -334,7 +334,7 @@ public class WeChatController implements IBaseController {
private String createUserSession(User user, Merchant merchant, String redirect, String domain, Long registerFrom) {
log.info("[WeChatController][createUserSession]微信授权及跳转:user:{},merchant:{},redirect:{},domain:{},registerFrom:{}", user, merchant, redirect, domain, registerFrom);
LoginProperties loginProperties = new LoginProperties("", 4, Constants.Channel.WECHAT, registerFrom, String.valueOf(Constants.Channel.WECHAT), merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 4, Constants.Channel.WECHAT, registerFrom, String.valueOf(Constants.Channel.WECHAT), merchant.getId(), merchant.getName(), null);
if (StringUtils.isEmpty(redirect) || Constants.REDIRECT.equals(redirect)) {
log.info("微信登录:redirect为null,走正常流程.");
if (Constants.MERCHANT_BAITIAO.equals(merchant.getName())) {
......@@ -362,7 +362,7 @@ public class WeChatController implements IBaseController {
}
private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String domain, Long registerFrom) {
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, String.valueOf(Constants.Channel.WECHAT), merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, String.valueOf(Constants.Channel.WECHAT), merchant.getId(), merchant.getName(), null);
AuthBean authBean = sessionService.createSession(user, loginProperties);
log.info("[WeChatController][loginInWechatWithSessionCreated]微信授权及跳转:user:{},merchant:{},target:{},channelId:{},domain:{},registerFrom:{}", user, merchant, target, channelId, domain, registerFrom);
return domain + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom + "&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target;
......
......@@ -15,8 +15,10 @@ import cn.quantgroup.xyqb.security.AuthorizationPoint;
import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.IpUtil;
import cn.quantgroup.xyqb.util.TenantUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import com.sensorsdata.analytics.javasdk.ISensorsAnalytics;
import com.sensorsdata.analytics.javasdk.bean.EventRecord;
......@@ -51,6 +53,8 @@ public class AppController implements IBaseController {
@Autowired
private IUserService userService;
@Autowired
private IOauthLoginInfoService oauthLoginInfoService;
@Autowired
private IMerchantService merchantService;
@Autowired
private IUserRegisterService userRegisterService;
......@@ -66,8 +70,12 @@ public class AppController implements IBaseController {
@RequestParam(required = false) Long registerFrom,
@RequestParam(required = true) Long channelId,
@RequestParam(required = true) String appChannel,
@RequestParam(required = false) Integer tenantId,
HttpServletRequest request) {
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
JsonResult result = null;
Authentication authentication = AuthorityManager.authentication();
if(authentication.isAuthenticated()){
......@@ -81,8 +89,11 @@ public class AppController implements IBaseController {
if (user == null) {
// 未注册过
isRegister = true;
user = userRegisterService.register(registerFrom, phoneNumber, idNo, name, channelId, createdFrom);
user = userRegisterService.register(registerFrom, phoneNumber, idNo, name, channelId, createdFrom, tenantId);
}
// 无论是否注册过都添加映射
oauthLoginInfoService.addLoginInfo(user, tenantId);
if (user == null) {
result = JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
} else if (!user.getEnable()) {
......@@ -92,7 +103,7 @@ public class AppController implements IBaseController {
if (merchant == null) {
result = JsonResult.buildErrorStateResult("无效的商户", null);
}else{
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName(), null);
AuthBean bean = sessionService.createSession(user, loginProperties);
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(channelId);
......@@ -161,7 +172,8 @@ public class AppController implements IBaseController {
if (merchant == null) {
return JsonResult.buildErrorStateResult("无效的商户", null);
}
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName());
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName(), null);
AuthBean bean = sessionService.createSession(user, loginProperties);
log.info("第三方用户登录成功 [AppController] login --> loginFrom:{}, phoneNo:{},appChannel:{}", registerFrom, phoneNo, appChannel);
return JsonResult.buildSuccessResult("登录成功", bean);
......@@ -196,7 +208,11 @@ public class AppController implements IBaseController {
@RequestParam(required = false, defaultValue = "1") Long registerFrom,
@RequestParam(required = false, defaultValue = "1") Long channelId,
@RequestParam(required = false, defaultValue = "") String appChannel,
@RequestParam(required = false) Integer tenantId,
HttpServletRequest request) {
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
......@@ -221,7 +237,11 @@ public class AppController implements IBaseController {
if (merchant == null) {
return JsonResult.buildErrorStateResult("无效的商户", null);
}
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName());
//租户下新增用户
oauthLoginInfoService.addLoginInfo(user, tenantId);
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, merchant.getId(), merchant.getName(), tenantId);
AuthBean bean = sessionService.createSession(user, loginProperties);
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(new UserRet(user));
......@@ -297,7 +317,12 @@ public class AppController implements IBaseController {
@RequestParam(required = false, defaultValue = "1") Long registerFrom,
@RequestParam(required = false, defaultValue = "1") Long channelId,
@RequestParam(required = false, defaultValue = "") String appChannel,
@RequestParam(required = false) Integer tenantId,
HttpServletRequest request) {
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
......@@ -309,7 +334,9 @@ public class AppController implements IBaseController {
if (!user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, null, "");
//校验租户ID tenantId
oauthLoginInfoService.addLoginInfo(user, tenantId);
LoginProperties loginProperties = new LoginProperties("", 4, channelId, registerFrom, appChannel, null, "", tenantId);
AuthBean bean = sessionService.createSession(user, loginProperties);
log.info("第三方用户登录成功 [AppController] login2 --> loginFrom:{}, phoneNo:{},appChannel:{}", registerFrom, phoneNo, appChannel);
return JsonResult.buildSuccessResult("登录成功", bean);
......
package cn.quantgroup.xyqb.controller.internal.user.center;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.service.user.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by 11 on 2017/3/22.
*/
@Slf4j
@RestController
@RequestMapping("/oauthClient")
public class OauthClientDetailsController {
@Autowired
private IOauthClientDetailsService oauthClientDetailsService;
@Autowired
private IOauthLoginInfoService oauthLoginInfoService;
@Autowired
private ISmsService smsService;
}
package cn.quantgroup.xyqb.controller.internal.user.center;
import cn.quantgroup.user.enums.BizType;
import cn.quantgroup.user.enums.EducationEnum;
import cn.quantgroup.user.enums.IncomeRangeEnum;
import cn.quantgroup.user.enums.MaritalStatus;
import cn.quantgroup.user.enums.OccupationEnum;
import cn.quantgroup.user.enums.*;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.limit.PasswordFreeAccessValidator;
import cn.quantgroup.xyqb.aspect.lock.RedisLock;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.entity.Contact;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserAttached;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.event.UserExtInfoSaveEvent;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.IAddressService;
import cn.quantgroup.xyqb.service.user.IContactService;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserExtInfoService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.user.UserCenterService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.util.TenantUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import io.swagger.annotations.ApiOperation;
......@@ -30,13 +17,8 @@ import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -73,8 +55,17 @@ public class UserCenterController {
return JsonResult.buildSuccessResultGeneric(userAttached);
}
/**
* @yapi http://yapi.quantgroups.com/project/17/interface/api/17291
* @param userIds
* @return
*/
@PostMapping("/attach/list")
public JsonResult queryUserAttachList(@RequestBody List<Long> userIds) {
public JsonResult queryUserAttachList(@RequestBody List<Long> userIds, @RequestParam(required = false) Integer tenantId) {
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (CollectionUtils.isEmpty(userIds)) {
return JsonResult.buildErrorStateResult("用户 ID 不能为空", null);
}
......@@ -82,7 +73,7 @@ public class UserCenterController {
if (userIds.size() > size) {
return JsonResult.buildErrorStateResult("超出最大条数限制" + size, null);
}
List<UserAttached> userAttachedList = userCenterService.searchUserAttachedListByUserId(userIds);
List<UserAttached> userAttachedList = userCenterService.searchUserAttachedListByUserId(userIds, tenantId);
return JsonResult.buildSuccessResultGeneric(userAttachedList);
}
......
package cn.quantgroup.xyqb.controller.middleoffice.applet;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.quantgroup.xyqb.controller.middleoffice.login.ILoginModule;
import cn.quantgroup.xyqb.controller.middleoffice.login.LoginVo;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
......@@ -18,6 +7,12 @@ import cn.quantgroup.xyqb.exception.DataException;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.middleoffice.applet.IAppletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
/**
* @author :dongjianhua
......@@ -57,7 +52,7 @@ public class AppletController {
Long userId = iAppletService.relevance(appletParamEntry);
LoginVo loginVo = loginModule.loginByUserId(appletParamEntry.getChannelId(),
appletParamEntry.getUtmSource(), userId);
appletParamEntry.getUtmSource(), userId, null);
return JsonResult
.buildSuccessResultGeneric(loginVo);
......@@ -68,12 +63,12 @@ public class AppletController {
*/
@Validated
@PostMapping("/login")
public JsonResult login(@RequestParam String appName, @RequestParam String openId, String utmSource) {
public JsonResult login(@RequestParam String appName, @RequestParam String openId, @RequestParam(required = false) Integer tenantId, String utmSource, @RequestParam(required = false) Integer appNo) {
if (!containsAppName(appName)) {
throw new DataException("appName不合法");
}
LoginVo login = iAppletService.login(appName, openId, utmSource);
LoginVo login = iAppletService.login(appName, openId, tenantId, utmSource);
return JsonResult.buildSuccessResultGeneric(login);
}
......
......@@ -11,5 +11,5 @@ public interface ILoginModule {
Boolean modifyPwd(VerifyTypeEnum type, String phoneNo, String password, String verify);
LoginVo loginByUserId(Long channelId, String appChannel, Long userId);
LoginVo loginByUserId(Long channelId, String appChannel, Long userId, Integer tenantId);
}
......@@ -83,7 +83,7 @@ public class LoginModule implements ILoginModule {
}
@Override
public LoginVo loginByUserId(Long channelId, String appChannel, Long userId) {
public LoginVo loginByUserId(Long channelId, String appChannel, Long userId, Integer tenantId) {
User user = userService.findById(userId);
if(null == user){
throw new DataException("未找到此用户");
......@@ -92,6 +92,7 @@ public class LoginModule implements ILoginModule {
.createdFrom(user.getRegisteredFrom())
.appChannel(appChannel == null ? "" : appChannel)
.channelId(channelId)
.tenantId(tenantId)
.build();
AuthBean session = sessionService.createSession(user, loginProperties);
return LoginVo.builder()
......
......@@ -4,8 +4,9 @@ import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.event.DisableActiveEvent;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
......@@ -15,6 +16,7 @@ import java.util.Map;
/**
* 用户信息
*/
@Slf4j
@RestController("middleUserController")
@RequestMapping("/middle_office/user")
public class UserController {
......@@ -79,21 +81,27 @@ public class UserController {
/**
* 根据uuid或者userids 获取用户信息
*
* @yapi http://yapi.quantgroups.com/project/17/interface/api/29902
* @param params
* @return
*/
@PostMapping("/getByUuidsOrUserIds")
public JsonResult getByUuidsOrUserIds(@RequestBody Map<String, Object> params) {
log.info("根据uuid或者userids 获取用户信息 {}", params);
List<String> vals = (List<String>) params.get("vals");
Integer type = (Integer) params.get("type");
Integer tenantId = Integer.valueOf(String.valueOf(params.get("tenantId")));
if (type == null || (type != 1 && type != 2)) {
return JsonResult.buildErrorStateResult("type错误", null);
}
if (vals.size() > 500) {
vals = vals.subList(0,500);
}
return JsonResult.buildSuccessResultGeneric(userService.findByUuidsOrUserIds(vals, type));
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
return JsonResult.buildSuccessResultGeneric(userService.findByUuidsOrUserIds(vals, type, tenantId));
}
}
package cn.quantgroup.xyqb.controller.middleoffice.wx;
import cn.quantgroup.xyqb.entity.CustomerInfoEntity;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.ITenantService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
......@@ -19,32 +25,104 @@ public class WxController {
@Resource
private IWechatService wechatService;
@Autowired
private ITenantService tenantService;
@Autowired
private IUserService userService;
/**
* @ yapi http://open.quantgroups.com/project/59/interface/api/693
* @ yapi http://yapi.quantgroups.com/project/17/interface/api/30122
* @param userId
* @return
*/
@GetMapping("/userId/{userId}")
public JsonResult openId(@PathVariable Long userId) {
WechatUserInfo wechatUserInfo = wechatService.queryByUserId(userId);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
public JsonResult openId(@PathVariable Long userId, @RequestParam(required = false) Integer tenantId) {
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
WechatUserInfo wechatUserInfo = wechatService.queryByUserId(userId);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}else {
User user = userService.findById(userId);
if (user == null) {
return JsonResult.buildSuccessResult();
}
CustomerInfoEntity tenantCustomerInfo = tenantService.getTenantCustomerInfo(user, tenantId);
if (tenantCustomerInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(tenantCustomerInfo.getSourceOpenId());
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}
/**
* @ yapi http://yapi.quantgroups.com/project/17/interface/api/30122
* @param userId
* @param appName
* @param tenantId
* @return
*/
@GetMapping("/userId/{userId}/{appName}")
public JsonResult openId(@PathVariable Long userId,@PathVariable String appName) {
WechatUserInfo wechatUserInfo = wechatService.queryByUserId(userId,appName);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
public JsonResult openId(@PathVariable Long userId,@PathVariable String appName, @RequestParam(required = false) Integer tenantId) {
//默认羊小咩租户
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
WechatUserInfo wechatUserInfo = wechatService.queryByUserId(userId,appName);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}else {
User user = userService.findById(userId);
if (user == null) {
return JsonResult.buildSuccessResult();
}
CustomerInfoEntity tenantCustomerInfo = tenantService.getTenantCustomerInfo(user, tenantId);
if (tenantCustomerInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(tenantCustomerInfo.getSourceOpenId());
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}
}
/**
* @yapi http://open.quantgroups.com/project/59/interface/api/693
* @yapi http://yapi.quantgroups.com/project/17/interface/api/30122
* @param phoneNo
* @return
*/
@GetMapping("/phoneNo/{phoneNo}")
public JsonResult openId(@PathVariable String phoneNo) {
WechatUserInfo wechatUserInfo = wechatService.findWechatUserInfoByPhoneNo(phoneNo);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
public JsonResult openId(@PathVariable String phoneNo, @RequestParam(required = false) Integer tenantId) {
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
if (tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
WechatUserInfo wechatUserInfo = wechatService.findWechatUserInfoByPhoneNo(phoneNo);
if (wechatUserInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}else {
User user = userService.findByPhoneInDb(phoneNo);
if (user == null) {
return JsonResult.buildSuccessResult();
}
CustomerInfoEntity tenantCustomerInfo = tenantService.getTenantCustomerInfo(user, tenantId);
if (tenantCustomerInfo == null) {
return JsonResult.buildSuccessResult();
}
return JsonResult.buildSuccessResultGeneric(tenantCustomerInfo.getSourceOpenId());
}
return JsonResult.buildSuccessResultGeneric(wechatUserInfo.getOpenId());
}
@RequestMapping("/code/{key}/{extdata}")
......
package cn.quantgroup.xyqb.controller.tenant;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import cn.quantgroup.xyqb.service.user.IProductLoginService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/tenant")
public class TenantController {
@Autowired
private IProductLoginService productLoginService;
@Autowired
private IOauthClientDetailsService oauthClientDetailsService;
@Autowired
private IUserService userService;
/**
* 根据用户ID查询租户列表
* @param userId
* @return
* @Yapi http://yapi.quantgroups.com/project/17/interface/api/30068
*/
@PostMapping("/userIdTenantList")
public JsonResult findTenantByUserId(Long userId) {
// 通过userId获取租户机构和产品
List<ProductLoginEntity> productLoginEntityList = productLoginService.findSlaveByUserId(userId);
List<Integer> tenantList = new ArrayList<>();
if (!productLoginEntityList.isEmpty()) {
// 通过机构和产品Id 获取租户id
tenantList = oauthClientDetailsService.findTenantList(productLoginEntityList);
}
if (tenantList.isEmpty()) {
User user = userService.findById(userId);
if (user == null) {
return JsonResult.buildErrorStateResult("该用户不存在", null);
}
tenantList.add(TenantUtil.TENANT_DEFAULT);
}
return JsonResult.buildSuccessResult("租户列表", tenantList);
}
}
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.baseEntity.PartitionEntity;
import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.util.StringUtils;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/9/23
* @Time: 11:02
* Description: No Description
*/
@Entity
@Table(name = "customer_info")
public class CustomerInfoEntity extends PartitionEntity implements Serializable {
private static final long serialVersionUID = -3639362579605273102L;
private final static String CLASS_NAME = CustomerInfoEntity.class.getSimpleName();
@Id
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "CUSTOMER_ID", nullable = false)
private long customerId;
@Column(name = "INSTITUTION_ID", nullable = false, length = 4)
private String institutionId;
@Column(name = "AVATAR_URL", nullable = true, length = 255)
private String avatarUrl;
@Column(name = "NICK_NAME", nullable = true, length = 50)
private String nickName;
@Column(name = "APP_NAME", nullable = true, length = 50)
private String appName;
@Column(name = "CITY", nullable = true, length = 36)
private String city;
@Column(name = "CITY_CODE", nullable = true)
private Long cityCode;
@Column(name = "COUNTRY", nullable = true, length = 50)
private String country;
@Column(name = "LANGUAGE", nullable = true, length = 30)
private String language;
@Column(name = "SOURCE_OPEN_ID", nullable = true, length = 128)
private String sourceOpenId;
@Column(name = "PRIVILEAGE", nullable = true, length = 255)
private String privileage;
@Column(name = "PROVINCE", nullable = true, length = 30)
private String province;
@Column(name = "PROVINCE_CODE", nullable = true)
private Long provinceCode;
@Column(name = "SEX", nullable = true)
private Gender sex;
@Column(name = "UNION_ID", nullable = true, length = 128)
private String unionId;
@Column(name = "UTM_SOURCE", nullable = true, length = 50)
private String utmSource;
@Column(name = "NAME", nullable = true, length = 50)
private String name;
@Column(name = "ID_CARD_NO", nullable = true, length = 32)
private String idCardNo;
@Column(name = "ID_CARD_TYPE", nullable = true)
private Byte idCardType;
@Column(name = "BIRTHDAY", nullable = true, length = 30)
private String birthday;
@Column(name = "PRODUCT_ID", nullable = false)
private String productId;
@Column(name = "SOURCE_TYPE", nullable = true, length = 255)
private String sourceType;
@Column(name = "TELEPHONE", nullable = true, length = 32)
private String telephone;
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getCityCode() {
return cityCode;
}
public void setCityCode(Long cityCode) {
this.cityCode = cityCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSourceOpenId() {
return sourceOpenId;
}
public void setSourceOpenId(String sourceOpenId) {
this.sourceOpenId = sourceOpenId;
}
public String getPrivileage() {
return privileage;
}
public void setPrivileage(String privileage) {
this.privileage = privileage;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Long getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(Long provinceCode) {
this.provinceCode = provinceCode;
}
public Gender getSex() {
return sex;
}
public void setSex(Gender sex) {
this.sex = sex;
}
public String getUnionId() {
return unionId;
}
public void setUnionId(String unionId) {
this.unionId = unionId;
}
public String getUtmSource() {
return utmSource;
}
public void setUtmSource(String utmSource) {
this.utmSource = utmSource;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCardNo() {
return idCardNo;
}
public void setIdCardNo(String idCardNo) {
this.idCardNo = idCardNo;
}
public Byte getIdCardType() {
return idCardType;
}
public void setIdCardType(Byte idCardType) {
this.idCardType = idCardType;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Override
public String getPersistentKey() {
return StringUtils.toDelimitedString(CLASS_NAME, customerId, institutionId);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.baseEntity.PartitionEntity;
import cn.quantgroup.xyqb.util.StringUtils;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Objects;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/9/23
* @Time: 11:02
* Description: No Description
*/
@Entity
@Table(name = "customer_login")
public class CustomerLoginEntity extends PartitionEntity implements Serializable {
private static final long serialVersionUID = -6859480785575072675L;
private final static String CLASS_NAME = CustomerLoginEntity.class.getSimpleName();
@Id
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "INSTITUTION_ID", nullable = false, length = 4)
private String institutionId;
@Column(name = "PRODUCT_ID", nullable = false, length = 4)
private String productId;
@Column(name = "CUSTOMER_ID", nullable = false)
private long customerId;
@Column(name = "UUID", nullable = true)
private Long uuid;
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public Long getUuid() {
return uuid;
}
public void setUuid(Long uuid) {
this.uuid = uuid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomerLoginEntity that = (CustomerLoginEntity) o;
return customerId == that.customerId;
}
@Override
public int hashCode() {
return Objects.hash(institutionId, productId, customerId, uuid);
}
@Override
public String getPersistentKey() {
return StringUtils.toDelimitedString(CLASS_NAME, institutionId, productId, customerId);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
package cn.quantgroup.xyqb.entity;
import java.util.Date;
/**
* Created by Administrator on 2021/8/27 0027.
*/
public class EntityBuilder {
public static ProductLoginEntity productLogin(String productId, String institutionId, String phoneNo,
Long customerId, String customerName, Integer partitionKey, Long id) {
ProductLoginEntity entity = new ProductLoginEntity();
// entity.setId(id);
entity.setCustomerId(customerId);
entity.setCustomerName(customerName);
entity.setPhoneNo(phoneNo);
entity.setProductId(productId);
entity.setInstitutionId(institutionId);
entity.setPartitionKey(partitionKey);
entity.setPassword("");
entity.setSaltValue("");
entity.setStatus("");
entity.setBatchNo(1);
entity.setCreatedDate(new Date());
entity.setModifiedDate(new Date());
entity.setCreatedBy("");
entity.setModifiedBy("");
return entity;
}
}
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.baseEntity.OptimisticEntity;
import cn.quantgroup.xyqb.util.StringUtils;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Objects;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/9/23
* @Time: 11:02
* Description: No Description
*/
@Entity
@Table(name = "oauth_client_details")
public class OauthClientDetailsEntity extends OptimisticEntity implements Serializable {
private static final long serialVersionUID = 3521505570429896355L;
private final static String CLASS_NAME = OauthClientDetailsEntity.class.getSimpleName();
@Id
@Column(name = "CLIENT_ID", nullable = false)
private Integer clientId;
@Column(name = "INSTITUTION_ID", nullable = false, length = 4)
private String institutionId;
@Column(name = "PRODUCT_ID", nullable = false, length = 4)
private String productId;
@Column(name = "ENCRYPTION_TYPE", nullable = false, length = 4)
private String encryptionType;
@Column(name = "ENABLE", nullable = false, length = 4)
private String enable;
@Column(name = "RESOURCE_IDS", nullable = true, length = 255)
private String resourceIds;
@Column(name = "CLIENT_SECRET", nullable = false, length = 255)
private String clientSecret;
@Column(name = "SCOPE", nullable = true, length = 255)
private String scope;
@Column(name = "AUTHORIZED_GRANT_TYPES", nullable = true, length = 255)
private String authorizedGrantTypes;
@Column(name = "WEB_SERVER_REDIRECT_URI", nullable = true, length = 255)
private String webServerRedirectUri;
@Column(name = "AUTHORITIES", nullable = true, length = 255)
private String authorities;
@Column(name = "ACCESS_TOKEN_VALIDITY", nullable = true)
private Integer accessTokenValidity;
@Column(name = "REFRESH_TOKEN_VALIDITY", nullable = true)
private Integer refreshTokenValidity;
@Column(name = "ADDITIONAL_INFORMATION", nullable = true, length = 4096)
private String additionalInformation;
@Column(name = "AUTOAPPROVE", nullable = true, length = 255)
private String autoapprove;
@Column(name = "SMS_REGISTER_TEMPLATE", nullable = true, length = 255)
private String smsRegisterTemplate;
public Integer getClientId() {
return clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getEncryptionType() {
return encryptionType;
}
public void setEncryptionType(String encryptionType) {
this.encryptionType = encryptionType;
}
public String getEnable() {
return enable;
}
public void setEnable(String enable) {
this.enable = enable;
}
public String getResourceIds() {
return resourceIds;
}
public void setResourceIds(String resourceIds) {
this.resourceIds = resourceIds;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getAuthorizedGrantTypes() {
return authorizedGrantTypes;
}
public void setAuthorizedGrantTypes(String authorizedGrantTypes) {
this.authorizedGrantTypes = authorizedGrantTypes;
}
public String getWebServerRedirectUri() {
return webServerRedirectUri;
}
public void setWebServerRedirectUri(String webServerRedirectUri) {
this.webServerRedirectUri = webServerRedirectUri;
}
public String getAuthorities() {
return authorities;
}
public void setAuthorities(String authorities) {
this.authorities = authorities;
}
public Integer getAccessTokenValidity() {
return accessTokenValidity;
}
public void setAccessTokenValidity(Integer accessTokenValidity) {
this.accessTokenValidity = accessTokenValidity;
}
public Integer getRefreshTokenValidity() {
return refreshTokenValidity;
}
public void setRefreshTokenValidity(Integer refreshTokenValidity) {
this.refreshTokenValidity = refreshTokenValidity;
}
public String getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(String additionalInformation) {
this.additionalInformation = additionalInformation;
}
public String getAutoapprove() {
return autoapprove;
}
public void setAutoapprove(String autoapprove) {
this.autoapprove = autoapprove;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OauthClientDetailsEntity that = (OauthClientDetailsEntity) o;
return Objects.equals(clientId, that.clientId) && Objects.equals(institutionId, that.institutionId) && Objects.equals(productId, that.productId) && Objects.equals(encryptionType, that.encryptionType) && Objects.equals(enable, that.enable) && Objects.equals(resourceIds, that.resourceIds) && Objects.equals(clientSecret, that.clientSecret) && Objects.equals(scope, that.scope) && Objects.equals(authorizedGrantTypes, that.authorizedGrantTypes) && Objects.equals(webServerRedirectUri, that.webServerRedirectUri) && Objects.equals(authorities, that.authorities) && Objects.equals(accessTokenValidity, that.accessTokenValidity) && Objects.equals(refreshTokenValidity, that.refreshTokenValidity) && Objects.equals(additionalInformation, that.additionalInformation) && Objects.equals(autoapprove, that.autoapprove);
}
@Override
public int hashCode() {
return Objects.hash(clientId, institutionId, productId, encryptionType, enable, resourceIds, clientSecret, scope, authorizedGrantTypes, webServerRedirectUri, authorities, accessTokenValidity, refreshTokenValidity, additionalInformation, autoapprove);
}
@Override
public String getPersistentKey() {
return StringUtils.toDelimitedString(CLASS_NAME, clientId);
}
public String getSmsRegisterTemplate() {
return smsRegisterTemplate;
}
public void setSmsRegisterTemplate(String smsRegisterTemplate) {
this.smsRegisterTemplate = smsRegisterTemplate;
}
}
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.baseEntity.PartitionEntity;
import cn.quantgroup.xyqb.util.StringUtils;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/9/23
* @Time: 11:03
* Description: No Description
*/
@Entity
@Table(name = "product_login")
public class ProductLoginEntity extends PartitionEntity implements Serializable {
private static final long serialVersionUID = 6495491112527859057L;
private final static String CLASS_NAME = ProductLoginEntity.class.getSimpleName();
@Id
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "CUSTOMER_ID", nullable = false)
private long customerId;
@Column(name = "CUSTOMER_NAME", nullable = false, length = 255)
private String customerName;
@Column(name = "INSTITUTION_ID", nullable = false, length = 4)
private String institutionId;
@Column(name = "PHONE_NO", nullable = false, length = 15)
private String phoneNo;
@Column(name = "PASSWORD", nullable = true, length = 256)
private String password;
@Column(name = "SALT_VALUE", nullable = true, length = 128)
private String saltValue;
@Column(name = "STATUS", nullable = false, length = 4)
private String status;
@Column(name = "STATUS_DATE", nullable = false)
private LocalDate statusDate;
@Column(name = "LAST_STATUS", nullable = true, length = 4)
private String lastStatus;
@Column(name = "LAST_LOGIN_TIME", nullable = true)
private Integer lastLoginTime;
@Column(name = "BATCH_NO", nullable = true)
private Integer batchNo;
@Column(name = "PRODUCT_ID", nullable = false, length = 4)
private String productId;
@Column(name = "EXTENSION_ACCOUNT_ID", nullable = true)
private Long extensionAccountId;
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customrId) {
this.customerId = customrId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSaltValue() {
return saltValue;
}
public void setSaltValue(String saltValue) {
this.saltValue = saltValue;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDate getStatusDate() {
return statusDate;
}
public void setStatusDate(LocalDate statusDate) {
this.statusDate = statusDate;
}
public String getLastStatus() {
return lastStatus;
}
public void setLastStatus(String lastStatus) {
this.lastStatus = lastStatus;
}
public Integer getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Integer lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public Long getExtensionAccountId() {
return extensionAccountId;
}
public void setExtensionAccountId(Long extensionAccountId) {
this.extensionAccountId = extensionAccountId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductLoginEntity that = (ProductLoginEntity) o;
return customerId == that.customerId && statusDate == that.statusDate&& Objects.equals(customerName, that.customerName) && Objects.equals(institutionId, that.institutionId) && Objects.equals(phoneNo, that.phoneNo) && Objects.equals(password, that.password) && Objects.equals(saltValue, that.saltValue) && Objects.equals(status, that.status) && Objects.equals(lastStatus, that.lastStatus) && Objects.equals(lastLoginTime, that.lastLoginTime) && Objects.equals(productId, that.productId) && Objects.equals(extensionAccountId, that.extensionAccountId);
}
@Override
public int hashCode() {
return Objects.hash(customerId, customerName, institutionId, phoneNo, password, saltValue, status, statusDate, lastStatus, lastLoginTime, productId, extensionAccountId);
}
@Override
public String getPersistentKey() {
return StringUtils.toDelimitedString(CLASS_NAME, institutionId, productId, phoneNo);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Integer getBatchNo() {
return batchNo;
}
public void setBatchNo(Integer batchNo) {
this.batchNo = batchNo;
}
}
package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.baseEntity.OptimisticEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/9/23
* @Time: 11:02
* Description: No Description
*/
@Entity
@Table(name = "sms_template")
public class SmsTemplateEntity extends OptimisticEntity implements Serializable {
private final static String CLASS_NAME = SmsTemplateEntity.class.getSimpleName();
private static final long serialVersionUID = -190846609680723652L;
@Id
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "CLIENT_ID", nullable = false)
private long clientId;
@Column(name = "TYPE", nullable = false, updatable = false, length = 11)
private String type;
@Column(name = "MERCHANT_ID", nullable = false, updatable = false, length = 11)
private String merchantId;
@Column(name = "CONTENT_ID", nullable = false, updatable = false, length = 11)
private String contentId;
@Column(name = "CONTENT", nullable = false, updatable = false)
private String content;
@Override
public String getPersistentKey() {
return null;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package cn.quantgroup.xyqb.entity.baseEntity;
public interface BasicEntity {
}
package cn.quantgroup.xyqb.entity.baseEntity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@EntityListeners({AuditingEntityListener.class})
@MappedSuperclass
public abstract class OptimisticEntity implements PersistentKey, BasicEntity {
@NotNull
@LastModifiedBy
@Column(
name = "MODIFIED_BY",
nullable = false,
updatable = false,
length = 36
)
private String modifiedBy;
@NotNull
@LastModifiedDate
@Column(
name = "MODIFIED_DATE",
nullable = false
)
private Date modifiedDate;
@NotNull
@CreatedBy
@Column(
name = "CREATED_BY",
nullable = false,
updatable = false,
length = 36
)
public String createdBy;
@NotNull
@CreatedDate
@Column(
name = "CREATED_DATE",
nullable = false,
updatable = false
)
public Date createdDate;
@NotNull
@Version
@Column(
name = "MODIFIED_NO",
nullable = false
)
private Integer modifiedNo = 1;
public OptimisticEntity() {
}
public String getModifiedBy() {
return this.modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Integer getModifiedNo() {
return this.modifiedNo;
}
public void setModifiedNo(Integer modifiedNo) {
this.modifiedNo = modifiedNo;
}
}
package cn.quantgroup.xyqb.entity.baseEntity;
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class PartitionEntity extends OptimisticEntity {
@Column(
name = "PARTITION_KEY",
nullable = false,
updatable = false
)
private Integer partitionKey;
public PartitionEntity() {
}
public Integer getPartitionKey() {
return this.partitionKey;
}
public void setPartitionKey(Integer partitionKey) {
this.partitionKey = partitionKey;
}
}
package cn.quantgroup.xyqb.entity.baseEntity;
public interface PersistentKey {
String getPersistentKey();
}
......@@ -76,4 +76,13 @@ public class AppletParamEntry {
*/
private String utmSource;
/**
* 租户ID
*/
private Integer tenantId;
/**
* 小程序编号
*/
private Integer appNo;
}
......@@ -35,4 +35,6 @@ public class LoginProperties {
private String appChannel = "";
private Long merchantId = 1L;
private String merchantName = "";
//租户ID
private Integer tenantId;
}
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.CustomerInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by Li Jianhua
*/
@Repository
public interface ICustomerInfoRepository extends JpaRepository<CustomerInfoEntity, Long> {
CustomerInfoEntity findByCustomerId(Long customerId);
CustomerInfoEntity findByInstitutionIdAndProductIdAndSourceOpenId(String institutionId, String productId, String OpenId);
}
\ No newline at end of file
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.CustomerLoginEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by hechao on 2020/2/17.
*/
@Repository
public interface ICustomerLoginRepository extends JpaRepository<CustomerLoginEntity, Long> {
CustomerLoginEntity findFirstByCustomerId(long customerId);
}
\ No newline at end of file
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.OauthClientDetailsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Created by hechao on 2020/2/17.
*/
@Repository
public interface IOauthClientDetailsRepository extends JpaRepository<OauthClientDetailsEntity, Long> {
OauthClientDetailsEntity findFirstByClientId(Integer clientID);
OauthClientDetailsEntity findFirstByInstitutionIdAndProductId(String institutionId, String productId);
}
\ No newline at end of file
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Li Jianhua
*/
@Repository
public interface IProductLoginRepository extends JpaRepository<ProductLoginEntity, Long> {
ProductLoginEntity findFirstByInstitutionIdAndProductIdAndPhoneNo(String institutionId, String productId, String phoneNo);
ProductLoginEntity findFirstByPhoneNo(String phoneNo);
ProductLoginEntity findByInstitutionIdAndProductIdAndExtensionAccountId(String institutionId, String productId, Long userId);
List<ProductLoginEntity> findByInstitutionIdAndProductIdAndExtensionAccountIdIn(String institutionId, String productId, List<Long> userIds);
List<ProductLoginEntity> findAllByExtensionAccountId(Long userId);
List<ProductLoginEntity> findAllByExtensionAccountIdIn(List<Long> userId);
/**
* @author -REYLI
* @createTime 2021-11-17
* @description 根据条件获取租户下用户列表
* @param institutionId
* @param productId
* @return Arraylist
*/
List<ProductLoginEntity> findProductLoginsByInstitutionIdAndProductId(String institutionId, String productId);
ProductLoginEntity findFirstByInstitutionIdAndProductIdAndCustomerId(String institutionId, String productId, long customerId);
}
\ No newline at end of file
package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.SmsTemplateEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* Created by hechao on 2020/2/17.
*/
@Repository
public interface ISmsTemplateRepository extends JpaRepository<SmsTemplateEntity, Long> {
Optional<SmsTemplateEntity> findFirstByClientIdAndType(Long clientId, String type);
}
\ No newline at end of file
......@@ -12,5 +12,5 @@ import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
*/
public interface IAppletService {
Long relevance(AppletParamEntry appletParamEntry);
LoginVo login(String appName, String openId,String utmSource);
LoginVo login(String appName, String openId, Integer tenantId, String utmSource);
}
......@@ -2,14 +2,17 @@ package cn.quantgroup.xyqb.service.middleoffice.applet.impl;
import cn.quantgroup.xyqb.controller.middleoffice.login.ILoginModule;
import cn.quantgroup.xyqb.controller.middleoffice.login.LoginVo;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.exception.AppletException;
import cn.quantgroup.xyqb.repository.IWeChatUserRepository;
import cn.quantgroup.xyqb.service.middleoffice.applet.IAppletService;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.service.user.ITenantService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
......@@ -34,6 +37,12 @@ public class AppletServiceImpl implements IAppletService {
private final IUserService userService;
private ILoginModule loginModule;
@Autowired
private IOauthLoginInfoService iOauthLoginInfoService;
@Autowired
private ITenantService tenantService;
@Autowired
public AppletServiceImpl(IWeChatUserRepository iWeChatUserRepository,
IUserRegisterService iUserRegisterService,
......@@ -48,57 +57,93 @@ public class AppletServiceImpl implements IAppletService {
@Override
@Transactional(rollbackFor = Exception.class)
public Long relevance(AppletParamEntry appletParamEntry) {
if (appletParamEntry.getTenantId() == null ) {
appletParamEntry.setTenantId(TenantUtil.TENANT_DEFAULT);
}
if (appletParamEntry.getTenantId().equals(TenantUtil.TENANT_DEFAULT)) {
WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(appletParamEntry.getOpenId(), appletParamEntry.getAppName());
//这个接口先不考虑更换手机号的情况
wechatUserInfo = (wechatUserInfo == null ? new WechatUserInfo() : wechatUserInfo);
wechatUserInfo.setNickName(appletParamEntry.getNickName());
wechatUserInfo.setCity(appletParamEntry.getCity());
wechatUserInfo.setCountry(appletParamEntry.getCountry());
wechatUserInfo.setProvince(appletParamEntry.getProvince());
wechatUserInfo.setAppName(appletParamEntry.getAppName());
wechatUserInfo.setHeadImgUrl(appletParamEntry.getAvatarUrl());
wechatUserInfo.setLanguage(appletParamEntry.getLanguage());
wechatUserInfo.setOpenId(appletParamEntry.getOpenId());
wechatUserInfo.setSex(appletParamEntry.getGender());
wechatUserInfo.setUnionId(appletParamEntry.getUnionId());
wechatUserInfo.setPhoneNo(appletParamEntry.getMobile());
wechatUserInfo.setUtmSource(appletParamEntry.getUtmSource());
if (null == wechatUserInfo.getUserId()) {//只要存在userid 就说明已经在用户表里了 不考虑小程序这边换手机号了
User user = userService.findByPhoneInDb(appletParamEntry.getMobile());
//如果不存在就去注册一下
if (null == user) {
user = iUserRegisterService.register(appletParamEntry.getChannelId(), appletParamEntry.getMobile());
}
iOauthLoginInfoService.addRegisterInfo(user, appletParamEntry);
wechatUserInfo.setUserId(user.getId());
}
WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(appletParamEntry.getOpenId(), appletParamEntry.getAppName());
//这个接口先不考虑更换手机号的情况
wechatUserInfo = (wechatUserInfo == null ? new WechatUserInfo() : wechatUserInfo);
wechatUserInfo.setNickName(appletParamEntry.getNickName());
wechatUserInfo.setCity(appletParamEntry.getCity());
wechatUserInfo.setCountry(appletParamEntry.getCountry());
wechatUserInfo.setProvince(appletParamEntry.getProvince());
wechatUserInfo.setAppName(appletParamEntry.getAppName());
wechatUserInfo.setHeadImgUrl(appletParamEntry.getAvatarUrl());
wechatUserInfo.setLanguage(appletParamEntry.getLanguage());
wechatUserInfo.setOpenId(appletParamEntry.getOpenId());
wechatUserInfo.setSex(appletParamEntry.getGender());
wechatUserInfo.setUnionId(appletParamEntry.getUnionId());
wechatUserInfo.setPhoneNo(appletParamEntry.getMobile());
wechatUserInfo.setUtmSource(appletParamEntry.getUtmSource());
if (null == wechatUserInfo.getUserId()) {//只要存在userid 就说明已经在用户表里了 不考虑小程序这边换手机号了
//如果存在就更新在微信表里
iWeChatUserRepository.save(wechatUserInfo);
return wechatUserInfo.getUserId();
} else {
User user = userService.findByPhoneInDb(appletParamEntry.getMobile());
//如果不存在就去注册一下
if (null == user) {
user = iUserRegisterService.register(appletParamEntry.getChannelId(), appletParamEntry.getMobile());
user = iUserRegisterService.register(appletParamEntry.getChannelId(), appletParamEntry.getMobile(), appletParamEntry.getTenantId());
}
wechatUserInfo.setUserId(user.getId());
iOauthLoginInfoService.addRegisterInfo(user, appletParamEntry);
return user.getId();
}
//如果存在就更新在微信表里
iWeChatUserRepository.save(wechatUserInfo);
return wechatUserInfo.getUserId();
}
@Override
public LoginVo login(String appName, String openId, String utmSource) {
WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(openId, appName);
if (null == wechatUserInfo) {
log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户","0401");
}
if (null == wechatUserInfo.getUserId()) {
log.warn("用户未绑定到xyqb,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户绑定信息","0401");
public LoginVo login(String appName, String openId, Integer tenantId, String utmSource) {
if (TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
tenantId = TenantUtil.TENANT_DEFAULT;
}
User user = userService.findById(wechatUserInfo.getUserId());
if (null == user) {
log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户","0401");
User user = null;
if (TenantUtil.TENANT_DEFAULT.equals(tenantId)) {
WechatUserInfo wechatUserInfo = iWeChatUserRepository.findByOpenIdAndAppName(openId, appName);
if (null == wechatUserInfo) {
log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户","0401");
}
if (null == wechatUserInfo.getUserId()) {
log.warn("用户未绑定到xyqb,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户绑定信息","0401");
}
user = userService.findById(wechatUserInfo.getUserId());
if (null == user) {
log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户","0401");
}
iOauthLoginInfoService.addLoginInfo(user, tenantId);
} else {
// 通过租户id和openId查询是否有关联
Long userId = tenantService.getTenantCustomerInfoByOpenId(openId, tenantId);
if (null == userId) {
log.warn("未找到此用户,tenantId:{} ,openId:{}", tenantId, openId);
throw new AppletException("未找到此用户","0401");
}
user = userService.findById(userId);
if (null == user) {
log.warn("未找到此用户,appName:{} ,openId:{}", appName, openId);
throw new AppletException("未找到此用户","0401");
}
}
LoginVo loginVo = loginModule.loginByUserId(user.getRegisteredFrom(),
utmSource == null ? "" : utmSource, user.getId());
LoginVo loginVo = loginModule.loginByUserId(user.getRegisteredFrom(),
utmSource == null ? "" : utmSource, user.getId(), tenantId);
return loginVo;
}
......
......@@ -13,6 +13,8 @@ import java.util.List;
public interface IUserRegisterService {
User register(Long registerFrom, String phoneNo);
User register(Long registerFrom, String phoneNo, Integer tenantId);
/**
* 替换AppController.register
* /app/login,/app/login_super
......@@ -27,6 +29,8 @@ public interface IUserRegisterService {
*/
User register(Long registerFrom, String phoneNo, String idNo, String name, Long channelId, Long btRegisterChannelId);
User register(Long registerFrom, String phoneNo, String idNo, String name, Long channelId, Long btRegisterChannelId, Integer tenantId);
/**
* 替换UserController.register里的userService.register
......@@ -57,6 +61,8 @@ public interface IUserRegisterService {
*/
User register(String phoneNo, Long channelId, Long registerFrom, String appChannel, Long btRegisterChannelId, String dimension);
User register(String phoneNo, Long channelId, Long registerFrom, String appChannel, Long btRegisterChannelId, String dimension, Integer tenantId);
/**
* 替换InnerController.saveMulti里的userService.registerAndReturn
* /innserapi/user/save_multi
......
......@@ -9,6 +9,7 @@ import cn.quantgroup.xyqb.model.UserRegisterParam;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationEventPublisher;
......@@ -16,7 +17,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
......@@ -51,6 +51,24 @@ import java.util.UUID;
return user;
}
@Transactional(rollbackFor = Exception.class)
@Override
public User register(Long registerFrom, String phoneNo, Integer tenantId) {
UserRegisterParam userRegisterParam = UserRegisterParam.builder()
.registerFrom(registerFrom)
.phoneNo(phoneNo)
.channelId(registerFrom)
.sendSuccessSms(true)
.sendAppSms(true)
.sendSuccessMq(true)
.build();
User user = saveUser(userRegisterParam);
if (tenantId == null || tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
applicationEventPublisher.publishEvent(new RegisterEvent(this, userRegisterParam));
}
return user;
}
@Transactional(rollbackFor = Exception.class)
@Override
public User register(Long registerFrom, String phoneNo, String idNo, String name, Long channelId, Long btRegisterChannelId) {
......@@ -70,6 +88,27 @@ import java.util.UUID;
return user;
}
@Transactional(rollbackFor = Exception.class)
@Override
public User register(Long registerFrom, String phoneNo, String idNo, String name, Long channelId, Long btRegisterChannelId, Integer tenantId) {
UserRegisterParam userRegisterParam = UserRegisterParam.builder()
.registerFrom(registerFrom)
.phoneNo(phoneNo)
.idNo(idNo)
.name(name)
.channelId(channelId)
.btRegisterChannelId(btRegisterChannelId)
.sendSuccessSms(true)
.sendAppSms(true)
.sendSuccessMq(true)
.build();
User user = saveUser(userRegisterParam);
if (tenantId == null || tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
applicationEventPublisher.publishEvent(new RegisterEvent(this, userRegisterParam));
}
return user;
}
private User saveUser(UserRegisterParam userRegisterParam) {
String uuid = UUID.randomUUID().toString();
User user = new User();
......@@ -136,6 +175,27 @@ import java.util.UUID;
return user;
}
@Transactional(rollbackFor = Exception.class)
@Override
public User register(String phoneNo, Long channelId, Long registerFrom, String appChannel, Long btRegisterChannelId, String dimension, Integer tenantId) {
UserRegisterParam userRegisterParam = UserRegisterParam.builder()
.registerFrom(registerFrom)
.phoneNo(phoneNo)
.channelId(channelId)
.btRegisterChannelId(btRegisterChannelId)
.dimension(dimension)
.sendSuccessSms(true)
.sendAppSms(true)
.sendSuccessMq(true)
.build();
User user = saveUser(userRegisterParam);
if (tenantId == null || tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
applicationEventPublisher.publishEvent(new RegisterEvent(this, userRegisterParam));
}
return user;
}
@Transactional(rollbackFor = Exception.class)
@Override
public User register(Long registeredFrom, Long channelId, String phoneNo, String name, String idNo, Address addressObj, String contacts, List<Contact> contactList, Long btRegisterChannelId) {
......
......@@ -10,6 +10,7 @@ import cn.quantgroup.xyqb.model.session.SessionValue;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.session.aspect.UserBtRegisterFill;
import cn.quantgroup.xyqb.util.MqUtils;
import cn.quantgroup.xyqb.util.TenantUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
......@@ -18,6 +19,7 @@ import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.sql.Timestamp;
......@@ -103,7 +105,13 @@ public class SessionServiceImpl implements ISessionService {
* @return redisKey. 用来标识这个渠道的用户 Session 是否存在
*/
private String generateLoginPropertiesKey(Long userId, LoginProperties properties) {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + userId + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
if (ObjectUtils.isEmpty(properties.getTenantId())) {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + userId + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
}else if (properties.getTenantId().equals(0) || TenantUtil.TENANT_DEFAULT.equals(properties.getTenantId())) {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + userId + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
}else {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + userId + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom() + ":" + properties.getTenantId();
}
}
private String findSessionValueBySessionId(String sessionId) {
......
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.CustomerInfoEntity;
/**
* Created by 11 on 2016/12/29.
*/
public interface ICustomerInfoService {
CustomerInfoEntity findSlaveByCustomerId(Long customerId);
CustomerInfoEntity findSlaveByOpenId(String openId, String institutionId, String productId);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.CustomerLoginEntity;
/**
* Created by 11 on 2016/12/29.
*/
public interface ICustomerLoginService {
CustomerLoginEntity findSlaveByCustomerId(Long customerId);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.OauthClientDetailsEntity;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* Created by Miraculous on 2017/1/3.
*/
public interface IOauthClientDetailsService {
OauthClientDetailsEntity findFirstByClientId(Integer clientId);
List<Integer> findTenantList(List<ProductLoginEntity> productLoginEntityList);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
/**
* Created by Li Jianhua on 2017/1/3.
*/
public interface IOauthLoginInfoService {
void addLoginInfo(User user, Integer tenantId);
void addRegisterInfo(User user, AppletParamEntry appletParamEntry);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import java.util.List;
/**
* Created by 11 on 2016/12/29.
*/
public interface IProductLoginService {
ProductLoginEntity findSlaveByPloginInfo(String institutionId, String productId, Long userId);
List<ProductLoginEntity> findSlaveByPloginInfos(String institutionId, String productId, List<Long> userId);
List<ProductLoginEntity> findSlaveByUserId(Long userId);
List<ProductLoginEntity> findSlaveByUserIds(List<Long> userIds);
/**
* @author -REYLI
* @createTime 2021-11-17
* @description 根据条件获取租户下用户列表
* @param institutionId
* @param productId
* @return Arraylist
*/
List<ProductLoginEntity> findProductLoginsByInstitutionIdAndProductId(String institutionId, String productId);
ProductLoginEntity findSlaveByCustomerInfo(long customerId, String institutionId, String productId);
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.SmsTemplateEntity;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.repository.ISmsTemplateRepository;
import cn.quantgroup.xyqb.util.GcodeUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.inject.Inject;
import java.util.*;
/**
* Created by hechao on 2020/2/17.
*/
@Slf4j
@Service
public class ISmsService {
@Inject
private ISmsTemplateRepository smsTemplateRepository;
public String sendSms(Long clientId, String type, String phoneNo) {
JsonResult res = new JsonResult();
String code = null;
try {
Optional<SmsTemplateEntity> optional = smsTemplateRepository.findFirstByClientIdAndType(clientId, type);
if (!optional.isPresent()) {
log.error("没有指定的模板");
return code;
}
SmsTemplateEntity smsTemplateEntity = optional.orElse(new SmsTemplateEntity());
RestTemplate restTemplate = new RestTemplate();
Map<String, Object> user = new HashMap<>();
List<String> contentArgs = new ArrayList<>();
code = GcodeUtils.generatedcode(5);
contentArgs.add(code);
user.put("merchantId", smsTemplateEntity.getMerchantId());
user.put("phoneNo", phoneNo);
user.put("contentId", smsTemplateEntity.getContentId());
user.put("contentArgs", contentArgs);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("https://msgapi-qa.liangkebang.net/middle_office/send/message/quick", user, String.class); //提交的body内容为user对象,请求的返回的body类型为String
int statusCode = responseEntity.getStatusCodeValue();
String bodyCode = JSONObject.parseObject(responseEntity.getBody(), HashMap.class).get("code").toString();
if (200 != statusCode || !"0".equals(bodyCode)) {
log.error("验证码发送失败");
return null;
}
} catch (Exception e) {
e.printStackTrace();
log.error("发送验证码异常---{}", e.getMessage());
}
return code;
}
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.CustomerInfoEntity;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.UserBrief;
import java.util.List;
/**
* Created by 11 on 2016/12/29.
*/
public interface ITenantService {
User getTenantUser(User user, Integer tenantId);
UserDetail getTenantUserDetail(UserDetail userDetail, Integer tenantId);
UserBrief getTenantCustomerInfo(UserDetail userDetail, Integer tenantId);
CustomerInfoEntity getTenantCustomerInfo(User user, Integer tenantId);
/**
* @author -REYLI
* @createTime 2021-11-17
* @description 根据条件获取租户下用户列表
* @param users
* @param tenantId
* @return Arraylist
*/
List<User> selectUsersByTenantId(List<User> users, Integer tenantId);
Long getTenantCustomerInfoByOpenId(String openId, Integer tenantId);
List<User> validationTentIdByTentId(List<User> users, Integer tenantId);
}
......@@ -38,7 +38,7 @@ public interface IUserService {
*/
String findUuid(String phoneNo, String idNo);
Map<Long, String> findPhoneByIdsInDb(List<Long> userIds);
Map<Long, String> findPhoneByIdsInDb(List<Long> userIds, Integer tenantId);
User saveUser(User user);
......@@ -80,7 +80,7 @@ public interface IUserService {
JsonResult loginFast(Long channelId, String appChannel, Long createdFrom, Long btRegisterChannelId,
String dimension, String clickId, HttpServletRequest request, Merchant merchant,
String phoneNo);
String phoneNo, Integer tenantId);
/**
* 查询用户全量信息
......@@ -96,7 +96,7 @@ public interface IUserService {
* @param type
* @return
*/
List<User> findByUuidsOrUserIds(List<String> vals,Integer type);
List<User> findByUuidsOrUserIds(List<String> vals,Integer type, Integer tenantId);
/**
* 登出
......
......@@ -21,7 +21,7 @@ public interface UserCenterService {
* @param userIds
* @return
*/
List<UserAttached> searchUserAttachedListByUserId(List<Long> userIds);
List<UserAttached> searchUserAttachedListByUserId(List<Long> userIds, Integer tenantId);
/**
* 保存用户头像
......
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.tech.db.DSType;
import cn.quantgroup.tech.db.TargetDataSource;
import cn.quantgroup.xyqb.entity.CustomerInfoEntity;
import cn.quantgroup.xyqb.repository.ICustomerInfoRepository;
import cn.quantgroup.xyqb.service.user.ICustomerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class CustomerInfoServiceImpl implements ICustomerInfoService {
@Autowired
private ICustomerInfoRepository customerInfoRepository;
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public CustomerInfoEntity findSlaveByCustomerId(Long customerId) {
CustomerInfoEntity customerInfo = customerInfoRepository.findByCustomerId(customerId);
return customerInfo;
}
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public CustomerInfoEntity findSlaveByOpenId(String openId, String institutionId, String productId) {
CustomerInfoEntity customerInfo = customerInfoRepository.findByInstitutionIdAndProductIdAndSourceOpenId(institutionId, productId, openId);
return customerInfo;
}
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.tech.db.DSType;
import cn.quantgroup.tech.db.TargetDataSource;
import cn.quantgroup.xyqb.entity.CustomerLoginEntity;
import cn.quantgroup.xyqb.repository.ICustomerLoginRepository;
import cn.quantgroup.xyqb.service.user.ICustomerLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class CustomerLoginServiceImpl implements ICustomerLoginService {
@Autowired
private ICustomerLoginRepository customerLoginRepository;
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public CustomerLoginEntity findSlaveByCustomerId(Long customerId) {
CustomerLoginEntity customerLogin = customerLoginRepository.findFirstByCustomerId(customerId);
return customerLogin;
}
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.entity.OauthClientDetailsEntity;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.repository.IOauthClientDetailsRepository;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class OauthClientDetailsServiceImpl implements IOauthClientDetailsService {
@Autowired
private IOauthClientDetailsRepository oauthClientDetailsRepository;
@Override
public OauthClientDetailsEntity findFirstByClientId(Integer clientId) {
OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(clientId);
return oauthClientDetailsEntity;
}
@Override
public List<Integer> findTenantList(List<ProductLoginEntity> productLoginEntityList) {
List<Integer> tenantList = new ArrayList<>();
for (ProductLoginEntity ple : productLoginEntityList) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsRepository.findFirstByInstitutionIdAndProductId(ple.getInstitutionId(), ple.getProductId());
if (null != oauthClientDetails) {
tenantList.add(oauthClientDetails.getClientId());
}
}
return tenantList;
}
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.middleoffice.AppletParamEntry;
import cn.quantgroup.xyqb.repository.ICustomerInfoRepository;
import cn.quantgroup.xyqb.repository.ICustomerLoginRepository;
import cn.quantgroup.xyqb.repository.IOauthClientDetailsRepository;
import cn.quantgroup.xyqb.repository.IProductLoginRepository;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.util.AtomicSequencer;
import cn.quantgroup.xyqb.util.RandomSequencer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService {
@Autowired
private IOauthClientDetailsRepository oauthClientDetailsRepository;
@Autowired
private IProductLoginRepository productLoginRepository;
@Autowired
private ICustomerInfoRepository customerInfoRepository;
@Autowired
private ICustomerLoginRepository customerLoginRepository;
@Autowired
private AtomicSequencer atomicSequencer;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addLoginInfo(User user, Integer tenantId) {
OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(tenantId);
if (oauthClientDetailsEntity != null) {
String institutionId = oauthClientDetailsEntity.getInstitutionId();
String productId = oauthClientDetailsEntity.getProductId();
String phoneNo = user.getPhoneNo();
Long userId = user.getId();
ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
long uuid = 0L;
// 如果找不到该用户就创建
if ("".equals(productLoginEntity) || productLoginEntity == null) {
// 添加用户到产品登录表
long customerId = atomicSequencer.nextId();
// long id = session.nextId();
long id = atomicSequencer.nextId();
String customerName = customerId + "";
uuid = RandomSequencer.randomUUID(customerId);
ProductLoginEntity entity = new ProductLoginEntity();
Integer partitionKey = atomicSequencer.partitionKey(customerId);
productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
productLoginEntity.setExtensionAccountId(userId);
productLoginRepository.save(productLoginEntity);
// 根据customerId 获取uuid
CustomerLoginEntity customerLoginEntity = customerLoginRepository.findFirstByCustomerId(productLoginEntity.getCustomerId());
if (null != customerLoginEntity) {
uuid = customerLoginEntity.getUuid();
}
// 添加用户到登录表
CustomerLoginEntity customerLogin = new CustomerLoginEntity();
// customerLogin.setId(atomicSequencer.nextId());
customerLogin.setInstitutionId(institutionId);
customerLogin.setProductId(productId);
customerLogin.setCustomerId(customerId);
customerLogin.setUuid(uuid);
customerLogin.setPartitionKey(partitionKey);
customerLogin.setCreatedDate(new Date());
customerLogin.setModifiedDate(new Date());
customerLogin.setCreatedBy("");
customerLogin.setModifiedBy("");
customerLoginRepository.save(customerLogin);
// 添加用户信息表
CustomerInfoEntity customerInfo = new CustomerInfoEntity();
// customerInfo.setId(atomicSequencer.nextId());
customerInfo.setCustomerId(customerId);
customerInfo.setInstitutionId(institutionId);
customerInfo.setProductId(productId);
customerInfo.setPartitionKey(partitionKey);
customerInfo.setCreatedDate(new Date());
customerInfo.setModifiedDate(new Date());
customerInfo.setCreatedBy("");
customerInfo.setModifiedBy("");
customerInfoRepository.save(customerInfo);
}
}
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addRegisterInfo(User user, AppletParamEntry appletParamEntry) {
OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(appletParamEntry.getTenantId());
if (oauthClientDetailsEntity != null) {
String institutionId = oauthClientDetailsEntity.getInstitutionId();
String productId = oauthClientDetailsEntity.getProductId();
String phoneNo = user.getPhoneNo();
Long userId = user.getId();
ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
long uuid = 0L;
// 如果找不到该用户就创建
if ("".equals(productLoginEntity) || productLoginEntity == null) {
// 添加用户到产品登录表
long customerId = atomicSequencer.nextId();
long id = atomicSequencer.nextId();
String customerName = customerId + "";
uuid = RandomSequencer.randomUUID(customerId);
ProductLoginEntity entity = new ProductLoginEntity();
Integer partitionKey = atomicSequencer.partitionKey(customerId);
productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
productLoginEntity.setExtensionAccountId(userId);
productLoginRepository.save(productLoginEntity);
// 根据customerId 获取uuid
CustomerLoginEntity customerLoginEntity = customerLoginRepository.findFirstByCustomerId(productLoginEntity.getCustomerId());
if (null != customerLoginEntity) {
uuid = customerLoginEntity.getUuid();
}
// 添加用户到登录表
CustomerLoginEntity customerLogin = new CustomerLoginEntity();
customerLogin.setId(atomicSequencer.nextId());
customerLogin.setInstitutionId(institutionId);
customerLogin.setProductId(productId);
customerLogin.setCustomerId(customerId);
customerLogin.setUuid(uuid);
customerLogin.setPartitionKey(partitionKey);
customerLogin.setCreatedDate(new Date());
customerLogin.setModifiedDate(new Date());
customerLogin.setCreatedBy("");
customerLogin.setModifiedBy("");
customerLoginRepository.save(customerLogin);
// 添加用户信息表
CustomerInfoEntity customerInfo = new CustomerInfoEntity();
customerInfo.setId(atomicSequencer.nextId());
customerInfo.setCustomerId(customerId);
customerInfo.setInstitutionId(institutionId);
customerInfo.setAvatarUrl(appletParamEntry.getAvatarUrl());
customerInfo.setNickName(appletParamEntry.getNickName());
customerInfo.setAppName(appletParamEntry.getAppName());
customerInfo.setCity(appletParamEntry.getCity());
customerInfo.setCountry(appletParamEntry.getCountry());
customerInfo.setProvince(appletParamEntry.getProvince());
customerInfo.setLanguage(appletParamEntry.getLanguage());
customerInfo.setSourceOpenId(appletParamEntry.getOpenId());
customerInfo.setSex(cn.quantgroup.xyqb.model.Gender.class.getEnumConstants()[appletParamEntry.getGender()]);
customerInfo.setUnionId(appletParamEntry.getUnionId());
customerInfo.setUtmSource(appletParamEntry.getUtmSource());
customerInfo.setProductId(productId);
customerInfo.setPartitionKey(partitionKey);
customerInfo.setCreatedDate(new Date());
customerInfo.setModifiedDate(new Date());
customerInfo.setCreatedBy("");
customerInfo.setModifiedBy("");
customerInfoRepository.save(customerInfo);
}
}
}
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.tech.db.DSType;
import cn.quantgroup.tech.db.TargetDataSource;
import cn.quantgroup.xyqb.entity.ProductLoginEntity;
import cn.quantgroup.xyqb.repository.IProductLoginRepository;
import cn.quantgroup.xyqb.service.user.IProductLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class ProductLoginServiceImpl implements IProductLoginService {
@Autowired
private IProductLoginRepository productLoginRepository;
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public ProductLoginEntity findSlaveByPloginInfo(String institutionId, String productId, Long userId) {
ProductLoginEntity productLogin = productLoginRepository.findByInstitutionIdAndProductIdAndExtensionAccountId(institutionId, productId, userId);
return productLogin;
}
@Override
public List<ProductLoginEntity> findSlaveByPloginInfos(String institutionId, String productId, List<Long> userIds) {
List<ProductLoginEntity> list = productLoginRepository.findByInstitutionIdAndProductIdAndExtensionAccountIdIn(institutionId, productId, userIds);
return list;
}
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public List<ProductLoginEntity> findSlaveByUserId(Long userId) {
List<ProductLoginEntity> productLoginEntityList = productLoginRepository.findAllByExtensionAccountId(userId);
return productLoginEntityList;
}
@Override
public List<ProductLoginEntity> findSlaveByUserIds(List<Long> userIds) {
List<ProductLoginEntity> productLoginEntityList = productLoginRepository.findAllByExtensionAccountIdIn(userIds);
return productLoginEntityList;
}
@Override
public List<ProductLoginEntity> findProductLoginsByInstitutionIdAndProductId(String institutionId, String productId) {
return productLoginRepository.findProductLoginsByInstitutionIdAndProductId(institutionId, productId);
}
@Override
public ProductLoginEntity findSlaveByCustomerInfo(long customerId, String institutionId, String productId) {
return productLoginRepository.findFirstByInstitutionIdAndProductIdAndCustomerId(institutionId, productId, customerId);
}
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.model.UserBrief;
import cn.quantgroup.xyqb.service.user.ICustomerInfoService;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import cn.quantgroup.xyqb.service.user.IProductLoginService;
import cn.quantgroup.xyqb.service.user.ITenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Created by 11 on 2016/12/29.
*/
@Slf4j
@Service
public class TenantServiceImpl implements ITenantService {
@Autowired
private IProductLoginService productLoginService;
@Autowired
private ICustomerInfoService customerInfoService;
@Autowired
private IOauthClientDetailsService oauthClientDetailsService;
@Override
public User getTenantUser(User user, Integer tenantId) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), user.getId());
if (productLogin != null) {
if (!user.getPhoneNo().equals(productLogin.getPhoneNo())) {
return null;
}
user.setPassword(productLogin.getPassword());
return user;
}
}
return null;
}
@Override
public UserDetail getTenantUserDetail(UserDetail userDetail, Integer tenantId) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), userDetail.getUserId());
if (productLogin != null) {
if (!userDetail.getPhoneNo().equals(productLogin.getPhoneNo())) {
return null;
}
CustomerInfoEntity customerInfo = customerInfoService.findSlaveByCustomerId(productLogin.getCustomerId());
if (customerInfo == null) {
return null;
}
UserDetail tenantUserDetail = new UserDetail();
tenantUserDetail.setUserId(userDetail.getUserId());
tenantUserDetail.setPhoneNo(userDetail.getPhoneNo());
tenantUserDetail.setIdNo(customerInfo.getIdCardNo());
tenantUserDetail.setName(customerInfo.getName());
tenantUserDetail.setCreatedAt(userDetail.getCreatedAt());
tenantUserDetail.setUpdatedAt(userDetail.getUpdatedAt());
return tenantUserDetail;
}
}
return null;
}
@Override
public UserBrief getTenantCustomerInfo(UserDetail userDetail, Integer tenantId) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), userDetail.getUserId());
if (productLogin != null) {
if (!userDetail.getPhoneNo().equals(productLogin.getPhoneNo())) {
return null;
}
CustomerInfoEntity customerInfo = customerInfoService.findSlaveByCustomerId(productLogin.getCustomerId());
if (customerInfo == null) {
return null;
}
UserBrief tenantUserBrief = new UserBrief();
tenantUserBrief.setAvatar(customerInfo.getAvatarUrl());
tenantUserBrief.setNick(customerInfo.getNickName());
tenantUserBrief.setName(customerInfo.getName());
tenantUserBrief.setSex(Optional.ofNullable(customerInfo.getSex()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).ordinal() + "");
tenantUserBrief.setPhoneNo(productLogin.getPhoneNo().substring(0, 3) + "****" + productLogin.getPhoneNo().substring(7, 11));
return tenantUserBrief;
}
}
return null;
}
@Override
public CustomerInfoEntity getTenantCustomerInfo(User user, Integer tenantId) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
ProductLoginEntity productLogin = productLoginService.findSlaveByPloginInfo(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), user.getId());
if (productLogin != null) {
if (!user.getPhoneNo().equals(productLogin.getPhoneNo())) {
return null;
}
CustomerInfoEntity customerInfo = customerInfoService.findSlaveByCustomerId(productLogin.getCustomerId());
if (customerInfo == null) {
return null;
}
return customerInfo;
}
}
return null;
}
@Override
public List<User> selectUsersByTenantId(List<User> users, Integer tenantId) {
List<User> result = new ArrayList<>();
if (users != null) {
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
List<ProductLoginEntity> productLoginEntities = productLoginService.findSlaveByPloginInfos(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), userIds);
if (productLoginEntities != null && productLoginEntities.size()>0) {
List<String> phoneNos = productLoginEntities.stream().map(ProductLoginEntity::getPhoneNo).collect(Collectors.toList());
users.forEach(a->{
if (phoneNos.contains(a.getPhoneNo())) {
result.add(a);
}
});
}
}
}
return result;
}
@Override
public Long getTenantCustomerInfoByOpenId(String openId, Integer tenantId) {
// 通过租户Id确认产品和机构Id
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
CustomerInfoEntity customerInfo = customerInfoService.findSlaveByOpenId(openId, oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId());
if (customerInfo != null ) {
ProductLoginEntity productLogin = productLoginService.findSlaveByCustomerInfo(customerInfo.getCustomerId(), oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId());
if (productLogin != null) {
return productLogin.getExtensionAccountId();
}
}
}
return null;
}
@Override
public List<User> validationTentIdByTentId(List<User> users, Integer tenantId) {
List<User> result = new ArrayList<>();
if (users != null) {
List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
OauthClientDetailsEntity oauthClientDetails = oauthClientDetailsService.findFirstByClientId(tenantId);
if (oauthClientDetails != null) {
List<ProductLoginEntity> slaveByPloginInfos = productLoginService.findSlaveByPloginInfos(oauthClientDetails.getInstitutionId(), oauthClientDetails.getProductId(), userIds);
users.forEach(a->{
if (slaveByPloginInfos != null && slaveByPloginInfos.size()>0) {
List<String> phoneNos = slaveByPloginInfos.stream().map(ProductLoginEntity::getPhoneNo).collect(Collectors.toList());
if (phoneNos.contains(a.getPhoneNo())) {
result.add(a);
}
}
});
}
List<ProductLoginEntity> slaveByUserIds = productLoginService.findSlaveByUserIds(userIds);
if (slaveByUserIds != null) {
List<Long> collect = slaveByUserIds.stream().map(ProductLoginEntity::getExtensionAccountId).collect(Collectors.toList());
users.forEach(a->{
if (collect != null) {
if (!collect.contains(a.getId())) {
result.add(a);
}
}
});
}
}
return result;
}
}
......@@ -2,22 +2,26 @@ package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.tech.db.DSType;
import cn.quantgroup.tech.db.TargetDataSource;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserAttached;
import cn.quantgroup.xyqb.repository.IUserAttachedRepository;
import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.service.user.ITenantService;
import cn.quantgroup.xyqb.service.user.UserCenterService;
import cn.quantgroup.xyqb.util.EmojiUtil;
import cn.quantgroup.xyqb.util.TenantUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Created by 11 on 2017/3/22.
......@@ -29,6 +33,12 @@ public class UserCenterServiceImpl implements UserCenterService {
@Autowired
private IUserAttachedRepository userAttachedRepository;
@Autowired
private IUserRepository userRepository;
@Autowired
private ITenantService tenantService;
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
// @Cacheable(value = "userAttachedCache", key = "'xyqbUserAttached' + #userId", unless = "#result == null", cacheManager = "cacheManager")
......@@ -37,8 +47,39 @@ public class UserCenterServiceImpl implements UserCenterService {
}
@Override
public List<UserAttached> searchUserAttachedListByUserId(List<Long> userIds) {
return userAttachedRepository.findByUserIdIn(userIds);
public List<UserAttached> searchUserAttachedListByUserId(List<Long> userIds, Integer tenantId) {
List<UserAttached> resultProductUsers = new ArrayList<>();
List<UserAttached> userAttacheds = userAttachedRepository.findByUserIdIn(userIds);
if (!tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
if (userAttacheds != null) {
//租户ID校验
if (!TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
List<User> users = userRepository.findByIdIn(userIds);
List<User> productUsers = tenantService.selectUsersByTenantId(users, tenantId);
if (productUsers != null) {
List<Long> collect = productUsers.stream().map(User::getId).collect(Collectors.toList());
userAttacheds.forEach(a->{
if (collect.contains(a.getUserId())) {
resultProductUsers.add(a);
}
});
}
return resultProductUsers;
}
}
}else {
List<User> users = userRepository.findByIdIn(userIds);
List<User> productUsers = tenantService.validationTentIdByTentId(users, tenantId);
if (productUsers != null) {
List<Long> collect = productUsers.stream().map(User::getId).collect(Collectors.toList());
userAttacheds.forEach(a->{
if (collect.contains(a.getUserId())) {
resultProductUsers.add(a);
}
});
}
}
return resultProductUsers;
}
@Override
......
......@@ -8,13 +8,7 @@ import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.lock.RedisLock;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.controller.internal.user.resp.UserFullResp;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.entity.UserHashMapping;
import cn.quantgroup.xyqb.entity.UserHashPhoneNoIdNoMapping;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.event.PhoneNoUpdateEvent;
import cn.quantgroup.xyqb.exception.DataException;
import cn.quantgroup.xyqb.exception.UserNotExistException;
......@@ -26,11 +20,7 @@ import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.HashUtil;
import cn.quantgroup.xyqb.util.IpUtil;
import cn.quantgroup.xyqb.util.MqUtils;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import cn.quantgroup.xyqb.util.*;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
......@@ -40,7 +30,6 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
......@@ -50,7 +39,6 @@ import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
......@@ -97,6 +85,12 @@ public class UserServiceImpl implements IUserService, IBaseController {
@Resource
private ILockIpv4Service lockIpv4Service;
@Autowired
private IOauthLoginInfoService oauthLoginInfoService;
@Autowired
private ITenantService tenantService;
@Override
// @Cacheable(value = "usercache", key = "'xyqbuser' + #phone", unless = "#result == null", cacheManager = "cacheManager")
public User findByPhoneInDb(String phone) {
......@@ -112,12 +106,18 @@ public class UserServiceImpl implements IUserService, IBaseController {
@Override
@TargetDataSource(type = DSType.SLAVE)//查询从库
public Map<Long, String> findPhoneByIdsInDb(List<Long> userIds) {
public Map<Long, String> findPhoneByIdsInDb(List<Long> userIds, Integer tenantId) {
if (CollectionUtils.isEmpty(userIds)) {
return Maps.newHashMap();
}
Map<Long, String> userIdAndPhoneMap = Maps.newHashMap();
List<User> users = userRepository.findByIdIn(userIds);
//校验租户ID
if (!TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
users = tenantService.selectUsersByTenantId(users, tenantId);
}else {
users = tenantService.validationTentIdByTentId(users, tenantId);
}
users.forEach(user -> userIdAndPhoneMap.put(user.getId(), user.getPhoneNo()));
return userIdAndPhoneMap;
}
......@@ -335,7 +335,7 @@ public class UserServiceImpl implements IUserService, IBaseController {
@Override
@RedisLock(prefix = "lock:login:fast:", key = "#this[8]")
public JsonResult loginFast(Long channelId, String appChannel, Long createdFrom, Long btRegisterChannelId,
String dimension, String clickId, HttpServletRequest request, Merchant merchant, String phoneNo) {
String dimension, String clickId, HttpServletRequest request, Merchant merchant, String phoneNo, Integer tenantId) {
Boolean register = false;
User user = findByPhoneWithCache(phoneNo);
if (user != null && !user.getEnable()) {
......@@ -390,7 +390,11 @@ public class UserServiceImpl implements IUserService, IBaseController {
} catch (Exception e) {
log.info("神策埋点出现问题", e);
}
LoginProperties loginProperties = new LoginProperties("", 3, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName());
//校验租户ID tenantId
if (!TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
oauthLoginInfoService.addLoginInfo(user, tenantId);
}
LoginProperties loginProperties = new LoginProperties("", 3, channelId, createdFrom, appChannel, merchant.getId(), merchant.getName(), tenantId);
AuthBean session = sessionService.createSession(user, loginProperties);
session.setRegister(register);
lockIpv4Service.unLockPhone(phoneNo);
......@@ -491,7 +495,7 @@ public class UserServiceImpl implements IUserService, IBaseController {
}
@Override
public List<User> findByUuidsOrUserIds(List<String> vals, Integer type) {
public List<User> findByUuidsOrUserIds(List<String> vals, Integer type, Integer tenantId) {
if (CollectionUtils.isEmpty(vals)) {
return Collections.EMPTY_LIST;
}
......@@ -501,10 +505,25 @@ public class UserServiceImpl implements IUserService, IBaseController {
List<Long> collect = vals.stream()
.map(Long::valueOf)
.collect(Collectors.toList());
return userRepository.findByIdIn(collect);
List<User> users = userRepository.findByIdIn(collect);
if (!tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
if (!TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
return tenantService.selectUsersByTenantId(users, tenantId);
}
}else {
return tenantService.validationTentIdByTentId(users, tenantId);
}
return users;
} else { //不是1 就是 uuids
return userRepository.findByUuidIn(vals);
List<User> users = userRepository.findByUuidIn(vals);
if (!tenantId.equals(TenantUtil.TENANT_DEFAULT)) {
if (!TenantUtil.validationTenantIdIsNullOrZero(tenantId)) {
return tenantService.selectUsersByTenantId(users, tenantId);
}else {
return tenantService.validationTentIdByTentId(users, tenantId);
}
}
return users;
}
}
......
......@@ -44,6 +44,13 @@ public class XyqbSessionContextHolder {
return getXSessionFromRedis(token);
}
public static String getXSessionFromTenantRedis() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String tenantId = request.getHeader(Constants.X_AUTH_TENANT);
log.info("getXSessionFromRedis token = 【{}】", tenantId);
return tenantId;
}
public static SessionStruct getXSessionFromRedis(String token) {
if (StringUtils.length(token) != Constants.TOKEN_LENGTH || Objects.isNull(redisTemplate)) {
return null;
......
package cn.quantgroup.xyqb.util;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author hechao
* @description
* @date 2020/7/24 13:45
* @modify 2020/7/24 13:45 by hechao
*/
@Component
public class AtomicSequencer {
private final AtomicLong INDEX = new AtomicLong(1L);
private IdentitySequencer sequencer;
public AtomicSequencer(IdentitySequencer sequencer) {
this.sequencer = sequencer;
}
public IdentitySequencer sequencer() {
return sequencer;
}
public long nextId() {
return nextId(INDEX.addAndGet(1L));
}
public long nextId(long position) {
return sequencer.nextId(Math.max(position % 225L, 1L));
}
public long workerId() {
return sequencer.workerId();
}
public long index() {
return INDEX.get();
}
public static long extractPosition(long id) {
return ((id >> 8 << 8) ^ id);
}
public int partitionKey(long id) {
return (int) ((id >> 8 << 8) ^ id);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Sequencer{")
.append("INDEX = ").append(index())
.append(",sequencer = ").append(sequencer)
.append("}");
return sb.toString();
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import cn.quantgroup.xyqb.config.SequencerProperties;
/**
* Created by hechao on 2020/2/3.
*/
public class DefaultSequencer extends SnowflakeIdentitySequencer {
public DefaultSequencer(long workerId, SequencerProperties properties) {
this(workerId, properties.getSequenceBits(), properties.getOperator());
}
public DefaultSequencer(long workerId, int sequenceBits, String oper) {
super(workerId, sequenceBits, oper);
}
public DefaultSequencer(long workerId, int sequenceBits) {
super(workerId, sequenceBits);
}
public DefaultSequencer(long workerId) {
super(workerId);
}
}
package cn.quantgroup.xyqb.util;
/**
* Created with IntelliJ IDEA.
*
* @author: Li JianHua
* @Date: 2021/10/13
* @Time: 16:53
* Description: No Description
*/
public class GcodeUtils {
/**
* 生成?位的数字类型的短信验证码
*
* @param count
* @return
*/
public static String generatedcode(int count) {
String code = String.valueOf((int)((Math.random()*9+1)* Math.pow(10,count-1)));
return code;
}
}
package cn.quantgroup.xyqb.util;
/**
* Created by hechao on 2017/8/28.
*/
public interface IdentitySequencer {
/**
* 得到下一个唯一ID
* @return
*/
long nextId();
/**
* 得到下一个唯一ID
* @param flake 片值
* @return
*/
long nextId(long flake);
/**
* 得到节点ID
* @return
*/
long workerId();
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.UUID;
/**
* Created by hechao on 2020/2/13.
*/
public abstract class RandomSequencer {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final SecureRandom RANDOM = new SecureRandom();
public static String randomNumber() {
char[] chars = new char[32];
for (int index = 0; index < chars.length; ++index) {
chars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(chars);
}
public static int next() {
return next(3, 0, 0);
}
public static int next(int size, int zeros) {
return next(size, zeros, 0);
}
public static int next(int size, int zeros, int minimum) {
int s = (int) (System.nanoTime() % (int) Math.pow(10, size));
return Math.max(s - (s % (int) Math.pow(10, zeros)), minimum);
}
public static long randomUUID(Long id) {
UUID uuid = UUID.randomUUID();
String most = Long.toHexString(uuid.getMostSignificantBits());
String least = Long.toHexString(uuid.getLeastSignificantBits());
return id ^ Long.parseLong(most.substring(0, 8), 16) * 31L
^ Long.parseLong(least.substring(0, 4), 16) * 31L
^ Long.parseLong(most.substring(8, 12), 16) * 31L
^ Long.parseLong(least.substring(4), 16) * 31L
^ Long.parseLong(most.substring(12), 16) * 31L;
}
//number
public static String hexUUID(Long id) {
// return Long.toHexString(id) + Long.toHexString(UUID.randomUUID().getMostSignificantBits());
Long uuid = randomUUID(id);
return new StringBuilder().append(Long.toHexString(id & 0xFFFFFFFFL)).append(Long.toHexString(uuid)).append(Long.toHexString(id >> 32)).toString();
}
public static String decUUID(Long id) {
LocalDate date = LocalDate.now();
long time = (long) date.getYear() * 10000L;
time = time + ((long) date.getMonthValue() * 100L);
time = (time + (long) date.getDayOfMonth()) * 100000L + (long) LocalTime.now().toSecondOfDay();
return new StringBuilder().append(time).append(randomUUID(id)).toString();
}
public static void main(String[] args) {
long id = 255255255255L ^ 8000L;
SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(id, 8);
String decUUID = RandomSequencer.decUUID(snowflakeIdWorker.nextId());
System.out.println(decUUID);
System.out.println(RandomSequencer.next(3, 0));
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import org.springframework.core.env.Environment;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;
/**
* Created by hechao on 2020/1/21.
*/
public abstract class ServerUtils {
public static Set<ObjectName> getMBeanSet(String name, String attr, String value) throws MalformedObjectNameException {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> names = beanServer.queryNames(new ObjectName(name)
, Query.match(Query.attr(attr), Query.value(value)));
return names;
}
public static String getHostAddress() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
public static String getPort(Environment environment) throws MalformedObjectNameException {
Set<ObjectName> mBeanSet = getMBeanSet("*:type=Connector,port=*", "scheme", "domain");
String port = null;
if (mBeanSet.size() > 0) {
port = mBeanSet.iterator().next().getKeyProperty("port");
}
if (port == null) {
port = environment.getProperty("server.port");
}
return port;
}
public static Long getLongHostAddress(String address) throws UnknownHostException {
String[] ip = address.split("\\.");
return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
}
public static Long getLongHostAddress() throws UnknownHostException {
return getLongHostAddress(getHostAddress());
}
public static Integer getIntegerPort(Environment environment) throws MalformedObjectNameException {
String port = getPort(environment);
return port == null || port.equals("") ? null : Integer.valueOf(port);
}
public static Integer getIntegerPort() throws MalformedObjectNameException {
return getIntegerPort(null);
}
public static void main(String[] args) {
try {
System.out.println(ServerUtils.getLongHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
package cn.quantgroup.xyqb.util;
/**
* Created by hechao on 2017/8/28.
*/
public class SnowflakeIdentitySequencer implements IdentitySequencer {
private static final long MAX_WORKER_ID = 0xFFFFFFFFFFL;
private final static int bits = 63;
private final static int SEQ_MAX_BITS = 8;
private final static int SEQ_MIN_BITS = 2;
private final static int timestampMinBits = 41;
private final static int FLAKE_BITS = 8;
private final long twepoch;
private final static long START_DATE = 473356800000L;
private final int sequenceBits;
private volatile long lastTimestamp = -1L;
private volatile long timestamp = -1L;
private volatile long sequence = 0L;
private final long sequenceMask;
private final long workerId;
public final static String TWEPOCH_XOR = "TWEPOCH_XOR";
public final static String TWEPOCH_PLUS = "TWEPOCH_PLUS";
public SnowflakeIdentitySequencer(long workerId, int sequenceBits, String oper) {
if (workerId > MAX_WORKER_ID || workerId < 1) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID, 1));
}
if (sequenceBits > SEQ_MAX_BITS || sequenceBits < 2) {
throw new IllegalArgumentException(String.format("sequence bits can't be greater than %d or less than 0", SEQ_MAX_BITS, 2));
}
this.workerId = workerId;
if (TWEPOCH_XOR.equals(oper)) {
this.twepoch = START_DATE ^ workerId;
} else if (TWEPOCH_PLUS.equals(oper)) {
this.twepoch = START_DATE + workerId;
} else {
throw new IllegalArgumentException("operator use TWEPOCH_XOR or TWEPOCH_PLUS");
}
this.sequenceBits = sequenceBits;
this.sequenceMask = -1 << sequenceBits ^ -1;
}
public SnowflakeIdentitySequencer(long workerId, int sequenceBits) {
this(workerId, sequenceBits, TWEPOCH_XOR);
}
public SnowflakeIdentitySequencer(long workerId) {
this(workerId, SEQ_MAX_BITS);
}
public synchronized long nextId(long flake) {
timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
while (timestamp == lastTimestamp) {
timestamp = System.currentTimeMillis();
}
}
}
lastTimestamp = timestamp;
return ((((timestamp - twepoch) << sequenceBits) | sequence) << FLAKE_BITS) | flake;
// return ((timestamp - twepoch) << sequenceBits) | sequence;
}
public long nextId() {
return nextId(0L);
}
@Override
public long workerId() {
return workerId;
}
@Override
public String toString() {
return "SnowflakeIdWorker{" +
"sequence=" + sequence +
", twepoch=" + twepoch +
", workerId=" + workerId +
'}';
}
public static void main(String[] args) {
SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(255255255255L ^ 8000, 8);
// SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(1099511627775L, 8, TWEPOCH_PLUS);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(255255255255L, 16, 8);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(255255255255L, 16, 8);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(17202801560208L);
Long nextId = snowflakeIdWorker.nextId(245);
System.out.println(nextId);
// for(int i=0; i<300;i++){
// System.out.println(i+":"+(i&255));
// }
// for (int i = 0; i < 100; i++) {
// new Thread(new Running(snowflakeIdWorker)).start();
// }
// System.out.println(73361139375145112L ^ (73361139375145112L >> 8 << 8));
// System.out.println((nextId >> 8 << 8) ^ nextId);
// for (int i = 0; i < 10000; i++) {
// System.out.println(snowflakeIdWorker.nextId());
// }
}
public static class Running implements Runnable {
SnowflakeIdentitySequencer sequencer;
public Running(SnowflakeIdentitySequencer sequencer) {
this.sequencer = sequencer;
}
@Override
public void run() {
System.out.println(this.sequencer.nextId(255));
}
}
}
package cn.quantgroup.xyqb.util;
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import java.io.Serializable;
import org.slf4j.helpers.MessageFormatter;
public class StringUtils extends org.springframework.util.StringUtils {
public static final char DELIMITED_ID_SEP = '$';
public static final char DELIMITED_ID_WCHAR = '*';
public StringUtils() {
}
public static String defaultIfNull(String object, String defaultValue) {
return object == null ? defaultValue : object;
}
public static <T extends Serializable> String toDelimitedString(T... ids) {
return toDelimitedString('$', ids);
}
public static <T extends Serializable> String toDelimitedString(char separator, T... ids) {
int len = ids.length;
StringBuilder builder = new StringBuilder();
Serializable[] var4 = ids;
int var5 = ids.length;
for(int var6 = 0; var6 < var5; ++var6) {
Object id = var4[var6];
if (id == null) {
builder.append('*');
} else {
builder.append(id.toString());
}
--len;
if (len == 0) {
break;
}
builder.append(separator);
}
return builder.toString();
}
public static String format(String msg, Object... args) {
return MessageFormatter.arrayFormat(msg, args).getMessage();
}
}
package cn.quantgroup.xyqb.util;
public class TenantUtil {
/* 租户羊小咩 */
public static final Integer TENANT_DEFAULT = 560761;
public static final String TENANT_USER_ERROR = "该租户下未找到此用户";
/* 验证租户ID是否为空或0 */
public static boolean validationTenantIdIsNullOrZero(Integer tenantId) {
if (tenantId == null || tenantId.equals(0)) {
return true;
}
return false;
}
}
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment