Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

处理java端用户体系和node逻辑保持一致 #367

Merged
merged 4 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
public enum RespErrorCode {
AUTHENTICATION_FAILED(1001, "没有权限"),
PARAMETER_ERROR(1002, "参数有误"),
ENCRYPTION_ERROR(1003, "加密异常"),
USER_EXISTS(2001, "用户已存在"),
USER_NOT_EXISTS(2002, "用户不存在"),
USER_PASSWORD_ERROR(2003, "用户名或密码错误"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public UserVo register(UserParam userParam) {
//保存
User user = new User();
user.setUsername(userParam.getUsername());
user.setPassword(AuthUtil.encryptPassword(userParam.getPassword(), userParam.getUsername()));
user.setPassword(AuthUtil.hash256(userParam.getPassword()));
mongoRepository.save(user);
return createTokenAndDeleteCaptcha(userParam);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.xiaojusurvey.engine.core.auth.util;


import com.xiaojusurvey.engine.common.constants.RespErrorCode;
import com.xiaojusurvey.engine.common.exception.ServiceException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

Expand Down Expand Up @@ -31,5 +34,29 @@ public static String encryptPassword(String password, String username) {
}
}

/**
* SHA-256
* @param password
* @return
*/
public static String hash256(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes());
// 将 byte 数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new ServiceException(RespErrorCode.ENCRYPTION_ERROR.getMessage(), RespErrorCode.ENCRYPTION_ERROR.getCode());
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public Token generateToken(User user) {
Date expiryDate = new Date(now.getTime() + expirationTime * HOUR_MILLISECOND);
String token = JWT.create()
.withClaim("username", user.getUsername())
.withClaim("password", user.getPassword())
.withClaim("_id", user.getId())
.withExpiresAt(expiryDate)
.withJWTId(UUID.randomUUID().toString())
.sign(Algorithm.HMAC256(secret));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ public interface UserService {
List<User> findAllUser();

User loadUserByUsernameAndPassword(String username, String password);

User getUserById(String userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public List<User> findAllUser() {
@Override
public User loadUserByUsernameAndPassword(String username, String password) {
Query query = new Query();
String encryptPassword = AuthUtil.encryptPassword(password, username);
String encryptPassword = AuthUtil.hash256(password);
query.addCriteria(Criteria.where("username").is(username).and("password").is(encryptPassword));
//查询用户并返回
User user = mongoRepository.findOne(query, User.class);
Expand All @@ -44,4 +44,9 @@ public User loadUserByUsernameAndPassword(String username, String password) {
}
return user;
}

@Override
public User getUserById(String userId) {
return mongoRepository.findOne(new Query(Criteria.where("_id").is(userId)), User.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@

public class LoginInterceptor implements HandlerInterceptor {

public static final String USER_NAME = "username";
public static final String USER_ID = "_id";

@Resource
private JwtTokenUtil jwtTokenUtil;

@Resource
private UserService userService;

Expand All @@ -39,14 +43,19 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
//查询用户信息
Map<String, Claim> claims = jwt.getClaims();
//获取用户名,密码
String username = claims.get("username").asString();
String password = claims.get("password").asString();
String username = null, userId = null;
if (!ObjectUtils.isEmpty(claims.get(USER_NAME))) {
username = claims.get(USER_NAME).asString();
}
if (!ObjectUtils.isEmpty(claims.get(USER_ID))) {
userId = claims.get(USER_ID).asString();
}
//判空
if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) {
if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(userId)) {
//token超时
throw new ServiceException(RespErrorCode.USER_CREDENTIALS_ERROR.getMessage(), RespErrorCode.USER_CREDENTIALS_ERROR.getCode());
}
User user = userService.loadUserByUsernameAndPassword(username, password);
User user = userService.getUserById(userId);
request.setAttribute("user", user);
return HandlerInterceptor.super.preHandle(request, response, handler);
}
Expand Down