Skip to content
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
1 change: 1 addition & 0 deletions src/common/constants/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const ERROR_MESSAGE = {
USER_NOT_FOUND: '사용자를 찾을 수 없습니다.',
EMAIL_REQUIRED: '이메일을 입력해야 합니다.',
EMAIL_ALREADY_EXISTS: '이미 사용 중인 이메일입니다.',
NICKNAME_ALREADY_EXISTS: '이미 사용 중인 닉네임입니다.',
FAILED_TO_FETCH_USERS: '사용자 목록을 조회하지 못했습니다.',
FAILED_TO_FETCH_USER: '사용자를 조회하지 못했습니다.',
FAILED_TO_CREATE_USER: '사용자를 생성하지 못했습니다.',
Expand Down
7 changes: 7 additions & 0 deletions src/repositories/user.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ export class UserRepository {
.first();
}

findByNickname(nickname) {
return this.#users
.where({ nickname })
.select(...this.#fields)
.first();
}

findById(id) {
return this.#users
.where({ id })
Expand Down
94 changes: 94 additions & 0 deletions src/services/auth.service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { DB_ERROR, ERROR_MESSAGE } from '#constants';
import { ConflictException, UnauthorizedException } from '#exceptions';

export class AuthService {
#userRepository;
#passwordProvider;
#tokenProvider;

constructor({ userRepository, passwordProvider, tokenProvider }) {
this.#userRepository = userRepository;
this.#passwordProvider = passwordProvider;
this.#tokenProvider = tokenProvider;
}

//회원가입 비즈니스 로직
async signUp({ email, password, nickname }) {
//이메일 중복 검증
const existingUser = await this.#userRepository.findByEmail(email);
if (existingUser) {
throw new ConflictException(ERROR_MESSAGE.EMAIL_ALREADY_EXISTS);
}

//닉네임 중복 검증
const existNickname = await this.#userRepository.findByNickname(nickname);
if (existNickname) {
throw new ConflictException(ERROR_MESSAGE.NICKNAME_ALREADY_EXISTS);
}

//패스워드 해시 진행 (회원가입이니까)
const hashedPassword = await this.#passwordProvider.hash(password);

//회원 등록
try {
const user = await this.#userRepository.create({
email,
password: hashedPassword,
nickname,
});

//토큰 2개 발급
const tokens = this.#tokenProvider.generateTokens(user);

return { user, tokens };
} catch (error) {
if (error.sqlState === DB_ERROR.UNIQUE_VIOLATION) {
throw new ConflictException(ERROR_MESSAGE.RESOURCE_CONFLICT);
}
throw error;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

//로그인 비즈니스 로직
async logIn({ email, password }) {
//유저가 존재하는지 이메일로 확인
const user = await this.#userRepository.findByEmail(email, {
includePassword: true,
});
if (!user || !user.password) {
throw new UnauthorizedException(ERROR_MESSAGE.INVALID_CREDENTIALS);
}

//패스워드 검증
const isPasswordValid = await this.#passwordProvider.compare(
password,
user.password,
);
if (!isPasswordValid) {
throw new UnauthorizedException(ERROR_MESSAGE.INVALID_CREDENTIALS);
}

//토큰 2개 발급
const tokens = this.#tokenProvider.generateTokens(user);
const { password: _password, ...rest } = user;

return { user: rest, tokens };
}

//새 토큰 발급
async refreshTokens(refreshToken) {
const payload = this.#tokenProvider.verifyRefreshToken(refreshToken);
if (!payload) {
throw new UnauthorizedException(ERROR_MESSAGE.INVALID_TOKEN);
}

const user = await this.#userRepository.findById(payload.userId);
if (!user) {
throw new UnauthorizedException(ERROR_MESSAGE.USER_NOT_FOUND_FROM_TOKEN);
}

const tokens = this.#tokenProvider.generateTokens(user);

return { user, tokens };
}
}
1 change: 1 addition & 0 deletions src/services/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './health-check.service.js';
export * from './auth.service.js';