app 用户登录 用户注册 退出

redis 5库 token的key为ONLINE_APP_USER:用户id
app端 登录校验 code -4 账号过期
app端 版本是否更新校验
 redis 5库 版本是否更新的key为LDBL_APP_VERSION:android/ios:版本号
全局跨域放行处理
经纬度计算距离工作类
This commit is contained in:
2024-04-03 10:51:46 +08:00
parent fc3d04ca33
commit 976f63d09c
8 changed files with 231 additions and 68 deletions

View File

@@ -37,6 +37,7 @@ public class LoginFilter implements Filter {
"css/**",
"js/**",
"cashierService/phoneValidateCode",//验证码
"cashierService/tbPlatformDict",//
"cashierService/home/homePageUp",//首页上半
"cashierService/home",//首页
"cashierService/login/**"//登录部分接口不校验
@@ -68,14 +69,14 @@ public class LoginFilter implements Filter {
}
String environment = request.getHeader("environment");
//token校验目前只对app生效
if(!environment.equals("app")){
if (StringUtils.isNotBlank(environment) || !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);
Result result = new Result(CodeEnum.TOKEN_EXEIST);
String jsonString = JSONObject.toJSONString(result);
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
response.getWriter().print(jsonObject);
@@ -86,8 +87,8 @@ public class LoginFilter implements Filter {
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);
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);
@@ -96,7 +97,7 @@ public class LoginFilter implements Filter {
}
String redisToken = JSON.parseObject(message).getString("token");
if (!token.equals(redisToken)) {
Result result = new Result(CodeEnum.TOKEN_EXPIRED);
Result result = new Result(CodeEnum.TOKEN_EXPIRED);
String jsonString = JSONObject.toJSONString(result);
JSONObject jsonObject = JSONObject.parseObject(jsonString, JSONObject.class);
response.getWriter().print(jsonObject);

View File

@@ -0,0 +1,61 @@
package com.chaozhanggui.system.cashierservice.config;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chaozhanggui.system.cashierservice.sign.Result;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* 方法调用统一切面处理
*/
@Aspect
@Component
@Slf4j
public class AppApiMethodAspect {
@Autowired
RedisUtil redisUtil;
@Pointcut("execution(public * (" +
"com.chaozhanggui.system.cashierservice.controller.* " +
").*(..))")
public void pkg() {
}
@Around("pkg()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
HttpServletRequest req = request;
//version版本号
//type: ios; android;
//environment:app;wx
String environment = req.getHeader("environment");
if (StringUtils.isNotBlank(environment) && environment.equals("app")) {
String type = req.getHeader("type");
String version = req.getHeader("version");
//LDBL_APP_VERSION:ios:version 存在即需要强制更新
String message = redisUtil.getMessage(RedisCst.LDBL_APP_VERSION + type + ":" + version);
if (StringUtils.isNotBlank(message)) {
return Result.success(CodeEnum.UPGRADE_REQUIRED, message);
}
}
// 执行被拦截的方法
Object result = pjp.proceed();
return result;
}
}

View File

@@ -0,0 +1,35 @@
package com.chaozhanggui.system.cashierservice.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
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;
/**
* 跨域过滤器
*/
@Slf4j
@Component
@Order(1)
@WebFilter(filterName = "CorsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest reqs = (HttpServletRequest) req;
String curOrigin = reqs.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,signature");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
}
}

View File

@@ -1,36 +1,35 @@
package com.chaozhanggui.system.cashierservice.controller;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chaozhanggui.system.cashierservice.dao.TbMerchantAccountMapper;
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.OnlineUserDto;
import com.chaozhanggui.system.cashierservice.redis.RedisCst;
import com.chaozhanggui.system.cashierservice.redis.RedisUtil;
import com.chaozhanggui.system.cashierservice.service.LoginService;
import com.chaozhanggui.system.cashierservice.service.OnlineUserService;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.IpUtil;
import com.chaozhanggui.system.cashierservice.util.JSONUtil;
import com.chaozhanggui.system.cashierservice.util.MD5Utils;
import com.chaozhanggui.system.cashierservice.util.StringUtil;
import com.chaozhanggui.system.cashierservice.util.TokenUtil;
import com.chaozhanggui.system.cashierservice.wxUtil.WechatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin(origins = "*")
@RestController
@@ -58,6 +57,8 @@ public class LoginContoller {
@Resource
TbMerchantAccountMapper merchantAccountMapper;
@Autowired
RedisUtil redisUtil;
@RequestMapping("/wx/business/login")
@@ -223,35 +224,37 @@ public class LoginContoller {
/**
* 用户注册
*
* @param phone 手机号
* @param nickName 用户昵称
* @param password 密
* @param code 验证码
* phone 手机号
* nickName 用户昵称
* password 密码
* 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("验证码校验失败");
}
}
// @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 验证码登录时使用
* App登录用户端的请求接口 登录即注册
* 查看 {@link com.chaozhanggui.system.cashierservice.entity.dto.AuthUserDto}
* username 手机号
* password 密码登录时使用
* code 验证码登录时使用
* @return
*/
@PostMapping("/app/login")
public Result applogin(@RequestBody AuthUserDto authUserDto) {
if (ObjectUtil.isNull(authUserDto.getCode())) {
if(StringUtils.isBlank(authUserDto.getPassword())){
return Result.fail("请输入密码,或使用验证码登录");
}
//验证密码
String mdPasswordString = MD5Utils.MD5Encode(authUserDto.getPassword(), "utf-8");
return loginService.appLogin(authUserDto.getUsername(), mdPasswordString);
@@ -266,4 +269,15 @@ public class LoginContoller {
}
//退出登录的接口
@PostMapping("/loginOut")
public Result loginOut(HttpServletRequest request) {
String token = request.getHeader("token");
//获取当前登录人的账号
String userId = TokenUtil.parseParamFromToken(token, "userId").toString();
redisUtil.deleteByKey(RedisCst.ONLINE_APP_USER.concat(userId));
return Result.success(CodeEnum.SUCCESS);
}
}

View File

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

View File

@@ -45,7 +45,6 @@ public class LoginService {
TbTokenMapper tbTokenMapper;
@Autowired
RedisUtil redisUtil;
@@ -158,49 +157,44 @@ public class LoginService {
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());
public TbUserInfo register(String phone, String password, String nickName) {
TbUserInfo 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());
if(StringUtils.isNotBlank(password)){
userInfo.setPassword(MD5Utils.MD5Encode(password, "UTF-8"));
tbUserInfoMapper.insert(userInfo);
} else {
return Result.fail("用户已注册");
}
//app与微信小程序用户关联
tbUserInfoMapper.insert(userInfo);
//注册时 app与微信小程序用户关联
TbUserInfo wechatUser = tbUserInfoMapper.selectUserByPhone(phone, "WECHAT-APP");
TbUserInfo appUser = tbUserInfoMapper.selectByPhone(phone);
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);
return appUser;
}
/**
@@ -226,7 +220,8 @@ public class LoginService {
public Result appLogin(String username, String password) {
TbUserInfo userInfo = tbUserInfoMapper.selectUserByPhone(username, "APP");
if (ObjectUtil.isNull(userInfo)) {
return Result.fail("用户未注册");
//注册
userInfo=register(username, password, username);
}
if (StringUtils.isNotBlank(password) && !password.equalsIgnoreCase(userInfo.getPassword())) {
return Result.fail("密码错误");
@@ -242,7 +237,7 @@ public class LoginService {
try {
map.put("token", token);
map.put("userInfo", userInfo);
redisUtil.saveMessage(RedisCst.ONLINE_APP_USER.concat(userInfo.getId()+""), JSON.toJSONString(map));
redisUtil.saveMessage(RedisCst.ONLINE_APP_USER.concat(userInfo.getId() + ""), JSON.toJSONString(map));
return Result.success(CodeEnum.SUCCESS, map);
} catch (Exception e) {
e.printStackTrace();

View File

@@ -5,6 +5,7 @@ public enum CodeEnum {
//系统编码
SYS_EXCEPTION("999",false,"系统异常","fail"),
SUCCESS("0",false,"成功","success"),
UPGRADE_REQUIRED("426",true,"成功","success"),
ENCRYPT("0",true,"成功","success"),
FAIL("1",false,"失败","fail"),
TOKEN_EXEIST("-2",false,"token不能为空","fail"),

View File

@@ -0,0 +1,55 @@
package com.chaozhanggui.system.cashierservice.util;
import static java.lang.Math.*;
import static java.lang.Math.sin;
public class LocationUtils {
/**
* 将角度转化为弧度
*/
public static double radians(double d) {
return d * Math.PI / 180.0;
}
/**
* 根据两点经纬度坐标计算直线距离
* <p>
* S = 2arcsin√sin²(a/2)+cos(lat1)*cos(lat2)*sin²(b/2) ̄*6378.137
* <p>
* 1. lng1 lat1 表示A点经纬度lng2 lat2 表示B点经纬度<br>
* 2. a=lat1 lat2 为两点纬度之差 b=lng1 -lng2 为两点经度之差;<br>
* 3. 6378.137为地球赤道半径,单位为千米;
*
* @param lng1 点1经度
* @param lat1 点1纬度
* @param lng2 点2经度
* @param lat2 点2纬度
* @return 距离,单位千米(KM)
* @see <a href="https://zh.wikipedia.org/wiki/%E5%8D%8A%E6%AD%A3%E7%9F%A2%E5%85%AC%E5%BC%8F">半正矢(Haversine)公式</a>
*/
public static double getDistanceFrom2LngLat(double lng1, double lat1, double lng2, double lat2) {
//将角度转化为弧度
double radLng1 = radians(lng1);
double radLat1 = radians(lat1);
double radLng2 = radians(lng2);
double radLat2 = radians(lat2);
double a = radLat1 - radLat2;
double b = radLng1 - radLng2;
return 2 * asin(sqrt(sin(a / 2) * sin(a / 2) + cos(radLat1) * cos(radLat2) * sin(b / 2) * sin(b / 2))) * 6378.137;
}
// public static void main(String[] args) {
// // 示例经纬度坐标
// double lat1 = 108.954398;
// double lon1 = 34.308687;
//
// double lat2 = 108.953555;
// double lon2 = 34.276169;
//
// // 计算距离
// double distance = getDistanceFrom2LngLat(lat1, lon1, lat2, lon2);
// System.out.println("Distance between the two points is: " + distance + " km");
// }
}