MCPcopy Create free account
hub / github.com/LQF-dev/smart-hr / AuthService

Class AuthService

back/src/main/java/com/smarthr/service/AuthService.java:27–154  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

25import org.springframework.transaction.annotation.Transactional;
26
27@Slf4j
28@Service
29@RequiredArgsConstructor
30public class AuthService {
31
32 private final AuthenticationManager authenticationManager;
33 private final UserRepository userRepository;
34 private final PasswordEncoder passwordEncoder;
35 private final JwtTokenProvider jwtTokenProvider;
36 private final JwtProperties jwtProperties;
37
38 /**
39 * 用户登录
40 */
41 public AuthResponse login(LoginRequest request) {
42 log.info("User login attempt: {}", request.getUsername());
43
44 // 认证
45 Authentication authentication = authenticationManager.authenticate(
46 new UsernamePasswordAuthenticationToken(
47 request.getUsername(),
48 request.getPassword()
49 )
50 );
51
52 UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
53
54 // 生成 Token
55 String accessToken = jwtTokenProvider.generateToken(userPrincipal);
56 String refreshToken = jwtTokenProvider.generateRefreshToken(userPrincipal);
57
58 log.info("User logged in successfully: {}", request.getUsername());
59
60 return buildAuthResponse(userPrincipal, accessToken, refreshToken);
61 }
62
63 /**
64 * 用户注册
65 */
66 @Transactional
67 public AuthResponse register(RegisterRequest request) {
68 log.info("User registration attempt: {}", request.getUsername());
69
70 // 检查用户名是否已存在
71 if (userRepository.existsByUsername(request.getUsername())) {
72 throw new RuntimeException("用户名已存在: " + request.getUsername());
73 }
74
75 // 检查邮箱是否已存在
76 if (request.getEmail() != null && userRepository.existsByEmail(request.getEmail())) {
77 throw new RuntimeException("邮箱已被使用: " + request.getEmail());
78 }
79
80 // 创建用户
81 User user = User.builder()
82 .username(request.getUsername())
83 .password(passwordEncoder.encode(request.getPassword()))
84 .email(request.getEmail())

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected