Перенос из 3 лабы
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package org.example.controller;
|
||||
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.example.dto.response.SessionInfoResponse;
|
||||
import org.example.dto.response.SessionResponse;
|
||||
import org.example.exception.UnauthorizedException;
|
||||
import org.example.service.AuthService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
|
||||
@PostMapping("/sessions")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public SessionResponse login(HttpServletRequest request) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith("Basic ")) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String decoded;
|
||||
try {
|
||||
decoded = new String(
|
||||
Base64.getDecoder().decode(header.substring(6).trim()),
|
||||
StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
int colon = decoded.indexOf(':');
|
||||
if (colon < 0) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String username = decoded.substring(0, colon);
|
||||
String password = decoded.substring(colon + 1);
|
||||
return authService.login(username, password);
|
||||
}
|
||||
|
||||
@DeleteMapping("/sessions/current")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void revokeCurrent(HttpServletRequest request) {
|
||||
String header = request.getHeader("Authorization");
|
||||
if (header == null || !header.startsWith("Bearer ")) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
String token = header.substring(7).trim();
|
||||
if (token.isEmpty()) {
|
||||
throw new UnauthorizedException("Unauthorized");
|
||||
}
|
||||
authService.logoutCurrent(token);
|
||||
}
|
||||
|
||||
@GetMapping("/sessions")
|
||||
public List<SessionInfoResponse> sessions() {
|
||||
return authService.listSessionsForCurrentUser();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user