51 lines
1.7 KiB
Java
51 lines
1.7 KiB
Java
package com.learn.controller;
|
|
|
|
import com.learn.dto.ApiResponse;
|
|
import com.learn.dto.LoginRequest;
|
|
import com.learn.service.AuthService;
|
|
import jakarta.validation.Valid;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* 认证接口(第 2 天)
|
|
*
|
|
* POST /api/auth/register —— 注册
|
|
* POST /api/auth/login —— 登录,返回 JWT
|
|
*
|
|
* 这些接口在 SecurityConfig 中设置了 permitAll(),无需认证即可访问。
|
|
*/
|
|
@RestController
|
|
@RequestMapping("/api/auth")
|
|
public class AuthController {
|
|
|
|
private final AuthService authService;
|
|
|
|
public AuthController(AuthService authService) {
|
|
this.authService = authService;
|
|
}
|
|
|
|
@PostMapping("/register")
|
|
public ResponseEntity<ApiResponse<Map<String, Object>>> register(@RequestBody Map<String, String> body) {
|
|
try {
|
|
Map<String, Object> result = authService.register(
|
|
body.get("username"), body.get("password"));
|
|
return ResponseEntity.ok(ApiResponse.success("注册成功", result));
|
|
} catch (RuntimeException e) {
|
|
return ResponseEntity.badRequest().body(ApiResponse.badRequest(e.getMessage()));
|
|
}
|
|
}
|
|
|
|
@PostMapping("/login")
|
|
public ResponseEntity<ApiResponse<Map<String, Object>>> login(@Valid @RequestBody LoginRequest req) {
|
|
try {
|
|
Map<String, Object> result = authService.login(req);
|
|
return ResponseEntity.ok(ApiResponse.success("登录成功", result));
|
|
} catch (RuntimeException e) {
|
|
return ResponseEntity.status(401).body(ApiResponse.error(401, e.getMessage()));
|
|
}
|
|
}
|
|
}
|