Skip to content

Commit

Permalink
#26 Feat: IdentityService & Controller 로직 구체화 및 재학증, 메타데이터 관리 로직 수정[박한솔]
Browse files Browse the repository at this point in the history
pjhcsols committed Oct 17, 2024
1 parent dc73f01 commit 4ddc5ef
Showing 15 changed files with 613 additions and 145 deletions.
1 change: 1 addition & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions web3-credential-server/build/resources/main/data.sql
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@ VALUES
('pjhcsols@naver.com', '$2a$10$ENYqGvZ3p6LvtsBnRWINSOJHKlMt1Ykgb3.jCnoKkrhMihviXhkDu'),
('exampleuser@example.com', '$2a$10$EXAMPLEHASHFORUSERPASSWORD');

INSERT INTO wallets (user_id, pdfUrl,privateKey, publicKey, address)
INSERT INTO wallets (user_id, pdfUrl,privateKey, publicKey)
VALUES
(1, 'https://web3credentialbucket.s3.ap-northeast-2.amazonaws.com/ssa_1727764703278_ssa','privateKeyForUser1', 'publicKeyForUser1', 'addressForUser1'),
(2,null,'privateKeyForUser2', 'publicKeyForUser2', 'addressForUser2');
(1,'https://basilium-product-bucket.s3.ap-northeast-2.amazonaws.com/1_certifications.pdf','privateKeyForUser1', 'publicKeyForUser1'),
(2,null,'privateKeyForUser2', 'publicKeyForUser2');
1 change: 0 additions & 1 deletion web3-credential-server/build/resources/main/schema.sql
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@ CREATE TABLE wallets (
pdfUrl VARCHAR(255),
privateKey VARCHAR(255) NOT NULL,
publicKey VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);

Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,40 +1,152 @@
package web3.controller.Identity;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import web3.domain.wallet.Wallet;
import web3.exception.S3.S3UploadException;
import web3.s3Storage.dto.DeleteCertRequest;
import web3.service.Identity.IdentityService;
import web3.service.dto.Identity.StudentCertificationDto;
import web3.service.wallet.WalletService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/certifications")
@Slf4j
public class IdentityController {

private final IdentityService identityService;

private final WalletService walletService;
@Autowired
public IdentityController(IdentityService identityService) {
public IdentityController(IdentityService identityService, WalletService walletService) {
this.identityService = identityService;
this.walletService = walletService;
}

@PostMapping("/register")
public ResponseEntity<String> registerCertification(@RequestBody StudentCertificationDto certificationDto) {
try {
identityService.registerStudentCertification(certificationDto);
return ResponseEntity.ok("재학증이 성공적으로 등록되었습니다.");
} catch (Exception e) {
return ResponseEntity.status(500).body("재학증 등록 중 오류 발생: " + e.getMessage());
}
public ResponseEntity<String> registerCertification(
@RequestParam("file") MultipartFile file,
@RequestParam("walletId") Long walletId,
@RequestParam("email") String email,
@RequestParam("univName") String univName,
@RequestParam("univCheck") Boolean univCheck) {

StudentCertificationDto certificationDto = new StudentCertificationDto(email, univName, univCheck);

identityService.registerStudentCertification(walletId, certificationDto, file);

return ResponseEntity.ok("재학증이 성공적으로 등록되었습니다.");
}

@Operation(summary = "사용자의 등록된 인증서 key 목록 전체 얻기", description = "사용자의 등록된 인증서 이름 목록을 전체를 가져옵니다.")
@GetMapping("/get-cert-names")
public ResponseEntity<Set<String>> getCertNames(
@Parameter(description = "pdf 파일 경로", required = true)
@RequestParam String pdfUrl) {

// 인증서 이름 목록 얻기
Set<String> certNames = identityService.getCertNames(pdfUrl);

return ResponseEntity.ok().body(certNames);
}

@Operation(summary = "특정 인증서 삭제",description = "지갑에서 특정 인증서를 삭제합니다. 즉,S3 스토리지에 pdf 파일에서 특정 페이지를 삭제합니다.")
@PatchMapping ("/delete-one")
public ResponseEntity<Void> deleteCertForPage(
@Parameter(description = "walletId와 삭제할 page가 담긴 Dto",required = true)
@RequestBody DeleteCertRequest request
) throws IOException, S3UploadException {
Long walletId = request.getWalletId();
int page = request.getPage();
Wallet wallet = walletService.getWalletById(walletId).orElseThrow(()-> new EntityNotFoundException("Wallet does not exist"));
identityService.deletePdfForPage(wallet,page);
return ResponseEntity.noContent().build();
}

@Operation(summary = "모든 인증서 삭제(지갑 삭제)",description = "모든 인증서를 삭제합니다. 즉,s3 스토리지에 pdf 파일을 모두 삭제합니다.")
@DeleteMapping("/delete-pdf")
public ResponseEntity<Void> deleteWallet(
@Parameter(description = "지울 pdf 파일 경로 관련 Dto",required = true)
@RequestParam("pdfUrl") String pdfUrl,
@RequestParam("walletId") Long walletId) {
identityService.deletePdf(pdfUrl, walletId);
return ResponseEntity.noContent().build();
}

@GetMapping("/{key}")
public ResponseEntity<StudentCertificationDto> getCertification(@PathVariable String key) {
@Operation(summary = "인증서 리스트 얻기",description = "개인의 인증서{(key : value)..(key : value)}들을 모두 가져옵니다.")
@GetMapping("/certs")
public ResponseEntity<HashMap<String,String>> getCertList(
@Parameter(description = "pdf 파일 경로",required = true)
@RequestParam("pdfUrl") String pdfUrl) {
HashMap<String, String> certList = identityService.getCertList(pdfUrl);
HashMap<String, String> decodedMetadata = identityService.decodeMetadata(certList);

return ResponseEntity.ok().body(decodedMetadata);

}

@Operation(summary = "인증서 리스트 얻기 - pdf 형식",description = "개인의 인증서들을 pdf의 형식으로 모두 가져옵니다.")
@GetMapping("/get-pdf")
public ResponseEntity<byte[]> getPdf(
@Parameter(description = "pdf 파일 경로",required = true)
@RequestParam("pdfUrl") String pdfUrl) {
try {
StudentCertificationDto certificationDto = identityService.queryStudentCertification(key);
return ResponseEntity.ok(certificationDto);
} catch (Exception e) {
return ResponseEntity.status(404).body(null);
byte[] pdfData = identityService.getPdf(pdfUrl).readAllBytes();
return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF).body(pdfData);
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

@Operation(summary = "pdf 대체하기",description = "원하는 페이지를 원하는 pdf로 대체합니다.")
@PostMapping("/replace-pdf")
public ResponseEntity<String> replacePdf(
@Parameter(description = "pdf 파일",required = true)
@RequestParam("file") MultipartFile file,
@Parameter(description = "페이지 번호",required = true)
@RequestParam("page") int page,
@Parameter(description = "사용자 지갑ID",required = true)
@RequestParam("walletId") Long walletId) throws IOException {
Wallet wallet = walletService.getWalletById(walletId).orElseThrow(()-> new EntityNotFoundException("Wallet does not exist"));
String pdfUrl = identityService.replacePdfPage(wallet, page, file);
return ResponseEntity.ok(pdfUrl);
}

@Operation(summary = "사용자의 해당되는 인증서의 특정 value 얻기",description = "사용자의 인증서 목록중 원하는 인증서의 내용들을 가져옵니다.")
@GetMapping("/get-content")
public ResponseEntity<List<Map.Entry<String, String>>> getPdfKey(
@Parameter(description = "pdf 파일 경로",required = true)
@RequestParam String pdfUrl,
@Parameter(description = "인증서 이름",required = true)
@RequestParam String certName,
@Parameter(description = "지갑 ID",required = true)
@RequestParam Long walletId) {

List<Map.Entry<String, String>> contentsForCertName = identityService.getContentsForCertName(pdfUrl, certName, walletId);
return ResponseEntity.ok().body(contentsForCertName);
}

@Operation(summary = "PDF 페이지 수 얻기", description = "특정 PDF의 총 페이지 수 반환")
@GetMapping("/get-pdf-page-count")
public ResponseEntity<Integer> getPdfPageCount(
@Parameter(description = "PDF file URL", required = true)
@RequestParam String pdfUrl) {
int pageCount = identityService.getPdfPageCount(pdfUrl);
return ResponseEntity.ok(pageCount);
}

}
Original file line number Diff line number Diff line change
@@ -54,9 +54,8 @@ public ResponseEntity<Wallet> getMyWallet(@LoginMember User loginUser) {
public ResponseEntity<Wallet> createWallet(
@LoginMember User loginUser, // 로그인한 사용자 정보 주입
@RequestParam String privateKey,
@RequestParam String publicKey,
@RequestParam String address) throws WalletAlreadyExistsException {
Wallet wallet = walletService.createWallet(loginUser, privateKey, publicKey, address);
@RequestParam String publicKey) throws WalletAlreadyExistsException {
Wallet wallet = walletService.createWallet(loginUser, privateKey, publicKey);
return new ResponseEntity<>(wallet, HttpStatus.CREATED);
}

Original file line number Diff line number Diff line change
@@ -24,34 +24,30 @@ public class Wallet {
@Column(nullable = false)
private String publicKey;

@Column(nullable = false)
private String address;

public void setPdfUrl(String pdfUrl) {
this.pdfUrl = pdfUrl;
}

//JPA 기본 생성자
protected Wallet() {}

// 생성자: 필드 값을 모두 제공
public Wallet(User user, String privateKey, String publicKey, String address) {
public Wallet(User user, String privateKey, String publicKey) {
this.user = user;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.address = address;
}

public void updateWallet(String privateKey, String publicKey, String address) {
public void updateWallet(String privateKey, String publicKey) {
this.privateKey = privateKey;
this.publicKey = publicKey;
this.address = address;
}

public void updatePdfUrl(String pdfUrl) {
this.pdfUrl = pdfUrl;
}

public void updatePrivateKey(String privateKey) {
this.privateKey = privateKey;
}

// Getter 메서드
public Long getId() {
return id;
@@ -71,9 +67,6 @@ public String getPublicKey() {
return publicKey;
}

public String getAddress() {
return address;
}

@Override
public boolean equals(Object o) {
@@ -97,7 +90,6 @@ public String toString() {
", user=" + user +
", privateKey='" + privateKey + '\'' +
", publicKey='" + publicKey + '\'' +
", address='" + address + '\'' +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -58,4 +58,5 @@ public ResponseEntity<String> handleWalletPrivateKeyNotEqualsException(WalletAlr
public ResponseEntity<String> handleGeneralException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error.");
}

}
Original file line number Diff line number Diff line change
@@ -122,11 +122,11 @@ private void uploadToS3(String fileName, Map<String, String> metadata, byte[] re
}

private static String getFileName(Wallet wallet) {
return wallet.getAddress() + "_" + System.currentTimeMillis() + "_" + wallet.getAddress();
return wallet.getId() + "_" + System.currentTimeMillis() + "_" + wallet.getId();
}

private static String getEmptyFilename(Wallet wallet) {
return wallet.getAddress() + "_" + System.currentTimeMillis() + "_" + "empty.pdf";
return wallet.getId() + "_" + System.currentTimeMillis() + "_" + "empty.pdf";
}

public byte[] mergePdfs(byte[] pdf1, byte[] pdf2){

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,48 +1,27 @@
package web3.service.dto.Identity;

public class StudentCertificationDto {
private String key; //재학증_walletId
private String email;
private String univName;
private boolean univCheck;

public StudentCertificationDto(String key, String email, String univName, boolean univCheck) {
this.key = key;
public StudentCertificationDto(String email, String univName, boolean univCheck) {

this.email = email;
this.univName = univName;
this.univCheck = univCheck;
}

// Getters and Setters
public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getUnivName() {
return univName;
}

public void setUnivName(String univName) {
this.univName = univName;
}

public boolean isUnivCheck() {
return univCheck;
}

public void setUnivCheck(boolean univCheck) {
this.univCheck = univCheck;
}
}
Original file line number Diff line number Diff line change
@@ -171,7 +171,6 @@ public Map<String, Object> sendWalletInfo(User user, String accessToken) {
response.put("walletId", wallet.getId());
response.put("privateKey", wallet.getPrivateKey());
response.put("publicKey", wallet.getPublicKey());
response.put("address", wallet.getAddress());

logger.info("지갑 정보 전송 완료: {}", response);
return response;
@@ -200,8 +199,8 @@ private void sendKakaoWalletInfo(User user, String accessToken, Wallet wallet) {
private String createWalletTemplateObject(User user, Wallet wallet) {
Map<String, Object> templateObject = new HashMap<>();
templateObject.put("object_type", "text");
templateObject.put("text", String.format("지갑 정보\n이메일: %s\nPrivate Key: %s\nPublic Key: %s\nAddress: %s",
user.getEmail(), wallet.getPrivateKey(), wallet.getPublicKey(), wallet.getAddress()));
templateObject.put("text", String.format("지갑 정보\n이메일: %s\nPrivate Key: %s\nPublic Key: %s\n인증서: %s",
user.getEmail(), wallet.getPrivateKey(), wallet.getPublicKey(), wallet.getPdfUrl()));
templateObject.put("link", Map.of("web_url", "http://your-web-url.com"));

try {
Original file line number Diff line number Diff line change
@@ -24,12 +24,12 @@ public WalletService(WalletRepository walletRepository) {
}

//지갑 생성
public Wallet createWallet(User user, String privateKey, String publicKey, String address) throws WalletAlreadyExistsException {
public Wallet createWallet(User user, String privateKey, String publicKey) throws WalletAlreadyExistsException {
Optional<Wallet> existingWallet = walletRepository.findByUser(user);
if (existingWallet.isPresent()) {
throw new WalletAlreadyExistsException("User already has a wallet");
}
Wallet wallet = new Wallet(user, privateKey, publicKey, address);
Wallet wallet = new Wallet(user, privateKey, publicKey);
return walletRepository.save(wallet);
}

@@ -47,7 +47,7 @@ public Optional<Wallet> getWalletByUser(User user) {
public Wallet updateWallet(Long id, String privateKey, String publicKey, String address) {
Wallet existingWallet = walletRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Wallet not found"));
existingWallet.updateWallet(privateKey, publicKey, address);
existingWallet.updateWallet(privateKey, publicKey);
return walletRepository.save(existingWallet);
}

6 changes: 3 additions & 3 deletions web3-credential-server/src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@ VALUES
('pjhcsols@naver.com', '$2a$10$ENYqGvZ3p6LvtsBnRWINSOJHKlMt1Ykgb3.jCnoKkrhMihviXhkDu'),
('exampleuser@example.com', '$2a$10$EXAMPLEHASHFORUSERPASSWORD');

INSERT INTO wallets (user_id, pdfUrl,privateKey, publicKey, address)
INSERT INTO wallets (user_id, pdfUrl,privateKey, publicKey)
VALUES
(1, 'https://web3credentialbucket.s3.ap-northeast-2.amazonaws.com/ssa_1727764703278_ssa','privateKeyForUser1', 'publicKeyForUser1', 'addressForUser1'),
(2,null,'privateKeyForUser2', 'publicKeyForUser2', 'addressForUser2');
(1,'https://basilium-product-bucket.s3.ap-northeast-2.amazonaws.com/1_certifications.pdf','privateKeyForUser1', 'publicKeyForUser1'),
(2,null,'privateKeyForUser2', 'publicKeyForUser2');
1 change: 0 additions & 1 deletion web3-credential-server/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@ CREATE TABLE wallets (
pdfUrl VARCHAR(255),
privateKey VARCHAR(255) NOT NULL,
publicKey VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
);

0 comments on commit 4ddc5ef

Please sign in to comment.