app 用户登录 用户注册

新增 登录过滤器 仅对app作用
This commit is contained in:
2024-03-28 10:59:15 +08:00
parent 57dc6be120
commit 09e29ca20b
10 changed files with 451 additions and 119 deletions

View File

@@ -0,0 +1,127 @@
package com.chaozhanggui.system.cashierservice.auth;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* 登录的拦截器
* 目前仅限APP使用
*/
@Slf4j
@Component
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
/**
* 不登录就可以访问的接口
*/
private static final List<String> NOT_LOGIN_URL = Arrays.asList(
// 忽略静态资源
"css/**",
"js/**",
"cashierService/phoneValidateCode",//验证码
"cashierService/login/**"//登录部分接口不校验
);
@Autowired
private RedisUtil redisUtil;
/**
* 登陆过滤器具体实现
*/
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
// OPTIONS请求类型不做校验
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
chain.doFilter(req, resp);
return;
}
// 获取请求地址
String url = request.getRequestURI();
// 不需要授权的接口直接访问的地址
if (containsUrl(NOT_LOGIN_URL, url)) {
chain.doFilter(req, resp);
return;
}
String environment = request.getHeader("environment");
//token校验目前只对app生效
if(!environment.equals("app")){
chain.doFilter(req, resp);
return;
}
// 判断用户TOKEN是否存在
String token = request.getHeader("token");
if (StringUtils.isBlank(token)) {
Result result = new Result(CodeEnum.TOKEN_EXEIST);
String jsonString = JSONObject.toJSONString(result);
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
response.getWriter().print(jsonObject);
response.getWriter().flush();//流里边的缓存刷出
return;
}
//获取当前登录人的用户id
String loginName = TokenUtil.parseParamFromToken(token, "userId").toString();
//获取redis中的token
String message = redisUtil.getMessage(RedisCst.ONLINE_APP_USER.concat(loginName));
if(StringUtils.isBlank(message)){
Result result = new Result(CodeEnum.TOKEN_EXPIRED);
String jsonString = JSONObject.toJSONString(result);
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
response.getWriter().print(jsonObject);
response.getWriter().flush();//流里边的缓存刷出
return;
}
String redisToken = JSON.parseObject(message).getString("token");
if (!token.equals(redisToken)) {
Result result = new Result(CodeEnum.TOKEN_EXPIRED);
String jsonString = JSONObject.toJSONString(result);
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
response.getWriter().print(jsonObject);
response.getWriter().flush();//流里边的缓存刷出
return;
}
chain.doFilter(req, resp);
}
/**
* 判断url请求是否配置在urls列表中
*/
private boolean containsUrl(List<String> urls, String url) {
if (urls == null || urls.isEmpty()) {
return false;
}
for (String s : urls) {
if (s.endsWith("**")) {
if (url.startsWith("/" + s.substring(0, s.length() - 2))) {
return true;
}
} else {
if (url.equals("/" + s)) {
return true;
}
}
}
return false;
}
}

View File

