REMOVED OLD ENDPOINTS AND SOME ENCRYPTION AND DECRYPTION METHODS
This commit is contained in:
-93
@@ -1,93 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.config.HDFSConfig;
|
||||
import com.skycrate.backend.skycrateBackend.dto.LoginUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.dto.RegisterUserDto;
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
import com.skycrate.backend.skycrateBackend.utils.EncryptionUtil;
|
||||
import com.skycrate.backend.skycrateBackend.utils.RSAKeyUtil;
|
||||
import org.apache.hadoop.fs.FileSystem;
|
||||
import org.apache.hadoop.fs.Path;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.security.KeyPair;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
|
||||
public AuthenticationService(UserRepository userRepository,
|
||||
AuthenticationManager authenticationManager,
|
||||
PasswordEncoder passwordEncoder) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
public User signUp(RegisterUserDto inputUser) {
|
||||
// Generate RSA key pair
|
||||
KeyPair keyPair;
|
||||
try {
|
||||
keyPair = RSAKeyUtil.generateKeyPair();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("Failed to generate RSA key pair", e);
|
||||
}
|
||||
|
||||
// Encrypt private key using password-derived AES key
|
||||
byte[] salt = EncryptionUtil.generateSalt();
|
||||
byte[] iv = EncryptionUtil.generateIv();
|
||||
byte[] encryptedPrivateKey;
|
||||
try {
|
||||
SecretKey aesKey = EncryptionUtil.deriveKey(inputUser.getPassword().toCharArray(), salt);
|
||||
encryptedPrivateKey = EncryptionUtil.encrypt(keyPair.getPrivate().getEncoded(), aesKey, iv);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to encrypt private key", e);
|
||||
}
|
||||
|
||||
// Create user entity with encrypted private key, salt, and iv
|
||||
User user = User.builder()
|
||||
.fullname(inputUser.getFirstname() + " " + inputUser.getLastname())
|
||||
.username(inputUser.getUsername())
|
||||
.email(inputUser.getEmail())
|
||||
.password(passwordEncoder.encode(inputUser.getPassword()))
|
||||
.publicKey(keyPair.getPublic().getEncoded())
|
||||
.privateKey(encryptedPrivateKey)
|
||||
.privateKeySalt(salt)
|
||||
.privateKeyIv(iv)
|
||||
.build();
|
||||
|
||||
// Save user
|
||||
User savedUser = userRepository.save(user);
|
||||
|
||||
// Create HDFS directory in root with username
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
Path userDir = new Path("/" + savedUser.getUsername());
|
||||
if (!fs.exists(userDir)) {
|
||||
fs.mkdirs(userDir);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to create HDFS directory for user: " + savedUser.getUsername(), e);
|
||||
}
|
||||
|
||||
return savedUser;
|
||||
}
|
||||
|
||||
public User authenticate(LoginUserDto inputUser) {
|
||||
authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(inputUser.getEmail(), inputUser.getPassword())
|
||||
);
|
||||
|
||||
return userRepository.findByEmail(inputUser.getEmail())
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import javax.crypto.*;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.KeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
public class EncryptionUtil {
|
||||
|
||||
private static final int SALT_LENGTH = 16; // in bytes
|
||||
private static final int IV_LENGTH = 16; // for AES CBC
|
||||
private static final int ITERATIONS = 65536;
|
||||
private static final int KEY_LENGTH = 256; // bits
|
||||
|
||||
// --- AES key derivation using PBKDF2 ---
|
||||
public static SecretKey deriveAESKey(char[] password, byte[] salt)
|
||||
throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
|
||||
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
|
||||
|
||||
KeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
|
||||
byte[] keyBytes = factory.generateSecret(spec).getEncoded();
|
||||
|
||||
return new SecretKeySpec(keyBytes, "AES");
|
||||
}
|
||||
|
||||
// --- Encrypt data using AES-CBC ---
|
||||
public static byte[] encrypt(byte[] data, SecretKey key, byte[] iv)
|
||||
throws GeneralSecurityException {
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(iv);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
|
||||
|
||||
return cipher.doFinal(data);
|
||||
}
|
||||
|
||||
// --- Decrypt data using AES-CBC ---
|
||||
public static byte[] decrypt(byte[] encryptedData, SecretKey key, byte[] iv)
|
||||
throws GeneralSecurityException {
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(iv);
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
|
||||
|
||||
return cipher.doFinal(encryptedData);
|
||||
}
|
||||
|
||||
// --- Generate random salt ---
|
||||
public static byte[] generateSalt() {
|
||||
byte[] salt = new byte[SALT_LENGTH];
|
||||
new SecureRandom().nextBytes(salt);
|
||||
return salt;
|
||||
}
|
||||
|
||||
// --- Generate random IV ---
|
||||
public static byte[] generateIV() {
|
||||
byte[] iv = new byte[IV_LENGTH];
|
||||
new SecureRandom().nextBytes(iv);
|
||||
return iv;
|
||||
}
|
||||
|
||||
// --- Optional: Utility to base64 encode data ---
|
||||
public static String encodeBase64(byte[] data) {
|
||||
return Base64.getEncoder().encodeToString(data);
|
||||
}
|
||||
|
||||
public static byte[] decodeBase64(String base64) {
|
||||
return Base64.getDecoder().decode(base64);
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.config.HDFSConfig;
|
||||
import com.skycrate.backend.skycrateBackend.entity.FileMetadata;
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.FileMetadataRepository;
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
import com.skycrate.backend.skycrateBackend.utils.EncryptionUtil;
|
||||
import com.skycrate.backend.skycrateBackend.utils.RSAKeyUtil;
|
||||
import org.apache.hadoop.fs.FSDataInputStream;
|
||||
import org.apache.hadoop.fs.FSDataOutputStream;
|
||||
import org.apache.hadoop.fs.FileSystem;
|
||||
import org.apache.hadoop.fs.Path;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
|
||||
@Service
|
||||
public class FileService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FileService.class);
|
||||
|
||||
private final FileMetadataRepository fileMetadataRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public FileService(FileMetadataRepository fileMetadataRepository, UserRepository userRepository) {
|
||||
this.fileMetadataRepository = fileMetadataRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public void uploadEncryptedFile(String username, byte[] fileContent, String filename) throws Exception {
|
||||
log.info("Starting upload for user={}, file={}", username, filename);
|
||||
try {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new RuntimeException("User not found: " + username));
|
||||
|
||||
SecretKey aesKey = EncryptionUtil.generateAESKey();
|
||||
byte[] salt = EncryptionUtil.generateSalt(); // reserved for future use
|
||||
byte[] iv = EncryptionUtil.generateIv();
|
||||
|
||||
byte[] encryptedData = EncryptionUtil.encrypt(fileContent, aesKey, iv);
|
||||
|
||||
PublicKey publicKey = RSAKeyUtil.decodePublicKey(user.getPublicKey());
|
||||
byte[] encryptedAesKey = EncryptionUtil.encryptRSA(aesKey.getEncoded(), publicKey);
|
||||
|
||||
Path userDir = new Path("/" + username);
|
||||
Path filePath = new Path(userDir, filename);
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
|
||||
if (!fs.exists(userDir)) {
|
||||
log.info("Creating directory in HDFS: {}", userDir);
|
||||
fs.mkdirs(userDir);
|
||||
}
|
||||
|
||||
log.info("Writing encrypted file to HDFS: {}", filePath);
|
||||
try (FSDataOutputStream out = fs.create(filePath, true);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(encryptedData)) {
|
||||
in.transferTo(out);
|
||||
}
|
||||
|
||||
FileMetadata metadata = FileMetadata.builder()
|
||||
.username(username)
|
||||
.filePath(filePath.toString())
|
||||
.salt(salt)
|
||||
.iv(iv)
|
||||
.encryptedKey(encryptedAesKey)
|
||||
.uploadedAt(System.currentTimeMillis())
|
||||
.build();
|
||||
|
||||
fileMetadataRepository.save(metadata);
|
||||
log.info("Upload complete: file={} for user={}", filename, username);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error during file upload for user={}, file={}: {}", username, filename, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] downloadDecryptedFile(String username, String password, String filename) throws Exception {
|
||||
log.info("Download request: user={}, file={}", username, filename);
|
||||
try {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new RuntimeException("User not found: " + username));
|
||||
|
||||
Path filePath = new Path("/" + username + "/" + filename);
|
||||
FileMetadata metadata = fileMetadataRepository.findByUsernameAndFilePath(username, filePath.toString())
|
||||
.orElseThrow(() -> new RuntimeException("File metadata not found for: " + filePath));
|
||||
|
||||
SecretKey derivedKey = EncryptionUtil.deriveKey(password.toCharArray(), user.getPrivateKeySalt());
|
||||
byte[] decryptedPrivateKeyBytes = EncryptionUtil.decrypt(user.getPrivateKey(), derivedKey, user.getPrivateKeyIv());
|
||||
PrivateKey privateKey = RSAKeyUtil.decodePrivateKey(decryptedPrivateKeyBytes);
|
||||
|
||||
byte[] aesKeyBytes = EncryptionUtil.decryptRSA(metadata.getEncryptedKey(), privateKey);
|
||||
SecretKey aesKey = EncryptionUtil.rebuildAESKey(aesKeyBytes);
|
||||
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
byte[] encryptedData;
|
||||
try (FSDataInputStream in = fs.open(filePath)) {
|
||||
encryptedData = in.readAllBytes();
|
||||
}
|
||||
|
||||
return EncryptionUtil.decrypt(encryptedData, aesKey, metadata.getIv());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Download failed for user={}, file={}: {}", username, filename, e.getMessage(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.config.HDFSConfig;
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
import com.skycrate.backend.skycrateBackend.utils.RSAKeyUtil;
|
||||
import org.apache.hadoop.fs.FSDataOutputStream;
|
||||
import org.apache.hadoop.fs.FileStatus;
|
||||
import org.apache.hadoop.fs.FileSystem;
|
||||
import org.apache.hadoop.fs.Path;
|
||||
import org.apache.hadoop.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class HDFSOperations {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
public HDFSOperations(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
// public void uploadFile(byte[] fileData, String hdfsPath, String uploadedFileName, String username) {
|
||||
// try {
|
||||
// FileSystem fs = HDFSConfig.getHDFS();
|
||||
//
|
||||
// // Create an InputStream from the byte array
|
||||
// ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
|
||||
//
|
||||
// // Prepare the path for HDFS
|
||||
// String finalHdfsPath = hdfsPath.endsWith("/") ? hdfsPath + uploadedFileName : hdfsPath + "/" + uploadedFileName;
|
||||
//
|
||||
// // Upload the file directly to HDFS from the InputStream
|
||||
// Path hdfsFilePath = new Path(finalHdfsPath);
|
||||
// FSDataOutputStream outputStream = fs.create(hdfsFilePath);
|
||||
// IOUtils.copyBytes(inputStream, outputStream, 4096, true);
|
||||
//
|
||||
// } catch (IOException e) {
|
||||
// // Handle I/O exception and log the error
|
||||
// throw new RuntimeException("Failed to upload file to HDFS: " + e.getMessage(), e);
|
||||
// } catch (Exception e) {
|
||||
// // Catch any other exceptions
|
||||
// throw new RuntimeException("Failed to upload file to HDFS: " + e.getMessage(), e);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public void downloadFile(String hdfsEncPath, String localPathWithoutExt, String username) {
|
||||
// try {
|
||||
// FileSystem fs = HDFSConfig.getHDFS();
|
||||
//
|
||||
// // Extract file name and extension
|
||||
// String encFileName = new File(hdfsEncPath).getName();
|
||||
// String originalFileName = encFileName.replace(".enc", "");
|
||||
// String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
|
||||
//
|
||||
// String fullDecryptedPath = localPathWithoutExt + "/" + originalFileName;
|
||||
// String encFilePath = fullDecryptedPath + ".enc";
|
||||
// String keyFilePath = fullDecryptedPath + ".key";
|
||||
//
|
||||
// // Download encrypted file and AES key from HDFS
|
||||
// fs.copyToLocalFile(new Path(hdfsEncPath), new Path(encFilePath));
|
||||
// fs.copyToLocalFile(new Path(hdfsEncPath.replace(".enc", ".key")), new Path(keyFilePath));
|
||||
//
|
||||
// // Read the encrypted AES key
|
||||
// byte[] encryptedAesKey = Files.readAllBytes(Paths.get(keyFilePath));
|
||||
// System.out.println("Length of encrypted AES key: " + encryptedAesKey.length);
|
||||
//
|
||||
// // Retrieve the RSA private key for the user
|
||||
// User user = userRepository.findByUsername(username)
|
||||
// .orElseThrow(() -> new RuntimeException("User not found"));
|
||||
// PrivateKey privateKey = RSAKeyUtil.getPrivateKeyFromBytes(user.getPrivateKey());
|
||||
//
|
||||
// Cipher rsaCipher = Cipher.getInstance("RSA");
|
||||
// rsaCipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
// byte[] aesKeyBytes = rsaCipher.doFinal(encryptedAesKey);
|
||||
//
|
||||
// // Ensure valid AES key length
|
||||
// if (aesKeyBytes.length != 16 && aesKeyBytes.length != 24 && aesKeyBytes.length != 32) {
|
||||
// throw new RuntimeException("Invalid AES key length: " + aesKeyBytes.length + " bytes");
|
||||
// }
|
||||
//
|
||||
// SecretKey aesKey = new SecretKeySpec(aesKeyBytes, 0, aesKeyBytes.length, "AES");
|
||||
//
|
||||
// // Read the encrypted file content
|
||||
// byte[] encryptedFileContent = Files.readAllBytes(Paths.get(encFilePath));
|
||||
//
|
||||
// // Decrypt the file content using AES
|
||||
// Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // Specify padding
|
||||
// aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
|
||||
// byte[] decryptedFileContent = aesCipher.doFinal(encryptedFileContent);
|
||||
//
|
||||
// // Write the decrypted content to the original file
|
||||
// Files.write(Paths.get(fullDecryptedPath + "." + fileExtension), decryptedFileContent);
|
||||
//
|
||||
// // Cleanup temporary files
|
||||
// Files.deleteIfExists(Paths.get(encFilePath));
|
||||
// Files.deleteIfExists(Paths.get(keyFilePath));
|
||||
//
|
||||
// } catch (Exception e) {
|
||||
// throw new RuntimeException("Failed to download or decrypt file: " + e.getMessage(), e);
|
||||
// }
|
||||
// }
|
||||
|
||||
public void uploadFile(byte[] fileData, String hdfsPath, String uploadedFileName, String username) {
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
|
||||
String finalHdfsPath = hdfsPath.endsWith("/") ? hdfsPath + uploadedFileName : hdfsPath + "/" + uploadedFileName;
|
||||
Path hdfsFilePath = new Path(finalHdfsPath);
|
||||
try (FSDataOutputStream outputStream = fs.create(hdfsFilePath)) {
|
||||
IOUtils.copyBytes(inputStream, outputStream, 4096, true);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to upload file to HDFS: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public void downloadFile(String hdfsEncPath, String localPathWithoutExt, String username) {
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
String encFilePath = localPathWithoutExt + ".enc";
|
||||
fs.copyToLocalFile(new Path(hdfsEncPath), new Path(encFilePath));
|
||||
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
PrivateKey privateKey = RSAKeyUtil.getPrivateKeyFromBytes(user.getPrivateKey());
|
||||
|
||||
byte[] encryptedFileContent = Files.readAllBytes(Paths.get(encFilePath));
|
||||
byte[] decryptedFileContent = RSAKeyUtil.decrypt(encryptedFileContent, privateKey);
|
||||
|
||||
Files.write(Paths.get(localPathWithoutExt), decryptedFileContent);
|
||||
Files.deleteIfExists(Paths.get(encFilePath));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to download or decrypt file: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void createFolder(String hdfsPath) {
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
Path path = new Path(hdfsPath);
|
||||
if (!fs.exists(path)) {
|
||||
fs.mkdirs(path);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Handle I/O exception and log the error
|
||||
throw new RuntimeException("Failed to create folder in HDFS due to I/O issue: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
// Catch any other exceptions
|
||||
throw new RuntimeException("Failed to create folder: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteFile(String hdfsFilePath) {
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
Path path = new Path(hdfsFilePath);
|
||||
if (fs.exists(path)) {
|
||||
fs.delete(path, false);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Handle I/O exception and log the error
|
||||
throw new RuntimeException("Failed to delete file due to I/O issue: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
// Catch any other exceptions
|
||||
throw new RuntimeException("Failed to delete file: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteFolder(String hdfsFolderPath) {
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
Path path = new Path(hdfsFolderPath);
|
||||
if (fs.exists(path)) {
|
||||
fs.delete(path, true);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Handle I/O exception and log the error
|
||||
throw new RuntimeException("Failed to delete folder due to I/O issue: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
// Catch any other exceptions
|
||||
throw new RuntimeException("Failed to delete folder: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> listFilesAndFolders(String hdfsPath) {
|
||||
List<String> results = new ArrayList<>();
|
||||
try {
|
||||
FileSystem fs = HDFSConfig.getHDFS();
|
||||
Path path = new Path(hdfsPath);
|
||||
|
||||
if (fs.exists(path)) {
|
||||
listFilesAndFoldersRecursively(fs, path, "", results);
|
||||
} else {
|
||||
throw new RuntimeException("HDFS path does not exist: " + hdfsPath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to list files and folders due to I/O issue: " + e.getMessage(), e);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to list files and folders: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private void listFilesAndFoldersRecursively(FileSystem fs, Path path, String indent, List<String> results) throws IOException {
|
||||
FileStatus[] fileStatuses = fs.listStatus(path);
|
||||
for (FileStatus fileStatus : fileStatuses) {
|
||||
String entry = indent + (fileStatus.isDirectory() ? "📁 " : "📄 ") + fileStatus.getPath().getName();
|
||||
results.add(entry);
|
||||
|
||||
if (fileStatus.isDirectory()) {
|
||||
listFilesAndFoldersRecursively(fs, fileStatus.getPath(), indent + " ", results);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
public class JwtService {
|
||||
|
||||
@Value("${security.jwt.secret-key}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${security.jwt.expiration-time}")
|
||||
private long expirationTime;
|
||||
|
||||
private static final String SECRET_KEY = "PPp27xSTfBwOpRn4/AV6gPzQSnQg+Oi80KdWfCcuAHs=";
|
||||
|
||||
private Key getSigningKey() {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
Claims claims = Jwts.parserBuilder()
|
||||
.setSigningKey(getSigningKey())
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, UserDetails userDetails) {
|
||||
final String username = extractUsername(token);
|
||||
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
|
||||
}
|
||||
|
||||
public boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
public String generateToken(UserDetails userDetails) {
|
||||
return Jwts.builder()
|
||||
.setSubject(userDetails.getUsername())
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + expirationTime))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public String generateToken(User user) {
|
||||
return generateToken((UserDetails) user);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// NEED TO IMPLEMENT SAHI SE
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
public class RateLimiterService {
|
||||
private final ConcurrentHashMap<String, Integer> attempts = new ConcurrentHashMap<>();
|
||||
|
||||
public boolean isBlocked(String ip) {
|
||||
return attempts.getOrDefault(ip, 0) >= 5;
|
||||
}
|
||||
|
||||
public void recordFailedAttempt(String ip) {
|
||||
attempts.put(ip, attempts.getOrDefault(ip, 0) + 1);
|
||||
}
|
||||
|
||||
public void resetAttempts(String ip) {
|
||||
attempts.remove(ip);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.entity.RefreshToken;
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.RefreshTokenRepository;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class RefreshTokenService {
|
||||
|
||||
private final RefreshTokenRepository refreshTokenRepo;
|
||||
|
||||
@Value("${security.jwt.refresh-expiry-ms:604800000}") // 7 days default
|
||||
private Long refreshTokenDurationMs;
|
||||
|
||||
public RefreshTokenService(RefreshTokenRepository refreshTokenRepo) {
|
||||
this.refreshTokenRepo = refreshTokenRepo;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RefreshToken createRefreshToken(User user) {
|
||||
refreshTokenRepo.deleteByUser(user);
|
||||
refreshTokenRepo.flush();
|
||||
|
||||
RefreshToken token = new RefreshToken();
|
||||
token.setUser(user);
|
||||
token.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
|
||||
token.setToken(UUID.randomUUID().toString());
|
||||
return refreshTokenRepo.save(token);
|
||||
}
|
||||
|
||||
public Optional<RefreshToken> findByToken(String token) {
|
||||
return refreshTokenRepo.findByToken(token);
|
||||
}
|
||||
|
||||
public boolean isExpired(RefreshToken token) {
|
||||
return token.getExpiryDate().isBefore(Instant.now());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteByUser(User user) {
|
||||
refreshTokenRepo.deleteByUser(user);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.skycrate.backend.skycrateBackend.services;
|
||||
|
||||
import com.skycrate.backend.skycrateBackend.dto.SignupRequest;
|
||||
import com.skycrate.backend.skycrateBackend.entity.User;
|
||||
import com.skycrate.backend.skycrateBackend.repository.UserRepository;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
public void registerUser(SignupRequest request) {
|
||||
if (isPasswordPwned(request.getPassword())) {
|
||||
throw new IllegalArgumentException("Password has been compromised in data breaches.");
|
||||
}
|
||||
|
||||
User user = new User();
|
||||
user.setUsername(request.getUsername());
|
||||
user.setEmail(request.getEmail());
|
||||
user.setPassword(passwordEncoder.encode(request.getPassword()));
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
private boolean isPasswordPwned(String password) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
byte[] hash = md.digest(password.getBytes());
|
||||
String fullHash = String.format("%040x", new BigInteger(1, hash)).toUpperCase();
|
||||
String prefix = fullHash.substring(0, 5);
|
||||
String suffix = fullHash.substring(5);
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
String response = restTemplate.getForObject("https://api.pwnedpasswords.com/range/" + prefix, String.class);
|
||||
|
||||
return response != null && response.contains(suffix);
|
||||
} catch (Exception e) {
|
||||
return false; // If API fails, allow but log in production
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user