Commit 09c37a12 authored by huangcb's avatar huangcb

增加Token生成、校验方法

parent 7e4e4bba
package com.esv.freight.app.common.component;
import com.esv.freight.app.common.constants.AccountConstants;
import com.esv.freight.app.common.exception.EException;
import com.esv.freight.app.common.response.ECode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* @description: 协议组件
* @project: app-service
* @name: com.esv.freight.app.common.component.ProtocolComponent
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 15:58
* @version:1.0
*/
@Component
@Slf4j
public class ProtocolComponent {
/**
* description 校验Http请求的Header
* Map<String,String> map = new HashMap<>();
* map.put("requestSource", "2"); // 终端类型:2-Android端、3-iOS端
* map.put("Union-Authorization", AppConfig.getInstance().getToken()); // token
* map.put("osType", osType); // 客户端操作系统名称
* map.put("osVer", osVer); // 客户端操作系统版本
* map.put("mobileId", mobileId); // 手机唯一标识
* map.put("cVer", cVer); // 客户端版本
* map.put("accountType", "1"); // 帐号身份类型:1-司机、2-货主
* param [request]
* return void
* author Administrator
* createTime 2020/05/14 16:00
**/
public void checkReqHeader(HttpServletRequest request) throws EException {
if (!String.valueOf(AccountConstants.APP_TYPE_ANDROID).equals(request.getHeader("requestSource"))
&& !String.valueOf(AccountConstants.APP_TYPE_IOS).equals(request.getHeader("requestSource"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[requestSource]不符合协议");
}
if (StringUtils.isBlank(request.getHeader("osType"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[osType]不符合协议");
}
if (StringUtils.isBlank(request.getHeader("osVer"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[osVer]不符合协议");
}
if (StringUtils.isBlank(request.getHeader("mobileId"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[mobileId]不符合协议");
}
if (StringUtils.isBlank(request.getHeader("cVer"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[cVer]不符合协议");
}
if (!String.valueOf(AccountConstants.ACCOUNT_TYPE_DRIVER).equals(request.getHeader("accountType"))
&& !String.valueOf(AccountConstants.ACCOUNT_TYPE_GOODS_OWNER).equals(request.getHeader("accountType"))) {
throw new EException(ECode.PROTOCOL_ILLEGAL.code(), "请求头[accountType]不符合协议");
}
}
}
package com.esv.freight.app.common.component;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.esv.freight.app.common.constants.AccountConstants;
import com.esv.freight.app.common.exception.EException;
import com.esv.freight.app.common.response.ECode;
import com.esv.freight.app.common.util.AESSecretUtils;
import com.esv.freight.app.common.util.DateUtils;
import com.esv.freight.app.common.util.ReqUtils;
import com.esv.freight.app.module.account.entity.AppLoginEntity;
import com.esv.freight.app.module.account.pojo.TokenInfoPojo;
import com.esv.freight.app.module.account.service.AppLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @description: Token组件
* @project: app-service
* @name: com.esv.freight.app.common.component.TokenComponent
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 11:26
* @version:1.0
*/
@Component
@Slf4j
public class TokenComponent {
@Value("${spring.application.name}")
private String applicationName;
@Value("${aes.sha1prng.key:freight-app-service-001}")
private String AES_KEY;
/**
* 访问Token:1天
**/
@Value("${token.access.valid.time:1}")
private Integer accessTokenValidTime;
/**
* 刷新Token:30天
**/
@Value("${token.refresh.valid.time:30}")
private Integer refreshTokenValidTime;
private static final Integer TOKEN_TIME = 86400;
@Autowired
private RedisComponent redisComponent;
@Autowired
private AppLoginService appLoginService;
/**
* description 创建司机Token信息
* param [tokenInfoPojo, driverAccountInfoPojo]
* return void
* author Administrator
* createTime 2020/05/14 13:48
**/
public void generateTokenInfo(TokenInfoPojo tokenInfoPojo) {
// 构建Token信息
tokenInfoPojo.setIp(ReqUtils.getHttpClientIp());
tokenInfoPojo.setSn(ReqUtils.getRequestHeader("mobileId"));
tokenInfoPojo.setDeviceType(Integer.parseInt(ReqUtils.getRequestHeader("requestSource")));
tokenInfoPojo.setOsType(ReqUtils.getRequestHeader("osType"));
tokenInfoPojo.setOsVersion(ReqUtils.getRequestHeader("osVer"));
tokenInfoPojo.setAppVersion(ReqUtils.getRequestHeader("cVer"));
tokenInfoPojo.setAccountType(Integer.parseInt(ReqUtils.getRequestHeader("accountType")));
String accessToken = AESSecretUtils.encryptToStr(this.getAccessTokenOriginalContent(tokenInfoPojo), AES_KEY);
tokenInfoPojo.setAccessToken(accessToken);
String refreshToken = AESSecretUtils.encryptToStr(this.getRefreshTokenOriginalContent(tokenInfoPojo), AES_KEY);
tokenInfoPojo.setRefreshToken(refreshToken);
Date loginTime = new Date();
tokenInfoPojo.setLoginTime(loginTime.getTime());
Date accessTokenValidTime = DateUtils.plusDays(loginTime, this.accessTokenValidTime);
Date refreshTokenValidTime = DateUtils.plusDays(loginTime, this.refreshTokenValidTime);
tokenInfoPojo.setAccessTokenValidTime(accessTokenValidTime.getTime());
tokenInfoPojo.setRefreshTokenValidTime(refreshTokenValidTime.getTime());
// 缓存Token信息
String cacheKey = this.getTokenInfoCacheKey(tokenInfoPojo.getAccount(), tokenInfoPojo.getAccountType());
redisComponent.set(cacheKey, tokenInfoPojo.toString(), this.accessTokenValidTime * TOKEN_TIME);
}
/**
* description 校验Token是否过期
* param [accessToken]
* return void
* author Administrator
* createTime 2020/05/14 17:37
**/
public void checkAccessToken(String accessToken) throws EException {
// 获取Token信息
TokenInfoPojo tokenInfoPojo = this.getTokenInfo(accessToken);
if (null == tokenInfoPojo) {
throw new EException(ECode.TOKEN_INVALID.code(), ECode.TOKEN_INVALID.message());
}
// 校验Token是否过期
Long accessTokenValidTime = tokenInfoPojo.getAccessTokenValidTime();
if (System.currentTimeMillis() > accessTokenValidTime) {
throw new EException(ECode.TOKEN_EXPIRED.code(), ECode.TOKEN_EXPIRED.message());
}
}
/**
* description 获取Token信息
* param [accessToken]
* return com.esv.freight.app.module.account.pojo.TokenInfoPojo
* author Administrator
* createTime 2020/05/14 17:41
**/
public TokenInfoPojo getTokenInfo(String accessToken) {
if (StringUtils.isBlank(accessToken)) {
return null;
}
// 解密Token并基础校验
String decryptToken = AESSecretUtils.decryptToStr(accessToken, AES_KEY);
if (StringUtils.isBlank(decryptToken)) {
return null;
}
String[] tokenArr = decryptToken.split(",");
if (4 != tokenArr.length || 11 != tokenArr[0].length()) {
return null;
}
if (!AccountConstants.ACCOUNT_TYPE_DRIVER.equals(Integer.parseInt(tokenArr[1]))
&& !AccountConstants.ACCOUNT_TYPE_GOODS_OWNER.equals(Integer.parseInt(tokenArr[1]))) {
return null;
}
String account = tokenArr[0];
Integer accountType = Integer.parseInt(tokenArr[1]);
return this.getTokenInfo(account, accountType);
}
/**
* description 获取Token信息
* param [account, accountType]
* return com.esv.freight.app.module.account.pojo.TokenInfoPojo
* author Administrator
* createTime 2020/05/14 17:34
**/
public TokenInfoPojo getTokenInfo(String account, Integer accountType) {
String cacheKey = this.getTokenInfoCacheKey(account, accountType);
String cacheInfo = (String) redisComponent.get(cacheKey);
TokenInfoPojo tokenInfoPojo = null;
if (null == cacheInfo) {
AppLoginEntity appLoginEntity = appLoginService.getBaseMapper().selectOne(new QueryWrapper<AppLoginEntity>().lambda()
.eq(AppLoginEntity::getAccountType, accountType)
.eq(AppLoginEntity::getPhone, account));
if (null != appLoginEntity) {
tokenInfoPojo = new TokenInfoPojo();
BeanUtils.copyProperties(appLoginEntity, tokenInfoPojo);
tokenInfoPojo.setAccountId(appLoginEntity.getId());
tokenInfoPojo.setAccount(appLoginEntity.getPhone());
tokenInfoPojo.setLoginTime(appLoginEntity.getLoginTime().getTime());
tokenInfoPojo.setRefreshTime(appLoginEntity.getRefreshTime().getTime());
tokenInfoPojo.setAccessTokenValidTime(appLoginEntity.getAccessTokenValidTime().getTime());
tokenInfoPojo.setRefreshTokenValidTime(appLoginEntity.getRefreshTokenValidTime().getTime());
}
} else {
tokenInfoPojo = JSONObject.toJavaObject(JSONObject.parseObject(cacheInfo), TokenInfoPojo.class);
}
return tokenInfoPojo;
}
/**
* description 获取访问Token原始内容
* param [tokenInfoPojo]
* return java.lang.String
* author Administrator
* createTime 2020/05/14 15:05
**/
public String getAccessTokenOriginalContent(TokenInfoPojo tokenInfoPojo) {
return tokenInfoPojo.getAccount() + "," + tokenInfoPojo.getAccountType() + ",accessToken," + System.currentTimeMillis();
}
/**
* description 获取刷新Token原始内容
* param [tokenInfoPojo]
* return java.lang.String
* author Administrator
* createTime 2020/05/14 15:06
**/
public String getRefreshTokenOriginalContent(TokenInfoPojo tokenInfoPojo) {
return tokenInfoPojo.getAccount() + "," + tokenInfoPojo.getAccountType() + ",refreshToken," + System.currentTimeMillis();
}
/**
* description 获取Token信息缓存Key
* param [account, accountType]
* return java.lang.String
* author Administrator
* createTime 2020/05/14 15:07
**/
public String getTokenInfoCacheKey(String account, Integer accountType) {
return applicationName + "::token::" + accountType + "::" + account;
}
}
package com.esv.freight.app.common.constants;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.common.constants.AccountConstants
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 10:12
* @version:1.0
*/
public class AccountConstants {
/**
* 终端类型:2-Android端、3-iOS端
**/
public static final Integer APP_TYPE_ANDROID = 2;
public static final Integer APP_TYPE_IOS = 3;
/**
* 帐号身份类型:1-司机、2-货主
**/
public static final Integer ACCOUNT_TYPE_DRIVER = 1;
public static final Integer ACCOUNT_TYPE_GOODS_OWNER = 2;
/**
* 帐号状态:1-正常、2-停用
**/
public static final Integer ACCOUNT_STATUS_NORMAL = 1;
public static final Integer ACCOUNT_STATUS_BLOCK = 2;
/**
* 帐号登录状态:1-登录中、2-已登出
**/
public static final Integer ACCOUNT_STATUS_LOGIN = 1;
public static final Integer ACCOUNT_STATUS_LOGOUT = 2;
/**
* 帐号登录方式:1-帐号密码登录、2-短信验证码登录
**/
public static final Integer ACCOUNT_LOGIN_MODE_PWD = 1;
public static final Integer ACCOUNT_LOGIN_MODE_SMS = 2;
}
package com.esv.freight.app.common.filter;
import com.esv.freight.app.common.response.ECode;
import com.esv.freight.app.common.component.ProtocolComponent;
import com.esv.freight.app.common.component.TokenComponent;
import com.esv.freight.app.common.exception.EException;
import com.esv.freight.app.common.response.EResponse;
import com.esv.freight.app.common.util.AESSecretUtils;
import com.esv.freight.app.common.util.SecurityUtils;
import com.esv.freight.app.common.wrapper.RestRequestWrapper;
import com.esv.freight.app.module.account.CustomToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import javax.servlet.*;
......@@ -30,8 +29,17 @@ import java.io.PrintWriter;
@RefreshScope
public class AuthFilter implements Filter {
@Value("${aes.sha1prng.key:freight-app-service-001}")
private String AES_KEY;
/**
* 不需要TOKEN校验的URL
**/
private static final String[] NOT_TOKEN_URL = new String[]{"/app/ownerBackend/account/login/loginBySms", "/app/ownerBackend/account/login/loginByPwd",
"/app/driverBackend/account/login/loginBySms", "/app/driverBackend/account/login/loginByPwd"};
@Autowired
private ProtocolComponent protocolComponent;
@Autowired
private TokenComponent tokenComponent;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
......@@ -40,52 +48,37 @@ public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
/************************ Token加解密示例 ************************/
// log.info(AES_KEY);
// String tokenTest = "1,13912345678,sn001";
// String accessTokenTest = AESSecretUtils.encryptToStr(tokenTest, AES_KEY);
// log.info(tokenTest);
// log.info(accessTokenTest);
// log.info(AESSecretUtils.decryptToStr(accessTokenTest, AES_KEY));
/************************ Token加解密示例 ************************/
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
RestRequestWrapper requestWrapper = new RestRequestWrapper((HttpServletRequest)servletRequest);
/**
* APP请求头示例
*
*Map<String,String> map = new HashMap<>();
* map.put("requestSource", "2"); // 访问来源
* map.put("Union-Authorization", AppConfig.getInstance().getToken()); // token
* map.put("osType", osType); // 客户端操作系统名称
* map.put("osVer", osVer); // 客户端操作系统版本
* map.put("mobileId", mobileId); // 手机唯一标识
* map.put("cVer", cVer); // 客户端版本
*/
// 请求来源:1-浏览器端、2-Android端、3-iOS端、4-后台服务端
String requestSource = request.getHeader("requestSource");
if(!"2".equals(requestSource) && !"3".equals(requestSource)) { // 如果不是android或IOS端的请求直接返回
this.errorResponse(EResponse.error(ECode.ACCESS_DENIED), response);
// 请求头协议校验
try {
protocolComponent.checkReqHeader(requestWrapper);
} catch (EException e) {
this.errorResponse(EResponse.error(e.getCode(), e.getMessage()), response);
return;
}
String cVer = request.getHeader("cVer");
// TODO 终端程序的版本号,以后当程序升级时可以通过版本检测,过低的版本的请求可能需要返回“您的版本过低,请更新应用!”
String mobileId = request.getHeader("mobileId");
// TODO 设备标识,用于日后消息推送
String token = request.getHeader("Union-Authorization");
log.info(SecurityUtils.desDecode(AES_KEY, token));
CustomToken customToken = CheckCustomToken.getCustomToken(SecurityUtils.desDecode(AES_KEY, token));
// 校验token
RestRequestWrapper requestWrapper = new RestRequestWrapper((HttpServletRequest)servletRequest);
String url = requestWrapper.getRequestURI();
CheckCustomToken.check(customToken, url);
request.setAttribute("tokenInfo", customToken);
Boolean isCheckToken = true;
for (int i = 0; i < NOT_TOKEN_URL.length; i++) {
if (NOT_TOKEN_URL[i].equals(url)) {
isCheckToken = false;
break;
}
}
if (isCheckToken) {
String token = request.getHeader("Union-Authorization");
try {
tokenComponent.checkAccessToken(token);
} catch (EException e) {
this.errorResponse(EResponse.error(e.getCode(), e.getMessage()), response);
return;
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
......
......@@ -18,6 +18,7 @@ public class ECode {
public static final ECode PARAM_ERROR = new ECode(600, "参数不合法");
public static final ECode TOKEN_INVALID = new ECode(601, "无效的Token");
public static final ECode TOKEN_EXPIRED = new ECode(602, "Token已过期");
public static final ECode PROTOCOL_ILLEGAL = new ECode(700, "协议不合法");
public ECode(int code, String message) {
this.code = code;
......
package com.esv.freight.app.common.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.app.common.response.ECode;
import com.esv.freight.app.common.response.EResponse;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.common.util.FeignUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 10:04
* @version:1.0
*/
public class FeignUtils {
/**
* description 判断Feign请求是否成功
* param [feignResult]
* return java.lang.Boolean
* author Administrator
* createTime 2020/05/14 10:06
**/
public static Boolean isFeignSuccess(JSONObject feignResult) {
if (ECode.SUCCESS.code() == feignResult.getIntValue("code")) {
return true;
} else {
return false;
}
}
/**
* description 包装Feign请求的错误返回
* param [feignResult]
* return com.esv.freight.app.common.response.EResponse
* author Administrator
* createTime 2020/05/14 10:10
**/
public static EResponse getFeignEResponse(JSONObject feignResult) {
return EResponse.error(feignResult.getInteger("code"), feignResult.getString("message"));
}
/**
* description 获取Feign请求返回数据JSONObject格式
* param [feignResult]
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/05/14 11:11
**/
public static JSONObject getFeignDataJson(JSONObject feignResult) {
return feignResult.getJSONObject("data");
}
/**
* description 获取Feign请求返回数据JSONArray格式
* param [feignResult]
* return com.alibaba.fastjson.JSONArray
* author Administrator
* createTime 2020/05/14 11:12
**/
public static JSONArray getFeignDataJsonArray(JSONObject feignResult) {
return feignResult.getJSONArray("data");
}
}
......@@ -27,20 +27,33 @@ public class ReqUtils {
return (CustomToken) request.getAttribute("tokenInfo");
}
/**
* description 获得Http客户端的ip
* param []
* return java.lang.String
* author Administrator
* createTime 2020/05/14 13:54
**/
public static String getHttpClientIp() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
return getHttpClientIp(request);
}
/**
* 获得Http客户端的ip
* @param req
* @return
*/
public static String getHttpClientIp(HttpServletRequest req){
public static String getHttpClientIp(HttpServletRequest req) {
String ip = req.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
}
return ip;
......
......@@ -42,17 +42,17 @@ public class FeignConfigure {
RequestInterceptor requestInterceptor = ((requestTemplate -> {
requestTemplate.header("trace_id", MDC.get("traceId"));
requestTemplate.header("application_name", applicationName);
String requestSource = ReqUtils.getRequestHeader("requestSource");
requestTemplate.header("Source-Type", requestSource);
requestTemplate.header("Source-Type", ReqUtils.getRequestHeader("requestSource"));
requestTemplate.header("esv_data_perm", "0");
// requestTemplate.header("gateway_traceid", "1");
requestTemplate.header("esv_system", "app");
requestTemplate.header("esv_department", "5");
requestTemplate.header("esv_department_children", "5,6,7");
CustomToken customToken = ReqUtils.getTokenInfo();
if (null != customToken) {
requestTemplate.header("esv_user", customToken.getUserId());
requestTemplate.header("esv_account", customToken.getAccount());
requestTemplate.header("esv_tenant", String.valueOf(customToken.getTenantId()));
}
}));
return requestInterceptor;
}
......
......@@ -2,8 +2,9 @@ package com.esv.freight.app.module.account.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.app.common.response.ECode;
import com.esv.freight.app.common.constants.AccountConstants;
import com.esv.freight.app.common.response.EResponse;
import com.esv.freight.app.common.util.FeignUtils;
import com.esv.freight.app.common.util.ReqUtils;
import com.esv.freight.app.common.validator.groups.ValidatorInsert;
import com.esv.freight.app.common.validator.groups.ValidatorUpdate;
......@@ -14,16 +15,18 @@ import com.esv.freight.app.module.account.CustomToken;
import com.esv.freight.app.module.account.form.DriverAuthForm;
import com.esv.freight.app.module.account.form.LoginForm;
import com.esv.freight.app.module.account.form.RefreshTokenForm;
import com.esv.freight.app.module.account.pojo.DriverAccountInfoPojo;
import com.esv.freight.app.module.account.pojo.TokenInfoPojo;
import com.esv.freight.app.module.account.service.AppLoginService;
import com.esv.freight.app.module.account.validator.groups.ValidatorAccountExist;
import com.esv.freight.app.module.account.validator.groups.ValidatorDriverLoginBySms;
import com.esv.freight.app.module.account.validator.groups.ValidatorLoginByPwd;
import com.esv.freight.app.module.account.validator.groups.ValidatorLoginBySms;
import com.esv.freight.app.module.account.vo.AccountExistVO;
import com.esv.freight.app.module.account.vo.CarrierInfoBriefVO;
import com.esv.freight.app.module.account.vo.DriverAccountDetailVO;
import com.esv.freight.app.module.account.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
......@@ -107,18 +110,35 @@ public class DriverAccountController {
@PostMapping("/login/loginByPwd")
public EResponse loginByPwd(@RequestBody(required=false) @Validated(ValidatorLoginByPwd.class) LoginForm loginForm) {
// 调用帐号密码校验接口
// 1:调用帐号密码校验接口
JSONObject reqJson = new JSONObject();
reqJson.put("account", loginForm.getPhone());
reqJson.put("password", loginForm.getPwd());
JSONObject result = driverInterface.accountCheck(reqJson);
JSONObject result;
try {
result = driverInterface.accountCheck(reqJson);
} catch (Exception e) {
log.error("Feign请求时发生错误:" + e.getMessage(), e);
return EResponse.error();
}
if(result.getInteger("code") != 200) {
return EResponse.error(result.getInteger("code"), result.getString("message"));
if(!FeignUtils.isFeignSuccess(result)) {
return FeignUtils.getFeignEResponse(result);
}
LoginVO loginByPwdVO = appLoginService.login(loginForm.getPhone());
return EResponse.ok(loginByPwdVO);
// 2:校验帐号状态:1-正常、2-停用
DriverAccountInfoPojo driverAccountInfoPojo = JSONObject.toJavaObject(FeignUtils.getFeignDataJson(result), DriverAccountInfoPojo.class);
if (AccountConstants.ACCOUNT_STATUS_BLOCK.equals(driverAccountInfoPojo.getAccountStatus())) {
return EResponse.error(1003, "帐号已停用");
}
// LoginVO loginByPwdVO = appLoginService.login(loginForm.getPhone());
// 登录
driverAccountInfoPojo.setLoginMode(AccountConstants.ACCOUNT_LOGIN_MODE_PWD);
LoginVO vo = appLoginService.driverLogin(driverAccountInfoPojo);
return EResponse.ok(vo);
}
/**
......
package com.esv.freight.app.module.account.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
......@@ -22,7 +21,7 @@ public class AppLoginEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*
*/
@TableId
private Long id;
......@@ -31,13 +30,33 @@ public class AppLoginEntity implements Serializable {
*/
private String phone;
/**
* 访问token
* 帐号身份类型:1-司机、2-货主
*/
private String accessToken;
private Integer accountType;
/**
* 刷新token
* 帐号登录方式:1-帐号密码登录、2-短信验证码登录
*/
private String refreshToken;
private Integer loginMode;
/**
* 终端类型:2-Android端、3-iOS端
*/
private Integer deviceType;
/**
* 终端操作系统名称
*/
private String osType;
/**
* 终端操作系统版本
*/
private String osVersion;
/**
* 终端APP版本
*/
private String appVersion;
/**
* 终端登录时的IP
*/
private String ip;
/**
* 设备序列号
*/
......@@ -45,7 +64,7 @@ public class AppLoginEntity implements Serializable {
/**
* 登录状态:1-登录中、2-已登出
*/
private String loginStatus;
private Integer loginStatus;
/**
* 登录时间
*/
......@@ -53,10 +72,20 @@ public class AppLoginEntity implements Serializable {
/**
* 登出时间
*/
@TableField(insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
private Date logoutTime;
/**
* 访问token
*/
private String accessToken;
/**
* 刷新token
*/
private String refreshToken;
/**
* token刷新时间
*/
@TableField(insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
private Date refreshTime;
/**
* 访问token有效期
......
......@@ -2,6 +2,8 @@ package com.esv.freight.app.module.account.form;
import com.esv.freight.app.module.account.validator.groups.*;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
......@@ -45,4 +47,9 @@ public class LoginForm {
*/
@NotNull(message = "参数carrierId不能为空", groups = {ValidatorDriverLoginBySms.class})
private Long carrierId;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.freight.app.module.account.pojo;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.module.account.pojo.DriverDetailInfoPojo
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 9:53
* @version:1.0
*/
@Data
public class DriverAccountInfoPojo {
/**
*
*/
private Long id;
/**
* 承运商帐号ID
*/
private Long carrierId;
/**
* 承运商名称
*/
private String carrierName;
/**
* 登录帐号,司机手机号
*/
private String account;
/**
* 帐号状态:1-正常、2-停用
*/
private Integer accountStatus;
/**
* 创建来源:1-平台创建、2-自行注册
*/
private Integer sourceType;
/**
* 审核状态(字典表):0-待审核、1-审核成功,2-审核失败
*/
private Integer auditStatus;
/**
* 姓名
*/
private String name;
/**
* 身份证号码
*/
private String idCard;
/**
* 身份证有效期
*/
private String idCardExpireDate;
/**
* 身份证正面图片URL
*/
private String idCardFrontUrl;
/**
* 身份证背面图片URL
*/
private String idCardBackUrl;
/**
* 结算对象(字典表):1-个人、2-所属承运商
*/
private Integer settlementType;
/**
* 性别(字典表):1-男、2-女、3-未知
*/
private Integer sex;
/**
* 出生日期
*/
private String birthDate;
/**
* 名族
*/
private String nation;
/**
* 籍贯
*/
private String nativePlace;
/**
* 住址-省份代码
*/
private String provinceCode;
/**
* 住址-市代码
*/
private String cityCode;
/**
* 住址-区县代码
*/
private String districtCode;
/**
* 住址-详细地址
*/
private String detailAddress;
/**
* 驾驶证号码
*/
private String drivingLicense;
/**
* 驾驶证类型(字典表):1-A1、2-A2、3-A3、4-A1A2、5-A2E、6-A2D、7-B1、8-B2、9-C1、0-其他
*/
private Integer drivingLicenseType;
/**
* 驾驶证有效期起
*/
private String drivingLicenseStartDate;
/**
* 驾驶证有效期止
*/
private String drivingLicenseEndDate;
/**
* 发证机关
*/
private String drivingLicenseIssueDepartment;
/**
* 初次获得驾驶证日期
*/
private String drivingLicenseInitDate;
/**
* 驾驶证正面图片URL
*/
private String drivingLicenseUrl;
/**
* 道路运输从业资格证-所驾驶车辆(字典表):1-4.5吨及以下、2-4.5吨以上
*/
private Integer certificateVehicle;
/**
* 道路运输从业资格证-有效期止
*/
private String certificateEndDate;
/**
* 道路运输从业资格证-从业资格证号
*/
private String certificateNumber;
/**
* 道路运输从业资格证-正面图片URL
*/
private String certificateUrl;
/**
* 备注
*/
private String remark;
/**
* 创建者
*/
private String createUser;
/**
* 创建时间
*/
private Long createTime;
/**
* 帐号登录方式:1-帐号密码登录、2-短信验证码登录
*/
private Integer loginMode;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
package com.esv.freight.app.module.account.pojo;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.Date;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.module.account.pojo.TokenInfoPojo
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 11:21
* @version:1.0
*/
@Data
public class TokenInfoPojo {
/**
* 用户ID
*/
private Long accountId;
/**
* 手机号码(帐号)
*/
private String account;
/**
* 帐号身份类型:1-司机、2-货主
*/
private Integer accountType;
/**
* 帐号登录方式:1-帐号密码登录、2-短信验证码登录
*/
private Integer loginMode;
/**
* 访问token
*/
private String accessToken;
/**
* 刷新token
*/
private String refreshToken;
/**
* 登录时的IP
*/
private String ip;
/**
* 设备序列号
*/
private String sn;
/**
* 终端类型:2-Android端、3-iOS端
*/
private Integer deviceType;
/**
* 终端操作系统名称
*/
private String osType;
/**
* 终端操作系统版本
*/
private String osVersion;
/**
* 终端APP版本
*/
private String appVersion;
/**
* 登录时间
*/
private Long loginTime;
/**
* token刷新时间
*/
private Long refreshTime;
/**
* 访问token有效期
*/
private Long accessTokenValidTime;
/**
* 刷新token有效期
*/
private Long refreshTokenValidTime;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
......@@ -3,6 +3,8 @@ package com.esv.freight.app.module.account.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.freight.app.module.account.entity.AppLoginEntity;
import com.esv.freight.app.module.account.form.RefreshTokenForm;
import com.esv.freight.app.module.account.pojo.DriverAccountInfoPojo;
import com.esv.freight.app.module.account.pojo.TokenInfoPojo;
import com.esv.freight.app.module.account.vo.LoginVO;
/**
......@@ -23,6 +25,15 @@ public interface AppLoginService extends IService<AppLoginEntity> {
**/
LoginVO login(String phone);
/**
* description 司机帐号登录
* param [driverDetailInfoPojo]
* return com.esv.freight.app.module.account.vo.LoginVO
* author Administrator
* createTime 2020/05/14 13:17
**/
LoginVO driverLogin(DriverAccountInfoPojo driverAccountInfoPojo);
/**
* description 账号登出
* param [accessToken]
......
......@@ -2,14 +2,20 @@ package com.esv.freight.app.module.account.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.freight.app.common.component.TokenComponent;
import com.esv.freight.app.common.constants.AccountConstants;
import com.esv.freight.app.common.exception.EException;
import com.esv.freight.app.common.util.ReqUtils;
import com.esv.freight.app.module.account.dao.AppLoginDao;
import com.esv.freight.app.module.account.entity.AppLoginEntity;
import com.esv.freight.app.module.account.form.RefreshTokenForm;
import com.esv.freight.app.module.account.pojo.DriverAccountInfoPojo;
import com.esv.freight.app.module.account.pojo.TokenInfoPojo;
import com.esv.freight.app.module.account.service.AppLoginService;
import com.esv.freight.app.module.account.vo.LoginVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
......@@ -17,7 +23,10 @@ import java.util.Date;
import java.util.UUID;
@Service("appLoginService")
public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> implements AppLoginService {
public class AppLoginServiceImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> implements AppLoginService {
@Autowired
private TokenComponent tokenComponent;
private void createToken(AppLoginEntity entity) {
if(entity == null) {
......@@ -28,6 +37,35 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
entity.setRefreshToken(UUID.randomUUID().toString().replaceAll("-", ""));
}
@Override
public LoginVO driverLogin(DriverAccountInfoPojo driverAccountInfoPojo) {
// 1:初始化Token
TokenInfoPojo tokenInfoPojo = new TokenInfoPojo();
BeanUtils.copyProperties(driverAccountInfoPojo, tokenInfoPojo);
tokenInfoPojo.setAccountId(driverAccountInfoPojo.getId());
this.tokenComponent.generateTokenInfo(tokenInfoPojo);
// 2:保存或更新登录信息
AppLoginEntity record = this.baseMapper.selectOne(new QueryWrapper<AppLoginEntity>().lambda()
.eq(AppLoginEntity::getAccountType, tokenInfoPojo.getAccountType())
.eq(AppLoginEntity::getPhone, tokenInfoPojo.getAccount()));
AppLoginEntity appLoginEntity = new AppLoginEntity();
BeanUtils.copyProperties(tokenInfoPojo, appLoginEntity);
appLoginEntity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGIN);
appLoginEntity.setPhone(tokenInfoPojo.getAccount());
if (null == record) {
this.baseMapper.insert(appLoginEntity);
} else {
appLoginEntity.setId(record.getId());
this.baseMapper.updateById(appLoginEntity);
}
// 3:返回Token
LoginVO loginVO = new LoginVO();
BeanUtils.copyProperties(tokenInfoPojo, loginVO);
return loginVO;
}
@Override
public LoginVO login(String phone) {
......@@ -37,7 +75,7 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
}
createToken(appLoginEntity);
appLoginEntity.setLoginStatus("1");
appLoginEntity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGIN);
appLoginEntity.setLoginTime(new Date());
appLoginEntity.setRefreshTime(new Date());
appLoginEntity.setAccessTokenValidTime(getFuture(1));
......@@ -55,7 +93,7 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
AppLoginEntity appLoginEntity = new AppLoginEntity();
appLoginEntity.setPhone(phone);
createToken(appLoginEntity);
appLoginEntity.setLoginStatus("1");
appLoginEntity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGIN);
appLoginEntity.setLoginTime(new Date());
appLoginEntity.setRefreshTime(new Date());
appLoginEntity.setLogoutTime(new Date());
......@@ -79,7 +117,7 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
entity.setAccessToken("");
entity.setRefreshToken("");
entity.setLoginStatus("2");
entity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGOUT);
entity.setLogoutTime(new Date());
this.baseMapper.updateById(entity);
}
......@@ -93,7 +131,7 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
entity.setAccessToken("");
entity.setRefreshToken("");
entity.setLoginStatus("2");
entity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGOUT);
entity.setLogoutTime(new Date());
this.baseMapper.updateById(entity);
}
......@@ -111,7 +149,7 @@ public class AppLoginImpl extends ServiceImpl<AppLoginDao, AppLoginEntity> imple
createToken(entity);
entity.setRefreshTime(new Date());
entity.setLoginStatus("1");
entity.setLoginStatus(AccountConstants.ACCOUNT_STATUS_LOGIN);
entity.setAccessTokenValidTime(getFuture(1));
entity.setRefreshTokenValidTime(getFuture(30));
this.baseMapper.updateById(entity);
......
package com.esv.freight.app.module;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.module.BaseTestController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 10:21
* @version:1.0
*/
@Slf4j
@Data
public class BaseTestController {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void after() {
log.info("=================================== Test End ===================================");
}
public HttpHeaders getDefaultHttpHeaders() {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("gateway_traceid", String.valueOf(System.currentTimeMillis()));
httpHeaders.add("esv_system", "app");
httpHeaders.add("esv_data_perm", "1");
httpHeaders.add("esv_tenant", "1");
httpHeaders.add("esv_department", "1");
httpHeaders.add("esv_department_children", "1,2,3");
httpHeaders.add("esv_user", "1");
httpHeaders.add("esv_account", "admin");
httpHeaders.add("requestSource", "2");
httpHeaders.add("osType", "Android_test");
httpHeaders.add("osVer", "10.0.0_test");
httpHeaders.add("mobileId", "1234ASDFOWEF_test");
httpHeaders.add("cVer", "1.0.0");
httpHeaders.add("accountType", "1");
return httpHeaders;
}
}
package com.esv.freight.app.module.account;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.app.common.response.ECode;
import com.esv.freight.app.module.BaseTestController;
import com.esv.freight.app.module.account.form.LoginForm;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.transaction.annotation.Transactional;
/**
* @description:
* @project: app-service
* @name: com.esv.freight.app.module.account.DriverAccountControllerTest
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/05/14 10:24
* @version:1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
@Rollback(false)
public class DriverAccountControllerTest extends BaseTestController {
/**
* 帐号密码登录
**/
@Test
public void a1_loginByPwd_success_test() throws Exception {
String url = "/driverBackend/account/login/loginByPwd";
// 构造数据
LoginForm form = new LoginForm();
form.setPhone("18512340001");
form.setPwd("e10adc3949ba59abbe56e057f20f883e");
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.headers(this.getDefaultHttpHeaders())
.content(form.toString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
}
}
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