머지
This commit is contained in:
@@ -7,6 +7,7 @@ import lombok.RequiredArgsConstructor;
|
||||
@RequiredArgsConstructor
|
||||
public enum FileStorageType {
|
||||
LOCAL("로컬 스토리지"),
|
||||
S3("AWS S3 스토리지");
|
||||
S3("AWS S3 스토리지"),
|
||||
SFTP("SFTP");
|
||||
private final String desc;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ public enum FileUploadType {
|
||||
AcceptableFileType.PDF,
|
||||
AcceptableFileType.ZIP)),
|
||||
NOTICE(
|
||||
FileStorageType.LOCAL,
|
||||
FileStorageType.SFTP,
|
||||
"/notice",
|
||||
Set.of(
|
||||
AcceptableFileType.IMAGE,
|
||||
@@ -55,7 +55,7 @@ public enum FileUploadType {
|
||||
AcceptableFileType.ZIP)),
|
||||
|
||||
RECEIPT(
|
||||
FileStorageType.LOCAL,
|
||||
FileStorageType.SFTP,
|
||||
"/receipt",
|
||||
Set.of(
|
||||
AcceptableFileType.IMAGE
|
||||
|
||||
@@ -11,18 +11,24 @@ import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AESEncryptUtil {
|
||||
|
||||
@Value("${encrypt.aes.key}")
|
||||
@Value("${aes.secret-key}")
|
||||
private String key;
|
||||
|
||||
@Value("${encrypt.aes.iv}")
|
||||
private String iv;
|
||||
|
||||
private static final String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";
|
||||
public static final String ENCRYPT_IV = "0123456789ABCDEF";
|
||||
|
||||
public String encrypt(String text)
|
||||
throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException,
|
||||
IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException {
|
||||
@@ -48,6 +54,42 @@ public class AESEncryptUtil {
|
||||
return new String(decrypted, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
|
||||
public byte[] encryptAesCbc(byte[] plainData) {
|
||||
if (plainData == null || plainData.length == 0) {
|
||||
throw new IllegalArgumentException("데이터는 null이거나 비어 있을 수 없습니다.");
|
||||
}
|
||||
|
||||
try {
|
||||
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
|
||||
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
|
||||
return org.apache.commons.codec.binary.Base64.encodeBase64(cipher.doFinal(plainData));
|
||||
} catch (Exception e) {
|
||||
log.error("바이너리 데이터 암호화 실패", e);
|
||||
throw new RuntimeException("바이너리 데이터 암호화 실패", e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] decryptAesCbc(byte[] cipherData) {
|
||||
if (cipherData == null || cipherData.length == 0) {
|
||||
throw new IllegalArgumentException("암호문은 null이거나 비어 있을 수 없습니다.");
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] encrypted = org.apache.commons.codec.binary.Base64.decodeBase64(cipherData);
|
||||
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(ENCRYPT_IV.getBytes(StandardCharsets.UTF_8));
|
||||
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
|
||||
return cipher.doFinal(encrypted);
|
||||
} catch (Exception e) {
|
||||
log.error("바이너리 데이터 복호화 실패", e);
|
||||
throw new RuntimeException("바이너리 데이터 복호화 실패", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getTransformation() {
|
||||
return "AES/CBC/PKCS5Padding";
|
||||
}
|
||||
|
||||
@@ -3,9 +3,16 @@ package app.module.core.config.application.util;
|
||||
import app.module.core.config.adapters.web.security.domain.SocialUser;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
@@ -14,6 +21,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
@Slf4j
|
||||
public class CommonUtil {
|
||||
|
||||
/**
|
||||
@@ -106,4 +114,41 @@ public class CommonUtil {
|
||||
flashMessages.add(msg);
|
||||
session.setAttribute("flashAlertMessages", flashMessages);
|
||||
}
|
||||
|
||||
public static String normalizePath(String path) {
|
||||
if (path == null || path.trim().isEmpty()) {
|
||||
log.warn("normalizePath: Input path is null or empty, returning default path");
|
||||
String defaultPath = System.getProperty("user.home") + File.separator + "Downloads";
|
||||
return Paths.get(defaultPath).toAbsolutePath().normalize().toString();
|
||||
}
|
||||
|
||||
try {
|
||||
// Paths.get을 사용하여 경로 정규화
|
||||
Path normalizedPath = Paths.get(path).toAbsolutePath().normalize();
|
||||
String result = normalizedPath.toString();
|
||||
log.debug("Normalized path: {}", result);
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error("Error normalizing path: {}", path, e);
|
||||
throw new IllegalArgumentException("Failed to normalize path: " + path, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createDirectories(File directory) {
|
||||
if (directory == null) {
|
||||
throw new IllegalArgumentException("Directory cannot be null");
|
||||
}
|
||||
try {
|
||||
if (!directory.exists()) {
|
||||
boolean created = directory.mkdirs();
|
||||
log.info("Directory created: {} (Success: {})", directory.getAbsolutePath(), created);
|
||||
}
|
||||
if (!directory.canWrite()) {
|
||||
throw new IOException("No write permission for directory: " + directory.getAbsolutePath());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create directory: {}", directory.getAbsolutePath(), e);
|
||||
throw new RuntimeException("Failed to create directory", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package app.module.core.config.application.util;
|
||||
|
||||
import app.module.core.config.adapters.persistence.entity.UploadFile;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SftpFileDeleteUtil {
|
||||
|
||||
private final SftpConnector sftpConnector;
|
||||
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
/**
|
||||
* SFTP 서버에서 파일을 삭제하는 공통 메서드
|
||||
* @param deleteFile 삭제할 파일 정보
|
||||
* @throws JSchException SFTP 연결 오류
|
||||
* @throws SftpException SFTP 작업 오류
|
||||
*/
|
||||
public void deleteRealFile(UploadFile deleteFile) throws JSchException, SftpException {
|
||||
if (deleteFile == null || deleteFile.getPath() == null || deleteFile.getName() == null) {
|
||||
log.error("Invalid file information: {}", deleteFile);
|
||||
throw new IllegalArgumentException("Invalid file information");
|
||||
}
|
||||
|
||||
// 경로 검증 및 생성
|
||||
String filePath = constructSafeFilePath(deleteFile.getPath(), deleteFile.getName());
|
||||
log.info("Attempting to delete file from SFTP: {}", filePath);
|
||||
|
||||
// SFTP 연결 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.warn("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
log.error("SFTP channel is not initialized");
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
// 파일 삭제
|
||||
try {
|
||||
channelSftp.stat(filePath); // 파일 존재 여부 확인
|
||||
channelSftp.rm(filePath);
|
||||
log.info("File deleted successfully from SFTP: {}", filePath);
|
||||
} catch (SftpException e) {
|
||||
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
|
||||
log.warn("File does not exist on SFTP: {}", filePath);
|
||||
} else {
|
||||
log.error("Failed to delete file from SFTP: {}, error: {}", filePath, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 경로 조작 방지를 위해 안전한 파일 경로 생성
|
||||
*/
|
||||
private String constructSafeFilePath(String subPath, String fileName) {
|
||||
// 경로 및 파일 이름 정규화
|
||||
String normalizedSubPath = Paths.get(subPath).normalize().toString().replace("\\", "/");
|
||||
String normalizedFileName = Paths.get(fileName).getFileName().toString();
|
||||
String safePath = CommonUtil.removeLastChar(publicPath, "/") + "/" + normalizedSubPath + "/" + normalizedFileName;
|
||||
|
||||
// 경로가 publicPath로 시작하는지 검증
|
||||
if (!safePath.startsWith(publicPath)) {
|
||||
log.error("Invalid file path detected: {}", safePath);
|
||||
throw new IllegalArgumentException("Invalid file path: " + safePath);
|
||||
}
|
||||
|
||||
return safePath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package app.module.core.config.application.util;
|
||||
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.saveToStorage.ports.application.strategy.SftpConnector;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SftpFileDownloader {
|
||||
private final SftpConnector sftpConnector;
|
||||
private final AESEncryptUtil encryptUtil;
|
||||
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
@Value("${file.download.base-path:/tmp/downloads}")
|
||||
private String defaultDownloadBasePath;
|
||||
|
||||
public void downloadFile(GetFile file) throws JSchException, SftpException, IOException {
|
||||
// SFTP 연결 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.info("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp == null) {
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
try {
|
||||
// 원격 파일 경로 (암호화된 파일명 사용)
|
||||
String remoteFilePath = CommonUtil.removeLastChar(publicPath, "/") + file.getPath() + "/" +"encrypted_"+ file.getName();
|
||||
log.info("Remote file path: {}", remoteFilePath);
|
||||
|
||||
// 다운로드 경로 정규화
|
||||
String basePath = CommonUtil.normalizePath(defaultDownloadBasePath);
|
||||
log.info("Base path: {}", basePath);
|
||||
String localEncryptedFilePath = basePath + File.separator + "encrypted_" + file.getOriginName();
|
||||
String localDecryptedFilePath = basePath + File.separator + file.getOriginName();
|
||||
log.info("Local encrypted file path: {}", localEncryptedFilePath);
|
||||
log.info("Local decrypted file path: {}", localDecryptedFilePath);
|
||||
|
||||
// 로컬 디렉토리 생성
|
||||
File localDir = new File(localEncryptedFilePath).getParentFile();
|
||||
CommonUtil.createDirectories(localDir);
|
||||
|
||||
// 원격 파일 존재 여부 확인 (디버깅 용)
|
||||
try {
|
||||
channelSftp.lstat(remoteFilePath);
|
||||
log.info("Remote file exists: {}", remoteFilePath);
|
||||
} catch (SftpException e) {
|
||||
log.error("Remote file does not exist: {}", remoteFilePath, e);
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Remote file does not exist: " + remoteFilePath);
|
||||
}
|
||||
|
||||
// 암호화된 파일 다운로드
|
||||
try (FileOutputStream fos = new FileOutputStream(localEncryptedFilePath)) {
|
||||
channelSftp.get(remoteFilePath, fos);
|
||||
log.info("File downloaded to: {}", localEncryptedFilePath);
|
||||
}
|
||||
|
||||
// 파일 복호화
|
||||
try {
|
||||
byte[] encryptedContent = Files.readAllBytes(Paths.get(localEncryptedFilePath));
|
||||
byte[] decryptedContent = encryptUtil.decryptAesCbc(encryptedContent);
|
||||
Files.write(Paths.get(localDecryptedFilePath), decryptedContent);
|
||||
log.info("File decrypted and saved to: {}", localDecryptedFilePath);
|
||||
file.setLocalPath(localDecryptedFilePath);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to decrypt file: {}", file.getOriginName(), e);
|
||||
throw new IOException("Failed to decrypt file", e);
|
||||
} finally {
|
||||
// 암호화된 임시 파일 삭제
|
||||
Files.deleteIfExists(Paths.get(localEncryptedFilePath));
|
||||
log.info("Temporary encrypted file deleted: {}", localEncryptedFilePath);
|
||||
}
|
||||
|
||||
} catch (SftpException e) {
|
||||
log.error("Failed to download file: {} (Error: {})", file.getOriginName(), e.getMessage());
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
log.error("IO error during file download or decryption: {}", file.getOriginName(), e);
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error during file download: {}", file.getOriginName(), e);
|
||||
throw new RuntimeException("Unexpected error during file download", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public class AdminView implements Serializable {
|
||||
private Boolean accountDisabled;
|
||||
private Integer loginFailCnt;
|
||||
private Boolean accountLocked;
|
||||
private String lastLoginIp;
|
||||
private LocalDateTime createdAt;
|
||||
private String createdBy;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package app.module.core.usecase.file.downloadFile.adapters;
|
||||
|
||||
import app.module.core.config.application.util.SftpFileDownloader;
|
||||
import app.module.core.usecase.file.getFile.ports.GetFilePortIn;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFile;
|
||||
import app.module.core.usecase.file.getFile.ports.application.domain.GetFileCmd;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
class DownloadFileController {
|
||||
private final GetFilePortIn getFilePortIn;
|
||||
private final SftpFileDownloader sftpFileDownloader;
|
||||
|
||||
@GetMapping(path = "/api/file/download/{fileId}")
|
||||
ResponseEntity<?> downloadFile(@PathVariable Long fileId) throws JSchException, SftpException, IOException {
|
||||
GetFile file = getFilePortIn.operate(new GetFileCmd(fileId)).orElseThrow(() -> new IllegalArgumentException("File not found: " + fileId));
|
||||
|
||||
// SFTP에서 파일 다운로드
|
||||
sftpFileDownloader.downloadFile(file);
|
||||
|
||||
// 로컬 파일 경로
|
||||
File downloadedFile = new File(file.getLocalPath());
|
||||
if (!downloadedFile.exists()) {
|
||||
throw new IllegalStateException("Downloaded file not found: " + file.getLocalPath());
|
||||
}
|
||||
|
||||
|
||||
String encodedFileName = URLEncoder.encode(file.getOriginName(), StandardCharsets.UTF_8)
|
||||
.replace("+", "%20");
|
||||
// HTTP 헤더 설정
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
|
||||
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
|
||||
headers.add(HttpHeaders.PRAGMA, "no-cache");
|
||||
headers.add(HttpHeaders.EXPIRES, "0");
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.contentLength(downloadedFile.length())
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.body(new FileSystemResource(downloadedFile));
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,6 @@ import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@AllArgsConstructor
|
||||
@EqualsAndHashCode
|
||||
public class GetFile {
|
||||
private Long id;
|
||||
private FileUploadType type;
|
||||
@@ -18,8 +16,10 @@ public class GetFile {
|
||||
private String name;
|
||||
private String originName;
|
||||
private Long fileLength;
|
||||
private String localPath;
|
||||
private LocalDateTime createdAt;
|
||||
private String createdBy;
|
||||
private LocalDateTime updatedAt;
|
||||
private String updatedBy;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
|
||||
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSch;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.Session;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class SftpConnector {
|
||||
@Value("${file.upload.sftp.ip}")
|
||||
private String host;
|
||||
@Value("${file.upload.sftp.id}")
|
||||
private String id;
|
||||
@Value("${file.upload.sftp.password}")
|
||||
private String password;
|
||||
|
||||
@Value("${file.upload.sftp.port}")
|
||||
private int port;
|
||||
|
||||
private Session session;
|
||||
private ChannelSftp channelSftp;
|
||||
|
||||
public void connect() throws JSchException {
|
||||
|
||||
if (host == null || id == null || password == null) {
|
||||
throw new IllegalStateException("SFTP configuration is incomplete: host=" + host + ", id=" + id + ", password=" + (password != null ? "****" : null));
|
||||
}
|
||||
|
||||
try {
|
||||
JSch jsch = new JSch();
|
||||
// 세션 설정
|
||||
session = jsch.getSession(id, host, port);
|
||||
session.setPassword(password);
|
||||
// 호스트 키 검증 비활성화 (개발 환경에서만 사용, 프로덕션에서는 적절히 설정)
|
||||
session.setConfig("StrictHostKeyChecking", "no");
|
||||
// 연결
|
||||
session.connect();
|
||||
|
||||
// SFTP 채널 열기
|
||||
channelSftp = (ChannelSftp) session.openChannel("sftp");
|
||||
channelSftp.connect();
|
||||
log.info("SFTP connection established successfully");
|
||||
}catch (JSchException e){
|
||||
log.error("Failed to connect to SFTP server", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
if (channelSftp != null && channelSftp.isConnected()) {
|
||||
channelSftp.disconnect();
|
||||
log.info("SFTP channel disconnected");
|
||||
}
|
||||
if (session != null && session.isConnected()) {
|
||||
session.disconnect();
|
||||
log.info("SFTP channel disconnected");
|
||||
}
|
||||
}
|
||||
public boolean isConnected() {
|
||||
return channelSftp != null && channelSftp.isConnected() && session != null && session.isConnected();
|
||||
}
|
||||
|
||||
// ChannelSftp 객체 반환
|
||||
public ChannelSftp getChannelSftp() {
|
||||
return channelSftp;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package app.module.core.usecase.file.saveToStorage.ports.application.strategy;
|
||||
|
||||
import app.module.core.config.application.enums.FileStorageType;
|
||||
import app.module.core.config.application.util.AESEncryptUtil;
|
||||
import app.module.core.config.application.util.CommonUtil;
|
||||
import com.jcraft.jsch.ChannelSftp;
|
||||
import com.jcraft.jsch.JSchException;
|
||||
import com.jcraft.jsch.SftpException;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SftpStorageFileUploadStrategy implements FileUploadStrategy {
|
||||
@Value("${path.upload.sftp.public}")
|
||||
private String publicPath;
|
||||
|
||||
@Value("${path.upload.sftp.tmpdir}")
|
||||
private String tmpPath;
|
||||
|
||||
private final SftpConnector sftpConnector;
|
||||
private final AESEncryptUtil aesEncryptUtil; // EncryptUtil 주입
|
||||
|
||||
@PostConstruct
|
||||
public void initialize() throws Exception {
|
||||
log.info("FileIoService - initialize : path.upload.public is {}", publicPath);
|
||||
log.info("FileIoService - initialize : path.upload.tmpdir is {}", tmpPath);
|
||||
|
||||
try {
|
||||
Files.createDirectories(Paths.get(tmpPath));
|
||||
// SFTP 연결 초기화
|
||||
sftpConnector.connect();
|
||||
// 원격 디렉토리 생성
|
||||
createRemoteDirectories(publicPath);
|
||||
} catch (JSchException | SftpException e) {
|
||||
throw new IOException("Could not initialize SFTP connection or directories", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createRemoteDirectories(String path) throws SftpException {
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
if (channelSftp != null) {
|
||||
String[] folders = path.split("/");
|
||||
String currentPath = "";
|
||||
for (String folder : folders) {
|
||||
if (!folder.isEmpty()) {
|
||||
currentPath += "/" + folder;
|
||||
try {
|
||||
channelSftp.cd(currentPath);
|
||||
} catch (SftpException e) {
|
||||
channelSftp.mkdir(currentPath);
|
||||
channelSftp.cd(currentPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileStorageType getStorageType() {
|
||||
return FileStorageType.SFTP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void operate(MultipartFile multipartFile, String createSubPath, String createFilename) throws IOException {
|
||||
if (multipartFile == null || multipartFile.isEmpty()) {
|
||||
throw new RuntimeException("Failed to store empty file.");
|
||||
}
|
||||
|
||||
// 로컬 임시 파일 저장
|
||||
Path tmpFile = Paths.get(tmpPath, createFilename);
|
||||
Files.createDirectories(tmpFile.getParent());
|
||||
try (InputStream inputStream = multipartFile.getInputStream()) {
|
||||
Files.copy(inputStream, tmpFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
// 파일 내용 암호화
|
||||
Path encryptedFile = Paths.get(tmpPath, "encrypted_" + createFilename);
|
||||
try {
|
||||
// 파일 읽기
|
||||
byte[] fileContent = Files.readAllBytes(tmpFile);
|
||||
// 암호화
|
||||
byte[] encryptedContent = aesEncryptUtil.encryptAesCbc(fileContent);
|
||||
// 암호화된 내용을 임시 파일로 저장
|
||||
Files.write(encryptedFile, encryptedContent);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to encrypt file: {}", createFilename, e);
|
||||
throw new IOException("Failed to encrypt file", e);
|
||||
}
|
||||
|
||||
String remotePath = CommonUtil.removeLastChar(publicPath, "/") + createSubPath;
|
||||
String remoteFilePath = remotePath + "/" + "encrypted_" + createFilename;
|
||||
|
||||
try {
|
||||
// 연결 상태 확인 및 재연결
|
||||
if (!sftpConnector.isConnected()) {
|
||||
log.warn("SFTP connection lost, attempting to reconnect");
|
||||
sftpConnector.connect();
|
||||
}
|
||||
|
||||
createRemoteDirectories(remotePath);
|
||||
ChannelSftp channelSftp = sftpConnector.getChannelSftp();
|
||||
|
||||
if (channelSftp == null) {
|
||||
throw new SftpException(ChannelSftp.SSH_FX_NO_CONNECTION, "SFTP channel is not initialized");
|
||||
}
|
||||
|
||||
// 암호화된 파일 업로드
|
||||
try (InputStream encryptedInputStream = Files.newInputStream(encryptedFile)) {
|
||||
channelSftp.put(encryptedInputStream, remoteFilePath);
|
||||
channelSftp.chmod(0644, remoteFilePath); // 권한 변경 (0777 -> 0644로 보안 강화)
|
||||
log.info("Encrypted file uploaded to SFTP: {}", remoteFilePath);
|
||||
}
|
||||
} catch (SftpException | JSchException e) {
|
||||
throw new RuntimeException("Failed to upload encrypted file to SFTP", e);
|
||||
} finally {
|
||||
// 임시 파일 삭제
|
||||
Files.deleteIfExists(tmpFile);
|
||||
Files.deleteIfExists(encryptedFile);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void cleanup() {
|
||||
sftpConnector.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package app.module.core.usecase.file.url.strategy;
|
||||
|
||||
import app.module.core.config.application.enums.FileStorageType;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class SftpFileUrlStrategy implements FileUrlStrategy {
|
||||
|
||||
@Override
|
||||
public FileStorageType getStorageType() {
|
||||
return FileStorageType.SFTP;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getInlineURL(String subPath, String filename) {
|
||||
return String.format("/content-disposition/inline%s/%s", subPath, filename);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAttachmentURL(Long fileId) {
|
||||
return String.format("/api/file/download/%s", fileId);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -36,8 +36,6 @@ public class GetHousehold {
|
||||
private Boolean isPanel;
|
||||
private String memo;
|
||||
private String dropReason;
|
||||
private LocalDate latestRegisterStartDate;
|
||||
private LocalDate latestRegisterEndDate;
|
||||
private LocalDateTime createdAt;
|
||||
private String createdBy;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@@ -9,5 +9,7 @@ import org.apache.ibatis.annotations.Param;
|
||||
@Mapper
|
||||
public interface URIMapper {
|
||||
URITopTier findTopTierByAppType(@Param("appType") AppType appType);
|
||||
URITopTier findTopTierByAppTypeByRoleId(@Param("appType") AppType appType,@Param("roleId") String roleId);
|
||||
List<URITopTier> findChildrenByParentId(@Param("parentId") String parentId);
|
||||
List<URITopTier> findChildrenByParentIdByRoleId(@Param("parentId") String parentId,@Param("roleId") String roleId);
|
||||
}
|
||||
|
||||
@@ -25,12 +25,33 @@ public class URITopTierDao implements URITopTierPortOut {
|
||||
|
||||
return recursiveMapping(top);
|
||||
}
|
||||
@Override
|
||||
@Transactional
|
||||
public URITopTier connectRoleId(AppType appType, String roleId) {
|
||||
URITopTier top = uriMapper.findTopTierByAppTypeByRoleId(appType,roleId);
|
||||
if (top == null) {
|
||||
throw new RuntimeException("There is no top tier item of " + appType);
|
||||
}
|
||||
|
||||
return recursiveMapping(top,roleId);
|
||||
}
|
||||
|
||||
private URITopTier recursiveMapping(URITopTier current) {
|
||||
List<URITopTier> children = uriMapper.findChildrenByParentId(current.getId());
|
||||
current.setChildren(children.stream()
|
||||
.map(this::recursiveMapping)
|
||||
.map(this::recursiveMapping)
|
||||
.collect(Collectors.toList()));
|
||||
return current;
|
||||
}
|
||||
|
||||
private URITopTier recursiveMapping(URITopTier current,String roleId) {
|
||||
List<URITopTier> children = uriMapper.findChildrenByParentIdByRoleId(current.getId(),roleId);
|
||||
current.setChildren(children.stream()
|
||||
.map(uri -> recursiveMapping(uri,roleId))
|
||||
.collect(Collectors.toList()));
|
||||
return current;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -5,4 +5,5 @@ import app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier;
|
||||
|
||||
public interface URITopTierPortIn {
|
||||
URITopTier connect(AppType appType);
|
||||
URITopTier connectRoleId(AppType appType, String roleId);
|
||||
}
|
||||
|
||||
@@ -6,4 +6,5 @@ import app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier;
|
||||
public interface URITopTierPortOut {
|
||||
|
||||
URITopTier connect(AppType appType);
|
||||
URITopTier connectRoleId(AppType appType,String roleId);
|
||||
}
|
||||
|
||||
@@ -19,4 +19,10 @@ public class URITopTierService implements URITopTierPortIn {
|
||||
public URITopTier connect(AppType appType) {
|
||||
return topTierPortOut.connect(appType);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public URITopTier connectRoleId(AppType appType, String roleId) {
|
||||
return topTierPortOut.connectRoleId(appType,roleId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,12 +18,17 @@
|
||||
a.account_disabled,
|
||||
a.login_fail_cnt,
|
||||
a.account_locked,
|
||||
liu.clientip as last_login_ip,
|
||||
a.created_at,
|
||||
a.created_by,
|
||||
a.updated_at,
|
||||
a.updated_by
|
||||
FROM admin a
|
||||
WHERE id = #{id}
|
||||
LEFT JOIN ( SELECT clientip,login_id
|
||||
FROM logged_in_user liu
|
||||
ORDER BY last_logged_in_at desc
|
||||
LIMIT 1 ) liu on liu.login_id = a.id
|
||||
WHERE a.id = #{id}
|
||||
AND a.is_deleted = false
|
||||
</select>
|
||||
|
||||
|
||||
@@ -26,18 +26,11 @@
|
||||
h.is_panel,
|
||||
h.memo,
|
||||
h.drop_reason,
|
||||
dr.start_date as latest_register_start_date,
|
||||
dr.end_date as latest_register_end_date,
|
||||
h.created_at,
|
||||
h.created_by,
|
||||
h.updated_at,
|
||||
h.updated_by
|
||||
FROM household h
|
||||
LEFT JOIN (
|
||||
SELECT start_date , end_date ,household_seq
|
||||
FROM daily_record dr
|
||||
ORDER BY start_date desc
|
||||
LIMIT 1 ) dr ON dr.household_seq = h.seq
|
||||
WHERE h.household_num = #{householdNum}
|
||||
AND h.is_deleted = false
|
||||
</select>
|
||||
|
||||
@@ -2,32 +2,65 @@
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
|
||||
<mapper namespace="app.module.core.usecase.uri.toptier.adapters.persistence.URIMapper">
|
||||
<select id="findTopTierByAppType" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
SELECT
|
||||
u.id,
|
||||
u.app_type,
|
||||
u.text,
|
||||
u.uri,
|
||||
u.show_on_navi,
|
||||
u.order_no
|
||||
FROM uri u
|
||||
WHERE u.app_type = #{appType}
|
||||
AND u.parent_id IS NULL
|
||||
AND u.is_deleted = false
|
||||
</select>
|
||||
|
||||
<select id="findTopTierByAppType" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
<select id="findChildrenByParentId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
SELECT
|
||||
u.id,
|
||||
u.app_type,
|
||||
u.text,
|
||||
u.uri,
|
||||
u.show_on_navi,
|
||||
u.order_no
|
||||
FROM uri u
|
||||
WHERE u.parent_id = #{parentId}
|
||||
AND u.is_deleted = false
|
||||
ORDER BY u.order_no ASC
|
||||
</select>
|
||||
|
||||
<select id="findTopTierByAppTypeByRoleId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
SELECT
|
||||
id,
|
||||
app_type,
|
||||
text,
|
||||
uri,
|
||||
show_on_navi,
|
||||
order_no
|
||||
FROM uri
|
||||
WHERE app_type = #{appType}
|
||||
AND parent_id IS NULL
|
||||
AND is_deleted = false
|
||||
u.id,
|
||||
u.app_type,
|
||||
u.text,
|
||||
u.uri,
|
||||
u.show_on_navi,
|
||||
u.order_no
|
||||
FROM uri u
|
||||
JOIN uri_has_role uhr ON u.id = uhr.uri_id and uhr.is_deleted = false
|
||||
WHERE u.app_type = #{appType}
|
||||
AND u.parent_id IS NULL
|
||||
AND u.is_deleted = false
|
||||
AND uhr.role_id = #{roleId}
|
||||
AND u.show_on_navi = true
|
||||
</select>
|
||||
|
||||
<select id="findChildrenByParentId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
<select id="findChildrenByParentIdByRoleId" resultType="app.module.core.usecase.uri.toptier.ports.application.domain.URITopTier">
|
||||
SELECT
|
||||
id,
|
||||
app_type,
|
||||
text,
|
||||
uri,
|
||||
show_on_navi,
|
||||
order_no
|
||||
FROM uri
|
||||
WHERE parent_id = #{parentId}
|
||||
AND is_deleted = false
|
||||
ORDER BY order_no ASC
|
||||
u.id,
|
||||
u.app_type,
|
||||
u.text,
|
||||
u.uri,
|
||||
u.show_on_navi,
|
||||
u.order_no
|
||||
FROM uri u
|
||||
JOIN uri_has_role uhr ON u.id = uhr.uri_id and uhr.is_deleted = false
|
||||
WHERE u.parent_id = #{parentId}
|
||||
AND u.is_deleted = false
|
||||
AND uhr.role_id = #{roleId}
|
||||
AND u.show_on_navi = true
|
||||
ORDER BY u.order_no ASC
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -831,23 +831,26 @@ COMMENT ON COLUMN operation_log.is_deleted IS '삭제여부';
|
||||
|
||||
-- ============================================
|
||||
-- TABLE : logged_in_user
|
||||
-- DESC : 로그인 사용자 정보 테이블
|
||||
-- DESC : 로그인 사용자 이력 테이블
|
||||
-- ============================================
|
||||
CREATE SEQUENCE logged_in_user_seq START WITH 1 INCREMENT BY 1 CACHE 1 NO CYCLE;
|
||||
CREATE TABLE logged_in_user (
|
||||
id bigint DEFAULT nextval('logged_in_user_seq') NOT NULL, -- 로그 ID (PK)
|
||||
app_type varchar(255) NOT NULL, -- 앱 타입 (FRONT / ADMIN)
|
||||
id varchar(255) NOT NULL, -- 로그인 아이디
|
||||
login_id varchar(255) NOT NULL, -- 로그인 아이디
|
||||
last_logged_in_at timestamp(6), -- 마지막 로그인 날짜
|
||||
clientip varchar(255), -- 접속 아이피
|
||||
|
||||
CONSTRAINT logged_in_user_pkey PRIMARY KEY (app_type, id),
|
||||
CONSTRAINT logged_in_user_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT logged_in_user_app_type_check
|
||||
CHECK (app_type::text = ANY (ARRAY['FRONT', 'ADMIN']))
|
||||
);
|
||||
|
||||
COMMENT ON TABLE logged_in_user IS '로그인사용자정보테이블';
|
||||
COMMENT ON TABLE logged_in_user IS '로그인사용자이력테이블';
|
||||
|
||||
COMMENT ON COLUMN logged_in_user.id IS '로그 ID';
|
||||
COMMENT ON COLUMN logged_in_user.app_type IS '앱 타입';
|
||||
COMMENT ON COLUMN logged_in_user.id IS '로그인 아이디';
|
||||
COMMENT ON COLUMN logged_in_user.login_id IS '로그인 아이디';
|
||||
COMMENT ON COLUMN logged_in_user.last_logged_in_at IS '마지막 로그인 날짜';
|
||||
COMMENT ON COLUMN logged_in_user.clientip IS '접속 아이피';
|
||||
|
||||
|
||||
@@ -153,8 +153,8 @@ CREATE TABLE daily_income (
|
||||
quantity varchar(10), -- 수량
|
||||
unit_code varchar(255), -- 단위(매핑코드)
|
||||
unit_self varchar(100), -- 단위(직접입력)
|
||||
price integer, -- 현금(원)
|
||||
estimated_value integer, -- 현물(평가액)
|
||||
price bigint, -- 현금(원)
|
||||
estimated_value bigint, -- 현물(평가액)
|
||||
created_at timestamp(6), -- 생성일
|
||||
created_by varchar(255), -- 생성자
|
||||
updated_at timestamp(6), -- 수정일
|
||||
@@ -211,11 +211,11 @@ CREATE TABLE daily_expense (
|
||||
expense_kind varchar(100), -- 지출의 종류
|
||||
expense_kind_mark varchar(10), -- 종류 부호
|
||||
source_purpose varchar(10), -- 지출원(용도)
|
||||
quantity varchar(10), -- 수량
|
||||
quantity varchar(10), -- 수량
|
||||
unit_code varchar(255), -- 단위(매핑코드)
|
||||
unit_self varchar(100), -- 단위(직접입력)
|
||||
price integer, -- 현금(원)
|
||||
estimated_value integer, -- 현물(평가액)
|
||||
unit_self varchar(100), -- 단위(직접입력)
|
||||
price bigint, -- 현금(원)
|
||||
estimated_value bigint, -- 현물(평가액)
|
||||
created_at timestamp(6), -- 생성일
|
||||
created_by varchar(255), -- 생성자
|
||||
updated_at timestamp(6), -- 수정일
|
||||
@@ -386,7 +386,7 @@ CREATE TABLE daily_forestry (
|
||||
quantity varchar(10), -- 수량
|
||||
unit_code varchar(255), -- 단위(매핑코드)
|
||||
unit_self varchar(100), -- 단위(직접입력)
|
||||
estimated_value integer, -- 현물평가
|
||||
estimated_value bigint, -- 현물평가
|
||||
created_at timestamp(6), -- 생성일
|
||||
created_by varchar(255), -- 생성자
|
||||
updated_at timestamp(6), -- 수정일
|
||||
@@ -437,7 +437,7 @@ CREATE TABLE daily_farming (
|
||||
quantity varchar(10), -- 수량
|
||||
unit_code varchar(255), -- 단위(매핑코드)
|
||||
unit_self varchar(100), -- 단위(직접입력)
|
||||
estimated_value integer, -- 현물평가액
|
||||
estimated_value bigint, -- 현물평가액
|
||||
created_at timestamp(6), -- 생성일
|
||||
created_by varchar(255), -- 생성자
|
||||
updated_at timestamp(6), -- 수정일
|
||||
|
||||
@@ -80,5 +80,5 @@ SELECT
|
||||
a.name AS researcher_name,
|
||||
a.phone AS researcher_phone
|
||||
FROM researcher_has_household rhh
|
||||
JOIN admin a ON rhh.admin_seq = a.seq
|
||||
JOIN admin a ON rhh.admin_seq = a.seq and a.account_disabled = false
|
||||
WHERE rhh.is_deleted = false;
|
||||
Reference in New Issue
Block a user