package ru.mtusi.messenger.controller; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import ru.mtusi.messenger.dto.SessionResponse; import ru.mtusi.messenger.exception.UnauthorizedException; import ru.mtusi.messenger.repository.SessionRepository; import ru.mtusi.messenger.service.SessionService; import java.nio.charset.StandardCharsets; import java.util.Base64; @RestController @RequestMapping("/api/v1/auth") public class AuthController { private final SessionService sessionService; private final SessionRepository sessionRepository; // <-- ДОБАВЛЕНО public AuthController(SessionService sessionService, SessionRepository sessionRepository) { this.sessionService = sessionService; this.sessionRepository = sessionRepository; // <-- ДОБАВЛЕНО } @PostMapping("/sessions") @ResponseStatus(HttpStatus.CREATED) public SessionResponse createSession( @RequestHeader(value = "Authorization", required = false) String authHeader) { if (authHeader == null || !authHeader.startsWith("Basic ")) { throw new UnauthorizedException("Missing or invalid Authorization header"); } String base64Credentials = authHeader.substring(6); String credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8); int colonIndex = credentials.indexOf(':'); if (colonIndex == -1) { throw new UnauthorizedException("Invalid Basic Auth format"); } String username = credentials.substring(0, colonIndex); String password = credentials.substring(colonIndex + 1); return sessionService.createSession(username, password); } @DeleteMapping("/sessions/current") @ResponseStatus(HttpStatus.NO_CONTENT) public void logout(@RequestHeader("Authorization") String authHeader) { if (authHeader != null && authHeader.startsWith("Bearer ")) { String token = authHeader.substring(7); sessionRepository.deleteById(token); } } }