@@ -10,6 +10,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.TbMerchantAccountMapper; import com.chaozhanggui.system.cashierservice.dao.TbMerchantAccountMapper;
import com.chaozhanggui.system.cashierservice.entity.TbMerchantAccount; import com.chaozhanggui.system.cashierservice.entity.TbMerchantAccount;
import com.chaozhanggui.system.cashierservice.entity.TbUserInfo;
import com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto; import com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto;
import com.chaozhanggui.system.cashierservice.entity.dto.OnlineUserDto; import com.chaozhanggui.system.cashierservice.entity.dto.OnlineUserDto;
import com.chaozhanggui.system.cashierservice.service.LoginService; import com.chaozhanggui.system.cashierservice.service.LoginService;
@@ -29,8 +30,7 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.HashMap; import java.util.*;
import java.util.Map;
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
@RestController @RestController
@@ -89,11 +89,6 @@ public class LoginContoller {
} }
@RequestMapping("/wx/custom/login") @RequestMapping("/wx/custom/login")
public Result wxCustomLogin(HttpServletRequest request, @RequestBody Map<String, String> map public Result wxCustomLogin(HttpServletRequest request, @RequestBody Map<String, String> map
// , // ,
@@ -102,23 +97,23 @@ public class LoginContoller {
) { ) {
if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map)||!map.containsKey("code")||ObjectUtil.isEmpty(map.get("code"))) { if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("code") || ObjectUtil.isEmpty(map.get("code"))) {
Result.fail("code不能为空"); Result.fail("code不能为空");
} }
String code=map.get("code").toString(); String code = map.get("code").toString();
String qrCode=map.get("qrCode"); String qrCode = map.get("qrCode");
String rawData=map.get("rawData"); String rawData = map.get("rawData");
String signature=map.get("signature"); String signature = map.get("signature");
String encryptedData=map.get("encryptedData"); String encryptedData = map.get("encryptedData");
String ivStr=map.get("iv"); String ivStr = map.get("iv");
String phone=map.get("phone"); String phone = map.get("phone");
// 用户非敏感信息rawData // 用户非敏感信息rawData
// 签名signature // 签名signature
@@ -136,11 +131,11 @@ public class LoginContoller {
return Result.fail("签名校验失败"); return Result.fail("签名校验失败");
} }
String nickName = rawDataJson.getString( "nickName"); String nickName = rawDataJson.getString("nickName");
String avatarUrl = rawDataJson.getString( "avatarUrl"); String avatarUrl = rawDataJson.getString("avatarUrl");
try { try {
return loginService.wxCustomLogin(openid, avatarUrl, nickName, phone,qrCode, IpUtil.getIpAddr(request)); return loginService.wxCustomLogin(openid, avatarUrl, nickName, phone, qrCode, IpUtil.getIpAddr(request));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -151,16 +146,16 @@ public class LoginContoller {
@RequestMapping("getPhoneNumber") @RequestMapping("getPhoneNumber")
public Result getPhoneNumber(@RequestBody Map<String,String> map){ public Result getPhoneNumber(@RequestBody Map<String, String> map) {
if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map)||!map.containsKey("code")||ObjectUtil.isEmpty(map.get("code"))) { if (ObjectUtil.isNull(map) || ObjectUtil.isEmpty(map) || !map.containsKey("code") || ObjectUtil.isEmpty(map.get("code"))) {
Result.fail("code不能为空"); Result.fail("code不能为空");
} }
String code=map.get("code").toString(); String code = map.get("code").toString();
String encryptedData=map.get("encryptedData"); String encryptedData = map.get("encryptedData");
String ivStr=map.get("iv"); String ivStr = map.get("iv");
JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code, customAppId, customSecrete); JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code, customAppId, customSecrete);
@@ -168,8 +163,8 @@ public class LoginContoller {
String openid = SessionKeyOpenId.getString("openid"); String openid = SessionKeyOpenId.getString("openid");
String sessionKey = SessionKeyOpenId.getString("session_key"); String sessionKey = SessionKeyOpenId.getString("session_key");
String data= WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr); String data = WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr);
if(ObjectUtil.isNotEmpty(data)&&JSONObject.parseObject(data).containsKey("phoneNumber")){ if (ObjectUtil.isNotEmpty(data) && JSONObject.parseObject(data).containsKey("phoneNumber")) {
return Result.success(CodeEnum.SUCCESS, JSONObject.parseObject(data).get("phoneNumber")); return Result.success(CodeEnum.SUCCESS, JSONObject.parseObject(data).get("phoneNumber"));
} }
return Result.fail("获取手机号失败"); return Result.fail("获取手机号失败");
@@ -196,34 +191,79 @@ public class LoginContoller {
//生成token //生成token
String token = StringUtil.genRandomNum(6) + StringUtil.getBillno() + StringUtil.genRandomNum(6); String token = StringUtil.genRandomNum(6) + StringUtil.getBillno() + StringUtil.genRandomNum(6);
//存入redis //存入redis
OnlineUserDto jwtUserDto = onlineUserService.save(merchantAccount.getName(), merchantAccount.getAccount(), Integer.valueOf(merchantAccount.getShopId()), token,merchantAccount.getStatus()); OnlineUserDto jwtUserDto = onlineUserService.save(merchantAccount.getName(), merchantAccount.getAccount(), Integer.valueOf(merchantAccount.getShopId()), token, merchantAccount.getStatus());
//组装登录数据 //组装登录数据
Map<String, Object> authInfo = new HashMap<String, Object>(2) {{ Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
put("token", token); put("token", token);
put("user", jwtUserDto); put("user", jwtUserDto);
}}; }};
return Result.success(CodeEnum.ENCRYPT,authInfo); return Result.success(CodeEnum.ENCRYPT, authInfo);
} }
/** /**
* 获取会员码 * 获取会员码
*
* @param openId * @param openId
* @param token * @param token
* @param id * @param id
* @return * @return
*/ */
@RequestMapping("createCardNo") @RequestMapping("createCardNo")
public Result createCardNo(@RequestHeader("openId") String openId,@RequestHeader("token") String token,@RequestHeader("id") String id){ public Result createCardNo(@RequestHeader("openId") String openId, @RequestHeader("token") String token, @RequestHeader("id") String id) {
return loginService.createCardNo(id,openId); return loginService.createCardNo(id, openId);
} }
@GetMapping("/wx/userInfo") @GetMapping("/wx/userInfo")
public Result userInfo(@RequestParam("userId") Integer userId,@RequestParam("shopId") String shopId ){ public Result userInfo(@RequestParam("userId") Integer userId, @RequestParam("shopId") String shopId) {
return loginService.userInfo(userId,shopId); return loginService.userInfo(userId, shopId);
} }
/**
* 用户注册
*
* @param phone 手机号
* @param nickName 用户昵称
* @param password 密码
* @param code 验证码
* @return
*/
@PostMapping("register")
public Result register(@RequestBody TbUserInfo userInfo) {
boolean tf = loginService.validate(userInfo.getCode(), userInfo.getTelephone());
if (tf) {
return loginService.register(userInfo.getTelephone(), userInfo.getPassword(), userInfo.getNickName());
} else {
return Result.fail("验证码校验失败");
}
}
/**
* App登录用户端的请求接口
*
* @param username 手机号
* @param password 密码登录时使用
* @param code 验证码登录时使用
* @return
*/
@PostMapping("/app/login")
public Result applogin(@RequestBody AuthUserDto authUserDto) {
if (ObjectUtil.isNull(authUserDto.getCode())) {
//验证密码
String mdPasswordString = MD5Utils.MD5Encode(authUserDto.getPassword(), "utf-8");
return loginService.appLogin(authUserDto.getUsername(), mdPasswordString);
} else {
boolean tf = loginService.validate(authUserDto.getCode(), authUserDto.getUsername());
if (tf) {
return loginService.appLogin(authUserDto.getUsername(), null);
} else {
return Result.fail("验证码输入有误");
}
}
}
} }

