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>> register(@RequestBody Map body) { try { Map 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>> login(@Valid @RequestBody LoginRequest req) { try { Map result = authService.login(req); return ResponseEntity.ok(ApiResponse.success("登录成功", result)); } catch (RuntimeException e) { return ResponseEntity.status(401).body(ApiResponse.error(401, e.getMessage())); } } }