Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/4-find-user-id #13

Merged
merged 3 commits into from
Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public enum ErrorCode {
EXIST_USER_ID(HttpStatus.BAD_REQUEST, "이미 μ‘΄μž¬ν•˜λŠ” μ•„μ΄λ””μž…λ‹ˆλ‹€."),
EXIST_USER_EMAIL(HttpStatus.BAD_REQUEST, "이미 μ‘΄μž¬ν•˜λŠ” μ΄λ©”μΌμž…λ‹ˆλ‹€."),
NOT_MATCH_PASSWORD(HttpStatus.BAD_REQUEST, "νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€."),
NOT_FOUND_EMAIL(HttpStatus.NOT_FOUND, "κ°€μž…λ˜μ§€ μ•Šμ€ 이메일 μž…λ‹ˆλ‹€."),
NOT_MATCH_USERNAME(HttpStatus.BAD_REQUEST, "잘λͺ»λœ μ΄λ¦„μž…λ‹ˆλ‹€."),

//토큰 μ˜ˆμ™Έ
TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED, "토큰이 λ§Œλ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package com.sptp.backend.email.service;

public interface EmailService {
String sendMessage(String to)throws Exception;
void sendMessage(String to)throws Exception;
}
54 changes: 13 additions & 41 deletions src/main/java/com/sptp/backend/email/service/EmailServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.sptp.backend.email.service;

import com.sptp.backend.email.service.EmailService;
import com.sptp.backend.member.repository.Member;
import com.sptp.backend.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
Expand All @@ -16,12 +18,11 @@
public class EmailServiceImpl implements EmailService {

private final JavaMailSender emailSender;
private final MemberRepository memberRepository;

public static final String ePw = createKey();

private MimeMessage createMessage(String to)throws Exception{
private MimeMessage createMessage(String to, String UserId)throws Exception{
System.out.println("λ³΄λ‚΄λŠ” λŒ€μƒ : "+ to);
System.out.println("인증 번호 : "+ePw);
System.out.println("아이디 : "+ UserId);
MimeMessage message = emailSender.createMimeMessage();

message.addRecipients(Message.RecipientType.TO, to);//λ³΄λ‚΄λŠ” λŒ€μƒ
Expand All @@ -31,56 +32,27 @@ private MimeMessage createMessage(String to)throws Exception{
msgg+= "<div style='margin:20px;'>";
msgg+= "<h1> μ•ˆλ…•ν•˜μ„Έμš” Attiesμž…λ‹ˆλ‹€. </h1>";
msgg+= "<br>";
msgg+= "<p>μ•„λž˜ μ½”λ“œλ₯Ό 볡사해 μž…λ ₯ν•΄μ£Όμ„Έμš”<p>";
msgg+= "<br>";
msgg+= "<p>κ°μ‚¬ν•©λ‹ˆλ‹€.<p>";
msgg+= "<br>";
msgg+= "<div align='center' style='border:1px solid black; font-family:verdana';>";
msgg+= "<h3 style='color:blue;'>νšŒμ›κ°€μž… 인증 μ½”λ“œμž…λ‹ˆλ‹€.</h3>";
msgg+= "<h3 style='color:blue;'>μ•„λž˜λŠ” νšŒμ›λ‹˜μ˜ μ•„μ΄λ””μž…λ‹ˆλ‹€.</h3>";
msgg+= "<div style='font-size:130%'>";
msgg+= "CODE : <strong>";
msgg+= ePw+"</strong><div><br/> ";
msgg+= "νšŒμ›ID : <strong>";
msgg+= UserId+"</strong><div><br/> ";
msgg+= "</div>";
message.setText(msgg, "utf-8", "html");//λ‚΄μš©
message.setFrom(new InternetAddress("[email protected]","limjunho"));//λ³΄λ‚΄λŠ” μ‚¬λžŒ
message.setFrom(new InternetAddress("[email protected]","Atties"));//λ³΄λ‚΄λŠ” μ‚¬λžŒ

return message;
}

public static String createKey() {
StringBuffer key = new StringBuffer();
Random rnd = new Random();

for (int i = 0; i < 8; i++) { // μΈμ¦μ½”λ“œ 8자리
int index = rnd.nextInt(3); // 0~2 κΉŒμ§€ 랜덀

switch (index) {
case 0:
key.append((char) ((int) (rnd.nextInt(26)) + 97));
// a~z (ex. 1+97=98 => (char)98 = 'b')
break;
case 1:
key.append((char) ((int) (rnd.nextInt(26)) + 65));
// A~Z
break;
case 2:
key.append((rnd.nextInt(10)));
// 0~9
break;
}
}
return key.toString();
}
@Override
public String sendMessage(String to)throws Exception {
// TODO Auto-generated method stub
MimeMessage message = createMessage(to);
try{//μ˜ˆμ™Έμ²˜λ¦¬
public void sendMessage(String to)throws Exception {
String UserId = memberRepository.findByEmail(to).get().getUserId();
MimeMessage message = createMessage(to, UserId);
try{
emailSender.send(message);
}catch(MailException es){
es.printStackTrace();
throw new IllegalArgumentException();
}
return ePw;
}
}
24 changes: 16 additions & 8 deletions src/main/java/com/sptp/backend/member/service/MemberService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.sptp.backend.member.service;

import com.sptp.backend.member.web.dto.request.MemberFindIdRequestDto;
import com.sptp.backend.member.web.dto.request.MemberLoginRequestDto;
import com.sptp.backend.member.web.dto.request.MemberSaveRequestDto;
import com.sptp.backend.member.repository.Member;
Expand All @@ -16,8 +17,11 @@
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -70,21 +74,25 @@ public TokenDto login(MemberLoginRequestDto dto) {
return tokenDto;
}

public Member findByEmail(MemberFindIdRequestDto dto) {

// 이메일 및 μœ μ €μ΄λ¦„ μœ νš¨μ„± 체크
Member findMember = memberRepository.findByEmail(dto.getEmail())
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_EMAIL));
if (!dto.getUsername().equals(findMember.getUsername())) {
throw new CustomException(ErrorCode.NOT_MATCH_USERNAME);
}

return findMember;
}

public void logout(String accessToken) {
Long expiration = jwtTokenProvider.getExpiration(accessToken);

redisTemplate.opsForValue()
.set(accessToken, "blackList", expiration, TimeUnit.MILLISECONDS);
}

public Optional<Member> findByEmail(String email) {
Optional<Member> findUser = memberRepository.findByEmail(email);
if (findUser.isPresent()) {
return findUser;
}
return null;
}

public void checkDuplicateMemberID(String userId) {
if (memberRepository.existsByUserId(userId)) {
throw new CustomException(ErrorCode.EXIST_USER_ID);
Expand Down
37 changes: 21 additions & 16 deletions src/main/java/com/sptp/backend/member/web/MemberController.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.sptp.backend.member.web;

import com.sptp.backend.member.web.dto.request.MemberFindIdRequestDto;
import com.sptp.backend.jwt.service.JwtService;
import com.sptp.backend.jwt.web.JwtTokenProvider;
import com.sptp.backend.member.web.dto.request.MemberLoginRequestDto;
Expand All @@ -11,13 +12,18 @@
import com.sptp.backend.email.service.EmailService;
import com.sptp.backend.jwt.web.dto.TokenDto;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.net.URI;
import java.util.HashMap;
import java.util.Optional;
import java.util.Map;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -76,9 +82,9 @@ public ResponseEntity<?> refresh(@RequestHeader("refreshToken") String refreshTo
.build();

return ResponseEntity.status(HttpStatus.OK).body(tokenResponseDto);

}

// λ‘œκ·Έμ•„μ›ƒ
@PostMapping("/members/logout")
public ResponseEntity logout(@RequestHeader("accessToken") String accessToken) {

Expand All @@ -87,24 +93,23 @@ public ResponseEntity logout(@RequestHeader("accessToken") String accessToken) {
return new ResponseEntity(HttpStatus.OK);
}

@PostMapping("/emailConfirm")
public String emailConfirm(@RequestParam String email) throws Exception {
// 아이디 μ°ΎκΈ°
@PostMapping("/members/id")
public ResponseEntity<?> findId(@RequestBody MemberFindIdRequestDto memberFindIdRequestDto) {

String confirm = emailService.sendMessage(email);
emailMap.put(email, confirm);
return confirm;
}
Member member = memberService.findByEmail(memberFindIdRequestDto);

@PostMapping("/emailConfirmCheck")
public String emailCheck(@RequestParam String email, @RequestParam String code) {
if (emailMap.get(email).equals(code)) {
emailMap.remove(email);
return "OK";
}else{
return "NO";
}
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("/emailId?email=" + member.getEmail()));

return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
}

// μ΄λ©”μΌλ‘œ 아이디 λ°œμ†‘
@PostMapping("/emailId")
public ResponseEntity emailConfirm(@RequestParam String email) throws Exception {

emailService.sendMessage(email);
return new ResponseEntity(HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sptp.backend.member.web.dto.request;

import lombok.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MemberFindIdRequestDto {

private String username;
private String email;
}