View File

@@ -7,8 +7,7 @@ import com.chaozhanggui.system.cashierservice.util.RedisUtils;
import com.chaozhanggui.system.cashierservice.util.StringUtil; import com.chaozhanggui.system.cashierservice.util.StringUtil;
import com.chaozhanggui.system.cashierservice.util.ValidateCodeUtil; import com.chaozhanggui.system.cashierservice.util.ValidateCodeUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy; import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@@ -40,7 +39,9 @@ public class PhoneValidateCodeController {
*/ */
@GetMapping @GetMapping
public Result verifyPhoneIsExist(@RequestParam String phone) { public Result verifyPhoneIsExist(@RequestParam String phone) {
if (StringUtils.isBlank(phone)) {
return Result.fail("手机号不可为空!");
}
String random = StringUtil.random(6); String random = StringUtil.random(6);
validateCodeUtil.requestValidateCodeAli(phone, random); validateCodeUtil.requestValidateCodeAli(phone, random);
//存入缓存 //存入缓存

View File

@@ -22,5 +22,20 @@ public interface TbUserInfoMapper {
TbUserInfo selectByOpenId(String openId); TbUserInfo selectByOpenId(String openId);
/**
* 通过手机号查询
* @param phone
* @param source 公众号 WECHAT 小程序 WECHAT-APP 手机注册 TELEPHONE 移动端 APP
* @return
*/
TbUserInfo selectUserByPhone(String phone,String source);
/**
* 查询来源为APP 未绑定微信用户的 用户数据
* @param phone
* @return
*/
TbUserInfo selectByPhone(String phone);
} }

View File

@@ -5,6 +5,7 @@ import java.math.BigDecimal;
public class TbUserInfo implements Serializable { public class TbUserInfo implements Serializable {
private Integer id; private Integer id;
private Integer userId;
private BigDecimal amount; private BigDecimal amount;
@@ -93,6 +94,7 @@ public class TbUserInfo implements Serializable {
private Long bindParentAt; private Long bindParentAt;
private String grandParentId; private String grandParentId;
private String password;
private String avatar = ""; private String avatar = "";
@@ -475,4 +477,20 @@ public class TbUserInfo implements Serializable {
public void setGrandParentId(String grandParentId) { public void setGrandParentId(String grandParentId) {
this.grandParentId = grandParentId == null ? null : grandParentId.trim(); this.grandParentId = grandParentId == null ? null : grandParentId.trim();
} }
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} }

View File

@@ -10,6 +10,7 @@ public class RedisCst {
//在线用户 //在线用户
public static final String ONLINE_USER = "ONLINE_USER:"; public static final String ONLINE_USER = "ONLINE_USER:";
public static final String ONLINE_APP_USER = "ONLINE_APP_USER:";
public static final String TABLE_CART = "TABLE:CART:"; public static final String TABLE_CART = "TABLE:CART:";
public static final String PRODUCT = "PRODUCT:"; public static final String PRODUCT = "PRODUCT:";

View File

@@ -9,17 +9,16 @@ import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil; import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.MD5Utils;
import com.chaozhanggui.system.cashierservice.util.TokenUtil; import com.chaozhanggui.system.cashierservice.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service @Service
public class LoginService { public class LoginService {
@@ -52,11 +51,11 @@ public class LoginService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public Result wxCustomLogin(String openId,String headImage,String nickName,String telephone,String qrCode,String ip) throws Exception { public Result wxCustomLogin(String openId, String headImage, String nickName, String telephone, String qrCode, String ip) throws Exception {
TbUserInfo userInfo= tbUserInfoMapper.selectByOpenId(openId); TbUserInfo userInfo = tbUserInfoMapper.selectByOpenId(openId);
if(ObjectUtil.isNull(userInfo)){ if (ObjectUtil.isNull(userInfo)) {
userInfo=new TbUserInfo(); userInfo = new TbUserInfo();
userInfo.setAmount(BigDecimal.ZERO); userInfo.setAmount(BigDecimal.ZERO);
userInfo.setChargeAmount(BigDecimal.ZERO); userInfo.setChargeAmount(BigDecimal.ZERO);
@@ -65,9 +64,9 @@ public class LoginService {
userInfo.setConsumeAmount(BigDecimal.ZERO); userInfo.setConsumeAmount(BigDecimal.ZERO);
userInfo.setTotalScore(0); userInfo.setTotalScore(0);
userInfo.setLockScore(0); userInfo.setLockScore(0);
userInfo.setHeadImg(ObjectUtil.isNotNull(headImage)?headImage:""); userInfo.setHeadImg(ObjectUtil.isNotNull(headImage) ? headImage : "");
userInfo.setNickName(ObjectUtil.isNotNull(nickName)?nickName:"微信用户"); userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户");
userInfo.setTelephone(ObjectUtil.isNotNull(telephone)?telephone:""); userInfo.setTelephone(ObjectUtil.isNotNull(telephone) ? telephone : "");
userInfo.setMiniAppOpenId(openId); userInfo.setMiniAppOpenId(openId);
userInfo.setStatus(Byte.parseByte("1")); userInfo.setStatus(Byte.parseByte("1"));
userInfo.setParentType("PERSON"); userInfo.setParentType("PERSON");
@@ -82,31 +81,39 @@ public class LoginService {
userInfo.setUpdatedAt(System.currentTimeMillis()); userInfo.setUpdatedAt(System.currentTimeMillis());
tbUserInfoMapper.insert(userInfo); tbUserInfoMapper.insert(userInfo);
}else { } else {
userInfo.setHeadImg(ObjectUtil.isNotNull(headImage)?headImage:""); userInfo.setHeadImg(ObjectUtil.isNotNull(headImage) ? headImage : "");
userInfo.setNickName(ObjectUtil.isNotNull(nickName)?nickName:"微信用户"); userInfo.setNickName(ObjectUtil.isNotNull(nickName) ? nickName : "微信用户");
userInfo.setTelephone(ObjectUtil.isNotNull(telephone)?telephone:""); userInfo.setTelephone(ObjectUtil.isNotNull(telephone) ? telephone : "");
tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); tbUserInfoMapper.updateByPrimaryKeySelective(userInfo);
} }
//app与微信用户 互相关联
if (ObjectUtil.isNotNull(telephone)) {
TbUserInfo appUser = tbUserInfoMapper.selectByPhone(telephone);
if (appUser != null) {
TbUserInfo wechatUser = tbUserInfoMapper.selectByOpenId(openId);
appUser.setUserId(wechatUser.getId());
tbUserInfoMapper.updateByPrimaryKey(appUser);
wechatUser.setUserId(appUser.getId());
tbUserInfoMapper.updateByPrimaryKey(wechatUser);
}
}
TbShopInfo tbShopInfo = null;
if (ObjectUtil.isEmpty(qrCode)) {
tbShopInfo = tbShopInfoMapper.selectByPhone(defaultPhone);
TbShopInfo tbShopInfo=null; } else {
if(ObjectUtil.isEmpty(qrCode)){ tbShopInfo = tbShopInfoMapper.selectByQrCode(qrCode);
tbShopInfo=tbShopInfoMapper.selectByPhone(defaultPhone);
}else {
tbShopInfo= tbShopInfoMapper.selectByQrCode(qrCode);
} }
TbShopUser tbShopUser = null;
TbShopUser tbShopUser=null; Map<String, String> shopMap = new HashMap<>();
Map<String,String> shopMap=new HashMap<>(); if (ObjectUtil.isNotEmpty(tbShopInfo)) {
if(ObjectUtil.isNotEmpty(tbShopInfo)){ tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(userInfo.getId().toString(), tbShopInfo.getId().toString());
tbShopUser= tbShopUserMapper.selectByUserIdAndShopId(userInfo.getId().toString(),tbShopInfo.getId().toString()); if (ObjectUtil.isEmpty(tbShopUser)) {
if(ObjectUtil.isEmpty(tbShopUser)){ tbShopUser = new TbShopUser();
tbShopUser=new TbShopUser();
tbShopUser.setAmount(BigDecimal.ZERO); tbShopUser.setAmount(BigDecimal.ZERO);
tbShopUser.setCreditAmount(BigDecimal.ZERO); tbShopUser.setCreditAmount(BigDecimal.ZERO);
tbShopUser.setConsumeAmount(BigDecimal.ZERO); tbShopUser.setConsumeAmount(BigDecimal.ZERO);
@@ -119,32 +126,31 @@ public class LoginService {
tbShopUser.setCreatedAt(System.currentTimeMillis()); tbShopUser.setCreatedAt(System.currentTimeMillis());
tbShopUserMapper.insert(tbShopUser); tbShopUserMapper.insert(tbShopUser);
} }
shopMap.put("shopId",tbShopUser.getShopId()); shopMap.put("shopId", tbShopUser.getShopId());
shopMap.put("name",tbShopInfo.getShopName()); shopMap.put("name", tbShopInfo.getShopName());
shopMap.put("amount",BigDecimal.ZERO.toPlainString()); shopMap.put("amount", BigDecimal.ZERO.toPlainString());
shopMap.put("levelConsume",BigDecimal.ZERO.toPlainString()); shopMap.put("levelConsume", BigDecimal.ZERO.toPlainString());
} }
//生成token 信息 //生成token 信息
String token = TokenUtil.generateToken(userInfo.getId(), userInfo.getMiniAppOpenId(), userInfo.getTelephone(),userInfo.getNickName()); String token = TokenUtil.generateToken(userInfo.getId(), userInfo.getMiniAppOpenId(), userInfo.getTelephone(), userInfo.getNickName());
//存储登录记录 //存储登录记录
TbToken tbToken = new TbToken(tbShopInfo.getId(), userInfo.getId(),"wx_lite", token, ip, "1", new Date()); TbToken tbToken = new TbToken(tbShopInfo.getId(), userInfo.getId(), "wx_lite", token, ip, "1", new Date());
tbTokenMapper.insert(tbToken); tbTokenMapper.insert(tbToken);
Map<String, Object> map = new HashMap<>();
Map<String,Object> map=new HashMap<>();
try { try {
map.put("token",token); map.put("token", token);
map.put("userInfo",userInfo); map.put("userInfo", userInfo);
map.put("shopUser",shopMap); map.put("shopUser", shopMap);
map.put("shopInfo",tbShopInfo); map.put("shopInfo", tbShopInfo);
redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map)); redisUtil.saveMessage(RedisCst.ONLINE_USER.concat(openId), JSON.toJSONString(map));
return Result.success(CodeEnum.SUCCESS,map); return Result.success(CodeEnum.SUCCESS, map);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -152,67 +158,159 @@ public class LoginService {
return Result.fail("登录失败"); return Result.fail("登录失败");
} }
public Result register(String phone, String password, String nickName) {
TbUserInfo userInfo = tbUserInfoMapper.selectByPhone(phone);
if (ObjectUtil.isNull(userInfo)) {
userInfo = new TbUserInfo();
userInfo.setAmount(BigDecimal.ZERO);
userInfo.setChargeAmount(BigDecimal.ZERO);
userInfo.setLineOfCredit(BigDecimal.ZERO);
userInfo.setConsumeNumber(0);
userInfo.setConsumeAmount(BigDecimal.ZERO);
userInfo.setTotalScore(0);
userInfo.setLockScore(0);
userInfo.setHeadImg("");
userInfo.setNickName(nickName);
userInfo.setTelephone(phone);
userInfo.setStatus(Byte.parseByte("1"));
userInfo.setParentType("PERSON");
userInfo.setIsResource(Byte.parseByte("0"));
userInfo.setIsOnline(Byte.parseByte("0"));
userInfo.setIsVip(Byte.parseByte("0"));
userInfo.setSourcePath("APP");
userInfo.setIsAttentionMp(Byte.parseByte("0"));
userInfo.setSearchWord("||移动端用户");
userInfo.setLastLogInAt(System.currentTimeMillis());
userInfo.setCreatedAt(System.currentTimeMillis());
userInfo.setUpdatedAt(System.currentTimeMillis());
userInfo.setPassword(MD5Utils.MD5Encode(password, "UTF-8"));
tbUserInfoMapper.insert(userInfo);
} else {
return Result.fail("用户已注册");
}
//app与微信小程序用户关联
public Result createCardNo(String id,String openId){ TbUserInfo wechatUser = tbUserInfoMapper.selectUserByPhone(phone, "WECHAT-APP");
if(ObjectUtil.isEmpty(id)||ObjectUtil.isEmpty(openId)){ if (wechatUser != null) {
TbUserInfo appUser = tbUserInfoMapper.selectByPhone(phone);
appUser.setUserId(wechatUser.getId());
tbUserInfoMapper.updateByPrimaryKey(appUser);
wechatUser.setUserId(appUser.getId());
tbUserInfoMapper.updateByPrimaryKey(wechatUser);
}
return Result.success(CodeEnum.SUCCESS);
}
/**
* 手机号 短信验证码 校验
*
* @param code
* @param phone
* @return
*/
public boolean validate(String code, String phone) {
if (StringUtils.isNotBlank(code)) {
String message = redisUtil.getMessage(phone);
boolean tf = Objects.equals(code, message);
if (tf) {
redisUtil.deleteByKey(phone);
return true;
}
}
return false;
}
@Transactional(rollbackFor = Exception.class)
public Result appLogin(String username, String password) {
TbUserInfo userInfo = tbUserInfoMapper.selectUserByPhone(username, "APP");
if (ObjectUtil.isNull(userInfo)) {
return Result.fail("用户未注册");
}
if (StringUtils.isNotBlank(password) && !password.equalsIgnoreCase(userInfo.getPassword())) {
return Result.fail("密码错误");
}
//生成token 信息
String token = null;
try {
token = TokenUtil.generateToken(userInfo.getId(), null, userInfo.getTelephone(), userInfo.getNickName());
} catch (Exception e) {
throw new RuntimeException(e);
}
Map<String, Object> map = new HashMap<>();
try {
map.put("token", token);
map.put("userInfo", userInfo);
redisUtil.saveMessage(RedisCst.ONLINE_APP_USER.concat(userInfo.getId()+""), JSON.toJSONString(map));
return Result.success(CodeEnum.SUCCESS, map);
} catch (Exception e) {
e.printStackTrace();
}
return Result.fail("登录失败");
}
public Result createCardNo(String id, String openId) {
if (ObjectUtil.isEmpty(id) || ObjectUtil.isEmpty(openId)) {
return Result.fail("head 信息不允许为空"); return Result.fail("head 信息不允许为空");
} }
TbUserInfo userInfo= tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(id)); TbUserInfo userInfo = tbUserInfoMapper.selectByPrimaryKey(Integer.valueOf(id));
if(userInfo==null||ObjectUtil.isEmpty(userInfo)){ if (userInfo == null || ObjectUtil.isEmpty(userInfo)) {
userInfo=tbUserInfoMapper.selectByOpenId(openId); userInfo = tbUserInfoMapper.selectByOpenId(openId);
} }
if(userInfo==null||ObjectUtil.isEmpty(userInfo)){ if (userInfo == null || ObjectUtil.isEmpty(userInfo)) {
return Result.fail("用户信息不存在"); return Result.fail("用户信息不存在");
} }
String cardNo= RandomUtil.randomNumbers(10); String cardNo = RandomUtil.randomNumbers(10);
userInfo.setCardNo(cardNo); userInfo.setCardNo(cardNo);
userInfo.setUpdatedAt(System.currentTimeMillis()); userInfo.setUpdatedAt(System.currentTimeMillis());
tbUserInfoMapper.updateByPrimaryKeySelective(userInfo); tbUserInfoMapper.updateByPrimaryKeySelective(userInfo);
return Result.success(CodeEnum.SUCCESS,cardNo) ; return Result.success(CodeEnum.SUCCESS, cardNo);
} }
public Result userInfo(Integer userId,String shopId){ public Result userInfo(Integer userId, String shopId) {
TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(userId); TbUserInfo tbUserInfo = tbUserInfoMapper.selectByPrimaryKey(userId);
if (tbUserInfo == null){ if (tbUserInfo == null) {
return Result.success(CodeEnum.ENCRYPT,new ArrayList()); return Result.success(CodeEnum.ENCRYPT, new ArrayList());
} }
TbShopInfo tbShopInfo=null; TbShopInfo tbShopInfo = null;
if(ObjectUtil.isEmpty(shopId)){ if (ObjectUtil.isEmpty(shopId)) {
tbShopInfo=tbShopInfoMapper.selectByPhone(defaultPhone); tbShopInfo = tbShopInfoMapper.selectByPhone(defaultPhone);
}else { } else {
tbShopInfo=tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(shopId)); tbShopInfo = tbShopInfoMapper.selectByPrimaryKey(Integer.valueOf(shopId));
} }
TbShopUser tbShopUser=null; TbShopUser tbShopUser = null;
Map<String,String> shopMap=new HashMap<>(); Map<String, String> shopMap = new HashMap<>();
if(ObjectUtil.isNotEmpty(tbShopInfo)){ if (ObjectUtil.isNotEmpty(tbShopInfo)) {
tbShopUser= tbShopUserMapper.selectByUserIdAndShopId(tbUserInfo.getId().toString(),tbShopInfo.getId().toString()); tbShopUser = tbShopUserMapper.selectByUserIdAndShopId(tbUserInfo.getId().toString(), tbShopInfo.getId().toString());
shopMap.put("shopId",tbShopUser.getShopId()); shopMap.put("shopId", tbShopUser.getShopId());
shopMap.put("name",tbShopInfo.getShopName()); shopMap.put("name", tbShopInfo.getShopName());
shopMap.put("amount",BigDecimal.ZERO.toPlainString()); shopMap.put("amount", BigDecimal.ZERO.toPlainString());
shopMap.put("levelConsume",BigDecimal.ZERO.toPlainString()); shopMap.put("levelConsume", BigDecimal.ZERO.toPlainString());
} }
Map<String,Object> map=new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("userInfo",tbUserInfo); map.put("userInfo", tbUserInfo);
map.put("shopUser",shopMap); map.put("shopUser", shopMap);
map.put("shopInfo",tbShopInfo); map.put("shopInfo", tbShopInfo);
return Result.success(CodeEnum.ENCRYPT,map); return Result.success(CodeEnum.ENCRYPT, map);
} }
public static void main(String[] args){
for(int i =0;i<10;i++){ public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(RandomUtil.randomNumbers(10)); System.out.println(RandomUtil.randomNumbers(10));
} }
} }

View File

@@ -38,7 +38,7 @@ public class OnlineUserService {
onlineUserDto.setLoginTime(new Date()); onlineUserDto.setLoginTime(new Date());
onlineUserDto.setShopId(shopId); onlineUserDto.setShopId(shopId);
try { try {
// redisUtils.set("online-token-"+token, onlineUserDto, MILLIS_MINUTE); redisUtils.set("online-token-"+token, onlineUserDto, MILLIS_MINUTE);//30分钟
}catch (Exception e){ }catch (Exception e){
throw new MsgException("登录错误"); throw new MsgException("登录错误");
} }

View File

@@ -7,6 +7,8 @@ public enum CodeEnum {
SUCCESS("0",false,"成功","success"), SUCCESS("0",false,"成功","success"),
ENCRYPT("0",true,"成功","success"), ENCRYPT("0",true,"成功","success"),
FAIL("1",false,"失败","fail"), FAIL("1",false,"失败","fail"),
TOKEN_EXEIST("-2",false,"token不能为空","fail"),
TOKEN_EXPIRED("-4",false,"账号已过期,请重新登陆","fail"),
SIGN_FAIL("100013",false,"签名不正确","fail"), SIGN_FAIL("100013",false,"签名不正确","fail"),
ORGAN_NO_EXEIST("100010",false,"机构代码不存在或状态异常,请联系服务商","fail"), ORGAN_NO_EXEIST("100010",false,"机构代码不存在或状态异常,请联系服务商","fail"),

View File

@@ -3,6 +3,7 @@
<mapper namespace="com.chaozhanggui.system.cashierservice.dao.TbUserInfoMapper"> <mapper namespace="com.chaozhanggui.system.cashierservice.dao.TbUserInfoMapper">
<resultMap id="BaseResultMap" type="com.chaozhanggui.system.cashierservice.entity.TbUserInfo"> <resultMap id="BaseResultMap" type="com.chaozhanggui.system.cashierservice.entity.TbUserInfo">
<id column="id" jdbcType="INTEGER" property="id" /> <id column="id" jdbcType="INTEGER" property="id" />
<id column="user_id" jdbcType="INTEGER" property="userId" />
<result column="amount" jdbcType="DECIMAL" property="amount" /> <result column="amount" jdbcType="DECIMAL" property="amount" />
<result column="charge_amount" jdbcType="DECIMAL" property="chargeAmount" /> <result column="charge_amount" jdbcType="DECIMAL" property="chargeAmount" />
<result column="line_of_credit" jdbcType="DECIMAL" property="lineOfCredit" /> <result column="line_of_credit" jdbcType="DECIMAL" property="lineOfCredit" />
@@ -47,15 +48,16 @@
<result column="updated_at" jdbcType="BIGINT" property="updatedAt" /> <result column="updated_at" jdbcType="BIGINT" property="updatedAt" />
<result column="bind_parent_at" jdbcType="BIGINT" property="bindParentAt" /> <result column="bind_parent_at" jdbcType="BIGINT" property="bindParentAt" />
<result column="grand_parent_id" jdbcType="VARCHAR" property="grandParentId" /> <result column="grand_parent_id" jdbcType="VARCHAR" property="grandParentId" />
<result column="password" jdbcType="VARCHAR" property="password" />
</resultMap> </resultMap>
<sql id="Base_Column_List"> <sql id="Base_Column_List">
id, amount, charge_amount, line_of_credit, consume_amount, consume_number, total_score, id,user_id, amount, charge_amount, line_of_credit, consume_amount, consume_number, total_score,
lock_score, card_no, card_password, level_id, head_img, nick_name, telephone, wx_ma_app_id, lock_score, card_no, card_password, level_id, head_img, nick_name, telephone, wx_ma_app_id,
birth_day, sex, mini_app_open_id, open_id, union_id, code, type, identify, status, birth_day, sex, mini_app_open_id, open_id, union_id, code, type, identify, status,
parent_id, parent_level, parent_type, project_id, merchant_id, is_resource, is_online, parent_id, parent_level, parent_type, project_id, merchant_id, is_resource, is_online,
is_vip, vip_effect_at, tips, source_path, is_sales_person, is_attention_mp, city, is_vip, vip_effect_at, tips, source_path, is_sales_person, is_attention_mp, city,
search_word, last_log_in_at, last_leave_at, created_at, updated_at, bind_parent_at, search_word, last_log_in_at, last_leave_at, created_at, updated_at, bind_parent_at,
grand_parent_id grand_parent_id,password
</sql> </sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select select
@@ -69,7 +71,7 @@
</delete> </delete>
<insert id="insert" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo" useGeneratedKeys="true" keyProperty="id"> <insert id="insert" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo" useGeneratedKeys="true" keyProperty="id">
insert into tb_user_info (id, amount, charge_amount, insert into tb_user_info (id,user_id, amount, charge_amount,
line_of_credit, consume_amount, consume_number, line_of_credit, consume_amount, consume_number,
total_score, lock_score, card_no, total_score, lock_score, card_no,
card_password, level_id, head_img, card_password, level_id, head_img,
@@ -83,9 +85,9 @@
tips, source_path, is_sales_person, tips, source_path, is_sales_person,
is_attention_mp, city, search_word, is_attention_mp, city, search_word,
last_log_in_at, last_leave_at, created_at, last_log_in_at, last_leave_at, created_at,
updated_at, bind_parent_at, grand_parent_id updated_at, bind_parent_at, grand_parent_id,password
) )
values (#{id,jdbcType=INTEGER}, #{amount,jdbcType=DECIMAL}, #{chargeAmount,jdbcType=DECIMAL}, values (#{id,jdbcType=INTEGER},#{userId,jdbcType=INTEGER}, #{amount,jdbcType=DECIMAL}, #{chargeAmount,jdbcType=DECIMAL},
#{lineOfCredit,jdbcType=DECIMAL}, #{consumeAmount,jdbcType=DECIMAL}, #{consumeNumber,jdbcType=INTEGER}, #{lineOfCredit,jdbcType=DECIMAL}, #{consumeAmount,jdbcType=DECIMAL}, #{consumeNumber,jdbcType=INTEGER},
#{totalScore,jdbcType=INTEGER}, #{lockScore,jdbcType=INTEGER}, #{cardNo,jdbcType=VARCHAR}, #{totalScore,jdbcType=INTEGER}, #{lockScore,jdbcType=INTEGER}, #{cardNo,jdbcType=VARCHAR},
#{cardPassword,jdbcType=VARCHAR}, #{levelId,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR}, #{cardPassword,jdbcType=VARCHAR}, #{levelId,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR},
@@ -99,7 +101,7 @@
#{tips,jdbcType=VARCHAR}, #{sourcePath,jdbcType=VARCHAR}, #{isSalesPerson,jdbcType=TINYINT}, #{tips,jdbcType=VARCHAR}, #{sourcePath,jdbcType=VARCHAR}, #{isSalesPerson,jdbcType=TINYINT},
#{isAttentionMp,jdbcType=TINYINT}, #{city,jdbcType=VARCHAR}, #{searchWord,jdbcType=VARCHAR}, #{isAttentionMp,jdbcType=TINYINT}, #{city,jdbcType=VARCHAR}, #{searchWord,jdbcType=VARCHAR},
#{lastLogInAt,jdbcType=BIGINT}, #{lastLeaveAt,jdbcType=BIGINT}, #{createdAt,jdbcType=BIGINT}, #{lastLogInAt,jdbcType=BIGINT}, #{lastLeaveAt,jdbcType=BIGINT}, #{createdAt,jdbcType=BIGINT},
#{updatedAt,jdbcType=BIGINT}, #{bindParentAt,jdbcType=BIGINT}, #{grandParentId,jdbcType=VARCHAR} #{updatedAt,jdbcType=BIGINT}, #{bindParentAt,jdbcType=BIGINT}, #{grandParentId,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
) )
</insert> </insert>
<insert id="insertSelective" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo"> <insert id="insertSelective" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo">
@@ -108,6 +110,9 @@
<if test="id != null"> <if test="id != null">
id, id,
</if> </if>
<if test="userId != null and userId != ''">
user_id,
</if>
<if test="amount != null"> <if test="amount != null">
amount, amount,
</if> </if>
@@ -240,11 +245,17 @@
<if test="grandParentId != null"> <if test="grandParentId != null">
grand_parent_id, grand_parent_id,
</if> </if>
<if test="password != null and password != ''">
password
</if>
</trim> </trim>
<trim prefix="values (" suffix=")" suffixOverrides=","> <trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null"> <if test="id != null">
#{id,jdbcType=INTEGER}, #{id,jdbcType=INTEGER},
</if> </if>
<if test="userId != null and userId != ''">
#{userId,jdbcType=INTEGER},
</if>
<if test="amount != null"> <if test="amount != null">
#{amount,jdbcType=DECIMAL}, #{amount,jdbcType=DECIMAL},
</if> </if>
@@ -377,11 +388,17 @@
<if test="grandParentId != null"> <if test="grandParentId != null">
#{grandParentId,jdbcType=VARCHAR}, #{grandParentId,jdbcType=VARCHAR},
</if> </if>
<if test="password != null and password != ''">
#{password,jdbcType=VARCHAR}
</if>
</trim> </trim>
</insert> </insert>
<update id="updateByPrimaryKeySelective" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo"> <update id="updateByPrimaryKeySelective" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo">
update tb_user_info update tb_user_info
<set> <set>
<if test="userId != null and userId != ''">
user_id = #{userId,jdbcType=INTEGER},
</if>
<if test="amount != null"> <if test="amount != null">
amount = #{amount,jdbcType=DECIMAL}, amount = #{amount,jdbcType=DECIMAL},
</if> </if>
@@ -514,12 +531,16 @@
<if test="grandParentId != null"> <if test="grandParentId != null">
grand_parent_id = #{grandParentId,jdbcType=VARCHAR}, grand_parent_id = #{grandParentId,jdbcType=VARCHAR},
</if> </if>
<if test="password != null and password != ''">
password = #{password,jdbcType=VARCHAR},
</if>
</set> </set>
where id = #{id,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER}
</update> </update>
<update id="updateByPrimaryKey" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo"> <update id="updateByPrimaryKey" parameterType="com.chaozhanggui.system.cashierservice.entity.TbUserInfo">
update tb_user_info update tb_user_info
set amount = #{amount,jdbcType=DECIMAL}, set user_id = #{userId,jdbcType=INTEGER},
amount = #{amount,jdbcType=DECIMAL},
charge_amount = #{chargeAmount,jdbcType=DECIMAL}, charge_amount = #{chargeAmount,jdbcType=DECIMAL},
line_of_credit = #{lineOfCredit,jdbcType=DECIMAL}, line_of_credit = #{lineOfCredit,jdbcType=DECIMAL},
consume_amount = #{consumeAmount,jdbcType=DECIMAL}, consume_amount = #{consumeAmount,jdbcType=DECIMAL},
@@ -562,7 +583,8 @@
created_at = #{createdAt,jdbcType=BIGINT}, created_at = #{createdAt,jdbcType=BIGINT},
updated_at = #{updatedAt,jdbcType=BIGINT}, updated_at = #{updatedAt,jdbcType=BIGINT},
bind_parent_at = #{bindParentAt,jdbcType=BIGINT}, bind_parent_at = #{bindParentAt,jdbcType=BIGINT},
grand_parent_id = #{grandParentId,jdbcType=VARCHAR} grand_parent_id = #{grandParentId,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER}
</update> </update>
@@ -571,4 +593,12 @@
select * from tb_user_info where mini_app_open_id=#{openId} select * from tb_user_info where mini_app_open_id=#{openId}
</select> </select>
<select id="selectUserByPhone" resultMap="BaseResultMap">
select * from tb_user_info where telephone=#{phone} AND source_path=#{source}
</select>
<select id="selectByPhone" resultMap="BaseResultMap">
select * from tb_user_info where telephone=#{phone} AND source_path='APP' AND user_id is null
</select>
</mapper> </mapper>