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

[BE] 회원가입 기능을 구현한다. #774

Merged
merged 20 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
f898fbb
feat: PasswordEncoder 구현
tkdgur0906 Oct 7, 2024
633fa50
test: e2e 테스트 헤더 로직 통일
tkdgur0906 Oct 7, 2024
06c633c
feat: User에 Password 필드 추가 및 형식 검증
tkdgur0906 Oct 7, 2024
6e5fda6
feat: password 컬럼 sql 설정에 추가
tkdgur0906 Oct 9, 2024
fe6ab1c
feat: email 클래스 생성하여 역할 분리
tkdgur0906 Oct 9, 2024
47bc872
feat: 회원가입 기능 구현
tkdgur0906 Oct 9, 2024
8380e95
feat: User의 email, loginType 유니크 제약조건 추가
tkdgur0906 Oct 10, 2024
1493ad1
feat: 동일한 이메일로 회원가입 하지 못하도록 구현
tkdgur0906 Oct 10, 2024
8e08cb3
feat: salt 랜덤으로 생성하도록 변경
tkdgur0906 Oct 10, 2024
28135cf
refactor: 회원가입 엔드포인트 변경
tkdgur0906 Oct 10, 2024
b00c448
style: 이메일, 비밀번호 정책 주석 추가
tkdgur0906 Oct 10, 2024
935ee5b
feat: data.sql 비밀번호 암호화하여 삽입
tkdgur0906 Oct 10, 2024
bc0484b
test: 중복 테스트 삭제
tkdgur0906 Oct 10, 2024
d900f0f
refactor: Email, Password 검증 메서드명 명확히 수정
tkdgur0906 Oct 10, 2024
233ed59
feat: PasswordEncoder 커스텀 예외 처리 적용
tkdgur0906 Oct 10, 2024
fc5ff92
Merge remote-tracking branch 'origin/dev-be' into feat/729-register
tkdgur0906 Oct 10, 2024
4a412db
refactor: 미사용 db 메서드 제거
tkdgur0906 Oct 11, 2024
e09660c
refactor: PasswordEncoder encode시 외부에서 salt 주입받도록 변경
tkdgur0906 Oct 11, 2024
4f10903
feat: 기본 salt로 encode하는 메서드 추가
tkdgur0906 Oct 11, 2024
9b29556
refactor: PasswordEncoder 정적 클래스로 변경
tkdgur0906 Oct 11, 2024
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 @@ -4,31 +4,35 @@
import com.bang_ggood.auth.controller.cookie.CookieProvider;
import com.bang_ggood.auth.controller.cookie.CookieResolver;
import com.bang_ggood.auth.dto.request.OauthLoginRequest;
import com.bang_ggood.auth.dto.request.RegisterRequestV1;
import com.bang_ggood.auth.dto.response.AuthTokenResponse;
import com.bang_ggood.auth.dto.response.RefreshTokenCheckResponse;
import com.bang_ggood.auth.service.AuthService;
import com.bang_ggood.user.domain.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;

