Week 1-8: Spring Boot 学习计划完整项目
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
50
week5/src/main/java/com/learn/controller/AuthController.java
Normal file
50
week5/src/main/java/com/learn/controller/AuthController.java
Normal file
@@ -0,0 +1,50 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user