Commit ef595f7e authored by minminyan's avatar minminyan

合并代码

parents 8f6896b9 4c3b3444
......@@ -86,6 +86,9 @@ public class AppController implements IBaseController {
if (user == null) {
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
if (!user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("无效的商户", null);
......@@ -126,6 +129,9 @@ public class AppController implements IBaseController {
if (user == null) {
return JsonResult.buildErrorStateResult(USER_ERROR_OR_PASSWORD_ERROR, null);
}
if (!user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("无效的商户", null);
......
......@@ -4,15 +4,17 @@ import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.*;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.ValidationUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
......@@ -47,7 +49,8 @@ public class InnerController {
private IWechatService wechatService;
@Autowired
private IUserSpouseService userSpouseService;
@Autowired
private ISessionService sessionService;
@RequestMapping("/user/search/phoneNo")
public JsonResult findByPhoneNo(String phoneNo) {
......@@ -102,6 +105,7 @@ public class InnerController {
user.setUpdatedAt(new Timestamp(updatedAt));
user.setEnable(true);
user.setRegisteredFrom(registeredFrom);
user.setUuid(uuid);
user.setPassword(password);
user = userService.saveUser(user);
UserRet userRet = null;
......@@ -333,7 +337,10 @@ public class InnerController {
@RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
List<UserDetail> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) {
return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null);
}
List<UserDetailVO> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
return JsonResult.buildSuccessResult("success", userDetails);
}
......@@ -373,6 +380,25 @@ public class InnerController {
return JsonResult.buildSuccessResult(null, null == wechatUserInfo ? null : wechatUserInfo.getOpenId());
}
@RequestMapping("/user/disable")
public JsonResult disableUser(Long userId) {
if (null == userId || 0L == userId) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
User user = userService.findById(userId);
if (null == user) {
return JsonResult.buildErrorStateResult("未查询到该用户,用户id:" + userId, null);
}
user.setEnable(false);
user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
LOGGER.info("注销用户的信息,userId={}", userId);
user = userService.saveUser(user);
if (!user.getEnable()) {
sessionService.deleteByUserId(userId);
}
return JsonResult.buildSuccessResult("用户已禁用.", user.getEnable() == false);
}
@RequestMapping("/user/spouse/save")
public JsonResult saveSpouse(Long userId, MaritalStatus status, String spousePhone, String spouseName) {
if (userId == null || userId == 0) {
......
......@@ -42,419 +42,422 @@ import java.util.Random;
public class UserController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final String pwdSalt = "_lkb";
@Autowired
private IUserService userService;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Autowired
private ISmsService smsService;
@Autowired
private ISessionService sessionService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IMerchantService merchantService;
@Autowired
private IWechatService wechatService;
private static final char[] PWD_BASE = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
@RequestMapping("/login")
public JsonResult login(
@RequestParam(required = false, defaultValue = "1") Long channelId, String appChannel,
@RequestParam(required = false, defaultValue = "1") Long createdFrom,
@RequestParam(required = false, defaultValue = "") String userId, String key, HttpServletRequest request, String openId) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("未知的连接", null);
}
if (!StringUtils.isEmpty(userId) && userId.length() > 10) {
return loginWithUserId(channelId, appChannel, createdFrom, userId, merchant);
} else {
return loginWithHttpBasic(channelId, appChannel, createdFrom, merchant, request, openId);
}
}
@RequestMapping("/test")
public JsonResult test() {
return JsonResult.buildSuccessResult("", getCurrentUser());
}
@RequestMapping("/login/fast")
public JsonResult loginFast(
@RequestParam(required = false, defaultValue = "1") Long channelId, String appChannel,
@RequestParam(required = false, defaultValue = "1") Long createdFrom, String key, HttpServletRequest request) {
Map<String, JsonResult> validMap = getHeaderParam(request);
if (null != validMap.get("fail")) {
return validMap.get("fail");
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("未知的连接", null);
}
JsonResult successResult = validMap.get("success");
String phoneNo = successResult.getData().toString();
User user = userService.findByPhoneWithCache(phoneNo);
if (user == null) {
user = registerFastWhenLogin(phoneNo, channelId, createdFrom, appChannel);
if (user == null) {
throw new UserNotExistException("用户未找到");
}
}
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
// return createSession(channelId, createdFrom, appChannel, user);
}
/**
* 快速登录验证
*
* @param request
* @return
*/
private Map<String, JsonResult> getHeaderParam(HttpServletRequest request) {
Map<String, JsonResult> result = new HashMap<>();
String verificationHeader = "Verification ";
String credential = request.getHeader("authorization");
if (StringUtils.isBlank(credential)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
if (!credential.startsWith(verificationHeader)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
credential = credential.substring(verificationHeader.length(), credential.length());
byte[] buf = Base64.decodeBase64(credential);
try {
credential = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码.");
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
String[] credentialArr = credential.split(":");
if (credentialArr.length != 2) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
String phoneNo = credentialArr[0];
String verificationCode = credentialArr[1];
LOGGER.info("用户快速登录,phoneNo:{} , verificationCode:{}", phoneNo, verificationCode);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
if (!smsService.validateFastLoginVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户快速登录,验证码校验失败,phoneNo:{} , verificationCode:{}", phoneNo, verificationCode);
result.put("fail", JsonResult.buildErrorStateResult("验证码错误", null));
}
result.put("success", JsonResult.buildSuccessResult("", phoneNo));
return result;
}
/**
* 用户快速注册
*
* @param phoneNo
* @param verificationCode
* @param channelId
* @return
*/
@RequestMapping("/register/fast")
public JsonResult registerFast(@RequestParam String phoneNo, @RequestParam String verificationCode, @RequestParam(required = false) Long channelId,
@RequestParam(required = false) Long registerFrom, @RequestParam(required = false, defaultValue = "") String appChannel) {
String password = genRandomPwd();
LOGGER.info("用户快速注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},appChannel:{}", phoneNo, verificationCode, channelId, registerFrom, appChannel);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户快速注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
LOGGER.info("用户快速注册失败,密码不能为空, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
LOGGER.info("用户快速注册失败,密码长度须在6位至12位之间, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (null == registerFrom) {
registerFrom = 1L;
}
if (userService.exist(phoneNo)) {
LOGGER.info("用户快速注册失败,该手机号已经被注册, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经被注册", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户快速注册失败,短信验证码错误, registerFrom:{}, phoneNo:{}, verificationCode:{}", registerFrom, phoneNo, verificationCode);
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.register(phoneNo, password, registerFrom, getIp(), channelId)) {
LOGGER.info("用户快速注册失败,请稍后重试, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("注册失败,请稍后重试", null);
}
LOGGER.info("用户快速注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 用户登注册
*
* @param phoneNo
* @param password
* @param verificationCode
* @param channelId
* @return
*/
@RequestMapping("/register")
public JsonResult register(@RequestParam String phoneNo, @RequestParam String password,
@RequestParam String verificationCode, @RequestParam(required = false) Long channelId,
@RequestParam(required = false) Long registerFrom) {
LOGGER.info("用户注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{}", phoneNo, verificationCode, channelId, registerFrom);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
LOGGER.info("用户注册失败,密码不能为空, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
LOGGER.info("用户注册失败,密码长度须在6位至12位之间, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (null == registerFrom) {
registerFrom = 1L;
}
if (userService.exist(phoneNo)) {
LOGGER.info("用户注册失败,该手机号已经被注册, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经被注册", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户注册失败,短信验证码错误, registerFrom:{}, phoneNo:{}, verificationCode:{}", registerFrom, phoneNo, verificationCode);
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.register(phoneNo, password, registerFrom, getIp(), channelId)) {
LOGGER.info("用户快速注册失败,请稍后重试, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("注册失败,请稍后重试", null);
}
LOGGER.info("用户注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查用户是否存在
*
* @param phoneNo
* @return
*/
@RequestMapping("/exist")
public JsonResult exist(@RequestParam String phoneNo) {
LOGGER.info("检查用户是否存在, phoneNo:{}", phoneNo);
if (userService.exist(phoneNo)) {
LOGGER.info("该手机号已经注册, phoneNo:{}", phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经注册", null);
}
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查用户是否存在
*
* @param phoneNo
* @return
*/
@RequestMapping("/exist_check")
public JsonResult existForResetPwd(@RequestParam String phoneNo) {
LOGGER.info("检查用户是否存在, phoneNo:{}", phoneNo);
return JsonResult.buildSuccessResult(null, userService.exist(phoneNo));
}
/**
* 重置密码
*
* @param phoneNo
* @param password
* @param verificationCode
* @return
*/
@RequestMapping("/reset_password")
public JsonResult resetPassword(@RequestParam String phoneNo,
@RequestParam String password,
@RequestParam(required = false) String registerFrom,
@RequestParam String verificationCode) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.resetPassword(phoneNo, password)) {
return JsonResult.buildErrorStateResult("修改密码失败", null);
}
// TODO 加渠道号
LOGGER.info("修改密码成功, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查token是否已经过期不存在了
*
* @param token
* @return
*/
@RequestMapping("/exists_token")
public JsonResult checkToken(@RequestParam String token) {
String tokenKey = Constants.SESSION_PREFIX + token;
return JsonResult.buildSuccessResult(null, stringRedisTemplate.hasKey(tokenKey));
}
private String genRandomPwd() {
int pwdMax = PWD_BASE.length;
int i; // 生成的随机数
int count = 0; // 生成的密码的长度
StringBuffer pwd = new StringBuffer();
Random r = new Random();
while (count < 15) {
i = Math.abs(r.nextInt(pwdMax)); // 生成的数最大为36-1
if (i >= 0 && i < PWD_BASE.length) {
pwd.append(PWD_BASE[i]);
count++;
}
}
return pwd.toString();
}
@RequestMapping("/syncUserInfo")
public JsonResult syncUserInfo() {
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
//UserDetail detail = userDetailRepository.findByUserId(user.getId());
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult("token校验成功", userModel);
}
private User registerFastWhenLogin(String phoneNo, Long channelId, Long registerFrom, String appChannel) {
String password = genRandomPwd();
LOGGER.info("用户快速注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},appChannel:{}", phoneNo, channelId, registerFrom, appChannel);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户快速注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
throw new UserNotExistException("手机号错误");
}
if (null == registerFrom) {
registerFrom = 1L;
}
LOGGER.info("用户快速注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return userService.registerAndReturn(phoneNo, password, registerFrom);
}
private JsonResult loginWithHttpBasic(Long channelId, String appChannel, Long createdFrom, Merchant merchant, HttpServletRequest request, String openId) {
User user = verificateUserNameAndPassword(request, openId);
if (user == null) {
return JsonResult.buildErrorStateResult("用户名或密码不正确", null);
}
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
}
private User verificateUserNameAndPassword(HttpServletRequest request, String openId) {
String credential = request.getHeader("authorization");
if (!credential.startsWith("Basic ")) {
return null;
}
credential = credential.substring("Basic ".length(), credential.length());
byte[] buf = Base64.decodeBase64(credential);
String bufStr = "";
try {
bufStr = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码: ", e);
}
String[] credentialArr = bufStr.split(":");
if (credentialArr.length != 2) {
return null;
}
String userName = credentialArr[0];
String pass = credentialArr[1];
User user = userService.findByPhoneWithCache(userName);
if (user == null) {
return null;
}
//验证密码
if (!validatePassword(pass, user.getPassword())) {
return null;
}
return user;
}
private boolean validatePassword(String paramPass, String targetPassword) {
return StringUtils.defaultString(targetPassword, "").equals(PasswordUtil.MD5(paramPass.toLowerCase() + pwdSalt));
}
private JsonResult loginWithUserId(Long channelId, String appChannel, Long createdFrom, String userId, Merchant merchant) {
//查询用户,存在则保存用户session信息,userId为uuid
User user = userService.findByUuidInDb(userId);
//用户信息存在,更新session中的最后访问时间,重新写入缓存.
if (null != user) {
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
} else {
return JsonResult.buildErrorStateResult("登录失败", null);
}
}
@RequestMapping("/associate_wechat")
public JsonResult associateWithWechat(String openId) {
User user = getCurrentUser();
Long userId = user.getId();
WechatUserInfo userInfo = wechatService.findWechatUserInfoFromDb(openId);
// 已经绑定过了
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getPhoneNo())) {
return JsonResult.buildSuccessResult(null, null);
}
// 前置绑定微信出错
if (userInfo == null) {
return JsonResult.buildSuccessResult(null, null);
}
// 未绑定信用钱包用户
if (userInfo.getUserId() == null) {
userInfo.setUserId(userId);
userInfo.setPhoneNo(user.getPhoneNo());
try {
wechatService.saveWechatUserInfo(userInfo);
} catch (Exception ex) {
// 不做绑定
return JsonResult.buildErrorStateResult("该手机号已绑定其他微信号码", null);
}
return JsonResult.buildSuccessResult(null, null);
}
return JsonResult.buildSuccessResult(null, null);
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final String pwdSalt = "_lkb";
@Autowired
private IUserService userService;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Autowired
private ISmsService smsService;
@Autowired
private ISessionService sessionService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IMerchantService merchantService;
@Autowired
private IWechatService wechatService;
private static final char[] PWD_BASE = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
@RequestMapping("/login")
public JsonResult login(
@RequestParam(required = false, defaultValue = "1") Long channelId, String appChannel,
@RequestParam(required = false, defaultValue = "1") Long createdFrom,
@RequestParam(required = false, defaultValue = "") String userId, String key, HttpServletRequest request, String openId) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("未知的连接", null);
}
if (!StringUtils.isEmpty(userId) && userId.length() > 10) {
return loginWithUserId(channelId, appChannel, createdFrom, userId, merchant);
} else {
return loginWithHttpBasic(channelId, appChannel, createdFrom, merchant, request, openId);
}
}
@RequestMapping("/test")
public JsonResult test() {
return JsonResult.buildSuccessResult("", getCurrentUser());
}
@RequestMapping("/login/fast")
public JsonResult loginFast(
@RequestParam(required = false, defaultValue = "1") Long channelId, String appChannel,
@RequestParam(required = false, defaultValue = "1") Long createdFrom, String key, HttpServletRequest request) {
Map<String, JsonResult> validMap = getHeaderParam(request);
if (null != validMap.get("fail")) {
return validMap.get("fail");
}
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildErrorStateResult("未知的连接", null);
}
JsonResult successResult = validMap.get("success");
String phoneNo = successResult.getData().toString();
User user = userService.findByPhoneWithCache(phoneNo);
if (user != null && !user.getEnable()) {
return JsonResult.buildErrorStateResult("登录失败", null);
}
if (user == null) {
user = registerFastWhenLogin(phoneNo, channelId, createdFrom, appChannel);
if (user == null) {
throw new UserNotExistException("用户未找到");
}
}
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
// return createSession(channelId, createdFrom, appChannel, user);
}
/**
* 快速登录验证
*
* @param request
* @return
*/
private Map<String, JsonResult> getHeaderParam(HttpServletRequest request) {
Map<String, JsonResult> result = new HashMap<>();
String verificationHeader = "Verification ";
String credential = request.getHeader("authorization");
if (StringUtils.isBlank(credential)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
if (!credential.startsWith(verificationHeader)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
credential = credential.substring(verificationHeader.length(), credential.length());
byte[] buf = Base64.decodeBase64(credential);
try {
credential = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码.");
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
String[] credentialArr = credential.split(":");
if (credentialArr.length != 2) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
String phoneNo = credentialArr[0];
String verificationCode = credentialArr[1];
LOGGER.info("用户快速登录,phoneNo:{} , verificationCode:{}", phoneNo, verificationCode);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
result.put("fail", JsonResult.buildErrorStateResult("登录失败", null));
}
if (!smsService.validateFastLoginVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户快速登录,验证码校验失败,phoneNo:{} , verificationCode:{}", phoneNo, verificationCode);
result.put("fail", JsonResult.buildErrorStateResult("验证码错误", null));
}
result.put("success", JsonResult.buildSuccessResult("", phoneNo));
return result;
}
/**
* 用户快速注册
*
* @param phoneNo
* @param verificationCode
* @param channelId
* @return
*/
@RequestMapping("/register/fast")
public JsonResult registerFast(@RequestParam String phoneNo, @RequestParam String verificationCode, @RequestParam(required = false) Long channelId,
@RequestParam(required = false) Long registerFrom, @RequestParam(required = false, defaultValue = "") String appChannel) {
String password = genRandomPwd();
LOGGER.info("用户快速注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},appChannel:{}", phoneNo, verificationCode, channelId, registerFrom, appChannel);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户快速注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
LOGGER.info("用户快速注册失败,密码不能为空, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
LOGGER.info("用户快速注册失败,密码长度须在6位至12位之间, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (null == registerFrom) {
registerFrom = 1L;
}
if (userService.exist(phoneNo)) {
LOGGER.info("用户快速注册失败,该手机号已经被注册, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经被注册", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户快速注册失败,短信验证码错误, registerFrom:{}, phoneNo:{}, verificationCode:{}", registerFrom, phoneNo, verificationCode);
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.register(phoneNo, password, registerFrom, getIp(), channelId)) {
LOGGER.info("用户快速注册失败,请稍后重试, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("注册失败,请稍后重试", null);
}
LOGGER.info("用户快速注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 用户登注册
*
* @param phoneNo
* @param password
* @param verificationCode
* @param channelId
* @return
*/
@RequestMapping("/register")
public JsonResult register(@RequestParam String phoneNo, @RequestParam String password,
@RequestParam String verificationCode, @RequestParam(required = false) Long channelId,
@RequestParam(required = false) Long registerFrom) {
LOGGER.info("用户注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{}", phoneNo, verificationCode, channelId, registerFrom);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
LOGGER.info("用户注册失败,密码不能为空, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
LOGGER.info("用户注册失败,密码长度须在6位至12位之间, registerFrom:{}, phoneNo:{}, password:{}", registerFrom, phoneNo, password);
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (null == registerFrom) {
registerFrom = 1L;
}
if (userService.exist(phoneNo)) {
LOGGER.info("用户注册失败,该手机号已经被注册, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经被注册", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
LOGGER.info("用户注册失败,短信验证码错误, registerFrom:{}, phoneNo:{}, verificationCode:{}", registerFrom, phoneNo, verificationCode);
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.register(phoneNo, password, registerFrom, getIp(), channelId)) {
LOGGER.info("用户快速注册失败,请稍后重试, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildErrorStateResult("注册失败,请稍后重试", null);
}
LOGGER.info("用户注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查用户是否存在
*
* @param phoneNo
* @return
*/
@RequestMapping("/exist")
public JsonResult exist(@RequestParam String phoneNo) {
LOGGER.info("检查用户是否存在, phoneNo:{}", phoneNo);
if (userService.exist(phoneNo)) {
LOGGER.info("该手机号已经注册, phoneNo:{}", phoneNo);
return JsonResult.buildErrorStateResult("该手机号已经注册", null);
}
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查用户是否存在
*
* @param phoneNo
* @return
*/
@RequestMapping("/exist_check")
public JsonResult existForResetPwd(@RequestParam String phoneNo) {
LOGGER.info("检查用户是否存在, phoneNo:{}", phoneNo);
return JsonResult.buildSuccessResult(null, userService.exist(phoneNo));
}
/**
* 重置密码
*
* @param phoneNo
* @param password
* @param verificationCode
* @return
*/
@RequestMapping("/reset_password")
public JsonResult resetPassword(@RequestParam String phoneNo,
@RequestParam String password,
@RequestParam(required = false) String registerFrom,
@RequestParam String verificationCode) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号错误", null);
}
if (StringUtils.isEmpty(password)) {
return JsonResult.buildErrorStateResult("密码不能为空", null);
}
if (password.length() < 6 || password.length() > 12) {
return JsonResult.buildErrorStateResult("密码应为6-12位", null);
}
if (!smsService.validRegisterOrResetPasswdVerificationCode(phoneNo, verificationCode)) {
return JsonResult.buildErrorStateResult("短信验证码错误", null);
}
if (!userService.resetPassword(phoneNo, password)) {
return JsonResult.buildErrorStateResult("修改密码失败", null);
}
// TODO 加渠道号
LOGGER.info("修改密码成功, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return JsonResult.buildSuccessResult(null, null);
}
/**
* 检查token是否已经过期不存在了
*
* @param token
* @return
*/
@RequestMapping("/exists_token")
public JsonResult checkToken(@RequestParam String token) {
String tokenKey = Constants.SESSION_PREFIX + token;
return JsonResult.buildSuccessResult(null, stringRedisTemplate.hasKey(tokenKey));
}
private String genRandomPwd() {
int pwdMax = PWD_BASE.length;
int i; // 生成的随机数
int count = 0; // 生成的密码的长度
StringBuffer pwd = new StringBuffer();
Random r = new Random();
while (count < 15) {
i = Math.abs(r.nextInt(pwdMax)); // 生成的数最大为36-1
if (i >= 0 && i < PWD_BASE.length) {
pwd.append(PWD_BASE[i]);
count++;
}
}
return pwd.toString();
}
@RequestMapping("/syncUserInfo")
public JsonResult syncUserInfo() {
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult(null, null);
}
UserDetail detail = userDetailService.findByUserId(user.getId());
//UserDetail detail = userDetailRepository.findByUserId(user.getId());
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult("token校验成功", userModel);
}
private User registerFastWhenLogin(String phoneNo, Long channelId, Long registerFrom, String appChannel) {
String password = genRandomPwd();
LOGGER.info("用户快速注册, phoneNo:{}, verificationCode:{}, channelId:{}, registerFrom:{},appChannel:{}", phoneNo, channelId, registerFrom, appChannel);
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("用户快速注册失败,手机号错误, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
throw new UserNotExistException("手机号错误");
}
if (null == registerFrom) {
registerFrom = 1L;
}
LOGGER.info("用户快速注册成功, registerFrom:{}, phoneNo:{}", registerFrom, phoneNo);
return userService.registerAndReturn(phoneNo, password, registerFrom);
}
private JsonResult loginWithHttpBasic(Long channelId, String appChannel, Long createdFrom, Merchant merchant, HttpServletRequest request, String openId) {
User user = verificateUserNameAndPassword(request, openId);
if (user == null) {
return JsonResult.buildErrorStateResult("用户名或密码不正确", null);
}
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
}
private User verificateUserNameAndPassword(HttpServletRequest request, String openId) {
String credential = request.getHeader("authorization");
if (!credential.startsWith("Basic ")) {
return null;
}
credential = credential.substring("Basic ".length(), credential.length());
byte[] buf = Base64.decodeBase64(credential);
String bufStr = "";
try {
bufStr = new String(buf, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码: ", e);
}
String[] credentialArr = bufStr.split(":");
if (credentialArr.length != 2) {
return null;
}
String userName = credentialArr[0];
String pass = credentialArr[1];
User user = userService.findByPhoneWithCache(userName);
if (user == null || !user.getEnable()) {
return null;
}
//验证密码
if (!validatePassword(pass, user.getPassword())) {
return null;
}
return user;
}
private boolean validatePassword(String paramPass, String targetPassword) {
return StringUtils.defaultString(targetPassword, "").equals(PasswordUtil.MD5(paramPass.toLowerCase() + pwdSalt));
}
private JsonResult loginWithUserId(Long channelId, String appChannel, Long createdFrom, String userId, Merchant merchant) {
//查询用户,存在则保存用户session信息,userId为uuid
User user = userService.findByUuidInDb(userId);
//用户信息存在,更新session中的最后访问时间,重新写入缓存.
if (null != user || !user.getEnable()) {
return new JsonResult(sessionService.createSession(channelId, createdFrom, appChannel, user, merchant));
} else {
return JsonResult.buildErrorStateResult("登录失败", null);
}
}
@RequestMapping("/associate_wechat")
public JsonResult associateWithWechat(String openId) {
User user = getCurrentUser();
Long userId = user.getId();
WechatUserInfo userInfo = wechatService.findWechatUserInfoFromDb(openId);
// 已经绑定过了
if (userInfo != null && StringUtils.isNotEmpty(userInfo.getPhoneNo())) {
return JsonResult.buildSuccessResult(null, null);
}
// 前置绑定微信出错
if (userInfo == null) {
return JsonResult.buildSuccessResult(null, null);
}
// 未绑定信用钱包用户
if (userInfo.getUserId() == null) {
userInfo.setUserId(userId);
userInfo.setPhoneNo(user.getPhoneNo());
try {
wechatService.saveWechatUserInfo(userInfo);
} catch (Exception ex) {
// 不做绑定
return JsonResult.buildErrorStateResult("该手机号已绑定其他微信号码", null);
}
return JsonResult.buildSuccessResult(null, null);
}
return JsonResult.buildSuccessResult(null, null);
}
}
......@@ -2,11 +2,12 @@ package cn.quantgroup.xyqb.repository;
import cn.quantgroup.xyqb.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by Miraculous on 15/7/4.
*/
public interface IUserRepository extends JpaRepository<User, Long> {
public interface IUserRepository extends JpaRepository<User, Long> ,JpaSpecificationExecutor<User>{
User findByPhoneNo(String phoneNo);
......
......@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.session;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.function.OneArgFunction;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.session.SessionStruct;
......@@ -14,15 +13,19 @@ import cn.quantgroup.xyqb.model.session.SessionValue;
public interface ISessionService {
AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant);
AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant);
SessionStruct createSessionAndPersist(User user, LoginProperties loginProperties);
SessionStruct createSessionAndPersist(User user, LoginProperties loginProperties);
String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties);
String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties);
String findSessionValueBySessionId(String sessionId);
SessionStruct newSession(User user, LoginProperties properties);
void persistSession(String token, SessionValue sessionValue);
String findSessionValueBySessionId(String sessionId);
SessionStruct findSessionBySessionId(String sessionId);
SessionStruct newSession(User user, LoginProperties properties);
void persistSession(String token, SessionValue sessionValue);
SessionStruct findSessionBySessionId(String sessionId);
void deleteByUserId(long userId);
}
......@@ -3,154 +3,164 @@ package cn.quantgroup.xyqb.service.session.impl;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.function.OneArgFunction;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.model.session.SessionValue;
import cn.quantgroup.xyqb.service.session.ISessionService;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
*
* Created by 11 on 2016/12/28.
*/
@Slf4j
@Service
public class SessionServiceImpl implements ISessionService{
public class SessionServiceImpl implements ISessionService {
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Override
public AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant) {
AuthBean authBean = new AuthBean();
LoginProperties properties = new LoginProperties();
properties.setAppChannel(appChannel);
properties.setMerchantName(merchant.getName());
properties.setChannelId(channelId);
properties.setCreatedFrom(createdFrom);
//找到用户
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
// String sessionId = sessionService.findSessionIdByUserIdAndMerchant(user.getId(), merchant);
if(org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) {
SessionStruct sessionStruct = findSessionBySessionId(sessionId);
sessionStruct.setAttribute("channelId", String.valueOf(channelId));
sessionStruct.setAttribute("createdFrom", String.valueOf(createdFrom));
sessionStruct.setAttribute("appChannel", String.valueOf(appChannel));
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
}
SessionStruct sessionStruct = createSessionAndPersist(user, properties);
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
@Override
public AuthBean createSession(Long channelId, Long createdFrom, String appChannel, User user, Merchant merchant) {
AuthBean authBean = new AuthBean();
LoginProperties properties = new LoginProperties();
properties.setAppChannel(appChannel);
properties.setMerchantName(merchant.getName());
properties.setChannelId(channelId);
properties.setCreatedFrom(createdFrom);
//找到用户
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
// String sessionId = sessionService.findSessionIdByUserIdAndMerchant(user.getId(), merchant);
if (org.apache.commons.lang.StringUtils.isNotEmpty(sessionId)) {
SessionStruct sessionStruct = findSessionBySessionId(sessionId);
sessionStruct.setAttribute("channelId", String.valueOf(channelId));
sessionStruct.setAttribute("createdFrom", String.valueOf(createdFrom));
sessionStruct.setAttribute("appChannel", String.valueOf(appChannel));
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
}
SessionStruct sessionStruct = createSessionAndPersist(user, properties);
authBean.setPhoneNo(user.getPhoneNo());
authBean.setToken(sessionStruct.getSid());
log.info("用户登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", createdFrom, user.getPhoneNo(), appChannel);
return authBean;
}
@Override
public SessionStruct createSessionAndPersist(User user, LoginProperties properties) {
SessionStruct sessionStruct;
//获取sessionid
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
if (StringUtils.length(sessionId) == 36) {
sessionStruct = findSessionBySessionId(sessionId);
if (sessionStruct == null) {
sessionStruct = newSession(user, properties);
} else {
sessionStruct.getValues().setLoginProperties(properties);
}
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
} else {
sessionStruct = newSession(user, properties);
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
}
return sessionStruct;
@Override
public SessionStruct createSessionAndPersist(User user, LoginProperties properties) {
SessionStruct sessionStruct;
//获取sessionid
String sessionId = findSessionIdByUserIdLoginProperties(user.getId(), properties);
if (StringUtils.length(sessionId) == 36) {
sessionStruct = findSessionBySessionId(sessionId);
if (sessionStruct == null) {
sessionStruct = newSession(user, properties);
} else {
sessionStruct.getValues().setLoginProperties(properties);
}
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
} else {
sessionStruct = newSession(user, properties);
persistSession(sessionStruct.getSid(), sessionStruct.getValues());
}
return sessionStruct;
}
@Override
public String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties) {
return stringRedisTemplate.opsForValue().get(generateLoginPropertiesKey(userId, properties));
}
@Override
public String findSessionIdByUserIdLoginProperties(Long userId, LoginProperties properties) {
return stringRedisTemplate.opsForValue().get(generateLoginPropertiesKey(userId, properties));
}
private String generateLoginPropertiesKey(Long userId, LoginProperties properties) {
if ("baitiao".equals(properties.getMerchantName())) {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
} else {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName();
}
private String generateLoginPropertiesKey(Long userId, LoginProperties properties) {
if ("baitiao".equals(properties.getMerchantName())) {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName() + ":" + properties.getCreatedFrom();
} else {
return Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":" + properties.getMerchantName();
}
}
@Override
public String findSessionValueBySessionId(String sessionId){
String result = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + sessionId);
return StringUtils.defaultString(result, "");
}
@Override
public String findSessionValueBySessionId(String sessionId) {
String result = stringRedisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + sessionId);
return StringUtils.defaultString(result, "");
}
@Override
public SessionStruct newSession(User user, LoginProperties loginProperties){
Timestamp now = new Timestamp(System.currentTimeMillis());
SessionStruct sessionStruct = new SessionStruct();
SessionValue sessionValue = new SessionValue();
sessionStruct.setSid(UUID.randomUUID().toString());
sessionValue.setCreatedAt(now);
sessionValue.setLastAccessTime(now);
sessionValue.setUser(user);
sessionValue.setLoginProperties(loginProperties);
Map<String, String> values = new HashMap<>();
sessionValue.setValues(values);
sessionStruct.setValues(sessionValue);
return sessionStruct;
}
@Override
public SessionStruct newSession(User user, LoginProperties loginProperties) {
Timestamp now = new Timestamp(System.currentTimeMillis());
SessionStruct sessionStruct = new SessionStruct();
SessionValue sessionValue = new SessionValue();
sessionStruct.setSid(UUID.randomUUID().toString());
sessionValue.setCreatedAt(now);
sessionValue.setLastAccessTime(now);
sessionValue.setUser(user);
sessionValue.setLoginProperties(loginProperties);
Map<String, String> values = new HashMap<>();
sessionValue.setValues(values);
sessionStruct.setValues(sessionValue);
return sessionStruct;
}
@Override
public void persistSession(String token, SessionValue sessionValue) {
Timestamp current = new Timestamp(System.currentTimeMillis());
sessionValue.setLastAccessTime(current);
String json = JSON.toJSONString(sessionValue);
stringRedisTemplate.opsForValue().set(Constants.Session.USER_SESSION_CACHE + token, json,
Constants.Session.ONE_DAY, TimeUnit.SECONDS);
String key = generateLoginPropertiesKey(sessionValue.getUser().getId(), sessionValue.getLoginProperties());
stringRedisTemplate.opsForValue().set(key, token, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
}
@Override
public SessionStruct findSessionBySessionId(String sessionId) {
String sessionValue = findSessionValueBySessionId(sessionId);
if(StringUtils.isEmpty(sessionValue)) {
return null;
}
try {
SessionValue value = JSON.parseObject(sessionValue, SessionValue.class);
if (null == value) {
return null;
}
SessionStruct struct = new SessionStruct();
struct.setSid(sessionId);
struct.setValues(value);
return struct;
} catch (Exception ex) {
return null;
}
@Override
public void persistSession(String token, SessionValue sessionValue) {
Timestamp current = new Timestamp(System.currentTimeMillis());
sessionValue.setLastAccessTime(current);
String json = JSON.toJSONString(sessionValue);
stringRedisTemplate.opsForValue().set(Constants.Session.USER_SESSION_CACHE + token, json,
Constants.Session.ONE_DAY, TimeUnit.SECONDS);
String key = generateLoginPropertiesKey(sessionValue.getUser().getId(), sessionValue.getLoginProperties());
stringRedisTemplate.opsForValue().set(key, token, Constants.Session.ONE_DAY, TimeUnit.SECONDS);
}
@Override
public SessionStruct findSessionBySessionId(String sessionId) {
String sessionValue = findSessionValueBySessionId(sessionId);
if (StringUtils.isEmpty(sessionValue)) {
return null;
}
try {
SessionValue value = JSON.parseObject(sessionValue, SessionValue.class);
if (null == value) {
return null;
}
SessionStruct struct = new SessionStruct();
struct.setSid(sessionId);
struct.setValues(value);
return struct;
} catch (Exception ex) {
return null;
}
}
@Override
public void deleteByUserId(long userId) {
String pattern = Constants.Session.USER_SESSION_ID_CACHE + ":" + String.valueOf(userId) + ":*";
Set<String> keys = stringRedisTemplate.keys(pattern);
if (!CollectionUtils.isEmpty(keys)) {
log.info("删除用户userId={}的缓存信息,个数:{},keys={}", userId,
keys.size(),
Joiner.on(",").join(keys));
}
stringRedisTemplate.delete(keys);
}
}
package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import org.springframework.dao.DataIntegrityViolationException;
import java.util.List;
......@@ -9,13 +10,13 @@ import java.util.List;
* Created by 11 on 2016/12/29.
*/
public interface IUserDetailService {
UserDetail findByUserId(Long userId);
UserDetail findByUserId(Long userId);
UserDetail saveUserDetail(UserDetail userDetail) throws DataIntegrityViolationException;
UserDetail saveUserDetail(UserDetail userDetail) throws DataIntegrityViolationException;
UserDetail findByPhoneNo(String phoneNo);
UserDetail findByPhoneNo(String phoneNo);
void updateUserQQ(Long userId, String qq);
void updateUserQQ(Long userId, String qq);
List<UserDetail> searchUserDetailList(String name, String phoneNo, String idNo);
List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo);
}
package cn.quantgroup.xyqb.service.user.impl;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.repository.IUserDetailRepository;
import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.vo.UserDetailVO;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.persistence.criteria.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by 11 on 2016/12/29.
......@@ -19,52 +29,76 @@ import java.util.List;
@Service
public class UserDetailServiceImpl implements IUserDetailService {
@Autowired
private IUserDetailRepository userDetailRepository;
@Autowired
private IUserDetailRepository userDetailRepository;
@Autowired
private IUserRepository userRepository;
@Override
public UserDetail findByUserId(Long userId) {
return userDetailRepository.findByUserId(userId);
}
@Override
public UserDetail findByUserId(Long userId) {
return userDetailRepository.findByUserId(userId);
}
@Override
public UserDetail saveUserDetail(UserDetail userDetail) throws DataIntegrityViolationException {
return userDetailRepository.save(userDetail);
}
@Override
public UserDetail saveUserDetail(UserDetail userDetail) throws DataIntegrityViolationException {
return userDetailRepository.save(userDetail);
}
@Override
public UserDetail findByPhoneNo(String phoneNo) {
return userDetailRepository.findByPhoneNo(phoneNo);
}
@Override
public UserDetail findByPhoneNo(String phoneNo) {
return userDetailRepository.findByPhoneNo(phoneNo);
}
@Override
public void updateUserQQ(Long userId, String qq) {
userDetailRepository.updateUserQQ(qq, userId);
}
@Override
public void updateUserQQ(Long userId, String qq) {
userDetailRepository.updateUserQQ(qq, userId);
}
@Override
public List<UserDetail> searchUserDetailList(String name, String phoneNo, String idNo) {
return userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
@Override
public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) {
// return
List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
Map<Long, User> userMap = Maps.newHashMap();
if (!CollectionUtils.isEmpty(details)) {
List<Long> userIds = details.stream().map(d -> d.getUserId()).collect(Collectors.toList());
List<User> users = userRepository.findAll((root, query, cb) -> {
query.where(root.get("id").in(userIds));
return query.getRestriction();
});
userMap = users.stream().collect(Collectors.toMap(User::getId, o -> o));
}
Map<Long, User> finalUserMap = userMap;
List<UserDetailVO> userDetailVOS = details.stream().map(o -> fromUserDetailAndUserMap(o, finalUserMap)).collect(Collectors.toList());
return userDetailVOS;
}
private Specification<UserDetail> getSpecification(String name, String phoneNo, String idNo) {
List<Predicate> list = new ArrayList<>();
Specification<UserDetail> specification = new Specification<UserDetail>() {
@Override
public Predicate toPredicate(Root<UserDetail> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
if (!StringUtils.isEmpty(name)) {
list.add(criteriaBuilder.equal(root.get("name").as(String.class), name));
}
if (!StringUtils.isEmpty(phoneNo)) {
list.add(criteriaBuilder.equal(root.get("phoneNo").as(String.class), phoneNo));
}
if (!StringUtils.isEmpty(idNo)) {
list.add(criteriaBuilder.equal(root.get("idNo").as(String.class), idNo));
}
Predicate[] p = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(p));
}
};
return specification;
}
private Specification<UserDetail> getSpecification(String name, String phoneNo, String idNo) {
List<Predicate> list = new ArrayList<>();
Specification<UserDetail> specification = new Specification<UserDetail>() {
@Override
public Predicate toPredicate(Root<UserDetail> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
if (!StringUtils.isEmpty(name)) {
list.add(criteriaBuilder.equal(root.get("name").as(String.class), name));
}
if (!StringUtils.isEmpty(phoneNo)) {
list.add(criteriaBuilder.equal(root.get("phoneNo").as(String.class), phoneNo));
}
if (!StringUtils.isEmpty(idNo)) {
list.add(criteriaBuilder.equal(root.get("idNo").as(String.class), idNo));
}
Predicate[] p = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(p));
}
};
return specification;
private UserDetailVO fromUserDetailAndUserMap(UserDetail userDetail, Map<Long, User> userMap) {
UserDetailVO userDetailVO = UserDetailVO.fromUserDetail(userDetail);
User user = userMap.get(userDetail.getUserId());
if (user != null) {
userDetailVO.setEnable(user.getEnable());
}
return userDetailVO;
}
}
......@@ -24,120 +24,122 @@ import java.util.concurrent.TimeUnit;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
RedisTemplate<String, String> stringRedisTemplate;
@Autowired
private ILkbUserService lkbUserService;
@Autowired
private IUserRepository userRepository;
@Autowired
private ISmsService smsService;
@Override
public User findByPhoneInDb(String phone) {
return userRepository.findByPhoneNo(phone);
@Autowired
RedisTemplate<String, String> stringRedisTemplate;
@Autowired
private ILkbUserService lkbUserService;
@Autowired
private IUserRepository userRepository;
@Autowired
private ISmsService smsService;
@Override
public User findByPhoneInDb(String phone) {
return userRepository.findByPhoneNo(phone);
}
@Override
public User findByUuidInDb(String uuid) {
return userRepository.findByUuid(uuid);
}
@Override
@CacheEvict(value = "usercache", key = "'xyqbuser' + #user.phoneNo", cacheManager = "cacheManager")
public User saveUser(User user) {
return userRepository.save(user);
}
@Override
public User findById(Long userId) {
return userRepository.findById(userId);
}
@Override
public User registerAndReturn(String phoneNo, String password, Long registerFrom) {
String uuid = lkbUserService.registerApp(phoneNo, password);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
User user = new User();
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
user.setUuid(uuid);
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
user.setRegisteredFrom(registerFrom);
return userRepository.save(user);
}
@Override
@Cacheable(value = "usercache", key = "'xyqbuser' + #phone", unless = "#result == null", cacheManager = "cacheManager")
public User findByPhoneWithCache(String phone) {
return userRepository.findByPhoneNo(phone);
}
@Override
@Cacheable(value = "usercache", key = "'xyqbuser' + #uuid", unless = "#result == null", cacheManager = "cacheManager")
public User findByUuidWithCache(String uuid) {
return userRepository.findByUuid(uuid);
}
@Override
@Transactional(value = Transactional.TxType.REQUIRED)
public boolean register(String phoneNo, String password, Long registerFrom, String userIp, Long channelId) {
String uuid = lkbUserService.registerApp(phoneNo, password);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
User user = new User();
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
user.setUuid(uuid);
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
//解决线上白条registerFrom为1的问题
if (channelId == 222L) {
user.setRegisteredFrom(channelId);
} else {
user.setRegisteredFrom(registerFrom);
}
@Override
public User findByUuidInDb(String uuid) {
return userRepository.findByUuid(uuid);
}
@Override
public User saveUser(User user) {
return userRepository.save(user);
//user.setRegisteredFrom(registerFrom);
user = userRepository.save(user);
smsService.sendAfterRegister(phoneNo);
return user != null;
}
@Override
public boolean exist(String phoneNo) {
return userRepository.findByPhoneNo(phoneNo) != null;
}
/**
* 修改用户密码
*
* @param phoneNo
* @param password
* @return
* @date 2017-02-15 修改用户修改密码时,更新updatedAt时间
*/
@Override
@CacheEvict(value = "usercache", key = "'xyqbuser' + #phone", cacheManager = "cacheManager")
public boolean resetPassword(String phoneNo, String password) {
User user = userRepository.findByPhoneNo(phoneNo);
if (user == null) {
throw new RuntimeException("用户[" + phoneNo + "]不存在");
}
user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
user = userRepository.save(user);
stringRedisTemplate.expire("usercache:xyqbuser" + phoneNo, 1L, TimeUnit.MILLISECONDS);
return StringUtils.equals(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT), user.getPassword());
@Override
public User findById(Long userId) {
return userRepository.findById(userId);
}
@Override
public User registerAndReturn(String phoneNo, String password, Long registerFrom) {
String uuid = lkbUserService.registerApp(phoneNo, password);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
User user = new User();
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
user.setUuid(uuid);
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
user.setRegisteredFrom(registerFrom);
return userRepository.save(user);
}
@Override
@Cacheable(value = "usercache", key = "'xyqbuser' + #phone", unless = "#result == null", cacheManager = "cacheManager")
public User findByPhoneWithCache(String phone) {
return userRepository.findByPhoneNo(phone);
}
@Override
@Cacheable(value = "usercache", key = "'xyqbuser' + #uuid", unless = "#result == null", cacheManager = "cacheManager")
public User findByUuidWithCache(String uuid) {
return userRepository.findByUuid(uuid);
}
@Override
@Transactional(value = Transactional.TxType.REQUIRED)
public boolean register(String phoneNo, String password, Long registerFrom, String userIp, Long channelId) {
String uuid = lkbUserService.registerApp(phoneNo, password);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
User user = new User();
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
user.setUuid(uuid);
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
//解决线上白条registerFrom为1的问题
if(channelId == 222L) {
user.setRegisteredFrom(channelId);
} else {
user.setRegisteredFrom(registerFrom);
}
//user.setRegisteredFrom(registerFrom);
user = userRepository.save(user);
smsService.sendAfterRegister(phoneNo);
return user != null;
}
@Override
public boolean exist(String phoneNo) {
return userRepository.findByPhoneNo(phoneNo) != null;
}
/**
* 修改用户密码
* @date 2017-02-15 修改用户修改密码时,更新updatedAt时间
* @param phoneNo
* @param password
* @return
*/
@Override
@CacheEvict(value = "usercache", key = "'xyqbuser' + #phone", cacheManager = "cacheManager")
public boolean resetPassword(String phoneNo, String password) {
User user = userRepository.findByPhoneNo(phoneNo);
if (user == null) {
throw new RuntimeException("用户[" + phoneNo + "]不存在");
}
user.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
user = userRepository.save(user);
stringRedisTemplate.expire("usercache:xyqbuser" + phoneNo, 1L, TimeUnit.MILLISECONDS);
return StringUtils.equals(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT), user.getPassword());
}
}
}
package cn.quantgroup.xyqb.service.user.vo;
import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class UserDetailVO {
private Long id;
private Long userId;
private String phoneNo;
private String name;
private String idNo;
private IdType idType;
private Boolean isAuthenticated = false;
private Gender gender;
private String email;
private String qq;
private Boolean enable;
private Long createdAt;
private Long updatedAt;
public static UserDetailVO fromUserDetail(UserDetail userDetail) {
UserDetailVO userDetailVO = new UserDetailVO();
userDetailVO.id = userDetail.getId();
userDetailVO.userId = userDetail.getUserId();
userDetailVO.phoneNo = userDetail.getPhoneNo();
userDetailVO.name = userDetail.getName();
userDetailVO.idNo = userDetail.getIdNo();
userDetailVO.idType = userDetail.getIdType();
userDetailVO.isAuthenticated = userDetail.getIsAuthenticated();
userDetailVO.gender = userDetail.getGender();
userDetailVO.email = userDetail.getEmail();
userDetailVO.qq = userDetail.getQq();
if (userDetail.getCreatedAt() != null) {
userDetailVO.createdAt = userDetail.getCreatedAt().getTime();
}
if (userDetail.getUpdatedAt() != null) {
userDetailVO.updatedAt = userDetail.getUpdatedAt().getTime();
}
return userDetailVO;
}
}
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