Skip to content

Commit

Permalink
Merge pull request #14 from StudyFlexUMC5th/suhoon
Browse files Browse the repository at this point in the history
Suhoon
  • Loading branch information
s2hoon authored Jan 8, 2024
2 parents 53fcebe + d4701fe commit b587628
Show file tree
Hide file tree
Showing 14 changed files with 226 additions and 167 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ dependencies {
// school web mail
implementation 'com.github.in-seo:univcert:master-SNAPSHOT'

// password mail
implementation 'org.springframework.boot:spring-boot-starter-mail'


compileOnly 'org.projectlombok:lombok'
Expand Down
73 changes: 25 additions & 48 deletions src/main/java/com/umc/StudyFlexBE/config/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
package com.umc.StudyFlexBE.config.jwt;
//import org.springframework.security.core.userdetails.User;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import io.jsonwebtoken.*;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
Expand All @@ -12,14 +22,9 @@
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
Expand All @@ -31,6 +36,7 @@ public class JwtTokenProvider implements InitializingBean {

@Value("${jwt.token-validity-in-seconds}")
private long tokenValidityInMilliseconds;

private Key key;


Expand All @@ -41,35 +47,26 @@ public void afterPropertiesSet() throws Exception {
}

public String createToken(Authentication authentication) {

Long memberId = null;
if (authentication.getPrincipal() instanceof CustomUserDetails) {
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
memberId = userDetails.getMemberId();
}

String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));

// 토큰의 expire 시간을 설정
long now = (new Date()).getTime();
Date validity = new Date(now + this.tokenValidityInMilliseconds);

JwtBuilder builder = Jwts.builder()
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.forName("HS512"), key)
.setExpiration(validity);

if (memberId != null) {
builder.claim("memberId", memberId);
}
return builder.compact();
.claim(AUTHORITIES_KEY, authorities) // 정보 저장
.signWith(key, SignatureAlgorithm.HS512) // 사용할 암호화 알고리즘과 , signature 에 들어갈 secret값 세팅
.setExpiration(validity) // set Expire Time 해당 옵션 안넣으면 expire안함
.compact();
}

// 토큰으로 클레임을 만들고 이를 이용해 유저 객체를 만들어서 최종적으로 authentication 객체를 리턴
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parserBuilder()
Claims claims = Jwts
.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
Expand All @@ -80,31 +77,11 @@ public Authentication getAuthentication(String token) {
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());


CustomUserDetails principal = new CustomUserDetails(
claims.get("memberId", Long.class),
claims.getSubject(),
"",
authorities,
true,
true,
true,
true
);
User principal = new User(claims.getSubject(), "", authorities);

return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}

public Long getMemberIdFromToken(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();

return claims.get("memberId", Long.class);
}

// 토큰의 유효성 검증을 수행
public boolean validateToken(String token) {
try {
Expand All @@ -125,4 +102,4 @@ public boolean validateToken(String token) {
}
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
import com.umc.StudyFlexBE.service.ComplaintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
Expand All @@ -29,10 +32,8 @@ public ResponseEntity<BaseResponse<ComplaintResponseDto>> postComplaint(
@RequestBody ComplaintRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

ComplaintResponseDto complaintResponse = complaintService.postComplaint(memberId, studyId, request);
String email = authentication.getName();
ComplaintResponseDto complaintResponse = complaintService.postComplaint(email, studyId, request);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, complaintResponse));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down
24 changes: 13 additions & 11 deletions src/main/java/com/umc/StudyFlexBE/controller/InquiryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

import com.umc.StudyFlexBE.dto.request.Inquiry.InquiryAnswerRequestDto;
import com.umc.StudyFlexBE.dto.request.Inquiry.InquiryUploadRequestDto;
import com.umc.StudyFlexBE.dto.response.*;
import com.umc.StudyFlexBE.dto.response.BaseResponse;
import com.umc.StudyFlexBE.dto.response.BaseResponseStatus;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryAnswerResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryListResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryResponseDto;
import com.umc.StudyFlexBE.dto.response.Inquiry.InquiryUploadResponseDto;
import com.umc.StudyFlexBE.entity.Inquiry;
import com.umc.StudyFlexBE.security.CustomUserDetails;
import com.umc.StudyFlexBE.service.InquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/app/inquiry")
Expand All @@ -31,10 +37,8 @@ public ResponseEntity<BaseResponse<InquiryUploadResponseDto>> postInquiry(
@RequestBody InquiryUploadRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

Inquiry inquiry = inquiryService.createInquiry(memberId, request);
String email = authentication.getName();
Inquiry inquiry = inquiryService.createInquiry(email, request);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, new InquiryUploadResponseDto(inquiry.getId())));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down Expand Up @@ -78,10 +82,8 @@ public ResponseEntity<BaseResponse<InquiryAnswerResponseDto>> postAnswer(
@RequestBody InquiryAnswerRequestDto request) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
Long memberId = userDetails.getMemberId();

