Skip to content

Commit

Permalink
Feat: Email 인증 처리 (#48)
Browse files Browse the repository at this point in the history
* Feat: Event 기능 추가
  • Loading branch information
taking authored Oct 28, 2023
1 parent 959ff58 commit a542056
Show file tree
Hide file tree
Showing 27 changed files with 468 additions and 283 deletions.
13 changes: 3 additions & 10 deletions application.properties_docker
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ spring.data.mongodb.uri=mongodb://${DATABASE_USERID:-nw}:${DATABASE_USERPASS:-nw
spring.jackson.default-property-inclusion=NON_NULL
# logging.level.ROOT=DEBUG

# Redis connection properties
spring.data.redis.host=${REDIS_HOST:-nw-redis}
spring.data.redis.port=${REDIS_PORT:-8083}

#set your port
server.port=8888
#server.error.include-message=always
Expand All @@ -30,17 +26,14 @@ springdoc.swagger-ui.operations-sorter=alpha
lab.cherry.nw.jwtSecret= bGFiLWNoZXJyeS1udy1wcm9qZWN0LXNlY3JldC1rZXkK
lab.cherry.nw.jwtExpirationMs= 86400000


#Email
spring.mail.host=${SMTP_ADDRESS:-smtp.localhost.com}
spring.mail.port=${SMTP_PORT:-587}
spring.mail.properties.debug=true
spring.mail.properties.mail.smtp.auth=${SMTP_AUTH:-true}
spring.mail.properties.mail.smtp.ssl.enable=${SMTP_SSL:-false}
spring.mail.properties.mail.smtp.starttls.enable=${SMTP_STARTTLS:-true}
spring.mail.properties.mail.smtp.starttls.required=${SMTP_STARTTLS_REQURED:-true}

spring.mail.username=${SMTP_USER:-userName}
spring.mail.password=${SMTP_PASS:-passWord}
spring.mail.properties.mail.smtp.auth=${SMTP_AUTH:-true}
spring.mail.properties.mail.smtp.starttls.enable=${SMTP_STARTTLS:-true}

#echo 'lab-cherry-nw-project-secret-key' | base64
lab.cherry.nw.jwtSecret= bGFiLWNoZXJyeS1udy1wcm9qZWN0LXNlY3JldC1rZXkK
Expand Down
25 changes: 13 additions & 12 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,17 @@ services:
MAX_UPLOAD_SIZE: 3096MB
#SPRING_PROFILES_ACTIVE: prod
JAVA_OPTS: "-Xms256m -Xmx512m -XX:+UseG1GC"
SMTP_ADDRESS: nw-smtp
SMTP_PORT: 1025
SMTP_USER: test@test.com
SMTP_PASS: test@test.com
SMTP_AUTH: false
SMTP_STARTTLS: false
ports:
- "8081:8888"
depends_on:
- nw-db
- nw-redis
- nw-smtp
volumes:
- ./nw_data:/data

Expand All @@ -44,14 +50,9 @@ services:
- './mongodb_data:/bitnami'
- '/etc/localtime:/etc/localtime:ro'


nw-redis:
image: 'redis:latest'
container_name: nw-redis
restart: unless-stopped
entrypoint: redis-server --appendonly yes --maxmemory 4g --maxmemory-policy allkeys-lru
security_opt:
- no-new-privileges:true
volumes:
- './redis_data:/data'
- '/etc/localtime:/etc/localtime:ro'
nw-smtp:
image: jcalonso/mailhog
container_name: 'nw-smtp'
ports:
- "1025:1025" # smtp
- "8025:8025" # web-ui
16 changes: 6 additions & 10 deletions docker-compose/.env
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,13 @@ DATABASE_USERID=admin
DATABASE_USERPASS=admin
#SPRING_PROFILES_ACTIVE=prod
MAX_UPLOAD_SIZE=3096MB
REDIS_HOST=nw-redis
REDIS_PORT=8083
JAVA_OPTS="-Xms256m -Xmx512m -XX:+UseG1GC"
SMTP_ADDRESS=nw-smtp
SMTP_PORT=1025
SMTP_AUTH=false
SMTP_SSL=false
SMTP_STARTTLS=flse
SMTP_STARTTLS_REQURED=false
SMTP_USER=null
SMTP_PASS=null
SMTP_ADDRESS=smtp.naver.com
SMTP_PORT=465
SMTP_USER=yourId@naver.com
SMTP_PASS=yourPass@naver.com
SMTP_AUTH=true
SMTP_STARTTLS=true

# nw-db
MONGO_INITDB_DATABASE=nw
Expand Down
22 changes: 1 addition & 21 deletions docker-compose/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ services:
- "8081:8888"
depends_on:
- nw-db
- nw-redis
- nw-smtp

nw-db:
image: 'mongo:latest'
Expand All @@ -28,22 +26,4 @@ services:
env_file:
- ./.env
ports:
- '8082:27017'

nw-redis:
image: 'redis:latest'
container_name: nw-redis
restart: unless-stopped
entrypoint: redis-server --appendonly yes --maxmemory 4g --maxmemory-policy allkeys-lru
security_opt:
- no-new-privileges:true
volumes:
- './redis_data:/data'
- '/etc/localtime:/etc/localtime:ro'

mailhog:
image: jcalonso/mailhog
container_name: 'mailhog'
ports:
- "1025:1025" # smtp
- "8025:8025" # web-ui
- '8082:27017'
1 change: 0 additions & 1 deletion nw/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ dependencies {
implementation 'org.springframework:spring-context-support:6.0.7'
implementation 'jakarta.mail:jakarta.mail-api:2.1.2'
implementation 'org.springframework.boot:spring-boot-starter-mail:3.0.2'
implementation 'org.springframework.boot:spring-boot-starter-data-redis:3.0.2'
implementation 'io.lettuce:lettuce-core'
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
implementation 'com.google.code.gson:gson:2.8.6'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
"/swagger-resources/**",
"/swagger-ui/**",
"/swagger-ui.html",
"/api/v1/mail/**"
"/api/auth/confirm/**"
)
.permitAll()
.requestMatchers("/api/v1/**").hasAnyRole("ADMIN", "USER") // spring boot 에서 ROLE_ 은 자동으로 붙음
Expand Down
32 changes: 17 additions & 15 deletions nw/src/main/java/lab/cherry/nw/configuration/email/EmailConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,34 @@
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;


//@ConfigurationProperties(prefix = "mail")
@Configuration
@PropertySource("classpath:application.properties")
public class EmailConfig {
@Value("${spring.mail.username}")
private String id;
@Value("${spring.mail.password}")
private String password;

@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.port}")
private int port;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;

@Value("${spring.mail.properties.debug:false}")
private String debug;
@Value("${spring.mail.properties.mail.smtp.auth}")
private String auth;
@Value("${spring.mail.properties.mail.smtp.starttls.enable}")
private String starttls;

@Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

javaMailSender.setHost(host); // smtp 서버 주소
javaMailSender.setUsername(id); // 설정(발신) 메일 아이디
javaMailSender.setPort(port); //smtp 서버 포트
javaMailSender.setUsername(username); // 설정(발신) 메일 아이디
javaMailSender.setPassword(password); // 설정(발신) 메일 패스워드
javaMailSender.setPort(port); //smtp port
javaMailSender.setJavaMailProperties(getMailProperties()); // 메일 인증서버 정보 가져온다.
javaMailSender.setDefaultEncoding("UTF-8");
return javaMailSender;
Expand All @@ -38,13 +44,9 @@ public JavaMailSender javaMailService() {
private Properties getMailProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp"); // 프로토콜 설정
properties.setProperty("mail.smtp.auth", "true"); // smtp 인증
properties.setProperty("mail.smtp.starttls.enable", "true"); // smtp starttls 사용
properties.setProperty("mail.debug", "true"); // 디버그 사용
// properties.setProperty("mail.smtp.ssl.trust","smtp.mailplug.co.kr"); // ssl 인증 서버 주소
properties.setProperty("mail.smtp.ssl.trust","smtp.naver.com"); // ssl 인증 서버 주소

properties.setProperty("mail.smtp.ssl.enable","false"); // ssl 사용
properties.setProperty("mail.smtp.auth", auth); // smtp 인증
properties.setProperty("mail.smtp.starttls.enable", starttls); // smtp starttls 사용
properties.setProperty("mail.debug", debug); // 디버그 사용
return properties;
}
}
31 changes: 24 additions & 7 deletions nw/src/main/java/lab/cherry/nw/controller/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ public class AuthController {
})
@Operation(summary = "회원가입", description = "사용자를 추가합니다.")
public ResponseEntity<?> register(@Valid @RequestBody UserEntity.UserRegisterDto userRegisterDto) {

AccessToken accessToken = authService.register(userRegisterDto);
return new ResponseEntity<>(accessToken, new HttpHeaders(), HttpStatus.OK);
ResultResponse result = ResultResponse.of(SuccessCode.REGISTER_SUCCESS, authService.register(userRegisterDto));
return new ResponseEntity<>(result, new HttpHeaders(), HttpStatus.OK);
}

