提交 3aa5ac43 authored 作者: 吴德鹏's avatar 吴德鹏

优化

上级 7295a930
......@@ -16,6 +16,7 @@ import com.example.afrishop_v3.util.ValidateUtils;
import com.example.afrishop_v3.util.WordposHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
......@@ -66,12 +67,14 @@ public class CartController extends Controller {
}
//Add single item to the cart
// @Async
@PostMapping
public Result addToCart(@RequestBody TbCfCartRecordR itemDetail) {
TbCfUserInfo user = this.user.user();
if (user == null) {
return new Result(ResultCodeEnum.UN_LOGIN.getCode(), "need login");
}
String userId = user.getUserId();
if (itemDetail == null) {
......
......@@ -278,6 +278,9 @@ public class OrderController extends Controller {
@RequestParam(value = "open", required = false) boolean open
) throws ParseException {
TbCfUserInfo user = this.user.user();
if (user == null) {
return new Result(ResultCodeEnum.UN_LOGIN.getCode(), "need login");
}
String userId = user.getUserId();
int v_code = ResultCodeEnum.VALIDATE_ERROR.getCode();
......@@ -490,6 +493,9 @@ public class OrderController extends Controller {
@RequestParam(value = "name", required = false) String name
) {
TbCfUserInfo user = this.user.user();
if (user == null) {
return new Result(ResultCodeEnum.UN_LOGIN.getCode(), "need login");
}
Page<OrderCount> list;
PageRequest of = PageRequest.of(pageNum, pageSize, sort(sort));
String userId = user.getUserId();
......@@ -565,6 +571,9 @@ public class OrderController extends Controller {
logger.info("上传files:", comment);
TbCfUserInfo user = this.user.user();
if (user == null) {
return new Result(ResultCodeEnum.UN_LOGIN.getCode(), "need login");
}
String userId = user.getUserId();
......
......@@ -42,6 +42,9 @@ public class AuthTokenFilter extends OncePerRequestFilter {
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtUtils.generateJwtToken(authentication);
logger.info("token:==============="+token);
response.setHeader("Authorization","Bearer "+token);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
......
......@@ -2,10 +2,14 @@ package com.example.afrishop_v3.security.jwt;
import java.util.Date;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.security.services.UserDetailsImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
......@@ -13,46 +17,57 @@ import io.jsonwebtoken.*;
@Component
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${bezkoder.app.jwtSecret}")
private String jwtSecret;
@Value("${bezkoder.app.jwtExpirationMs}")
private int jwtExpirationMs;
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.setSubject((userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + (jwtExpirationMs * 365)))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${bezkoder.app.jwtSecret}")
private String jwtSecret;
@Value("${bezkoder.app.jwtExpirationMs}")
private int jwtExpirationMs;
@Autowired
private AuthenticationManager authenticationManager;
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
//token设置过期时间为1年
return Jwts.builder()
.setSubject((userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(new Date(new Date().getTime() + 3600l * 1000 * 24 * 365))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public String refreshToken(TbCfUserInfo userInfo) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(userInfo.getUserId(), userInfo.getPassword()));
String jwt = this.generateJwtToken(authentication);
return jwt;
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
......@@ -26,24 +26,15 @@ public class AuthenticationUser implements IAuthenticationFacade {
public TbCfUserInfo user() {
String name = getAuthentication().getName();
// UserDetailsImpl principal = (UserDetailsImpl) getAuthentication().getPrincipal();
//
// System.out.println("principal");
// System.out.println(principal);
//
//// logger.info("登录的用户:" + name);
// System.out.println("name");
// System.out.println(name);
Optional<TbCfUserInfo> user = repository.findById(name);
// logger.info("用户:" + user);
return user.orElse(null);
}
public String userId() {
TbCfUserInfo user = user();
if (user != null) {
return user().getUserId();
Optional<TbCfUserInfo> userOptional = Optional.ofNullable(user());
if (userOptional.isPresent()) {
return userOptional.get().getUserId();
}
return null;
}
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论