InquiryAnswerResponseDto inquiryAnswerResponse = inquiryService.postAnswer(inquiryId, request, memberId);
String email = authentication.getName();
InquiryAnswerResponseDto inquiryAnswerResponse = inquiryService.postAnswer(inquiryId, request, email);
return ResponseEntity.ok(new BaseResponse<>(BaseResponseStatus.SUCCESS, inquiryAnswerResponse));
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new BaseResponse<>(BaseResponseStatus.BAD_REQUEST));
Expand Down
75 changes: 62 additions & 13 deletions src/main/java/com/umc/StudyFlexBE/controller/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import com.umc.StudyFlexBE.dto.request.CheckAuthCodeDto;
import com.umc.StudyFlexBE.dto.request.LoginDto;
import com.umc.StudyFlexBE.dto.request.SearchPasswordDto;
import com.umc.StudyFlexBE.dto.request.SendAuthCodeDto;
import com.umc.StudyFlexBE.dto.request.SignUpDto;
import com.umc.StudyFlexBE.dto.request.SignUpOAuthDto;
Expand All @@ -20,23 +21,24 @@
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("app/member")
@RequiredArgsConstructor
public class MemberController {

private final MemberService memberService;
private final RestTemplate restTemplate;

@Value("${mail.api.key}")
private String mail_api_key;

@GetMapping("/checkEmail/{email}")
public BaseResponse<?> checkEmail(@PathVariable String email) {
try {
Expand Down Expand Up @@ -107,42 +109,89 @@ public BaseResponse<?> kakaoCallback(String code) {


@PostMapping("/sendAuthCode")
public BaseResponse<?> senAuthCode(@RequestBody SendAuthCodeDto sendAuthCodeDto) {
public BaseResponse<?> senAuthCode(@RequestBody SendAuthCodeDto sendAuthCodeDto) {
try {
Map<String, Object> result = UnivCert.certify(mail_api_key, sendAuthCodeDto.getEmail(), sendAuthCodeDto.getUnivName(), true);
UnivCert.clear(mail_api_key,sendAuthCodeDto.getEmail());
Map<String, Object> result = UnivCert.certify(mail_api_key, sendAuthCodeDto.getEmail(),
sendAuthCodeDto.getUnivName(), false);
if (result.isEmpty()) {
return new BaseResponse<>(BaseResponseStatus.SEND_EMAIL_FAILED);
}
if (result.get("success").equals(false)) {
return new BaseResponse<>(BaseResponseStatus.WEB_MAIL_CODE_FAILED);
}
return new BaseResponse<String>(BaseResponseStatus.SUCCESS, "인증 코드 발송 완료.");
} catch (Exception e){
} catch (Exception e) {
return new BaseResponse<>(BaseResponseStatus.SEND_EMAIL_FAILED);
}
}

@PostMapping("/checkAuthCode")
public BaseResponse<?> checkAuthCode(@RequestBody CheckAuthCodeDto checkAuthCodeDto) throws IOException {
Map<String, Object> result =UnivCert.certifyCode(mail_api_key,checkAuthCodeDto.getWebEmail(),checkAuthCodeDto.getUnivName(), checkAuthCodeDto.getCode());
Map<String, Object> result = UnivCert.certifyCode(mail_api_key, checkAuthCodeDto.getWebEmail(),
checkAuthCodeDto.getUnivName(), checkAuthCodeDto.getCode());
if (result.isEmpty()) {
return new BaseResponse<>(BaseResponseStatus.WEB_MAIL_CODE_FAILED);
}
if (result.get("success").equals(false)) {
return new BaseResponse<>(BaseResponseStatus.WEB_MAIL_CODE_FAILED);
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = (String) authentication.getPrincipal();
String email = authentication.getName();
System.out.println(email);
memberService.certifyWebMail(email, checkAuthCodeDto.getUnivName(), checkAuthCodeDto.getWebEmail());
return new BaseResponse<String>(BaseResponseStatus.SUCCESS, "인증 코드 확인 완료.");
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "인증 코드 확인 완료.");
}

@GetMapping("testauth")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public BaseResponse<?> test() {

return new BaseResponse<String>(BaseResponseStatus.SUCCESS, "굿");
@DeleteMapping("/deleteMember")
public BaseResponse<?> deleteMember(String password) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();
memberService.deleteMember(email);
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "회원 삭제 완료.");
}


@GetMapping("/searchPassword")
public BaseResponse<?> searchPassword(@RequestBody SearchPasswordDto searchPasswordDto) {
try {
memberService.sendPasswordMail(searchPasswordDto.getEmail(), searchPasswordDto.getPassword());
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "새로운 비밀번호 전송 완료.");
} catch (BaseException e) {
return new BaseResponse<>(BaseResponseStatus.CHANGE_PASSWORD_FAILED);
}
}

@PostMapping("/changeEmail")
public BaseResponse<?> changeEmail(String newEmail) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();
memberService.changeEmail(email , newEmail);
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "이메일 변경 완료.");
} catch (BaseException e) {
return new BaseResponse<>(BaseResponseStatus.CHANGE_EMAIL_FAILED);
}

}


@GetMapping("testauth")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public BaseResponse<?> test() {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();
System.out.println(email);
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "굿");
}

@PostMapping("clear")
public BaseResponse<?> clearing() throws IOException {
UnivCert.list(mail_api_key);
UnivCert.clear(mail_api_key);
UnivCert.list(mail_api_key);
return new BaseResponse<>(BaseResponseStatus.SUCCESS, "clear 완료");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.umc.StudyFlexBE.dto.request;

import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class SearchPasswordDto {
@JsonProperty
@NotNull
private String email;

@JsonProperty
@NotNull
private String password;
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public enum BaseResponseStatus {

SEND_EMAIL_FAILED(false,3005 ,"인증코드 요청 실패" ),
WEB_MAIL_CODE_FAILED(false, 3006, "인증코드 불일치"),
MAIL_SEND_FAILED(false, 3007,"이메일 전송 실패" ),
CHANGE_EMAIL_FAILED(false,3008 ,"이메일 변경 실패" ),
CHANGE_PASSWORD_FAILED(false,3009 ,"비밀번호 변경 실패" ),

/**
* 4XXX : Post
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/umc/StudyFlexBE/entity/Role.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.umc.StudyFlexBE.entity;

public enum Role {
ROLE_USER, ROLE_ADMIN
ROLE_USER, ROLE_ADMIN, ROLE_CERTIFIED
}
Loading

0 comments on commit b587628

Please sign in to comment.