-
Notifications
You must be signed in to change notification settings - Fork 8
feat: 이메일 인증 구현 #188
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
feat: 이메일 인증 구현 #188
Changes from all commits
468d477
c8b3ae9
9c16473
d70edf7
7d97e03
db7b56a
d5ddc90
1665905
f247820
36575a3
8e800b9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.example.solidconnection.auth.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
|
|
||
| public record EmailSignInRequest( | ||
|
|
||
| @NotBlank(message = "이메일을 입력해주세요.") | ||
| String email, | ||
|
|
||
| @NotBlank(message = "비밀번호를 입력해주세요.") | ||
| String password | ||
| ) { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package com.example.solidconnection.auth.dto; | ||
|
|
||
| import jakarta.validation.constraints.Email; | ||
| import jakarta.validation.constraints.NotBlank; | ||
|
|
||
| public record EmailSignUpTokenRequest( | ||
|
|
||
| @Email(message = "이메일을 입력해주세요.") | ||
| String email, | ||
|
|
||
| @NotBlank(message = "비밀번호를 입력해주세요.") | ||
| String password | ||
|
Comment on lines
+11
to
+12
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 나중에 비밀번호 조건 검증도 추가하면 좋겠네요! |
||
| ) { | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.example.solidconnection.auth.dto; | ||
|
|
||
| public record EmailSignUpTokenResponse( | ||
| String signUpToken | ||
| ) { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package com.example.solidconnection.auth.service; | ||
|
|
||
| import com.example.solidconnection.config.security.JwtProperties; | ||
| import com.example.solidconnection.custom.exception.CustomException; | ||
| import com.example.solidconnection.siteuser.domain.AuthType; | ||
| import com.example.solidconnection.util.JwtUtils; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import static com.example.solidconnection.auth.service.EmailSignUpTokenProvider.AUTH_TYPE_CLAIM_KEY; | ||
| import static com.example.solidconnection.custom.exception.ErrorCode.SIGN_UP_TOKEN_INVALID; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class CommonSignUpTokenProvider { | ||
|
|
||
| private final JwtProperties jwtProperties; | ||
|
|
||
| public AuthType parseAuthType(String signUpToken) { | ||
| try { | ||
| String authTypeStr = JwtUtils.parseClaims(signUpToken, jwtProperties.secret()).get(AUTH_TYPE_CLAIM_KEY, String.class); | ||
| return AuthType.valueOf(authTypeStr); | ||
| } catch (Exception e) { | ||
| throw new CustomException(SIGN_UP_TOKEN_INVALID); | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| package com.example.solidconnection.auth.service; | ||
|
|
||
| import com.example.solidconnection.auth.dto.EmailSignInRequest; | ||
| import com.example.solidconnection.auth.dto.SignInResponse; | ||
| import com.example.solidconnection.custom.exception.CustomException; | ||
| import com.example.solidconnection.siteuser.domain.AuthType; | ||
| import com.example.solidconnection.siteuser.domain.SiteUser; | ||
| import com.example.solidconnection.siteuser.repository.SiteUserRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| import static com.example.solidconnection.custom.exception.ErrorCode.USER_NOT_FOUND; | ||
|
|
||
| /* | ||
| * 보안을 위해 이메일과 비밀번호 중 무엇이 틀렸는지 구체적으로 응답하지 않는다. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 해킹 방지를 위해 해당 계정이 존재하는지 알리지 않는 것도 좋은 것 같네요. 다만 회원가입시에 중복가입이 불가능한 걸 알려주기에 다소 복잡하지만 해커가 계정 존재여부를 체크할 수 있을 것 같습니다. 반대로 이메일이 틀렸는지 비밀번호가 틀렸는지 알려주면 일반 사용자에게는 더 좋은 UX로 다가올 수 있을 것 같습니다.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
이 말씀은 "에러 메세지에서 다르게 응답하면 좋겠다는 말씀이 맞나요?"
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 네 그렇습니다!
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 저는 보안상 에러메시지를 통일하는 게 좋다고 생각합니다! 네이버 카카오 구글은 어떻게 되어있나 보았는데 네이버, 카카오는 응답메시지를 통일해서 주고, 구글의 경우는 이메일을 먼저 입력하는데 존재하는 이메일을 입력해야지만 비밀번호 입력으로 넘어가네요
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이메일 X 비밀번호 X → 이메일과 비밀번호를 확인해주세요 이렇게는 어떤가요?
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 음 저도 이메일 비밀번호 틀린요소에 관계없이 같은 메시지를 받는 것이 익숙하고 이것이 좋은 패턴이라 생각하는데요, 다만 현재 구조에서는 회원가입 부분이 뚫려있기에 해커 입장에서 어짜피 계정 유무를 판별할 수 있다고 판단해서 이런 건의를 드렸습니다. 다만 이후에 회원가입에 이메일 발송 인증이 들어가면 이 부분은 안전하게 되고, 동일한 메시지가 반환되는 것이 좋다고 생각하기에 해당부분은 수정하지 않아도 괜찮을 것 같습니다! |
||
| * */ | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class EmailSignInService { | ||
|
|
||
| private final SignInService signInService; | ||
| private final SiteUserRepository siteUserRepository; | ||
| private final PasswordEncoder passwordEncoder; | ||
|
|
||
| public SignInResponse signIn(EmailSignInRequest signInRequest) { | ||
| Optional<SiteUser> optionalSiteUser = siteUserRepository.findByEmailAndAuthType(signInRequest.email(), AuthType.EMAIL); | ||
| if (optionalSiteUser.isPresent()) { | ||
| SiteUser siteUser = optionalSiteUser.get(); | ||
| validatePassword(signInRequest.password(), siteUser.getPassword()); | ||
| return signInService.signIn(siteUser); | ||
| } | ||
| throw new CustomException(USER_NOT_FOUND, "이메일과 비밀번호를 확인해주세요."); | ||
| } | ||
|
|
||
| private void validatePassword(String rawPassword, String encodedPassword) throws CustomException { | ||
| if (!passwordEncoder.matches(rawPassword, encodedPassword)) { | ||
| throw new CustomException(USER_NOT_FOUND, "이메일과 비밀번호를 확인해주세요."); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package com.example.solidconnection.auth.service; | ||
|
|
||
| import com.example.solidconnection.auth.dto.SignUpRequest; | ||
| import com.example.solidconnection.custom.exception.CustomException; | ||
| import com.example.solidconnection.repositories.CountryRepository; | ||
| import com.example.solidconnection.repositories.InterestedCountyRepository; | ||
| import com.example.solidconnection.repositories.InterestedRegionRepository; | ||
| import com.example.solidconnection.repositories.RegionRepository; | ||
| import com.example.solidconnection.siteuser.domain.AuthType; | ||
| import com.example.solidconnection.siteuser.domain.SiteUser; | ||
| import com.example.solidconnection.siteuser.repository.SiteUserRepository; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import static com.example.solidconnection.custom.exception.ErrorCode.USER_ALREADY_EXISTED; | ||
|
|
||
| @Service | ||
| public class EmailSignUpService extends SignUpService { | ||
|
|
||
| private final EmailSignUpTokenProvider emailSignUpTokenProvider; | ||
|
|
||
| public EmailSignUpService(SignInService signInService, SiteUserRepository siteUserRepository, | ||
| RegionRepository regionRepository, InterestedRegionRepository interestedRegionRepository, | ||
| CountryRepository countryRepository, InterestedCountyRepository interestedCountyRepository, | ||
| EmailSignUpTokenProvider emailSignUpTokenProvider) { | ||
| super(signInService, siteUserRepository, regionRepository, interestedRegionRepository, countryRepository, interestedCountyRepository); | ||
| this.emailSignUpTokenProvider = emailSignUpTokenProvider; | ||
| } | ||
|
|
||
| public void validateUniqueEmail(String email) { | ||
| if (siteUserRepository.existsByEmailAndAuthType(email, AuthType.EMAIL)) { | ||
| throw new CustomException(USER_ALREADY_EXISTED); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| protected void validateSignUpToken(SignUpRequest signUpRequest) { | ||
| emailSignUpTokenProvider.validateSignUpToken(signUpRequest.signUpToken()); | ||
| } | ||
|
|
||
| @Override | ||
| protected void validateUserNotDuplicated(SignUpRequest signUpRequest) { | ||
| String email = emailSignUpTokenProvider.parseEmail(signUpRequest.signUpToken()); | ||
| if (siteUserRepository.existsByEmailAndAuthType(email, AuthType.EMAIL)) { | ||
| throw new CustomException(USER_ALREADY_EXISTED); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| protected SiteUser createSiteUser(SignUpRequest signUpRequest) { | ||
| String email = emailSignUpTokenProvider.parseEmail(signUpRequest.signUpToken()); | ||
| String encodedPassword = emailSignUpTokenProvider.parseEncodedPassword(signUpRequest.signUpToken()); | ||
| return signUpRequest.toEmailSiteUser(email, encodedPassword); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package com.example.solidconnection.auth.service; | ||
|
|
||
| import com.example.solidconnection.auth.domain.TokenType; | ||
| import com.example.solidconnection.auth.dto.EmailSignUpTokenRequest; | ||
| import com.example.solidconnection.config.security.JwtProperties; | ||
| import com.example.solidconnection.custom.exception.CustomException; | ||
| import com.example.solidconnection.siteuser.domain.AuthType; | ||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.SignatureAlgorithm; | ||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.Date; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
|
|
||
| import static com.example.solidconnection.custom.exception.ErrorCode.SIGN_UP_TOKEN_INVALID; | ||
| import static com.example.solidconnection.custom.exception.ErrorCode.SIGN_UP_TOKEN_NOT_ISSUED_BY_SERVER; | ||
| import static com.example.solidconnection.util.JwtUtils.parseClaims; | ||
| import static com.example.solidconnection.util.JwtUtils.parseSubject; | ||
|
|
||
| @Component | ||
| public class EmailSignUpTokenProvider extends TokenProvider { | ||
|
|
||
| static final String PASSWORD_CLAIM_KEY = "password"; | ||
| static final String AUTH_TYPE_CLAIM_KEY = "authType"; | ||
|
|
||
| private final PasswordEncoder passwordEncoder; | ||
|
|
||
| public EmailSignUpTokenProvider(JwtProperties jwtProperties, RedisTemplate<String, String> redisTemplate, | ||
| PasswordEncoder passwordEncoder) { | ||
| super(jwtProperties, redisTemplate); | ||
| this.passwordEncoder = passwordEncoder; | ||
| } | ||
|
|
||
| public String generateAndSaveSignUpToken(EmailSignUpTokenRequest request) { | ||
| String email = request.email(); | ||
| String password = request.password(); | ||
| String encodedPassword = passwordEncoder.encode(password); | ||
| Map<String, Object> emailSignUpClaims = new HashMap<>(Map.of( | ||
| PASSWORD_CLAIM_KEY, encodedPassword, | ||
| AUTH_TYPE_CLAIM_KEY, AuthType.EMAIL | ||
| )); | ||
| Claims claims = Jwts.claims(emailSignUpClaims).setSubject(email); | ||
| Date now = new Date(); | ||
| Date expiredDate = new Date(now.getTime() + TokenType.SIGN_UP.getExpireTime()); | ||
|
|
||
| String signUpToken = Jwts.builder() | ||
| .setClaims(claims) | ||
| .setIssuedAt(now) | ||
| .setExpiration(expiredDate) | ||
| .signWith(SignatureAlgorithm.HS512, jwtProperties.secret()) | ||
| .compact(); | ||
| return saveToken(signUpToken, TokenType.SIGN_UP); | ||
| } | ||
|
|
||
| public void validateSignUpToken(String token) { | ||
| validateFormatAndExpiration(token); | ||
| String email = parseEmail(token); | ||
| validateIssuedByServer(email); | ||
| } | ||
|
|
||
| private void validateFormatAndExpiration(String token) { | ||
| try { | ||
| Claims claims = parseClaims(token, jwtProperties.secret()); | ||
| Objects.requireNonNull(claims.getSubject()); | ||
| String encodedPassword = claims.get(PASSWORD_CLAIM_KEY, String.class); | ||
| Objects.requireNonNull(encodedPassword); | ||
| } catch (Exception e) { | ||
| throw new CustomException(SIGN_UP_TOKEN_INVALID); | ||
| } | ||
| } | ||
|
|
||
| private void validateIssuedByServer(String email) { | ||
| String key = TokenType.SIGN_UP.addPrefix(email); | ||
| if (redisTemplate.opsForValue().get(key) == null) { | ||
| throw new CustomException(SIGN_UP_TOKEN_NOT_ISSUED_BY_SERVER); | ||
| } | ||
| } | ||
|
|
||
| public String parseEmail(String token) { | ||
| return parseSubject(token, jwtProperties.secret()); | ||
| } | ||
|
|
||
| public String parseEncodedPassword(String token) { | ||
| Claims claims = parseClaims(token, jwtProperties.secret()); | ||
| return claims.get(PASSWORD_CLAIM_KEY, String.class); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
현재 구조로는 만약 이미 가입된 유저가 다시 가입을 시도 했을 때, 닉네임/프사/선호지역/등등... 을 모두 선택하고 가입하려는 순간! 이메일 중복 오류가 발생해서 허무하게 될 것 같은데요, 첫 이메일 토큰 발급시에 이메일 중복여부를 체크해서 알려주는 건 어떻게 생각하시나요?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ㅋㅋㅋㅋ 그렇겠네요! 반영했습니다~
8e800b9