Commit d3956a85 authored by minminyan's avatar minminyan

禁用用户的同时删除相应的缓存

parent 8aa4d2be
......@@ -4,6 +4,7 @@ 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.wechat.IWechatService;
import com.alibaba.fastjson.JSONObject;
......@@ -28,343 +29,352 @@ import java.util.List;
@RequestMapping("/innerapi")
public class InnerController {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class);
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class);
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IIdCardService idCardService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IContactService contactService;
@Autowired
private IAddressService addressService;
@Autowired
private IWechatService wechatService;
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IIdCardService idCardService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IContactService contactService;
@Autowired
private IAddressService addressService;
@Autowired
private IWechatService wechatService;
@Autowired
private ISessionService sessionService;
@RequestMapping("/user/search/phoneNo")
public JsonResult findByPhoneNo(String phoneNo) {
User user = userService.findByPhoneInDb(phoneNo);
if (user == null) {
return JsonResult.buildErrorStateResult("", null);
}
UserRet userRet = UserRet.getUserRet(user);
return JsonResult.buildSuccessResult("", userRet);
@RequestMapping("/user/search/phoneNo")
public JsonResult findByPhoneNo(String phoneNo) {
User user = userService.findByPhoneInDb(phoneNo);
if (user == null) {
return JsonResult.buildErrorStateResult("", null);
}
UserRet userRet = UserRet.getUserRet(user);
return JsonResult.buildSuccessResult("", userRet);
}
@RequestMapping("/user/search/uuid")
public JsonResult findByUuid(String uuid) {
User user = userService.findByUuidInDb(uuid);
if (user == null) {
return JsonResult.buildErrorStateResult("", null);
}
UserRet userRet = UserRet.getUserRet(user);
return JsonResult.buildSuccessResult("", userRet);
@RequestMapping("/user/search/uuid")
public JsonResult findByUuid(String uuid) {
User user = userService.findByUuidInDb(uuid);
if (user == null) {
return JsonResult.buildErrorStateResult("", null);
}
UserRet userRet = UserRet.getUserRet(user);
return JsonResult.buildSuccessResult("", userRet);
}
@RequestMapping("/user/save")
public JsonResult saveUser(
String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt,
String password, String uuid) {
//参数验证
if(StringUtils.isBlank(phoneNo)){
return JsonResult.buildErrorStateResult("用户手机号不能为空.", null);
}
if(registeredFrom == null){
registeredFrom = 0L;
}
if(StringUtils.isBlank(password)){
password = "";
}
if(StringUtils.isBlank(uuid)){
return JsonResult.buildErrorStateResult("用户uuid为空.", null);
}
if(createdAt == 0L || updatedAt == 0L){
createdAt = System.currentTimeMillis();
updatedAt = System.currentTimeMillis();
}
User user = userService.findByPhoneWithCache(phoneNo);
if (user == null) {
user = new User();
}
user.setPhoneNo(phoneNo);
user.setCreatedAt(new Timestamp(createdAt));
user.setUpdatedAt(new Timestamp(updatedAt));
user.setEnable(true);
user.setRegisteredFrom(registeredFrom);
user.setUuid(uuid);
user.setPassword(password);
user = userService.saveUser(user);
UserRet userRet = null;
if(user != null){
userRet = UserRet.getUserRet(user);
}
return JsonResult.buildSuccessResult(null, userRet);
@RequestMapping("/user/save")
public JsonResult saveUser(
String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt,
String password, String uuid) {
//参数验证
if (StringUtils.isBlank(phoneNo)) {
return JsonResult.buildErrorStateResult("用户手机号不能为空.", null);
}
if (registeredFrom == null) {
registeredFrom = 0L;
}
if (StringUtils.isBlank(password)) {
password = "";
}
if (StringUtils.isBlank(uuid)) {
return JsonResult.buildErrorStateResult("用户uuid为空.", null);
}
if (createdAt == 0L || updatedAt == 0L) {
createdAt = System.currentTimeMillis();
updatedAt = System.currentTimeMillis();
}
User user = userService.findByPhoneWithCache(phoneNo);
if (user == null) {
user = new User();
}
user.setPhoneNo(phoneNo);
user.setCreatedAt(new Timestamp(createdAt));
user.setUpdatedAt(new Timestamp(updatedAt));
user.setEnable(true);
user.setRegisteredFrom(registeredFrom);
user.setUuid(uuid);
user.setPassword(password);
user = userService.saveUser(user);
UserRet userRet = null;
if (user != null) {
userRet = UserRet.getUserRet(user);
}
return JsonResult.buildSuccessResult(null, userRet);
}
/**
* 保存用户详细信息
* @param userId
* @param phoneNo
* @param name
* @param idNo
* @param email
* @return
*/
@RequestMapping("/user_detail/save")
public JsonResult saveUserDetail(Long userId, String phoneNo, String name, String idNo,
String email, Long id){
//参数验证
if(userId == null || userId == 0L){
return JsonResult.buildErrorStateResult("用户id为空.", null);
}
if(StringUtils.isBlank(phoneNo)){
return JsonResult.buildErrorStateResult("用户手机号为空.", null);
}
if(StringUtils.isBlank(name)){
return JsonResult.buildErrorStateResult("用户名为空.", null);
}
if(StringUtils.isBlank(idNo)){
return JsonResult.buildErrorStateResult("用户身份证为空.", null);
}
UserDetail userDetail = new UserDetail();
if(id != null && id > 0){
userDetail.setId(id);
}
userDetail.setUserId(userId);
userDetail.setName(name);
userDetail.setPhoneNo(phoneNo);
userDetail.setIdNo(idNo);
Timestamp time = new Timestamp(System.currentTimeMillis());
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
userDetail.setIdType(IdType.ID_CARD);
try {
userDetail.setGender(idCardService.getIdCardInfo(idNo).getGender());
} catch (ParseException e) {
LOGGER.error("根据身份证获取性别出错,错误信息:" + e);
return JsonResult.buildErrorStateResult(null, null);
}
userDetail.setEmail(email);
userDetail = userDetailService.saveUserDetail(userDetail);
if(userDetail != null){
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("",null);
/**
* 保存用户详细信息
*
* @param userId
* @param phoneNo
* @param name
* @param idNo
* @param email
* @return
*/
@RequestMapping("/user_detail/save")
public JsonResult saveUserDetail(Long userId, String phoneNo, String name, String idNo,
String email, Long id) {
//参数验证
if (userId == null || userId == 0L) {
return JsonResult.buildErrorStateResult("用户id为空.", null);
}
if (StringUtils.isBlank(phoneNo)) {
return JsonResult.buildErrorStateResult("用户手机号为空.", null);
}
if (StringUtils.isBlank(name)) {
return JsonResult.buildErrorStateResult("用户名为空.", null);
}
if (StringUtils.isBlank(idNo)) {
return JsonResult.buildErrorStateResult("用户身份证为空.", null);
}
UserDetail userDetail = new UserDetail();
if (id != null && id > 0) {
userDetail.setId(id);
}
userDetail.setUserId(userId);
userDetail.setName(name);
userDetail.setPhoneNo(phoneNo);
userDetail.setIdNo(idNo);
Timestamp time = new Timestamp(System.currentTimeMillis());
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
userDetail.setIdType(IdType.ID_CARD);
try {
userDetail.setGender(idCardService.getIdCardInfo(idNo).getGender());
} catch (ParseException e) {
LOGGER.error("根据身份证获取性别出错,错误信息:" + e);
return JsonResult.buildErrorStateResult(null, null);
}
userDetail.setEmail(email);
userDetail = userDetailService.saveUserDetail(userDetail);
if (userDetail != null) {
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("", null);
}
/**
* 根据用户id查询用户的详细信息
* @param userId
* @return
*/
@RequestMapping("/user_detail/search/userId")
public JsonResult findUserDetailByUserId(Long userId){
UserDetail userDetail = userDetailService.findByUserId(userId);
if(userDetail != null){
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("", null);
/**
* 根据用户id查询用户的详细信息
*
* @param userId
* @return
*/
@RequestMapping("/user_detail/search/userId")
public JsonResult findUserDetailByUserId(Long userId) {
UserDetail userDetail = userDetailService.findByUserId(userId);
if (userDetail != null) {
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("", null);
}
@RequestMapping("/user/search/userId")
public JsonResult findUserByUserId(Long userId){
User user = userService.findById(userId);
if(user != null){
return JsonResult.buildSuccessResult(null, UserRet.getUserRet(user));
}
return JsonResult.buildErrorStateResult("", null);
@RequestMapping("/user/search/userId")
public JsonResult findUserByUserId(Long userId) {
User user = userService.findById(userId);
if (user != null) {
return JsonResult.buildSuccessResult(null, UserRet.getUserRet(user));
}
return JsonResult.buildErrorStateResult("", null);
}
@RequestMapping("/user_detail/search/phone")
public JsonResult findUserDetailByPhone(String phoneNo){
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo);
if(userDetail != null){
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("", null);
@RequestMapping("/user_detail/search/phone")
public JsonResult findUserDetailByPhone(String phoneNo) {
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo);
if (userDetail != null) {
return JsonResult.buildSuccessResult(null, UserDetailRet.getUserDetail(userDetail));
}
return JsonResult.buildErrorStateResult("", null);
}
@RequestMapping("/user_detail/update/qq")
public JsonResult updateUserQQ(String qq, Long userId){
if(StringUtils.isEmpty(qq) || userId == null || userId == 0L){
return JsonResult.buildErrorStateResult("参数校验失败,qq或用户id为空", null);
}
userDetailService.updateUserQQ(userId, qq);
return JsonResult.buildSuccessResult(null, null);
@RequestMapping("/user_detail/update/qq")
public JsonResult updateUserQQ(String qq, Long userId) {
if (StringUtils.isEmpty(qq) || userId == null || userId == 0L) {
return JsonResult.buildErrorStateResult("参数校验失败,qq或用户id为空", null);
}
userDetailService.updateUserQQ(userId, qq);
return JsonResult.buildSuccessResult(null, null);
}
@RequestMapping("/contact/search/user_id")
public JsonResult findContactsByUserId(Long userId) {
if (null == userId) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Contact> contacts = contactService.findByUserId(userId);
if(null == contacts || contacts.size() == 0) {
return JsonResult.buildErrorStateResult(null, Collections.emptyList());
}
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(contacts));
@RequestMapping("/contact/search/user_id")
public JsonResult findContactsByUserId(Long userId) {
if (null == userId) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Contact> contacts = contactService.findByUserId(userId);
if (null == contacts || contacts.size() == 0) {
return JsonResult.buildErrorStateResult(null, Collections.emptyList());
}
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(contacts));
}
@RequestMapping("/contact/save/contacts")
public JsonResult save2Contact(Long userId, @RequestParam(value = "contacts") String contactsStr) {
LOGGER.info("保存用户联系人:userId:{}, contacts:" + contactsStr);
if (StringUtils.isEmpty(contactsStr)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (userId == null) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Contact> userContact = contactService.findByUserId(userId);
if(userContact != null && userContact.size() >= 2) {
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(userContact));
}
List<Contact> contacts = JSONObject.parseObject(contactsStr, new TypeReference<List<Contact>>() {});
if (CollectionUtils.isEmpty(contacts)) {
return JsonResult.buildErrorStateResult(null, null);
}
Timestamp now = new Timestamp(System.currentTimeMillis());
for (Contact c : contacts) {
c.setId(null);
c.setUserId(userId);
c.setCreatedAt(now);
c.setUpdateAt(now);
}
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
@RequestMapping("/contact/save/contacts")
public JsonResult save2Contact(Long userId, @RequestParam(value = "contacts") String contactsStr) {
LOGGER.info("保存用户联系人:userId:{}, contacts:" + contactsStr);
if (StringUtils.isEmpty(contactsStr)) {
return JsonResult.buildErrorStateResult(null, null);
}
if (userId == null) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Contact> userContact = contactService.findByUserId(userId);
if (userContact != null && userContact.size() >= 2) {
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(userContact));
}
List<Contact> contacts = JSONObject.parseObject(contactsStr, new TypeReference<List<Contact>>() {
});
if (CollectionUtils.isEmpty(contacts)) {
return JsonResult.buildErrorStateResult(null, null);
}
Timestamp now = new Timestamp(System.currentTimeMillis());
for (Contact c : contacts) {
c.setId(null);
c.setUserId(userId);
c.setCreatedAt(now);
c.setUpdateAt(now);
}
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
}
@RequestMapping("/address/search/user_id")
public JsonResult findAddressByUserId(Long userId) {
if (userId == null) {
return JsonResult.buildErrorStateResult(null, null);
}
Address address = addressService.findByUserId(userId);
if (address == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult(null, AddressRet.address2AddressRet(address));
@RequestMapping("/address/search/user_id")
public JsonResult findAddressByUserId(Long userId) {
if (userId == null) {
return JsonResult.buildErrorStateResult(null, null);
}
Address address = addressService.findByUserId(userId);
if (address == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult(null, AddressRet.address2AddressRet(address));
}
@RequestMapping("/address/save")
public JsonResult saveAddress(
Long userId, Long provinceCode, Long cityCode, String city,
Long districtCode, String district, String address, String province) {
LOGGER.info("保存地址详情:city:{},province:{}" + city, province);
if (userId == null || provinceCode == null || cityCode == null) {
return JsonResult.buildErrorStateResult(null, null);
}
Address addressObj = addressService.findByUserId(userId);
if (addressObj == null) {
addressObj = new Address();
Timestamp now = new Timestamp(System.currentTimeMillis());
addressObj.setCreatedAt(now);
addressObj.setUpdateAt(now);
}
addressObj.setUserId(userId);
addressObj.setProvinceCode(provinceCode);
addressObj.setCityCode(cityCode);
addressObj.setCity(city);
addressObj.setDistrictCode(districtCode);
addressObj.setDistrict(district);
addressObj.setAddress(address);
addressObj.setProvince(province);
addressObj = addressService.save(addressObj);
return JsonResult.buildSuccessResult(null, AddressRet.address2AddressRet(addressObj));
@RequestMapping("/address/save")
public JsonResult saveAddress(
Long userId, Long provinceCode, Long cityCode, String city,
Long districtCode, String district, String address, String province) {
LOGGER.info("保存地址详情:city:{},province:{}" + city, province);
if (userId == null || provinceCode == null || cityCode == null) {
return JsonResult.buildErrorStateResult(null, null);
}
Address addressObj = addressService.findByUserId(userId);
if (addressObj == null) {
addressObj = new Address();
Timestamp now = new Timestamp(System.currentTimeMillis());
addressObj.setCreatedAt(now);
addressObj.setUpdateAt(now);
}
addressObj.setUserId(userId);
addressObj.setProvinceCode(provinceCode);
addressObj.setCityCode(cityCode);
addressObj.setCity(city);
addressObj.setDistrictCode(districtCode);
addressObj.setDistrict(district);
addressObj.setAddress(address);
addressObj.setProvince(province);
addressObj = addressService.save(addressObj);
return JsonResult.buildSuccessResult(null, AddressRet.address2AddressRet(addressObj));
}
@RequestMapping("/user_ext_info/update")
public JsonResult updateMarryStatus(
Long userId, IncomeEnum incomeEnum, IncomeRangeEnum incomeRangeEnum,
OccupationEnum occupationEnum, EducationEnum educationEnum, Boolean hasCar,
Boolean hasSocialSecurity, Boolean hasHouse, Boolean hasCreditCard, MaritalStatus maritalStatus) {
if (null == userId) {
return JsonResult.buildErrorStateResult("用户ID不能为空", null);
}
UserExtInfo info = userExtInfoService.findByUserId(userId);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo();
info.setUserId(userId);
info.setCreatedAt(now);
info.setUpdateAt(now);
}
if (incomeEnum != null) {
info.setIncomeEnum(incomeEnum);
}
if (incomeRangeEnum != null) {
info.setIncomeRangeEnum(incomeRangeEnum);
}
if (occupationEnum != null) {
info.setOccupationEnum(occupationEnum);
}
if (educationEnum != null) {
info.setEducationEnum(educationEnum);
}
if (hasCar != null) {
info.setHasCar(hasCar);
}
if (hasSocialSecurity != null) {
info.setHasCreditCard(hasCreditCard);
}
if (hasHouse != null) {
info.setHasHouse(hasHouse);
}
if (maritalStatus != null) {
info.setMarryStatus(maritalStatus);
}
info = userExtInfoService.save(info);
return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(info));
@RequestMapping("/user_ext_info/update")
public JsonResult updateMarryStatus(
Long userId, IncomeEnum incomeEnum, IncomeRangeEnum incomeRangeEnum,
OccupationEnum occupationEnum, EducationEnum educationEnum, Boolean hasCar,
Boolean hasSocialSecurity, Boolean hasHouse, Boolean hasCreditCard, MaritalStatus maritalStatus) {
if (null == userId) {
return JsonResult.buildErrorStateResult("用户ID不能为空", null);
}
@RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
List<UserDetail> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
return JsonResult.buildSuccessResult("success", userDetails);
UserExtInfo info = userExtInfoService.findByUserId(userId);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo();
info.setUserId(userId);
info.setCreatedAt(now);
info.setUpdateAt(now);
}
if (incomeEnum != null) {
info.setIncomeEnum(incomeEnum);
}
if (incomeRangeEnum != null) {
info.setIncomeRangeEnum(incomeRangeEnum);
}
if (occupationEnum != null) {
info.setOccupationEnum(occupationEnum);
}
if (educationEnum != null) {
info.setEducationEnum(educationEnum);
}
if (hasCar != null) {
info.setHasCar(hasCar);
}
if (hasSocialSecurity != null) {
info.setHasCreditCard(hasCreditCard);
}
if (hasHouse != null) {
info.setHasHouse(hasHouse);
}
if (maritalStatus != null) {
info.setMarryStatus(maritalStatus);
}
info = userExtInfoService.save(info);
return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(info));
}
@RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
List<UserDetail> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
return JsonResult.buildSuccessResult("success", userDetails);
}
@RequestMapping("/user_ext_info/search/user_id")
public JsonResult searchUserExtInfoByUserId(Long userId) {
if (userId == null) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
UserExtInfo userExtInfo = userExtInfoService.findByUserId(userId);
if (userExtInfo == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult("success", UserExtInfoRet.getUserExtInfoRet(userExtInfo));
@RequestMapping("/user_ext_info/search/user_id")
public JsonResult searchUserExtInfoByUserId(Long userId) {
if (userId == null) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
UserExtInfo userExtInfo = userExtInfoService.findByUserId(userId);
if (userExtInfo == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult("success", UserExtInfoRet.getUserExtInfoRet(userExtInfo));
}
@RequestMapping("/user/query/openId")
public JsonResult queryOpenIdByUserId(Long userId) {
if(userId == null) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
WechatUserInfo wechatUserInfo = wechatService.queryOpenIdByUserId(userId);
if(wechatUserInfo == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult("success", wechatUserInfo.getOpenId());
@RequestMapping("/user/query/openId")
public JsonResult queryOpenIdByUserId(Long userId) {
if (userId == null) {
return JsonResult.buildErrorStateResult("userId不能为空", null);
}
WechatUserInfo wechatUserInfo = wechatService.queryOpenIdByUserId(userId);
if (wechatUserInfo == null) {
return JsonResult.buildErrorStateResult(null, null);
}
return JsonResult.buildSuccessResult("success", 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 = userService.saveUser(user);
return JsonResult.buildSuccessResult("用户已禁用.", user.getEnable() == false);
@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);
}
}
\ No newline at end of file
......@@ -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,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);
}
}
......@@ -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());
}
}
}
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