개발자/Spring

url 유효기간 설정_세션동작방식

푸루닉 2023. 7. 13. 14:20
@GetMapping("/file/downloadURL")
public ResponseEntity<?> downloadURL(@RequestParam String fileId, HttpServletRequest request) throws MalformedURLException {
    // fileId를 통해 파일 정보 조회
    FileManageVO fileManageVO = fileManageService.selectFile(fileId);

    String orgnFileNm = fileManageVO.getOrgnFileNm();       // 원본 파일 이름
    String strgFileNm = fileManageVO.getStrgFileNm();       // 저장된 파일 이름
    String strgFilePth = fileManageVO.getStrgFilePath();    // 저장된 파일 경로
    String fileExtn = fileManageVO.getFileExt();            // 파일 확장자
    String encodedFileNm = UriUtils.encode(orgnFileNm, StandardCharsets.UTF_8);  // URL 인코딩된 파일 이름
    String disposition = "attachment; filename=\"" + encodedFileNm + ((fileExtn != null) ? "." + fileExtn : "") + "\""; // 다운로드 헤더 설정

    UrlResource resource = new UrlResource("file:" + uploadPath + File.separator + strgFilePth + File.separator + strgFileNm); // 다운로드할 파일의 URL 리소스 생성

    // 첫 다운로드 시간 저장 (파일 다운로드 시간 기준으로 유효 기간을 설정)
    String downloadStartTime = (String) request.getSession().getAttribute(fileId + "_downloadStartTime");
    if (downloadStartTime == null) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        downloadStartTime = now.format(formatter); // 현재 시간을 포맷에 맞게 문자열로 저장
        request.getSession().setAttribute(fileId + "_downloadStartTime", downloadStartTime); // 세션에 다운로드 시작 시간 저장
    }

    // 현재 시간과 다운로드 시작 시간을 비교하여 유효 기간 검사
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime downloadStartDateTime = LocalDateTime.parse(downloadStartTime, formatter); // 문자열로부터 LocalDateTime 객체로 변환
    Duration duration = Duration.between(downloadStartDateTime, now); // 다운로드 시간과 현재 시간의 간격을 계산하여 Duration 객체로 반환

    // 유효 기간이 30분 이내인지 검사
    if (duration.toMinutes() > 30) {
        // 유효 기간이 지났으므로 URL을 만료시키고 적절한 응답을 반환
        request.getSession().removeAttribute(fileId + "_downloadStartTime"); // 세션에서 다운로드 시작 시간 제거
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("URL의 유효 기간이 만료되었습니다."); // 403 Forbidden 응답 반환
    }

    // 파일 다운로드 응답 반환
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, disposition).body(resource);
}