提交 560aea49 authored 作者: zhengfg's avatar zhengfg

1、去除session和cookie后,加入spring security使用token登录

2、实现第三方接口业务流程
上级 b9458b12
......@@ -10,7 +10,7 @@
</parent>
<groupId>com.diaoyun</groupId>
<artifactId>zion</artifactId>
<version>0.1.1-SNAPSHOT</version>
<version>2.0.0</version>
<name>zion</name>
<description>逐渐把项目完善</description>
<packaging>war</packaging>
......@@ -39,10 +39,35 @@
</exclusions>-->
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<!-- <dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependency>
<dependency>
<!-- Make method based security testing easier -->
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<!-- Automatically restart whenever files on the classpath change -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<!-- JSON Web Token Support -->
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
......
package com.diaoyun.zion.chinafrica.api;
import com.alibaba.druid.support.json.JSONUtils;
import com.diaoyun.zion.chinafrica.service.TbCfOrderService;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.JodaDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
......@@ -23,19 +29,26 @@ import java.util.Map;
public class ThirdPartyController {
private static Logger logger= LoggerFactory.getLogger(ThirdPartyController.class);
@Autowired
private TbCfOrderService tbCfOrderService;
/**
*获取某段时间的单数据
*获取某段时间的付款订单数据
*/
@ApiOperation(value = "获取某段时间的单数据")
@ApiOperation(value = "获取某段时间的付款订单数据")
@GetMapping(value ="/order")
public String getOrderList(@RequestParam("beginTime")String beginTime,@RequestParam("endTime")String endTime) {
List<Map<String,Object>> returnList=new ArrayList<>();
Map<String,Object> map=new HashMap<>();
map.put("orderId","orderId8848");
map.put("userId","userId2019");
map.put("dealTime","订单成交时间时间戳1564558584");
returnList.add(map);
return JSONUtils.toJSONString(returnList);
public Result getOrderList(@ApiParam(value ="开始时间") @RequestParam("beginTime")long beginTime,
@ApiParam(value ="结束时间") @RequestParam("endTime")long endTime,
@ApiParam(value = "页数") @RequestParam(required = false) Integer pageNum,
@ApiParam(value ="每页大小 默认100") @RequestParam(required = false) Integer pageSize) {
if (pageNum == null) {
pageNum = 1;
}
if (pageSize == null) {
pageSize = 100;
}
return tbCfOrderService.getOrderListByTime(beginTime,endTime,pageNum,pageSize);
}
/**
......@@ -43,44 +56,26 @@ public class ThirdPartyController {
*/
@ApiOperation(value = "获取某段时间已发货订单数据")
@GetMapping(value ="/delivery")
public String getDeliveryList(@RequestParam("beginTime")String beginTime,@RequestParam("endTime")String endTime) {
List<Map<String,Object>> returnList=new ArrayList<>();
Map<String,Object> map=new HashMap<>();
map.put("orderId","orderId8848");
map.put("userId","userId2019");
map.put("deliveryAddress","收货人地址");
map.put("deliveryTime","发货时间戳1564558584");
map.put("itemType","货物类别Id");
map.put("expressId","快递单号");
returnList.add(map);
returnList.add(map);
return JSONUtils.toJSONString(returnList);
public Result getDeliveryList(@ApiParam(value ="开始时间") @RequestParam("beginTime")long beginTime,
@ApiParam(value ="结束时间") @RequestParam("endTime")long endTime,
@ApiParam(value = "页数") @RequestParam(required = false) Integer pageNum,
@ApiParam(value ="每页大小 默认100") @RequestParam(required = false) Integer pageSize) {
if (pageNum == null) {
pageNum = 1;
}
if (pageSize == null) {
pageSize = 100;
}
return tbCfOrderService.getDeliveryList(beginTime,endTime,pageNum,pageSize);
}
/**
*根据订单号获取详细订单数据
* 根据订单号获取详细订单数据
*/
@ApiOperation(value = "获取某段时间已发货订单数据")
@ApiOperation(value = "根据订单号获取详细订单数据")
@GetMapping(value ="/order/detail/{orderId}")
public String getOrderDetailById(@PathVariable("orderId")String orderId) {
Map<String,Object> map=new HashMap<>();
map.put("orderId","订单Id8848");
map.put("deliveryName","收货人");
map.put("deliveryPhone","收货人手机");
map.put("deliveryAddress","收货人地址");
List<Map<String,Object>> itemList=new ArrayList<>();
Map<String,Object> itemMap=new HashMap<>();
itemMap.put("itemCategory","品名");
itemMap.put("itemPrice","单价");
itemMap.put("itemNum","数量");
Map<String,Object> itemMap2=new HashMap<>();
itemMap2.put("itemCategory","品名2");
itemMap2.put("itemPrice","单价2");
itemMap2.put("itemNum","数量2");
itemList.add(itemMap);
itemList.add(itemMap2);
map.put("itemList",itemList);
return JSONUtils.toJSONString(map);
public Result getOrderDetail(@PathVariable("orderId")String orderId) {
return tbCfOrderService.getOrderDetail(orderId);
}
......
......@@ -3,8 +3,7 @@ package com.diaoyun.zion.chinafrica.client;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.exception.ValidateException;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
......@@ -27,6 +26,8 @@ public class TokenVerification {
private HttpServletRequest request;
@Resource(name="redisTokenManager")
private TokenManager tokenManager;
@Autowired
private JwtTokenProvider jwtTokenProvider;
//验证是否登录
//@Pointcut("!execution(* com.diaoyun.zion.chinafrica.controller.LoginController*.*(..))&&within(com.diaoyun.zion.chinafrica.controller.*)")
......@@ -46,7 +47,8 @@ public class TokenVerification {
@Around("controllerAspect()")
public Object validateLogin(ProceedingJoinPoint pjp) throws Throwable {
Result result;
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
//获取用户
String token = jwtTokenProvider.resolveToken(request);
//不需要登录
if (StringUtils.isNotBlank(token) && tokenManager.validate(token) != null) {
return pjp.proceed();
......
......@@ -21,4 +21,7 @@ public class KeyConstant {
public final static String ORDER_EXP="order_exp";
//订单详情前缀
public final static String ORDER_DET="order_det";
/////////////////订单 END////////////////
//验证码前缀
public final static String CAPTCHA="captcha_";
}
......@@ -28,104 +28,39 @@ import java.io.UnsupportedEncodingException;
public class LoginController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(LoginController.class);
// 登录页 TODO 改为配置
private static final String LOGIN_PATH = "page/login.html";
@Resource(name = "redisTokenManager")
private TokenManager tokenManager;
@Autowired
private HttpServletRequest request; //自动注入request
@Autowired
private HttpServletResponse response;
@Autowired
private TbCfUserInfoService tbCfUserInfoService;
@ApiOperation(value = "注册并登录")
@PostMapping(value = "/register")
public Result<TbCfUserInfoVo> registerAndLogin(@ApiParam("用户信息") @RequestBody TbCfUserInfoVo tbCfUserInfoVo) {
Result result = tbCfUserInfoService.registerAndLogin(tbCfUserInfoVo);
return result;
return tbCfUserInfoService.registerAndLogin(tbCfUserInfoVo);
}
/*@ApiOperation("登录页")
@RequestMapping(method = RequestMethod.GET)
public void login(
@ApiParam(value = "返回链接", required = true) @ValidateParam({ Validator.NOT_BLANK }) String backUrl,
HttpServletRequest request) throws IOException {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
if (StringUtils.isNotBlank(token) && tokenManager.validate(token) != null) {
response.sendRedirect(authBackUrl(backUrl, token));
//return "redirect:" + authBackUrl(backUrl, token);
}
else {
response.sendRedirect(goLoginPath(backUrl, request));
//return goLoginPath(backUrl, request);
}
}
*/
@ApiOperation("登录")
@PostMapping
public Result<TbCfUserInfoVo> login(@ApiParam(value = "登录名") @RequestParam(required = false) String account,
@ApiParam(value = "密码") @RequestParam(required = false) String password) {
Result result = tbCfUserInfoService.login(getIpAddr(request), account,password);
return result;
public Result<TbCfUserInfoVo> login(@ApiParam(value = "登录名")String account,
@ApiParam(value = "密码") String password) {
return tbCfUserInfoService.login(getIpAddr(request), account,password);
}
@ApiOperation("使用token登录")
@GetMapping("/token")
public Result<TbCfUserInfoVo> loginByToken() {
return tbCfUserInfoService.loginByToken(getIpAddr(request));
}
/*@ApiOperation(value = "登录")
@GetMapping("/form")
public Result login(@ApiParam(value = "登录名") @RequestParam(required = false) String account,
@ApiParam(value = "密码") @RequestParam(required = false) String password) {
Result result;
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
if (StringUtils.isNotBlank(token)) {// 有cookies的情况
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
if (tbCfUserInfoVo == null) {
CookieUtils.removeCookie(response, TokenManager.TOKEN, "/", null);
result = new Result().setCode(ResultCode.ERROR).setMessage("请重新登录");
} else {
result = tbCfUserInfoService.login(getIpAddr(request), tbCfUserInfoVo.getAccount(), tbCfUserInfoVo.getPassword());
SessionUtils.setSessionUser(request, new SessionUser(token, tbCfUserInfoVo.getAccount()));
}
} else {
Validator.NOT_BLANK.validate("登录名", account);
Validator.NOT_BLANK.validate("密码", password);
result = tbCfUserInfoService.login(getIpAddr(request), account, PasswordProvider.encrypt(password));
}
return result;
}
*/
@ApiOperation("第三方登录")
@PostMapping("/thirdParty")
public Result<TbCfUserInfoVo> loginByThirdParty(@ApiParam("第三方账号") @RequestParam(required = false) String amount,
@ApiParam("用户昵称 url编码") @RequestParam(required = false) String nick,
@ApiParam("账号类型") @RequestParam(required = false) String userType) throws UnsupportedEncodingException {
Result result=tbCfUserInfoService.loginByThirdParty(getIpAddr(request),amount,nick,userType);
return result;
}
/*private String authBackUrl(String backUrl, String token) {
StringBuilder sbf = new StringBuilder(backUrl);
if (backUrl.indexOf("?") > 0) {
sbf.append("&");
} else {
sbf.append("?");
}
sbf.append(SsoFilter.SSO_TOKEN_NAME).append("=").append(token);
return sbf.toString();
return tbCfUserInfoService.loginByThirdParty(getIpAddr(request),amount,nick,userType);
}
private String goLoginPath(String backUrl, HttpServletRequest request) {
request.setAttribute("backUrl", backUrl);
return LOGIN_PATH;
}*/
}
package com.diaoyun.zion.chinafrica.controller;
import com.diaoyun.zion.chinafrica.client.SessionUtils;
import com.diaoyun.zion.chinafrica.service.TbCfUserInfoService;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.util.CookieUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
......@@ -33,7 +26,6 @@ public class LogoutController {
@ApiOperation("登出")
@GetMapping
public Result logout() {
Result result=tbCfUserInfoService.logout();
return result;
return tbCfUserInfoService.logout();
}
}
\ No newline at end of file
......@@ -20,7 +20,7 @@ import java.util.Map;
*/
@Api(tags = "联系方式")
@RestController
@RequestMapping("contact")
@RequestMapping("/contact")
public class TbCfContactController {
@Autowired
private TbCfContactService tbCfContactService;
......
......@@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
/**
* 商品详情Controller
......@@ -34,7 +36,7 @@ public class TbCfItemDetailController {
@ApiOperation("加入到购物车")
@PostMapping("/cart")
public Result addToCart(@ApiParam("商品详情") @RequestBody TbCfItemDetailVo tbCfItemDetailVo) {
public Result addToCart(@ApiParam("商品详情") @RequestBody TbCfItemDetailVo tbCfItemDetailVo) throws InterruptedException, ExecutionException, TimeoutException {
return tbCfItemDetailService.addToCart(tbCfItemDetailVo);
}
......
......@@ -24,7 +24,7 @@ import java.util.concurrent.TimeoutException;
*/
@Api(tags = "订单")
@RestController
@RequestMapping("order")
@RequestMapping("/order")
public class TbCfOrderController {
@Autowired
private TbCfOrderService tbCfOrderService;
......@@ -71,13 +71,12 @@ public class TbCfOrderController {
}
@ApiOperation("根据订单id,查询物流详情")
@GetMapping("/logistics/{orderId}")
public Result queryOrderLogistics(@ApiParam("订单id")@PathVariable String orderId) {
return tbCfOrderService.queryOrderLogistics(orderId);
@GetMapping("/express/{orderId}")
public Result queryOrderExpressInfo(@ApiParam("订单id")@PathVariable String orderId) throws IOException {
return tbCfOrderService.queryOrderExpressInfo(orderId);
}
/*
@ApiOperation("取消订单")
@DeleteMapping
......
......@@ -20,7 +20,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
*/
@Api(tags = "独立站")
@RestController
@RequestMapping("platform")
@RequestMapping("/platform")
public class TbCfPlatformController {
@Autowired
private TbCfPlatformService tbCfPlatformService;
......
......@@ -22,7 +22,7 @@ import java.util.List;
*/
@Api(tags = "常见问题")
@RestController
@RequestMapping("problem")
@RequestMapping("/problem")
public class TbCfProblemController {
@Autowired
private TbCfProblemService tbCfProblemService;
......
......@@ -20,7 +20,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
*/
@Api(tags="商品独立站")
@RestController
@RequestMapping("itemStation")
@RequestMapping("/itemStation")
public class TbCfStationItemController {
@Autowired
private TbCfStationItemService tbCfStationItemService;
......
......@@ -6,7 +6,6 @@ import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.base.BaseController;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.PasswordProvider;
import com.diaoyun.zion.master.validator.Validator;
import com.diaoyun.zion.master.validator.annotation.ValidateParam;
import freemarker.template.TemplateException;
......@@ -18,6 +17,7 @@ import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
......@@ -30,7 +30,7 @@ import java.net.URLDecoder;
*/
@Api(tags = "用户相关")
@RestController
@RequestMapping("user")
@RequestMapping("/user")
public class TbCfUserInfoController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(TbCfUserInfoController.class);
......@@ -40,6 +40,8 @@ public class TbCfUserInfoController extends BaseController {
@Autowired
private TbCfUserInfoService tbCfUserInfoService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 获取邮箱验证码
......@@ -49,8 +51,9 @@ public class TbCfUserInfoController extends BaseController {
public Result getUserIdentifyCode(@ApiParam("用户邮箱") @PathVariable("email") @ValidateParam({Validator.NOT_BLANK}) String email,
@ApiParam("用户昵称 url编码") @PathVariable("nick") @ValidateParam({Validator.NOT_BLANK}) String nick) throws EmailException, TemplateException, IOException {
nick= URLDecoder.decode(nick, Consts.UTF_8.name());
Integer identifyCode = tbCfUserInfoService.sendRegisterIdentifyCode(email, nick);
request.getSession().setAttribute(KeyConstant.IDENTIFY_CODE, identifyCode);
tbCfUserInfoService.sendRegisterIdentifyCode(email, nick);
//request.getSession().setAttribute(KeyConstant.IDENTIFY_CODE, identifyCode);
// TODO 不能返回验证码,先做测试 identifyCode.toString(),
return new Result("Verification code has been sent");
}
......@@ -77,7 +80,7 @@ public class TbCfUserInfoController extends BaseController {
@PutMapping(value="/password/{newPassword}/{oldPassword}")
public Result updatePassWord(@ApiParam("新密码") @PathVariable @ValidateParam({Validator.NOT_BLANK}) String newPassword
,@ApiParam("旧密码") @PathVariable @ValidateParam({Validator.NOT_BLANK}) String oldPassword) {
return tbCfUserInfoService.updatePassWord(PasswordProvider.encrypt(newPassword),PasswordProvider.encrypt(oldPassword));
return tbCfUserInfoService.updatePassWord(passwordEncoder.encode(newPassword),passwordEncoder.encode(oldPassword));
}
......
package com.diaoyun.zion.chinafrica.dao;
import com.diaoyun.zion.chinafrica.entity.TbCfItemDetailEntity;
import com.diaoyun.zion.chinafrica.entity.TbCfItemShippedEntity;
import com.diaoyun.zion.chinafrica.entity.TbCfOrderEntity;
import com.diaoyun.zion.master.dao.BaseDao;
import java.util.Date;
import java.util.List;
/**
......@@ -27,4 +29,20 @@ public interface TbCfOrderDao extends BaseDao<TbCfOrderEntity> {
* @return
*/
List<TbCfItemDetailEntity> getOrderItemList(String orderId);
/**
* 获取付款订单
* @param beginDate
* @param endDate
* @return
*/
List<TbCfOrderEntity> getOrderListByTime(Date beginDate, Date endDate);
/**
* 获取某段时间已发货订单数据
* @param beginDate
* @param endDate
* @return
*/
List<TbCfItemShippedEntity> getDeliveryList(Date beginDate, Date endDate);
}
......@@ -42,6 +42,10 @@ public class TbCfFinanceEntity implements Serializable {
* 支付时间
*/
private Date payTime;
/**
* 支付结果页面
*/
private String receiptUrl;
/**
* 设置:财务报表id
......@@ -134,4 +138,12 @@ public class TbCfFinanceEntity implements Serializable {
public Date getPayTime() {
return payTime;
}
public String getReceiptUrl() {
return receiptUrl;
}
public void setReceiptUrl(String receiptUrl) {
this.receiptUrl = receiptUrl;
}
}
package com.diaoyun.zion.chinafrica.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 已发货订单
*
* @author G
* @date 2019-08-14 09:11:48
*/
public class TbCfItemShippedEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单id
*/
private String orderId;
/**
* 发货时间
*/
private Date deliveryTime;
/**
* 收货地址
*/
private String deliveryAddress;
/**
* 用户id
*/
private String userId;
/**
* 快递单号
*/
private String expressId;
/**
* 设置:订单id
*/
public void setOrderId(String orderId) {
this.orderId = orderId;
}
/**
* 获取:订单id
*/
public String getOrderId() {
return orderId;
}
public Date getDeliveryTime() {
return deliveryTime;
}
public void setDeliveryTime(Date deliveryTime) {
this.deliveryTime = deliveryTime;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getExpressId() {
return expressId;
}
public void setExpressId(String expressId) {
this.expressId = expressId;
}
}
......@@ -8,6 +8,8 @@ import com.diaoyun.zion.master.base.Result;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
/**
* 商品详情Service接口
......@@ -78,7 +80,7 @@ public interface TbCfItemDetailService {
* @param tbCfItemDetailVo
* @return
*/
Result addToCart(TbCfItemDetailVo tbCfItemDetailVo);
Result addToCart(TbCfItemDetailVo tbCfItemDetailVo) throws InterruptedException, ExecutionException, TimeoutException;
/**
* 更改购物车商品数量
......
......@@ -127,5 +127,32 @@ public interface TbCfOrderService {
* @param orderId
* @return
*/
Result queryOrderLogistics(String orderId);
Result queryOrderExpressInfo(String orderId) throws IOException;
/**
* 获取某段时间内的付款订单
* @param beginTime
* @param endTime
* @param pageNum
* @param pageSize
* @return
*/
Result getOrderListByTime(long beginTime, long endTime, Integer pageNum, Integer pageSize);
/**
* 获取某段时间已发货订单数据
* @param beginTime
* @param endTime
* @param pageNum
* @param pageSize
* @return
*/
Result getDeliveryList(long beginTime, long endTime, Integer pageNum, Integer pageSize);
/**
* 根据订单号获取详细订单数据
* @param orderId
* @return
*/
Result getOrderDetail(String orderId);
}
......@@ -136,4 +136,11 @@ public interface TbCfUserInfoService {
* @return
*/
Result loginByThirdParty(String ip,String amount,String nick,String userType) throws UnsupportedEncodingException;
/**
* 使用token登录
* @param ipAddr
* @return
*/
Result loginByToken(String ipAddr);
}
......@@ -10,7 +10,7 @@ import com.diaoyun.zion.chinafrica.vo.TbCfAddressVo;
import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.IdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -38,6 +38,8 @@ public class TbCfAddressServiceImpl implements TbCfAddressService {
@Resource(name="redisTokenManager")
private TokenManager tokenManager;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private HttpServletRequest request; //自动注入request
@Override
......@@ -78,7 +80,7 @@ public class TbCfAddressServiceImpl implements TbCfAddressService {
@Override
public TbCfAddressVo saveAddress(TbCfAddressVo tbCfAddressVo) {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
String userId=tbCfUserInfoVo.getUserId();
tbCfAddressVo.setUserId(userId);
......@@ -94,7 +96,7 @@ public class TbCfAddressServiceImpl implements TbCfAddressService {
@Override
public TbCfAddressVo updateAddress(TbCfAddressVo tbCfAddressVo) {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
String userId=tbCfUserInfoVo.getUserId();
tbCfAddressVo.setUserId(userId);
......@@ -110,7 +112,7 @@ public class TbCfAddressServiceImpl implements TbCfAddressService {
@Override
public List<TbCfAddressVo> getUserInfoList() {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
String userId=tbCfUserInfoVo.getUserId();
List<TbCfAddressEntity> tbCfAddressList=tbCfAddressDao.queryListByUserId(userId);
......@@ -127,7 +129,7 @@ public class TbCfAddressServiceImpl implements TbCfAddressService {
@Override
public int configDefaultAddress(String addressId) {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
String userId=tbCfUserInfoVo.getUserId();
//更新用户默认地址
......
......@@ -12,7 +12,7 @@ import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.common.RedisCache;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -48,6 +48,9 @@ public class TbCfCouponServiceImpl implements TbCfCouponService {
@Resource(name = "redisTokenManager")
private TokenManager tokenManager;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private HttpServletRequest request; //自动注入request
@Resource
......@@ -93,7 +96,7 @@ public class TbCfCouponServiceImpl implements TbCfCouponService {
public Result takeCoupon(String couponId) {
Result<TbCfCouponEntity> result=new Result<>();
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
//判断用户是否已经领取
boolean takeFlag=repeatTakeCoupon(tbCfUserInfoVo.getUserId(),couponId);
......
......@@ -8,7 +8,7 @@ import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
......@@ -33,6 +33,8 @@ public class TbCfFeedbackServiceImpl implements TbCfFeedbackService {
@Autowired
@Qualifier("redisTokenManager")
private TokenManager tokenManager;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private HttpServletRequest request; //自动注入request
......@@ -77,7 +79,7 @@ public class TbCfFeedbackServiceImpl implements TbCfFeedbackService {
public Result saveFeedback(TbCfFeedbackEntity tbCfFeedbackEntity) {
Result result=new Result();
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
tbCfFeedbackEntity.setFeedbackId(IdUtil.createIdbyUUID());
tbCfFeedbackEntity.setUserId(tbCfUserInfoVo.getUserId());
......
package com.diaoyun.zion.chinafrica.service.impl;
import com.diaoyun.zion.chinafrica.dao.TbCfCartRecordRDao;
import com.diaoyun.zion.chinafrica.dao.TbCfExpTemKeywordDao;
import com.diaoyun.zion.chinafrica.dao.TbCfItemDetailDao;
import com.diaoyun.zion.chinafrica.entity.TbCfCartRecordREntity;
import com.diaoyun.zion.chinafrica.entity.TbCfExpressTemplateEntity;
import com.diaoyun.zion.chinafrica.entity.TbCfItemDetailEntity;
import com.diaoyun.zion.chinafrica.service.TbCfItemDetailService;
import com.diaoyun.zion.chinafrica.vo.TbCfCartItemDetailVo;
......@@ -12,17 +14,20 @@ import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.WordposHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
/**
* 商品详情Service实现类
......@@ -37,10 +42,15 @@ public class TbCfItemDetailServiceImpl implements TbCfItemDetailService {
@Autowired
private TbCfCartRecordRDao tbCfCartRecordRDao;
@Autowired
private TbCfExpTemKeywordDao tbCfExpTemKeywordDao;
@Resource(name="redisTokenManager")
private TokenManager tokenManager;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private HttpServletRequest request; //自动注入request
......@@ -82,11 +92,14 @@ public class TbCfItemDetailServiceImpl implements TbCfItemDetailService {
}
@Override
public Result addToCart(TbCfItemDetailVo tbCfItemDetailVo) {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
public Result addToCart(TbCfItemDetailVo tbCfItemDetailVo) throws InterruptedException, ExecutionException, TimeoutException {
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
//填充新商品必要信息
fillItemInfo(tbCfItemDetailVo);
//为商品分类,后面计算运费
TbCfExpressTemplateEntity expressTemplate = recognizeItemCategory(tbCfItemDetailVo.getItemTitle());
tbCfItemDetailVo.setItemCategory(expressTemplate.getTemplateId());
//加入商品详情
TbCfItemDetailEntity tbCfItemDetail= new TbCfItemDetailEntity();
BeanUtils.copyProperties(tbCfItemDetailVo,tbCfItemDetail);
......@@ -120,7 +133,7 @@ public class TbCfItemDetailServiceImpl implements TbCfItemDetailService {
@Override
public List<TbCfCartItemDetailVo> getCartItemList() {
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
String userId=tbCfUserInfoVo.getUserId();
return tbCfItemDetailDao.getCartItemList(userId,null);
......@@ -144,4 +157,59 @@ public class TbCfItemDetailServiceImpl implements TbCfItemDetailService {
tbCfItemDetailVo.setItemId(IdUtil.createIdbyUUID());
tbCfItemDetailVo.setCreateTime(new Date());
}
/**
* 获取运费模板(包含分类)
*
* @param itemTitle
* @return
*/
private TbCfExpressTemplateEntity recognizeItemCategory(String itemTitle) throws ExecutionException, InterruptedException, TimeoutException {
Map<String, Object> wordResult = separateText(itemTitle);
//pos_code 16为名词,用名词去匹配; 23非汉字串
JSONArray baseTokens = (JSONArray) wordResult.get("base_tokens");
List<String> keywordList = new ArrayList<>();
for (int i = 0; i < baseTokens.size(); i++) {
JSONObject jsonObject = (JSONObject) baseTokens.get(i);
if (16 == (Integer) jsonObject.get("pos_code")) {
keywordList.add((String) jsonObject.get("word"));
}
if (23 == (Integer) jsonObject.get("pos_code")) {
keywordList.add((String) jsonObject.get("word"));
}
}
//总的可能适用的运费模板
Set<TbCfExpressTemplateEntity> totalTemplateSet = new HashSet<>();
if (!keywordList.isEmpty()) {
for (String keyword : keywordList) {
//根据keyword获取运费模板
List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword(keyword);
totalTemplateSet.addAll(tbCfExpressTemplateList);
}
}
//没有的话就设置 其他
if (totalTemplateSet.isEmpty()) {
//根据keyword获取运费模板
List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword("其他");
totalTemplateSet.addAll(tbCfExpressTemplateList);
}
//取第一个运费
Iterator<TbCfExpressTemplateEntity> iterator = totalTemplateSet.iterator();
TbCfExpressTemplateEntity useTemplate = iterator.next();
return useTemplate;
}
/**
* 分词
* @param text
* @return
*/
private Map<String, Object> separateText(String text) throws ExecutionException, InterruptedException, TimeoutException {
List<Map<String, Object>> futureList = new ArrayList<>();
Map<String, Object> titleMap = new HashMap<>();
titleMap.put("text", text);
WordposHelper.separeteText(futureList, titleMap, text);
WordposHelper.waitForResult(futureList);
return titleMap;
}
}
......@@ -18,16 +18,12 @@ import com.diaoyun.zion.master.common.RedisCache;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.config.DomainProperties;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.AESUtils;
import com.diaoyun.zion.master.util.CookieUtils;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.WordposHelper;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.*;
import com.diaoyun.zion.master.validator.Validator;
import com.github.pagehelper.PageInfo;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -77,7 +73,9 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
@Autowired
private TbCfFinanceDao tbCfFinanceDao;
@Autowired
private TbCfExpTemKeywordDao tbCfExpTemKeywordDao;
private TbCfExpressTemplateDao tbCfExpressTemplateDao;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private TbCfFeeService tbCfFeeService;
......@@ -137,7 +135,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
public Result settleAccount() throws IOException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
Result<TbCfOrderVo> result = new Result<>();
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
//获取购物车已勾选 商品
List<TbCfCartItemDetailVo> tbCfCartItemDetailList = tbCfItemDetailDao.getCartItemList(tbCfUserInfoVo.getUserId(), StateConstant.VALID);
......@@ -156,7 +154,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
public Result placeOrder(TbCfOrderVo pageOrder) throws IOException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
Result<TbCfOrderVo> result = new Result<>();
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
//获取购物车已勾选 商品
List<TbCfCartItemDetailVo> tbCfCartItemDetailList = tbCfItemDetailDao.getCartItemList(tbCfUserInfoVo.getUserId(), StateConstant.VALID);
......@@ -182,7 +180,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
public Result getUserOrderList(Integer pageNum, Integer pageSize) {
Result<PageInfo<TbCfOrderVo>> result = new Result<>();
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token = jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
//订单数据
List<TbCfOrderEntity> orderList = tbCfOrderDao.getUserOrderList(tbCfUserInfoVo.getUserId());
......@@ -240,7 +238,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
@Override
public Result payForOrder(String orderId, String token) {
Result result = new Result();
Result<TbCfFinanceEntity> result = new Result<>();
TbCfOrderVo tbCfOrderVo = (TbCfOrderVo) orderRedisCache.get(KeyConstant.ORDER_DET + orderId);
if (tbCfOrderVo != null) {
BigDecimal realityPay = tbCfOrderVo.getRealityPay();
......@@ -257,7 +255,8 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
//更改订单状态
changeOrderState(charge.getId(), tbCfOrderVo);
//生成流水记录
createFinance(charge, tbCfOrderVo);
TbCfFinanceEntity tbCfFinance = createFinance(charge, tbCfOrderVo);
result.setData(tbCfFinance);
} else {
result.setCode(ResultCodeEnum.SERVICE_ERROR.getCode()).setMessage("Payment failed!");
}
......@@ -275,9 +274,80 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
}
@Override
public Result queryOrderLogistics(String orderId) {
public Result queryOrderExpressInfo(String orderId) throws IOException {
String expressUrl = domainProperties.getProperty("express.info.api");
String userNo = domainProperties.getProperty("express.info.user_no");
String token = domainProperties.getProperty("express.info.token");
Map<String, Object> paramMap = new HashMap<>();
List<Map<String, String>> data = new ArrayList<>();
Map<String, String> dataMap = new HashMap<>();
dataMap.put("order_no", orderId);
data.add(dataMap);
paramMap.put("user_no", userNo);
paramMap.put("token", token);
paramMap.put("data", data);
String resultStr = HttpClientUtil.sendPostWithBodyParameter(expressUrl, paramMap);
Map resultMap = GsonUtil.GsonToMaps(resultStr);
return new Result<>(resultMap);
}
@Override
public Result getOrderListByTime(long beginTime, long endTime, Integer pageNum, Integer pageSize) {
Result result=new Result<>();
if((endTime-beginTime)>31*24*60*60) {
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("Time interval is too long");
} else {
startPage(pageNum, pageSize);
Date beginDate=new Date(beginTime*1000);
Date endDate=new Date(endTime*1000);
List<TbCfOrderEntity> orderList=tbCfOrderDao.getOrderListByTime(beginDate,endDate);
PageInfo<TbCfOrderEntity> pageInfo = new PageInfo<>(orderList);
result.setData(pageInfo);
}
return result;
}
return null;
@Override
public Result getDeliveryList(long beginTime, long endTime, Integer pageNum, Integer pageSize) {
Result result=new Result<>();
if((endTime-beginTime)>31*24*60*60) {
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("Time interval is too long");
} else {
startPage(pageNum, pageSize);
Date beginDate=new Date(beginTime*1000);
Date endDate=new Date(endTime*1000);
List<TbCfItemShippedEntity> orderList=tbCfOrderDao.getDeliveryList(beginDate,endDate);
PageInfo<TbCfItemShippedEntity> pageInfo = new PageInfo<>(orderList);
result.setData(pageInfo);
}
return result;
}
@Override
public Result getOrderDetail(String orderId) {
Result<TbCfOrderVo> result = new Result<>();
TbCfOrderEntity tbCfOrderEntity = tbCfOrderDao.queryObject(orderId);
TbCfOrderVo tbCfOrderVo = new TbCfOrderVo();
tbCfOrderVo.setOrderId(tbCfOrderEntity.getOrderId());
tbCfOrderVo.setDeliveryPhone(tbCfOrderEntity.getDeliveryPhone());
tbCfOrderVo.setDeliveryName(tbCfOrderEntity.getDeliveryName());
tbCfOrderVo.setDeliveryAddress(tbCfOrderEntity.getDeliveryAddress());
//获取订单内商品
List<TbCfItemDetailEntity> tbCfItemDetailList = tbCfOrderDao.getOrderItemList(orderId);
//返回的订单商品详情
List<TbCfCartItemDetailVo> itemDetailVoList = new ArrayList<>();
for (TbCfItemDetailEntity tbCfItemDetail : tbCfItemDetailList) {
TbCfCartItemDetailVo tbCfCartItemDetailVo = new TbCfCartItemDetailVo();
tbCfCartItemDetailVo.setItemNum(tbCfItemDetail.getItemNum());
tbCfCartItemDetailVo.setItemCategory(tbCfItemDetail.getItemCategory());
tbCfCartItemDetailVo.setItemPrice(tbCfItemDetail.getItemPrice());
tbCfCartItemDetailVo.setItemTitle(tbCfItemDetail.getItemTitle());
itemDetailVoList.add(tbCfCartItemDetailVo);
}
tbCfOrderVo.setItemDetailList(itemDetailVoList);
result.setData(tbCfOrderVo);
return result;
}
/**
......@@ -286,17 +356,19 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
* @param charge
* @param tbCfOrderVo
*/
private void createFinance(Charge charge, TbCfOrderVo tbCfOrderVo) {
private TbCfFinanceEntity createFinance(Charge charge, TbCfOrderVo tbCfOrderVo) {
TbCfFinanceEntity tbCfFinance = new TbCfFinanceEntity();
tbCfFinance.setOrderId(tbCfOrderVo.getOrderId());
tbCfFinance.setFinaceId(IdUtil.createIdbyUUID());
tbCfFinance.setPayAccount(tbCfOrderVo.getRealityPay());
tbCfFinance.setPayId(charge.getId());
tbCfFinance.setPayTime(new Date());
tbCfFinance.setReceiptUrl(charge.getReceiptUrl());
//暂时用 stripe
tbCfFinance.setPayWayCode("stripe");
tbCfFinance.setUserId(tbCfOrderVo.getUserId());
tbCfFinanceDao.save(tbCfFinance);
return tbCfFinance;
}
/**
......@@ -314,7 +386,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
tbCfOrder.setOrderStatus(OrderStatusEnum.PAID.getValue());
tbCfOrder.setDeliveryFlag(DeliveryStatusEnum.PROCESSING.getValue());
tbCfOrder.setPayId(payId);
tbCfOrder.setPayStatus(StateConstant.VALID);
tbCfOrder.setPayStatus(OrderStatusEnum.PAID.getValue());
tbCfOrderDao.update(tbCfOrder);
}
......@@ -503,7 +575,7 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
BigDecimal itemNum = BigDecimal.valueOf(tbCfCartItemDetailVo.getItemNum());
itemsPrice = itemsPrice.add(tbCfCartItemDetailVo.getItemPrice().multiply(itemNum));
//计算运费
BigDecimal expressCost = countExpressCost(tbCfCartItemDetailVo.getItemTitle());
BigDecimal expressCost = getExpressTemplate(tbCfCartItemDetailVo.getItemCategory());
expressCost = expressCost.multiply(itemNum);
totalExpressCost = totalExpressCost.add(expressCost);
}
......@@ -525,62 +597,15 @@ public class TbCfOrderServiceImpl implements TbCfOrderService {
}
/**
* 计算运费
*
* @param itemTitle
* 获取运费 TODO 运费模板可改为缓存
* @param templateId
* @return
*/
private BigDecimal countExpressCost(String itemTitle) throws ExecutionException, InterruptedException, TimeoutException {
BigDecimal itemExpressFee;
Map<String, Object> wordResult = separateText(itemTitle);
//pos_code 16为名词,用名词去匹配; 23非汉字串
JSONArray baseTokens = (JSONArray) wordResult.get("base_tokens");
List<String> keywordList = new ArrayList<>();
for (int i = 0; i < baseTokens.size(); i++) {
JSONObject jsonObject = (JSONObject) baseTokens.get(i);
if (16 == (Integer) jsonObject.get("pos_code")) {
keywordList.add((String) jsonObject.get("word"));
}
if (23 == (Integer) jsonObject.get("pos_code")) {
keywordList.add((String) jsonObject.get("word"));
}
}
//总的可能适用的运费模板
Set<TbCfExpressTemplateEntity> totalTemplateSet = new HashSet<>();
if (!keywordList.isEmpty()) {
for (String keyword : keywordList) {
//根据keyword获取运费模板
List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword(keyword);
totalTemplateSet.addAll(tbCfExpressTemplateList);
}
}
//没有的话就设置 其他
if (totalTemplateSet.isEmpty()) {
//根据keyword获取运费模板
List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword("其他");
totalTemplateSet.addAll(tbCfExpressTemplateList);
}
//取第一个运费
Iterator<TbCfExpressTemplateEntity> iterator = totalTemplateSet.iterator();
TbCfExpressTemplateEntity useTemplate = iterator.next();
itemExpressFee = useTemplate.getExpressFee();
return itemExpressFee;
private BigDecimal getExpressTemplate(String templateId) {
TbCfExpressTemplateEntity tbCfExpressTemplateEntity =tbCfExpressTemplateDao.queryObject(templateId);
return tbCfExpressTemplateEntity.getExpressFee();
}
/**
* 分词
*
* @param text
* @return
*/
public Map<String, Object> separateText(String text) throws ExecutionException, InterruptedException, TimeoutException {
List<Map<String, Object>> futureList = new ArrayList<>();
Map<String, Object> titleMap = new HashMap<>();
titleMap.put("text", text);
WordposHelper.separeteText(futureList, titleMap, text);
WordposHelper.waitForResult(futureList);
return titleMap;
}
/**
* 验证订单优惠券
......
......@@ -11,13 +11,16 @@ import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.bo.EmailTemplateBo;
import com.diaoyun.zion.master.common.RedisCache;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.config.DomainProperties;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.enums.SexEnum;
import com.diaoyun.zion.master.enums.TrueFalseEnum;
import com.diaoyun.zion.master.enums.UserTypeEnum;
import com.diaoyun.zion.master.exception.ApplicationException;
import com.diaoyun.zion.master.exception.ValidateException;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.*;
import com.diaoyun.zion.master.validator.Validator;
import freemarker.template.TemplateException;
......@@ -26,6 +29,11 @@ import org.apache.commons.mail.EmailException;
import org.apache.http.Consts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
......@@ -50,6 +58,15 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
@Autowired
private TbCfUserInfoDao tbCfUserInfoDao;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@Resource(name = "redisTokenManager")
private TokenManager tokenManager;
......@@ -65,6 +82,9 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
@Autowired
private HttpServletResponse response;
@Autowired
private RedisCache<Object> captchaRedisCache;
@Override
public TbCfUserInfoEntity queryObject(String userId) {
return tbCfUserInfoDao.queryObject(userId);
......@@ -108,13 +128,15 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
emailTemplateBo.setNick(nick);
emailTemplateBo.setIdentifyCode(randomCode);
Integer identifyCode = emailHelper.sendIdentifyEmail(email, EmailTemplateConstant.REGISTER, emailTemplateBo);
captchaRedisCache.set(KeyConstant.CAPTCHA + email, identifyCode, 1800);
return identifyCode;
}
@Override
public Result registerAndLogin(TbCfUserInfoVo tbCfUserInfoVo) {
Result result = new Result();
Integer identifyCode = (Integer) request.getSession().getAttribute(KeyConstant.IDENTIFY_CODE);
Integer identifyCode = (Integer) captchaRedisCache.get(KeyConstant.CAPTCHA + tbCfUserInfoVo.getAccount());
;
if (identifyCode == null || identifyCode.intValue() != tbCfUserInfoVo.getCaptcha().intValue()) {
result.setCode(ResultCodeEnum.VALIDATE_ERROR.getCode());
result.setMessage("Verification code error");
......@@ -122,8 +144,6 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
//验证邮箱有没有被注册
TbCfUserInfoEntity existUser = findByAccount(tbCfUserInfoVo.getEmail());
if (existUser == null) {
//验证邮箱格式
Validator.NOT_BLANK.validate("email", tbCfUserInfoVo.getEmail());
TbCfUserInfoEntity tbCfUserInfoEntity = new TbCfUserInfoEntity();
/**
......@@ -134,110 +154,63 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
tbCfUserInfoVo.setEmailFlag(StateConstant.VALID);
fillUserNecessayInfo(tbCfUserInfoVo);
//加密密码
String password = PasswordProvider.encrypt(tbCfUserInfoVo.getPassword());
String password = passwordEncoder.encode(tbCfUserInfoVo.getPassword());
tbCfUserInfoVo.setPassword(password);
BeanUtils.copyProperties(tbCfUserInfoVo, tbCfUserInfoEntity);
tbCfUserInfoDao.save(tbCfUserInfoEntity);
//注册成功 创建token
String token = createToken(tbCfUserInfoVo);
addTokenInCookie(token, request, response);
SessionUtils.setSessionUser(request, new SessionUser(token, tbCfUserInfoVo.getAccount()));
String token = jwtTokenProvider.createToken(tbCfUserInfoVo.getAccount());
tbCfUserInfoVo.setToken(token);
//保存在redis
tokenManager.addToken(token, tbCfUserInfoVo);
result.setMessage(ResultCodeEnum.SUCCESS.getDesc());
result.setData(tbCfUserInfoVo);
} else {
result.setCode(ResultCodeEnum.VALIDATE_ERROR.getCode());
result.setMessage("The mailbox has been registered");
result.setMessage("The mailbox or nick has been registered");
}
tbCfUserInfoVo.setEnableFlag(StateConstant.VALID);
}
return result;
}
@Override
public Result login(String ip, String account, String password) {
Result result = new Result();
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
if (StringUtils.isNotBlank(token)) {
TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
if (tbCfUserInfoVo == null) {
if(StringUtils.isBlank(account)||StringUtils.isBlank(password)) {
tokenManager.remove(token);
CookieUtils.removeCookie(response, TokenManager.TOKEN, "/", null);
result.setCode(ResultCodeEnum.NEED_LOGIN.getCode()).setMessage(ResultCodeEnum.NEED_LOGIN.getDesc());
} else {
password = PasswordProvider.encrypt(password);
result = loginOfficial(ip, account,password, token);
}
} else {
if(StringUtils.isBlank(account)) {
account=tbCfUserInfoVo.getAccount();
}
if(StringUtils.isBlank(password)) {
password=tbCfUserInfoVo.getPassword();
} else {
password = PasswordProvider.encrypt(password);
}
result = loginOfficial(ip, account,password, token);
}
} else {
Validator.NOT_BLANK.validate("account", account);
Validator.NOT_BLANK.validate("password", password);
password = PasswordProvider.encrypt(password);
result = loginOfficial(ip, account, password, null);
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(account, password));
String token = jwtTokenProvider.createToken(account);
//password = passwordEncoder.encode(password);
return loginOfficial(ip, account, token);
} catch (AuthenticationException e) {
throw new ApplicationException(ResultCodeEnum.NEED_LOGIN.getCode(),"Invalid username/password supplied or account is disable");
}
return result;
}
/**
* 登录
*
* @param ip
* @param account
* @param password
* @param token
* @return
*/
private Result loginOfficial(String ip, String account, String password, String token) {
Result result = new Result();
private Result loginOfficial(String ip, String account, String token) {
Result<TbCfUserInfoVo> result = new Result<>();
TbCfUserInfoEntity user = findByAccount(account);
if (user == null) {
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("Account does not exist");
} else if (user.getPassword()!=null&&!user.getPassword().equals(password)) {
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("The password is incorrect");
} else if (TrueFalseEnum.FALSE.getValue().equals(user.getEnableFlag())) {
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("User is disabled");
CookieUtils.removeCookie(response, TokenManager.TOKEN, "/", null);
} else {
user.setLastLoginIp(ip);
user.setLoginCount(user.getLoginCount() + 1);
user.setLastLoginTime(new Date());
tbCfUserInfoDao.update(user);
//登录成功
TbCfUserInfoVo loginUser = new TbCfUserInfoVo();
BeanUtils.copyProperties(user, loginUser);
if (StringUtils.isBlank(token)) {
//用户密码登录成功 创建token
token = createToken(loginUser);
addTokenInCookie(token, request, response);
} else {
//更新用户
tokenManager.addToken(token, loginUser);
}
SessionUtils.setSessionUser(request, new SessionUser(token, loginUser.getAccount()));
result.setData(loginUser).setMessage(ResultCodeEnum.SUCCESS.getDesc());
}
user.setLastLoginIp(ip);
user.setLoginCount(user.getLoginCount() + 1);
user.setLastLoginTime(new Date());
tbCfUserInfoDao.update(user);
TbCfUserInfoVo loginUser = new TbCfUserInfoVo();
BeanUtils.copyProperties(user, loginUser);
loginUser.setToken(token);
//更新用户
tokenManager.addToken(token, loginUser);
result.setData(loginUser).setMessage(ResultCodeEnum.SUCCESS.getDesc());
return result;
}
}
@Override
public TbCfUserInfoEntity findByAccount(String account) {
......@@ -248,7 +221,7 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
@Override
public Result updatePassWord(String newPassword, String oldPassword) {
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token=jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo loginUser = tokenManager.validate(token);
String userId = loginUser.getUserId();
Result result = new Result();
......@@ -264,18 +237,17 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
@Override
public Result logout() {
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token=jwtTokenProvider.resolveToken(request);
if (StringUtils.isNotBlank(token)) {
tokenManager.remove(token);
}
SessionUtils.invalidate(request);
return new Result("login out");
}
@Override
public int updateUserInfo(TbCfUserInfoVo tbCfUserInfoVo) {
//获取用户
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
String token=jwtTokenProvider.resolveToken(request);
TbCfUserInfoVo loginUser = tokenManager.validate(token);
String userId = loginUser.getUserId();
tbCfUserInfoVo.setUserId(userId);
......@@ -286,8 +258,9 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
}
@Override
// TODO
public Result loginByThirdParty(String ip, String account, String nick, String userType) throws UnsupportedEncodingException {
Result result = new Result();
/*Result result = new Result();
String token = CookieUtils.getCookie(request, TokenManager.TOKEN);
if (StringUtils.isNotBlank(token) && tokenManager.validate(token) != null) {
......@@ -296,13 +269,13 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
CookieUtils.removeCookie(response, TokenManager.TOKEN, "/", null);
result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("please login again");
} else {
if(StringUtils.isBlank(account)) {
account=tbCfUserInfoVo.getAccount();
if (StringUtils.isBlank(account)) {
account = tbCfUserInfoVo.getAccount();
}
if(StringUtils.isBlank(nick)) {
nick=tbCfUserInfoVo.getNick();
if (StringUtils.isBlank(nick)) {
nick = tbCfUserInfoVo.getNick();
}
loginByThirdPartyOfficial(token, ip,account ,nick , result);
loginByThirdPartyOfficial(token, ip, account, nick, result);
}
} else {
Validator.NOT_BLANK.validate("account", account);
......@@ -320,9 +293,9 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
tbCfUserInfoVo.setNick(nick);
tbCfUserInfoVo.setLastLoginIp(ip);
TbCfUserInfoEntity tbCfUserInfoEntity = new TbCfUserInfoEntity();
/**
*//**
* 填充必要信息
*/
*//*
fillUserNecessayInfo(tbCfUserInfoVo);
BeanUtils.copyProperties(tbCfUserInfoVo, tbCfUserInfoEntity);
......@@ -332,7 +305,7 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
buildUserToken(tbCfUserInfoEntity);
result.setMessage("登录成功").setData(tbCfUserInfoVo);
} else {
if(nick.equals(oldUser.getNick())) {
if (nick.equals(oldUser.getNick())) {
oldUser.setLastLoginIp(ip);
oldUser.setLoginCount(oldUser.getLoginCount() + 1);
oldUser.setLastLoginTime(new Date());
......@@ -345,13 +318,21 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
}
}
}
return result;
}*/
return null;
}
@Override
public Result loginByToken(String ip) {
String token=jwtTokenProvider.resolveToken(request);
String account=jwtTokenProvider.getUsername(token);
return loginOfficial(ip,account,token);
}
/**
* 获取用户类型
*
* @param userType
* @return
*/
......@@ -387,13 +368,13 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
*
* @param oldUser
*/
private void buildUserToken(TbCfUserInfoEntity oldUser) {
/* private void buildUserToken(TbCfUserInfoEntity oldUser) {
TbCfUserInfoVo loginUser = new TbCfUserInfoVo();
BeanUtils.copyProperties(oldUser, loginUser);
String newToken = createToken(loginUser);
addTokenInCookie(newToken, request, response);
SessionUtils.setSessionUser(request, new SessionUser(newToken, loginUser.getAccount()));
}
}*/
/**
* 第三方登录
......@@ -402,9 +383,9 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
* @param nick
* @return
*/
private void loginByThirdPartyOfficial(String token, String ip, String account, String nick, Result result) {
/* private void loginByThirdPartyOfficial(String token, String ip, String account, String nick, Result result) {
TbCfUserInfoEntity user = findByAccount(account);
if (user != null&&nick.equals(user.getNick())) {
if (user != null && nick.equals(user.getNick())) {
user.setLastLoginIp(ip);
user.setLoginCount(user.getLoginCount() + 1);
user.setLastLoginTime(new Date());
......@@ -419,7 +400,7 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
CookieUtils.removeCookie(response, TokenManager.TOKEN, "/", null);
result.setCode(ResultCodeEnum.NEED_LOGIN.getCode()).setMessage("please login again");
}
}
}*/
private void fillUserNecessayInfo(TbCfUserInfoVo tbCfUserInfoVo) {
......@@ -435,16 +416,16 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
}
//创建token
private String createToken(TbCfUserInfoVo loginUser) {
/* private String createToken(TbCfUserInfoVo loginUser) {
// 生成token
String token = IdUtil.createIdbyUUID();
// 缓存中添加token对应User
tokenManager.addToken(token, loginUser);
return token;
}
}*/
//添加cookie
private void addTokenInCookie(String token, HttpServletRequest request, HttpServletResponse response) {
/*private void addTokenInCookie(String token, HttpServletRequest request, HttpServletResponse response) {
// Cookie添加token
Cookie cookie = new Cookie(TokenManager.TOKEN, token);
cookie.setPath("/");
......@@ -453,6 +434,6 @@ public class TbCfUserInfoServiceImpl implements TbCfUserInfoService {
}
cookie.setHttpOnly(true);
response.addCookie(cookie);
}
}*/
}
......@@ -129,6 +129,11 @@ public class TbCfUserInfoVo implements Serializable {
@ApiModelProperty(value="验证码",required=true)
private Integer captcha;
/**
* token
*/
@ApiModelProperty(value="用户token")
private String token;
/**
......@@ -407,4 +412,12 @@ public class TbCfUserInfoVo implements Serializable {
public void setEmailFlag(Integer emailFlag) {
this.emailFlag = emailFlag;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
package com.diaoyun.zion.master.config;
import com.google.common.base.Predicates;
import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -8,10 +9,17 @@ import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;
@Configuration
@EnableSwagger2
@EnableWebMvc
......@@ -20,16 +28,23 @@ public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
.select()//
.apis(RequestHandlerSelectors.any())//
.paths(Predicates.not(PathSelectors.regex("/error")))//
.build()//
.apiInfo(apiInfo())//
.useDefaultResponseMessages(false)//
.securitySchemes(new ArrayList<>(Arrays.asList(new ApiKey("Bearer %token", "Authorization", "Header"))))//
.genericModelSubstitutes(Optional.class);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Chinafrica api文档")
.version("1.0")
.description(
"This is description")//
.version("1.0.0")//
.license("MIT License").licenseUrl("http://opensource.org/licenses/MIT")//
.contact(new Contact(null, null, "xxxx@gmail.com"))//
.build();
}
......
......@@ -20,7 +20,8 @@ import java.io.PrintWriter;
*
* @author Joe
*/
@Component("exceptionResolver")
//@Component("exceptionResolver")
@Deprecated
public class ExceptionResolver implements HandlerExceptionResolver {
private final Logger logger = LoggerFactory.getLogger(getClass());
......
package com.diaoyun.zion.master.exception;
import com.alibaba.fastjson.JSON;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/**
*
*/
@RestControllerAdvice
public class GlobalExceptionHandlerController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Bean
public ErrorAttributes errorAttributes() {
// Hide exception field in the return object
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(WebRequest requestAttributes, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
errorAttributes.remove("exception");
errorAttributes.put("code", errorAttributes.get("status"));
//处理403禁止访问
if(403==(int)errorAttributes.get("status")) {
errorAttributes.put("code", ResultCodeEnum.NEED_LOGIN.getCode());
errorAttributes.put("message", ResultCodeEnum.NEED_LOGIN.getDesc());
}
return errorAttributes;
}
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
Result result;
if (exception instanceof ApplicationException) {
ApplicationException ae = (ApplicationException) exception;
result = new Result(ae.getCode(),ae.getMessage());
}
else {
result = new Result(ResultCodeEnum.ERROR.getCode(),exception.getMessage());
logger.error(exception.getMessage(), exception);
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.OK.value());
PrintWriter writer=null;
try {
writer = response.getWriter();
writer.write(JSON.toJSONString(result));
}
catch (IOException ie) {
logger.error("Failed to serialize the object to json for exception resolver!", ie);
} finally {
writer.flush();
writer.close();
}
return new ModelAndView();
}
};
}
/*@ExceptionHandler(ApplicationException.class)
public void handleCustomException(HttpServletResponse res, ApplicationException ex) throws IOException {
res.sendError(ex.getCode(), ex.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(HttpServletResponse res,Exception ex) throws IOException {
res.sendError(HttpStatus.FORBIDDEN.value(), ex.getMessage());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleException(HttpServletResponse res,Exception ex) throws IOException {
res.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}*/
}
package com.diaoyun.zion.master.security;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.exception.ApplicationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// We should use OncePerRequestFilter since we are doing a database call, there is no point in doing this more than once
public class JwtTokenFilter extends OncePerRequestFilter {
private JwtTokenProvider jwtTokenProvider;
public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = jwtTokenProvider.resolveToken(httpServletRequest);
try {
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication auth = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (ApplicationException ex) {
//this is very important, since it guarantees the user is not authenticated at all
SecurityContextHolder.clearContext();
httpServletResponse.sendError(ex.getCode(), ex.getMessage());
return;
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
package com.diaoyun.zion.master.security;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class JwtTokenFilterConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private JwtTokenProvider jwtTokenProvider;
public JwtTokenFilterConfigurer(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
public void configure(HttpSecurity http) throws Exception {
JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}
package com.diaoyun.zion.master.security;
import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.exception.ApplicationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Date;
@Component
public class JwtTokenProvider {
/**
* THIS IS NOT A SECURE PRACTICE! For simplicity, we are storing a static key here. Ideally, in a
* microservices environment, this key would be kept on a config-server.
*/
@Value("${security.jwt.token.secret-key:secret-key}")
private String secretKey;
@Value("${security.jwt.token.expire-length:3600000}")
private long validityInMilliseconds = 3600000; // 1h
@Autowired
private MyUserDetails myUserDetails;
@Resource(name = "redisTokenManager")
private TokenManager tokenManager;
@PostConstruct
protected void init() {
secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
}
public String createToken(String username) {
Claims claims = Jwts.claims().setSubject(username);
//claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()//
.setClaims(claims)//
.setIssuedAt(now)//
.setExpiration(validity)//
.signWith(SignatureAlgorithm.HS256, secretKey)//
.compact();
}
public Authentication getAuthentication(String token) {
UserDetails userDetails = myUserDetails.loadUserByUsername(getUsername(token));
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
public String getUsername(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}
public String resolveToken(HttpServletRequest req) {
String bearerToken = req.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
TbCfUserInfoVo loginUser=tokenManager.validate(token);
if(loginUser==null) {
throw new ApplicationException(ResultCodeEnum.NEED_LOGIN.getCode(),"Expired or invalid JWT token");
}
return true;
} catch (JwtException | IllegalArgumentException e) {
throw new ApplicationException(ResultCodeEnum.NEED_LOGIN.getCode(),"Expired or invalid JWT token");
}
}
}
package com.diaoyun.zion.master.security;
import com.diaoyun.zion.chinafrica.entity.TbCfUserInfoEntity;
import com.diaoyun.zion.chinafrica.service.impl.TbCfUserInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MyUserDetails implements UserDetailsService {
@Autowired
private TbCfUserInfoServiceImpl tbCfUserInfoService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final TbCfUserInfoEntity user = tbCfUserInfoService.findByAccount(username);
if (user == null) {
throw new UsernameNotFoundException("User '" + username + "' not found or disable");
}
return org.springframework.security.core.userdetails.User//
.withUsername(username)//
.password(user.getPassword())//
.authorities("ROLE_ADMIN")//
.accountExpired(false)//
.accountLocked(false)//
.credentialsExpired(false)//
.disabled(false)//
.build();
}
}
package com.diaoyun.zion.master.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtTokenProvider jwtTokenProvider;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// Disable CSRF (cross site request forgery)
http.csrf().disable();
// No session will be created or used by spring security
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Entry points
http.authorizeRequests()//
/*.antMatchers("/spider/**").permitAll()//
.antMatchers("/platform/**").permitAll()//
.antMatchers("/itemStation/**").permitAll()//
.antMatchers("/login/**").permitAll()//
.antMatchers("/problem/**").permitAll()//
.antMatchers("/contact/**").permitAll()//
.antMatchers("/page/**").permitAll()//
.antMatchers("/css/**").permitAll()//
.antMatchers("/js/**").permitAll()//
.antMatchers("/user/register/identifyCode/**").permitAll()//*/
//.antMatchers("/h2-console/**/**").permitAll()//
.antMatchers("/**/**").permitAll()//
// Disallow everything else..
.anyRequest().authenticated();
// If a user try to access a resource without having enough permissions
http.exceptionHandling().accessDeniedPage("/login");
// Apply JWT
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
// Optional, if you want to test the API from a browser
// http.httpBasic();
}
@Override
public void configure(WebSecurity web) throws Exception {
// Allow swagger to be accessed without authentication
web.ignoring().antMatchers("/v2/api-docs")//
.antMatchers("/swagger-resources/**")//
.antMatchers("/swagger-ui.html")//
.antMatchers("/configuration/**")//
.antMatchers("/webjars/**")//
.antMatchers("/public")
// Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production)
.and()
.ignoring()
.antMatchers("/h2-console/**/**");;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
package com.diaoyun.zion.master.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* cookie操作工具
*
* @author Joe
*/
public class CookieUtils {
private CookieUtils() {
}
/**
* 按名称获取cookie
*
* @param request
* @param name
* @return
*/
public static String getCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies == null || StringUtils.isBlank(name)) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
/**
* 清除cookie
* @param response
* @param name
* @param path
* @param domain
*/
public static void removeCookie(HttpServletResponse response, String name, String path, String domain) {
Cookie cookie = new Cookie(name, null);
if (path != null) {
cookie.setPath(path);
}
if (domain != null) {
cookie.setDomain(domain);
}
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
package com.diaoyun.zion.master.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;
public class GsonUtil {
//不用创建对象,直接使用Gson.就可以调用方法
private static Gson gson = null;
//判断gson对象是否存在了,不存在则创建对象
static {
if (gson == null) {
//gson = new Gson(); //当使用GsonBuilder方式时属性为空的时候输出来的json字符串是有键值key的,显示形式是"key":null,而直接new出来的就没有"key":null的
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
}
}
//无参的私有构造方法
private GsonUtil() {
}
/**
* 将对象转成json格式
*
* @param object
* @return String
*/
public static String GsonString(Object object) {
String gsonString = null;
if (gson != null) {
gsonString = gson.toJson(object);
}
return gsonString;
}
/**
* 将json转成特定的cls的对象
*
* @param gsonString
* @param cls
* @return
*/
public static <T> T GsonToBean(String gsonString, Class<T> cls) {
T t = null;
if (gson != null) {
//传入json对象和对象类型,将json转成对象
t = gson.fromJson(gsonString, cls);
}
return t;
}
/**
* json字符串转成list
*
* @param gsonString
* @param cls
* @return
*/
public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
List<T> list = null;
if (gson != null) {
//根据泛型返回解析指定的类型,TypeToken<List<T>>{}.getType()获取返回类型
list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
}.getType());
}
return list;
}
/**
* json字符串转成list中有map的
*
* @param gsonString
* @return
*/
public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
List<Map<String, T>> list = null;
if (gson != null) {
list = gson.fromJson(gsonString,
new TypeToken<List<Map<String, T>>>() {
}.getType());
}
return list;
}
/**
* json字符串转成map的
*
* @param gsonString
* @return
*/
public static <T> Map<String, T> GsonToMaps(String gsonString) {
Map<String, T> map = null;
if (gson != null) {
map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
return map;
}
}
......@@ -2,7 +2,6 @@ package com.diaoyun.zion.master.util;
import com.diaoyun.zion.chinafrica.enums.PlatformEnum;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
......@@ -11,6 +10,8 @@ import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
......@@ -208,18 +209,20 @@ public class HttpClientUtil {
}
/**
* 获取商品物流信息 TODO 还需验证
* 发送带body参数的post请求
* @param url
* @param paramMap
* @return
* @throws URISyntaxException
* @throws IOException
*/
public static String getItemTrack(String url,Map<String,Object> paramMap) throws URISyntaxException, IOException {
List<NameValuePair> formparams = setHttpParams(paramMap);
String param = URLEncodedUtils.format(formparams, Consts.UTF_8.name());
public static String sendPostWithBodyParameter(String url,Map<String,Object> paramMap) throws IOException {
HttpPost httpPost = new HttpPost(); //构建一个Post请求
httpPost.setURI(URI.create(url + "?" + param));
httpPost.setURI(URI.create(url));
httpPost.setHeader("Content-Type", "application/json");
//放参数
StringEntity entity = new StringEntity(GsonUtil.GsonString(paramMap), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
//构造自定义的HttpClient对象
CloseableHttpClient sibClient = HttpClients.custom().build();
//执行请求,传入HttpContext,将会得到请求结果的信息
......
......@@ -13,6 +13,7 @@ import java.security.NoSuchAlgorithmException;
*
* @author Joe
*/
@Deprecated
public class PasswordProvider {
private static final String SUFFIX = "`1qazx";
......
......@@ -94,5 +94,11 @@ spring:
# 配置StatFilter
filter:
stat:
log-slow-sql: true
log-slow-sql: true
security:
jwt:
token:
secret-key: secret-key
expire-length: 604800000 # one week or 300000 5 minutes duration by default: 5 minutes * 60 seconds * 1000 miliseconds
......@@ -11,6 +11,7 @@
<result property="payId" column="pay_id"/>
<result property="payWayCode" column="pay_way_code"/>
<result property="payTime" column="pay_Time"/>
<result property="receiptUrl" column="receipt_url"/>
</resultMap>
<select id="queryObject" resultType="com.diaoyun.zion.chinafrica.entity.TbCfFinanceEntity">
......@@ -21,7 +22,8 @@
`pay_account`,
`pay_id`,
`pay_way_code`,
`pay_Time`
`pay_Time`,
`receipt_url`
from tb_cf_finance
where finace_id = #{id}
</select>
......@@ -34,7 +36,8 @@
`pay_account`,
`pay_id`,
`pay_way_code`,
`pay_Time`
`pay_Time`,
`receipt_url`
from tb_cf_finance
WHERE 1=1
<if test="name != null and name.trim() != ''">
......@@ -69,7 +72,8 @@
`pay_account`,
`pay_id`,
`pay_way_code`,
`pay_Time`)
`pay_Time`,
`receipt_url`)
values(
#{finaceId},
#{orderId},
......@@ -77,7 +81,8 @@
#{payAccount},
#{payId},
#{payWayCode},
#{payTime})
#{payTime},
#{receiptUrl})
</insert>
<update id="update" parameterType="com.diaoyun.zion.chinafrica.entity.TbCfFinanceEntity">
......@@ -89,6 +94,7 @@
<if test="payId != null">`pay_id` = #{payId}, </if>
<if test="payWayCode != null">`pay_way_code` = #{payWayCode}, </if>
<if test="payTime != null">`pay_Time` = #{payTime}</if>
<if test="receiptUrl != null">`receipt_url` = #{receiptUrl}</if>
</set>
where finace_id = #{finaceId}
</update>
......
......@@ -235,4 +235,18 @@
and t1.enable_flag=1 and t2.item_id=t1.item_id
</select>
<!--获取付款订单-->
<select id="getOrderListByTime" resultType="com.diaoyun.zion.chinafrica.entity.TbCfOrderEntity">
select user_id,order_id,deal_time from tb_cf_order where pay_status=20 and
deal_time <![CDATA[ >= ]]> #{beginDate} and deal_time <![CDATA[ < ]]> #{endDate}
</select>
<!--获取某段时间已发货订单数据-->
<select id="getDeliveryList" resultType="com.diaoyun.zion.chinafrica.entity.TbCfItemShippedEntity">
select t1.user_id,t1.order_id,t2.create_time "deliveryTime",t1.delivery_address,
t2.p_express_number "expressId" from tb_cf_order t1,tb_cf_platform_order t2 where t1.pay_status=40
and t1.order_id=t2.order_id
and t2.create_time <![CDATA[ >= ]]> #{beginDate} and t2.create_time <![CDATA[ < ]]> #{endDate}
</select>
</mapper>
\ No newline at end of file
......@@ -188,9 +188,10 @@
select * from tb_cf_user_info where nickname=#{nickname}
</select>
<!--根据userId 账号 手机 email nick 查找用户-->
<!--根据userId 账号 email nick 查找用户-->
<select id="findByAccount" resultType="com.diaoyun.zion.chinafrica.entity.TbCfUserInfoEntity">
select * from tb_cf_user_info where user_id=#{userId} or account=#{account} or phone=#{account} or email =#{account} or nick =#{account};
select * from tb_cf_user_info where enable_flag=1 and user_id=#{userId} or account=#{account}
or email =#{account} or nick =#{account};
</select>
<!--修改密码-->
......
......@@ -35,7 +35,16 @@ tencent.wordpos.app_url=https://api.ai.qq.com/fcgi-bin/nlp/nlp_wordpos
################腾讯翻译配置 END###################
##################stripe公钥(不加密)和私钥(已加密)################################
stripe.pk=pk_test_uljWJWUuD8fzZXPlGtDZ1fxx00o1ZKr7QL
stripe.sk=BbLXgo+ohgrAP7p3tB52YTqNwhAiTYzYWAX0W+/1PES6kOupxwc/7xpAR8QsG6gP
##################stripe公钥(不加密)和私钥(已用 AESUtils 加密)################################
stripe.pk=pk_test_rXUSgU8Kw7DLhDzMbHM0r55O00JAzVBBJR
stripe.sk=3ff57yz9S5INBexBOnzi/ZaxClXkXlJ+FZ6XLc/f2vpESScG7YOaQaG2YNRic3HF
######################outlook的账户公钥密钥#####################
#stripe.pk=pk_test_uljWJWUuD8fzZXPlGtDZ1fxx00o1ZKr7QL
#stripe.sk=BbLXgo+ohgrAP7p3tB52YTqNwhAiTYzYWAX0W+/1PES6kOupxwc/7xpAR8QsG6gP
######################outlook的账户公钥密钥 END#####################
##################stripe公钥和私钥 END###############################
#############################第三方物流公司接口#################################
express.info.api=http://shd.kjwlxt.com/api/track.php
express.info.user_no=shd806
express.info.token=d44426bd5b64dd2
######################################################################
......@@ -85,14 +85,14 @@ loginApp.controller('loginController', function ($scope, $q, $http) {
var handler=function(d) {
console.log(d);
}
/*
var xhr = new XMLHttpRequest();
var url = 'https://africa.gzdazt.com/zion/login';//?account=1244612031@qq.com&password=123456
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.onreadystatechange = handler;
xhr.send();
xhr.send();*/
/*var dataParam ={
targetUrl:"https://h5.m.taobao.com/awp/core/detail.htm?spm=a2141.9304519.0.0&id=9679381011&pvid=9e42d83a-82c7-43ac-a89f-199a74d48c2f&scene=3489&scm=1007.13489.98648.tab%3A0_id%3A9679381011_reason%3Ashoal_ranklist_rn%3A9e42d83a-82c7-43ac-a89f-199a74d48c2f"
......@@ -119,13 +119,13 @@ loginApp.controller('loginController', function ($scope, $q, $http) {
}
})*/
/*var xhr = new XMLHttpRequest();
var url = ' http://159.138.33.0/zion/address/default/1c0dd6fcefb64b4ebe5febb8e42adfc0';
var xhr = new XMLHttpRequest();
var url = 'https://africa.gzdazt.com/zion/user/register/identifyCode/1262837396@qq.com/123456';
xhr.open('PUT', url, true);
xhr.withCredentials = true;
xhr.onreadystatechange = handler;
xhr.send();*/
xhr.send();
......
package com.diaoyun.zion;
import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.service.SpiderService;
import com.diaoyun.zion.chinafrica.service.TbCfCouponService;
import com.diaoyun.zion.chinafrica.service.impl.TbCfOrderServiceImpl;
import com.diaoyun.zion.master.thread.TaskLimitSemaphore;
import com.diaoyun.zion.master.util.AESUtils;
import com.diaoyun.zion.master.util.GsonUtil;
import com.diaoyun.zion.master.util.HttpClientUtil;
import com.diaoyun.zion.master.util.WordposHelper;
import com.google.gson.Gson;
import com.stripe.exception.StripeException;
......@@ -283,14 +287,23 @@ public class ZionApplicationTests {
}*/
/*分词 END*****************8***/
/*String url="http://shd.kjwlxt.com/api/track.php";
Map<String,Object> paramMap= new HashMap<>();
List<Map<String,String>> data=new ArrayList<>();
Map<String,String> dataMap=new HashMap<>();
dataMap.put("order_no","ceshi20190917");
data.add(dataMap);
paramMap.put("user_no","shd806");
paramMap.put("token","d44426bd5b64dd2");
paramMap.put("data",data);
String res=HttpClientUtil.sendPostWithBodyParameter(url,paramMap);
Map map=GsonUtil.GsonToMaps(res);*/
String a="sk_test_yHGCVyKVI0soO8UQR9oivpB200s0lHEOFy";
String b=AESUtils.encrypt(KeyConstant.AES_KEY,a);
System.out.println(b);
List<String> cartRecordIdArray = new ArrayList<>();
cartRecordIdArray.add("a");
cartRecordIdArray.add("b");
cartRecordIdArray.add("c");
cartRecordIdArray.add("d");
String[] cartRecordIds = cartRecordIdArray.toArray(new String[0]);
System.out.println(cartRecordIds[0]+cartRecordIds[1]+cartRecordIds[2]+cartRecordIds[3]);
}
/*private void translateProp(Map<String, Object> propMap) throws ExecutionException, InterruptedException {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论