You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bloggingplatform/Frontend/api/auth/login.js

44 lines
1.4 KiB

@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder; // 用于加密密码
@Autowired
private JwtUtils jwtUtils; // 用于生成 JWT Token
@PostMapping("/login")
public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials) {
String loginAccount = credentials.get("loginAccount");
String password = credentials.get("password");
// 查找用户
User user = userRepository.findByLoginAccount(loginAccount)
.orElse(null);
if (user != null && passwordEncoder.matches(password, user.getPassword())) {
// 登录成功,生成 JWT Token
String token = jwtUtils.generateToken(user);
// 返回用户信息和 Token
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("user", user);
response.put("token", token);
return ResponseEntity.ok(response);
} else {
// 登录失败
Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", "账号或密码错误");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}
}
}