94 lines
2.9 KiB
Java
94 lines
2.9 KiB
Java
package com.emotionmuseum.controller;
|
|
|
|
import com.emotionmuseum.dto.Result;
|
|
import com.emotionmuseum.dto.auth.LoginRequest;
|
|
import com.emotionmuseum.dto.auth.LoginResponse;
|
|
import com.emotionmuseum.dto.auth.RegisterRequest;
|
|
import com.emotionmuseum.service.AuthService;
|
|
import io.swagger.v3.oas.annotations.Operation;
|
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import jakarta.validation.Valid;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
/**
|
|
* 认证控制器
|
|
*
|
|
* @author emotion-museum
|
|
* @version 1.0.0
|
|
* @since 2024-01-01
|
|
*/
|
|
@RestController
|
|
@RequestMapping("/auth")
|
|
@Tag(name = "认证管理", description = "用户认证相关接口")
|
|
@Slf4j
|
|
public class AuthController {
|
|
|
|
@Autowired
|
|
private AuthService authService;
|
|
|
|
/**
|
|
* 用户登录
|
|
*/
|
|
@PostMapping("/login")
|
|
@Operation(summary = "用户登录", description = "用户登录接口")
|
|
public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
|
|
log.info("用户登录请求: {}", request.getUsername());
|
|
return authService.login(request);
|
|
}
|
|
|
|
/**
|
|
* 用户注册
|
|
*/
|
|
@PostMapping("/register")
|
|
@Operation(summary = "用户注册", description = "用户注册接口")
|
|
public Result<String> register(@Valid @RequestBody RegisterRequest request) {
|
|
log.info("用户注册请求: {}", request.getUsername());
|
|
return authService.register(request);
|
|
}
|
|
|
|
/**
|
|
* 用户登出
|
|
*/
|
|
@PostMapping("/logout")
|
|
@Operation(summary = "用户登出", description = "用户登出接口")
|
|
public Result<String> logout(HttpServletRequest request) {
|
|
String token = extractToken(request);
|
|
log.info("用户登出请求");
|
|
return authService.logout(token);
|
|
}
|
|
|
|
/**
|
|
* 刷新令牌
|
|
*/
|
|
@PostMapping("/refresh")
|
|
@Operation(summary = "刷新令牌", description = "刷新访问令牌")
|
|
public Result<String> refreshToken(@RequestParam String refreshToken) {
|
|
log.info("刷新令牌请求");
|
|
return authService.refreshToken(refreshToken);
|
|
}
|
|
|
|
/**
|
|
* 验证令牌
|
|
*/
|
|
@GetMapping("/validate")
|
|
@Operation(summary = "验证令牌", description = "验证访问令牌是否有效")
|
|
public Result<Boolean> validateToken(HttpServletRequest request) {
|
|
String token = extractToken(request);
|
|
boolean isValid = authService.validateToken(token);
|
|
return Result.success("令牌验证完成", isValid);
|
|
}
|
|
|
|
/**
|
|
* 从请求中提取令牌
|
|
*/
|
|
private String extractToken(HttpServletRequest request) {
|
|
String bearerToken = request.getHeader("Authorization");
|
|
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
|
|
return bearerToken.substring(7);
|
|
}
|
|
return null;
|
|
}
|
|
} |