@RequiredArgsConstructor
@RestController
public class AuthController {

private final AuthService authService;
private final CookieProvider cookieProvider;
private final CookieResolver cookieResolver;

public AuthController(AuthService authService, CookieProvider cookieProvider, CookieResolver cookieResolver) {
this.authService = authService;
this.cookieProvider = cookieProvider;
this.cookieResolver = cookieResolver;
@PostMapping("/v1/local-auth/register")
public ResponseEntity<Void> register(@Valid @RequestBody RegisterRequestV1 request) {
Long userId = authService.register(request);
return ResponseEntity.created(URI.create("/v1/local-auth/register/" + userId)).build();
}

@PostMapping("/oauth/login")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.bang_ggood.auth.dto.request;

import com.bang_ggood.user.domain.LoginType;
import com.bang_ggood.user.domain.User;
import com.bang_ggood.user.domain.UserType;
import jakarta.validation.constraints.NotBlank;

public record RegisterRequestV1(@NotBlank(message = "이름이 존재하지 않습니다.") String name,
@NotBlank(message = "이메일이 존재하지 않습니다.") String email,
@NotBlank(message = "비밀번호가 존재하지 않습니다.") String password) {

public User toUserEntity() {
return new User(name(), email(), password(), UserType.USER, LoginType.LOCAL);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bang_ggood.auth.service;

import com.bang_ggood.auth.dto.request.OauthLoginRequest;
import com.bang_ggood.auth.dto.request.RegisterRequestV1;
import com.bang_ggood.auth.dto.response.AuthTokenResponse;
import com.bang_ggood.auth.dto.response.OauthInfoApiResponse;
import com.bang_ggood.auth.service.jwt.JwtTokenProvider;
Expand All @@ -9,12 +10,15 @@
import com.bang_ggood.global.DefaultChecklistService;
import com.bang_ggood.global.exception.BangggoodException;
import com.bang_ggood.global.exception.ExceptionCode;
import com.bang_ggood.user.domain.Email;
import com.bang_ggood.user.domain.LoginType;
import com.bang_ggood.user.domain.User;
import com.bang_ggood.user.domain.UserType;
import com.bang_ggood.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
Expand All @@ -32,11 +36,20 @@ public class AuthService {
private final DefaultChecklistService defaultChecklistService;
private final UserRepository userRepository; // TODO 리팩토링

@Transactional
public Long register(RegisterRequestV1 request) {
try {
return userRepository.save(request.toUserEntity()).getId();
} catch (DataIntegrityViolationException e) {
throw new BangggoodException(ExceptionCode.USER_EMAIL_ALREADY_USED);
}
}

@Transactional
public AuthTokenResponse login(OauthLoginRequest request) {
OauthInfoApiResponse oauthInfoApiResponse = oauthClient.requestOauthInfo(request);

User user = userRepository.findByEmail(oauthInfoApiResponse.kakao_account().email())
User user = userRepository.findByEmail(new Email(oauthInfoApiResponse.kakao_account().email()))
.orElseGet(() -> signUp(oauthInfoApiResponse));

String accessToken = jwtTokenProvider.createAccessToken(user);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.bang_ggood.auth.service;

import com.bang_ggood.global.exception.BangggoodException;
import com.bang_ggood.global.exception.ExceptionCode;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;

public class PasswordEncoder {

private static final String DELIMITER = ":";

public static String encodeWithGeneralSalt(String password) {
return encode(password, getSalt());
}

public static String encode(String password, byte[] salt) {
try {
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 512);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
byte[] hash = factory.generateSecret(spec).getEncoded();
String encodedPassword = Base64.getEncoder().encodeToString(hash);
String encodedSalt = Base64.getEncoder().encodeToString(salt);
return encodedPassword + DELIMITER + encodedSalt;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new BangggoodException(ExceptionCode.PASSWORD_HASHING_ERROR);
}
}

public static byte[] getSalt() {
SecureRandom secureRandom = new SecureRandom();
byte[] salt = new byte[64];
secureRandom.nextBytes(salt);
return salt;
}

private PasswordEncoder() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public void createGuestUser() {
List<User> foundGuestUser = userService.readUser(UserType.GUEST);

if (foundGuestUser.isEmpty()) {
User guestUser = new User("방끗", "bang-ggood@gmail.com", UserType.GUEST, LoginType.LOCAL);
User guestUser = new User("방끗", "bang-ggood1@gmail.com", UserType.GUEST, LoginType.LOCAL);
userService.createUser(guestUser);
defaultChecklistService.createDefaultChecklistAndQuestions(guestUser);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,17 @@ public enum ExceptionCode {

// User
USER_NOT_FOUND(HttpStatus.UNAUTHORIZED, "유저가 존재하지 않습니다."),
USER_EMAIL_ALREADY_USED(HttpStatus.CONFLICT, "이미 해당 이메일을 사용하는 유저가 존재합니다."),
GUEST_USER_NOT_FOUND(HttpStatus.INTERNAL_SERVER_ERROR, "게스트 유저가 존재하지 않습니다."),
GUEST_USER_UNEXPECTED_EXIST(HttpStatus.INTERNAL_SERVER_ERROR, "예상치 못한 게스트 유저가 존재합니다. 데이터베이스를 확인해주세요."),

//Email
EMAIL_INVALID_FORMAT(HttpStatus.BAD_REQUEST, "유효하지 않은 이메일 형식입니다."),

//Password
PASSWORD_INVALID_FORMAT(HttpStatus.BAD_REQUEST, "유효하지 않은 비밀번호 형식입니다."),
PASSWORD_HASHING_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "비밀번호 해싱 중 오류가 발생했습니다."),

// Answer
ANSWER_INVALID(HttpStatus.BAD_REQUEST, "점수가 유효하지 않습니다."),

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.bang_ggood.user.domain;

import com.bang_ggood.global.exception.BangggoodException;
import com.bang_ggood.global.exception.ExceptionCode;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Objects;
import java.util.regex.Pattern;

import static lombok.AccessLevel.PROTECTED;

@Embeddable
@Getter
@NoArgsConstructor(access = PROTECTED)
public class Email {

//이메일은 영문 대소문자, 숫자, 점, 하이픈, 언더스코어, 플러스 기호를 포함할 수 있으며,
// "@" 기호 뒤에 도메인 이름이 필요하고,
// 마지막에는 최소 2글자의 영문자로 이루어진 최상위 도메인이 포함되어야 한다..
private static final Pattern EMAIL_PATTERN =
Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
Comment on lines +22 to +23
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

주석 사용을 지양하긴 하지만, 빠르게 이해하기 쉽게 주석으로 간단히 설명 적어주면 좋을 것 같아요~


@Column(name = "email")
private String value;

public Email(String value) {
validateEmailPattern(value);
this.value = value;
}

public void validateEmailPattern(String email) {
if(!EMAIL_PATTERN.matcher(email).matches()) {
throw new BangggoodException(ExceptionCode.EMAIL_INVALID_FORMAT);
}
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Email email = (Email) o;
return Objects.equals(value, email.value);
}

@Override
public int hashCode() {
return Objects.hashCode(value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.bang_ggood.user.domain;

import com.bang_ggood.auth.service.PasswordEncoder;
import com.bang_ggood.global.exception.BangggoodException;
import com.bang_ggood.global.exception.ExceptionCode;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Objects;
import java.util.regex.Pattern;

import static lombok.AccessLevel.PROTECTED;

@Getter
@Embeddable
@NoArgsConstructor(access = PROTECTED)
public class Password {

//비밀번호는 최소 6자 이상이어야 하며, 영어 문자와 숫자를 각각 1개 이상 포함해야 한다.
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용한 PASSWORD 패턴 전략도 본문에 적어 주시면 좋을 거서 같아요!


@Column(name = "password")
private String value;

public Password(String value) {
validatePasswordPattern(value);
this.value = PasswordEncoder.encodeWithGeneralSalt(value);
}

public void validatePasswordPattern(String password) {
if (!PASSWORD_PATTERN.matcher(password).matches()) {
throw new BangggoodException(ExceptionCode.PASSWORD_INVALID_FORMAT);
}
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Password password1 = (Password) o;
return Objects.equals(value, password1.value);
}

@Override
public int hashCode() {
return Objects.hashCode(value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.bang_ggood.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
Expand All @@ -28,7 +29,11 @@ public class User extends BaseEntity {
private String name;

@Column(nullable = false)
private String email;
@Embedded
private Email email;

@Embedded
private Password password;

@Column(nullable = false)
@Enumerated(EnumType.STRING)
Expand All @@ -40,15 +45,23 @@ public class User extends BaseEntity {

public User(String name, String email, UserType userType, LoginType loginType) {
this.name = name;
this.email = email;
this.email = new Email(email);
this.userType = userType;
this.loginType = loginType;
}

public User(String name, String email, String password, UserType userType, LoginType loginType) {
this.name = name;
this.email = new Email(email);
this.password = new Password(password);
this.userType = userType;
this.loginType = loginType;
}

public User(Long id, String name, String email) { // TODO 테스트용
this.id = id;
this.name = name;
this.email = email;
this.email = new Email(email);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
public record UserResponse(Long userId, String userName, String userEmail, LocalDateTime createdAt) {
public static UserResponse from(User user) {
return new UserResponse(
user.getId(), user.getName(), user.getEmail(), user.getCreatedAt()
user.getId(), user.getName(), user.getEmail().getValue(), user.getCreatedAt()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.bang_ggood.global.exception.BangggoodException;
import com.bang_ggood.global.exception.ExceptionCode;
import com.bang_ggood.user.domain.Email;
import com.bang_ggood.user.domain.LoginType;
import com.bang_ggood.user.domain.User;
import com.bang_ggood.user.domain.UserType;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -22,7 +24,7 @@ default User getUserById(Long id) {
List<User> findUserByUserType(@Param("userType") UserType userType);

@Query("SELECT u FROM User u WHERE u.email = :email and u.deleted = false ")
Optional<User> findByEmail(@Param("email") String email);
Optional<User> findByEmail(@Param("email") Email email);

@Transactional
@Modifying(flushAutomatically = true, clearAutomatically = true)
Expand Down
6 changes: 4 additions & 2 deletions backend/bang-ggood/src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
INSERT INTO users(name, email, user_type, login_type, created_at, modified_at, deleted)
VALUES ('방방이', '[email protected]', 'USER', 'LOCAL', '2024-07-22 07:56:42', '2024-07-22 07:56:42', false);
-- 비밀번호 : password1234
INSERT INTO users(name, email, password, user_type, login_type, created_at, modified_at, deleted)
VALUES ('방방이', '[email protected]', 'xDNYKEJqE/36U0Dt3nXRMFPNEMEgjCYM7R/A4B29baOsv4KYQ9MGgcO3HUa11sNKCFb9ZXyYBqJqxNglvBzFvg==:7yejAszEpxBb7AyZNKvAqpmMEJiKFXIa8JKwAx3n4loB2DRcAC2pfwkgo/dzKzRvBX4RbrATWaIlPYrgAhbHZQ==',
'USER', 'LOCAL', '2024-07-22 07:56:42', '2024-07-22 07:56:42', false);

INSERT INTO custom_checklist_question(user_id, question, created_at, modified_at, deleted)
VALUES (1, 'ROOM_CONDITION_1', '2024-07-22 07:56:42', '2024-07-22 07:56:42', false),
Expand Down
8 changes: 5 additions & 3 deletions backend/bang-ggood/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,13 @@ CREATE TABLE users
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255) NOT NULL,
user_type VARCHAR(255) NOT NULL,
login_type VARCHAR(255) NOT NULL,
password VARCHAR(255),
user_type VARCHAR(255) NOT NULL,
login_type VARCHAR(255) NOT NULL,
created_at TIMESTAMP(6),
modified_at TIMESTAMP(6),
deleted BOOLEAN
deleted BOOLEAN,
CONSTRAINT unique_email_login_type UNIQUE (email, login_type)
Comment on lines +36 to +42
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prod 환경에 배포할 때 데이터 정합성 일치하도록 주의해주세요!

);

CREATE TABLE checklist
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class ArgumentResolverTest extends AcceptanceTest {
@Test
void resolveUserPrincipalArgument_returnGuestUser() {
// given & when
userRepository.save(UserFixture.GUEST_USER());
userRepository.save(UserFixture.GUEST_USER1());

User user = RestAssured.given().log().all()
.contentType(ContentType.JSON)
Expand Down
Loading
Loading