74 lines
2.5 KiB
Java
74 lines
2.5 KiB
Java
package com.label.controller;
|
||
|
||
import com.label.annotation.RequireAuth;
|
||
import com.label.common.auth.TokenPrincipal;
|
||
import com.label.common.result.Result;
|
||
import com.label.dto.LoginRequest;
|
||
import com.label.dto.LoginResponse;
|
||
import com.label.dto.UserInfoResponse;
|
||
import com.label.service.AuthService;
|
||
import io.swagger.v3.oas.annotations.Operation;
|
||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||
import jakarta.servlet.http.HttpServletRequest;
|
||
import lombok.RequiredArgsConstructor;
|
||
import org.springframework.web.bind.annotation.*;
|
||
|
||
/**
|
||
* 认证接口:登录、退出、获取当前用户。
|
||
*
|
||
* 路由设计:
|
||
* - POST /api/auth/login → 匿名(AuthInterceptor 跳过)
|
||
* - POST /api/auth/logout → 需要有效 Token(AuthInterceptor 校验)
|
||
* - GET /api/auth/me → 需要有效 Token(AuthInterceptor 校验)
|
||
*/
|
||
@Tag(name = "认证管理", description = "登录、退出和当前用户信息")
|
||
@RestController
|
||
@RequestMapping("/label/api/auth")
|
||
@RequiredArgsConstructor
|
||
public class AuthController {
|
||
|
||
private final AuthService authService;
|
||
|
||
/**
|
||
* 登录接口(匿名,无需 Token)。
|
||
*/
|
||
@Operation(summary = "用户登录,返回 Bearer Token")
|
||
@PostMapping("/login")
|
||
public Result<LoginResponse> login(@RequestBody LoginRequest request) {
|
||
return Result.success(authService.login(request));
|
||
}
|
||
|
||
/**
|
||
* 退出登录,立即删除 Redis Token。
|
||
*/
|
||
@Operation(summary = "退出登录并立即失效当前 Token")
|
||
@PostMapping("/logout")
|
||
@RequireAuth
|
||
public Result<Void> logout(HttpServletRequest request) {
|
||
String token = extractToken(request);
|
||
authService.logout(token);
|
||
return Result.success(null);
|
||
}
|
||
|
||
/**
|
||
* 获取当前登录用户信息。
|
||
* TokenPrincipal 由 AuthInterceptor 写入请求属性 "__token_principal__"。
|
||
*/
|
||
@Operation(summary = "获取当前登录用户信息")
|
||
@GetMapping("/me")
|
||
@RequireAuth
|
||
public Result<UserInfoResponse> me(HttpServletRequest request) {
|
||
TokenPrincipal principal = (TokenPrincipal) request.getAttribute("__token_principal__");
|
||
return Result.success(authService.me(principal));
|
||
}
|
||
|
||
/** 从 Authorization 头提取 Bearer token 字符串 */
|
||
private String extractToken(HttpServletRequest request) {
|
||
String authHeader = request.getHeader("Authorization");
|
||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||
return authHeader.substring(7).trim();
|
||
}
|
||
return null;
|
||
}
|
||
}
|