69 lines
2.3 KiB
Java
69 lines
2.3 KiB
Java
package com.bruce.sams.service.impl;
|
||
|
||
import com.bruce.sams.common.enums.UserStatus;
|
||
import com.bruce.sams.common.exception.AccountDisabledException;
|
||
import com.bruce.sams.common.exception.PasswordIncorrectException;
|
||
import com.bruce.sams.common.exception.UserNotFoundException;
|
||
import com.bruce.sams.common.utils.PasswordUtil;
|
||
import com.bruce.sams.common.utils.TokenUtil;
|
||
import com.bruce.sams.domain.entity.LoginRequest;
|
||
import com.bruce.sams.domain.sys.User;
|
||
import com.bruce.sams.mapper.RoleMapper;
|
||
import com.bruce.sams.mapper.UserMapper;
|
||
import com.bruce.sams.service.AuthService;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.stereotype.Service;
|
||
|
||
import java.util.List;
|
||
|
||
/**
|
||
* 认证服务类,支持 用户名、学号、邮箱 登录
|
||
*/
|
||
@Service
|
||
public class AuthServiceImpl implements AuthService {
|
||
|
||
@Autowired
|
||
private UserMapper userMapper;
|
||
|
||
@Autowired
|
||
private RoleMapper roleMapper;
|
||
|
||
/**
|
||
* 处理用户认证,支持用户名、学号、邮箱登录
|
||
*
|
||
* @param loginRequest 登录请求体(包含 username / schoolId / email + password)
|
||
* @return JWT 令牌(成功)或 null(失败)
|
||
*/
|
||
public String authenticate(LoginRequest loginRequest) {
|
||
User user = null;
|
||
|
||
// 根据提供的信息查询用户
|
||
if (!loginRequest.getUsername().isEmpty()) {
|
||
user = userMapper.findByUsername(loginRequest.getUsername());
|
||
} else if (!loginRequest.getSchoolId().isEmpty()) {
|
||
user = userMapper.findBySchoolId(loginRequest.getSchoolId());
|
||
} else if (!loginRequest.getEmail().isEmpty()) {
|
||
user = userMapper.findByEmail(loginRequest.getEmail());
|
||
}
|
||
System.out.println(user);
|
||
// 用户不存在
|
||
if (user == null) {
|
||
throw new UserNotFoundException();
|
||
}
|
||
|
||
// 检查密码是否匹配
|
||
if (!PasswordUtil.matches(loginRequest.getPassword(), user.getPassword())) {
|
||
|
||
throw new PasswordIncorrectException();
|
||
}
|
||
|
||
// 检查账号是否被禁用
|
||
if (UserStatus.BANNED.equals(user.getStatus())) {
|
||
throw new AccountDisabledException();
|
||
}
|
||
List<String> roleKeys = roleMapper.getRoleKeysByUserId(user.getUserId());
|
||
// 生成 JWT 令牌
|
||
return TokenUtil.generateToken(user,roleKeys);
|
||
}
|
||
}
|