/**
Expand Down Expand Up @@ -114,13 +114,11 @@ public ResponseEntity<?> existUserId(@PathVariable("userid") String userid) {

authService.checkExistsWithUserId(userid);

final ResultResponse response = ResultResponse.of(SuccessCode.OK);
final ResultResponse response = ResultResponse.of(SuccessCode.USERID_CHECK_OK);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}



@GetMapping("myinfo")
@GetMapping("/myinfo")
@Operation(summary = "사용자 정보 확인", description = "사용자 정보를 확인합니다.")
public ResponseEntity<?> myInfo() {
log.info("[AuthController] myInfo...!");
Expand All @@ -129,4 +127,23 @@ public ResponseEntity<?> myInfo() {
return new ResponseEntity<>(authService.myInfo(), new HttpHeaders(), HttpStatus.OK);
}

@GetMapping("/confirm")
@Operation(summary = "이메일 인증", description = "이메일 인증을 진행합니다.")
public ResponseEntity<?> confirmEmail(@RequestParam(required = true) String email, @RequestParam(required = true) String token) {
log.info("[AuthController] confirmEmail...!");

authService.confirmEmail(email, token);
final ResultResponse response = ResultResponse.of(SuccessCode.EMAIL_CHECK_OK);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}

@GetMapping("/confirm/{userSeq}")
@Operation(summary = "이메일 재인증", description = "이메일 재인증 메일을 발송합니다.")
public ResponseEntity<?> reConfirmEmail(@PathVariable("userSeq") String userSeq) {
log.info("[AuthController] reConfirmEmail...!");

authService.reConfirmEmail(userSeq);
final ResultResponse response = ResultResponse.of(SuccessCode.EMAIL_RESEND_OK);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}
}
53 changes: 28 additions & 25 deletions nw/src/main/java/lab/cherry/nw/controller/EmailController.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@
package lab.cherry.nw.controller;
// package lab.cherry.nw.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lab.cherry.nw.service.EmailService;
import lombok.RequiredArgsConstructor;
// import org.springframework.web.bind.annotation.PostMapping;
// import org.springframework.web.bind.annotation.RequestMapping;
// import org.springframework.web.bind.annotation.RequestParam;
// import org.springframework.web.bind.annotation.RestController;
// import io.swagger.v3.oas.annotations.Operation;
// import io.swagger.v3.oas.annotations.tags.Tag;
// import lab.cherry.nw.service.EmailService;
// import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/user")
public class EmailController{
// @RestController
// @RequiredArgsConstructor
// @RequestMapping("/api/v1/user")
// @Tag(name = "Authenticate", description = "Authenticate API Document")
// public class EmailController{

private final EmailService emailService;
// private final EmailService emailService;

// @PostMapping("/mail/send")
// @Operation(summary = "인증코드 발송", description = "인증코드를 발송합니다.")
// public String emailSend(@RequestParam String email) throws Exception {

// String confirm = emailService.sendSimpleMessage(email);

@PostMapping("/mail/send")
public String emailSend(@RequestParam String email) throws Exception {
// return confirm;
// }

String confirm = emailService.sendSimpleMessage(email);
// @PostMapping("/mail/check")
// @Operation(summary = "인증코드 확인", description = "인증코드를 확인합니다.")
// public Boolean emailAuth(@RequestParam String email, String code) {

return confirm;
}
// Boolean check = emailService.emailCheck(email,code);
// return check;
// }

@PostMapping("/mail/check")
public Boolean emailAuth(@RequestParam String email, String code) {

Boolean check = emailService.emailCheck(email,code);
return check;
}

}
// }

10 changes: 10 additions & 0 deletions nw/src/main/java/lab/cherry/nw/error/ResultResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,15 @@ private ResultResponse(final SuccessCode code) {

private ResultResponse(final SuccessCode code, final Object data) {
this.status = code.getStatus();
this.message = code.getMessage();
this.data = data;
}

private ResultResponse(final SuccessCode code, String message) {
this.status = code.getStatus();
this.message = message;
}

public static ResultResponse of(final SuccessCode code) {
return new ResultResponse(code);
}
Expand All @@ -40,5 +46,9 @@ public static ResultResponse of(final SuccessCode code, final Object data) {
return new ResultResponse(code, data);
}

public static ResultResponse of(final SuccessCode code, final String message) {
return new ResultResponse(code, message);
}

}

9 changes: 6 additions & 3 deletions nw/src/main/java/lab/cherry/nw/error/enums/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ public enum ErrorCode {
NOT_FOUND(404, "찾을 수 없습니다."),
FORBIDDEN(403, "접근 권한이 없어 거부되었습니다."),
ACCESS_DENIED_EXCEPTION(401, "인증 정보가 유효하지 않습니다."),
EXPIRED_EXCEPTION(401, "기간이 만료된 링크입니다."),
USER_DUPLICATE(409, "중복된 사용자가 있습니다."),
USER_NOTFOUND(409, "사용자를 찾을 수 없습니다."),
EMAIL_AUTH_ERROR(409, "이메일 인증이 진행 중이 아니거나, 이메일 코드가 유효하지 않습니다."),
REQUIRE_EMAIL_VERIFIED(409, "이메일 인증을 진행해주세요."),
DUPLICATE(409, "중복된 데이터가 있습니다."),
NO_BODY(400, "파라미터 값이 입력되지 않았습니다."),
URL_NOTFOUND(400, "Minio URL을 다시 확인해주세요."),
FILE_UPLOAD_FAILED(400, "파일 업로드에 실패했습니다."),
FOLDER_CREATE_FAILED(400, "uploadPath를 찾을 수 없습니다.");
FILE_UPLOAD_FAILED(400, "파일 업로드에 실패했습니다.");

private final int status;
private final String message;
Expand Down
6 changes: 5 additions & 1 deletion nw/src/main/java/lab/cherry/nw/error/enums/SuccessCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
public enum SuccessCode {

// Common
OK(200, "Success");
OK(200, "Success"),
REGISTER_SUCCESS(200, "회원가입 완료"),
USERID_CHECK_OK(200, "사용 가능합니다."),
EMAIL_CHECK_OK(200, "이메일 인증 완료"),
EMAIL_RESEND_OK(200, "이메일 인증 메일 재발송 완료");

private final int status;
private final String message;
Expand Down
Loading

0 comments on commit a542056

Please sign in to comment.