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

refactor: divide user resource directory #345

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
import { UsersModule } from './presentation/user/users.module';
import { CommonModule } from './common/common.module';
import { AuthModule } from './auth/auth.module';
import { MailModule } from './mail/mail.module';
Expand All @@ -15,7 +15,7 @@ import { TypeOrmConfigService } from './database/typerom-config.service';
import { OpenaiModule } from './openai/openai.module';
import { AppController } from './app.controller';
import { AopModule } from './common/aop/aop.module';
import { InfraModule } from './infra/infra.module';
import { InfraModule } from './infrastructure/infra.module';

@Module({
imports: [
Expand Down
2 changes: 1 addition & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
ApiUnauthorizedResponse,
} from '@nestjs/swagger';
import { ErrorOutput } from '../common/dtos/output.dto';
import { User } from '../users/entities/user.entity';
import { User } from '../domain/user/entities/user.entity';
import { AuthUser } from './auth-user.decorator';
import { AuthService } from './auth.service';
import {
Expand Down
7 changes: 4 additions & 3 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import { JwtStrategy } from './jwt/jwt.strategy';
import { GoogleStrategy } from './passport/google/google.strategy';
import { customJwtService } from './jwt/jwt.service';
import { TWOHOUR } from './jwt/jwt.payload';
import { UsersModule } from '../users/users.module';
import { UsersModule } from '../presentation/user/users.module';
import { OAuthUtil } from './util/oauth.util';
import { ContentsModule } from '../contents/contents.module';
import { OAuthService } from './oauth.service';
import { CategoryModule } from '../categories/category.module';
import { RedisModule } from '../infra/redis/redis.module';
import { RedisModule } from '../infrastructure/redis/redis.module';
import { UserDomainModule } from '../domain/user/user.module';

const accessTokenExpiration = TWOHOUR;
export const refreshTokenExpirationInCache = 60 * 60 * 24 * 365; // 1 year
Expand All @@ -29,7 +30,7 @@ export const verifyEmailExpiration = 60 * 5;
signOptions: { expiresIn: accessTokenExpiration },
}),
}),
UsersModule,
UserDomainModule,
ContentsModule,
CategoryModule,
RedisModule,
Expand Down
6 changes: 3 additions & 3 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm';
import { CONFIG_OPTIONS } from '../common/common.constants';
import { MailService } from '../mail/mail.service';
import { User, UserRole } from '../users/entities/user.entity';
import { User, UserRole } from '../domain/user/entities/user.entity';
import { DataSource, ObjectLiteral, Repository } from 'typeorm';
import { AuthService } from './auth.service';
import { customJwtService } from './jwt/jwt.service';
import { Cache } from 'cache-manager';
import { LoginBodyDto, LogoutBodyDto } from './dtos/login.dto';
import { UsersModule } from '../users/users.module';
import { UserRepository } from '../users/repository/user.repository';
import { UsersModule } from '../presentation/user/users.module';
import { UserRepository } from '../infrastructure/user/repository/user.repository';
import { TWOHOUR } from './jwt/jwt.payload';
import * as dotenv from 'dotenv';

Expand Down
18 changes: 8 additions & 10 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
BadRequestException,
Inject,
Injectable,
NotFoundException,
UnauthorizedException,
Expand All @@ -23,15 +24,15 @@ import { RefreshTokenDto, RefreshTokenOutput } from './dtos/token.dto';
import { ValidateUserDto, ValidateUserOutput } from './dtos/validate-user.dto';
import { ONEYEAR, Payload } from './jwt/jwt.payload';
import { customJwtService } from './jwt/jwt.service';
import { UserRepository } from '../users/repository/user.repository';
import { RedisService } from '../infra/redis/redis.service';
import { UserRepository } from '../domain/user/user.repository';
import { RedisService } from '../infrastructure/redis/redis.service';
import { PASSWORD_CODE_KEY, REFRESH_TOKEN_KEY } from './constants';

@Injectable()
export class AuthService {
constructor(
private readonly jwtService: customJwtService,
private readonly userRepository: UserRepository,
@Inject(UserRepository) private readonly userRepository: UserRepository,
private readonly mailService: MailService,
private readonly redisService: RedisService,
) {}
Expand Down Expand Up @@ -66,7 +67,7 @@ export class AuthService {
userId: number,
{ refresh_token: refreshToken }: LogoutBodyDto,
): Promise<LogoutOutput> {
const user = await this.userRepository.findOneBy({ id: userId });
const user = await this.userRepository.findById(userId);
if (user) {
if (!refreshToken) {
throw new BadRequestException('Refresh token is required');
Expand Down Expand Up @@ -100,7 +101,7 @@ export class AuthService {
} catch (e) {
throw new UnauthorizedException('Invalid refresh token');
}
const user = await this.userRepository.findOneBy({ id: decoded.sub });
const user = await this.userRepository.findById(decoded.sub);
if (!user) {
throw new NotFoundException('User not found');
}
Expand Down Expand Up @@ -140,7 +141,7 @@ export class AuthService {
async sendPasswordResetEmail(
email: string,
): Promise<sendPasswordResetEmailOutput> {
const user = await this.userRepository.findOneBy({ email });
const user = await this.userRepository.findByEmail(email);
if (user) {
if (!user.verified) {
throw new UnauthorizedException('User not verified');
Expand All @@ -167,10 +168,7 @@ export class AuthService {
password,
}: ValidateUserDto): Promise<ValidateUserOutput> {
try {
const user = await this.userRepository.findOne({
where: { email },
select: { id: true, password: true },
});
const user = await this.userRepository.findByEmail(email);
if (!user) {
throw new NotFoundException('User Not Found');
}
Expand Down
2 changes: 1 addition & 1 deletion src/auth/dtos/create-account.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { PickType } from '@nestjs/swagger';
import { CoreOutput } from '../../common/dtos/output.dto';
import { User } from '../../users/entities/user.entity';
import { User } from '../../domain/user/entities/user.entity';

// export class CreateAccountBodyDto extends PickType(User, [
// 'email',
Expand Down
2 changes: 1 addition & 1 deletion src/auth/dtos/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ApiProperty, PickType } from '@nestjs/swagger';
import { IsBoolean, IsOptional, IsString } from 'class-validator';
import { CoreOutput } from '../../common/dtos/output.dto';
import { User } from '../../users/entities/user.entity';
import { User } from '../../domain/user/entities/user.entity';

export class LoginBodyDto extends PickType(User, ['email', 'password']) {
@ApiProperty({
Expand Down
2 changes: 1 addition & 1 deletion src/auth/dtos/validate-user.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApiProperty, PickType } from '@nestjs/swagger';
import { CoreOutput } from '../../common/dtos/output.dto';
import { User } from '../../users/entities/user.entity';
import { User } from '../../domain/user/entities/user.entity';

export class ValidateUserDto extends PickType(User, ['email', 'password']) {}

Expand Down
10 changes: 6 additions & 4 deletions src/auth/jwt/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Payload } from './jwt.payload';
import { UserRepository } from '../../users/repository/user.repository';
import { UserRepository } from '../../domain/user/user.repository';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly userRepository: UserRepository) {
constructor(
@Inject(UserRepository) private readonly userRepository: UserRepository,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
Expand All @@ -15,7 +17,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}

async validate(payload: Payload) {
const user = await this.userRepository.findOneBy({ id: payload.sub });
const user = await this.userRepository.findById(payload.sub);
if (user) {
return user;
} else {
Expand Down
25 changes: 16 additions & 9 deletions src/auth/oauth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
UnauthorizedException,
BadRequestException,
InternalServerErrorException,
Inject,
NotFoundException,
} from '@nestjs/common';
import axios from 'axios';
import { refreshTokenExpirationInCache } from './auth.module';
Expand All @@ -13,20 +15,21 @@ import { Payload } from './jwt/jwt.payload';
import { customJwtService } from './jwt/jwt.service';
import { OAuthUtil } from './util/oauth.util';
import { CategoryRepository } from '../categories/category.repository';
import { User } from '../users/entities/user.entity';
import { UserRepository } from '../users/repository/user.repository';
import { User } from '../domain/user/entities/user.entity';

import * as CryptoJS from 'crypto-js';
import { CookieOptions } from 'express';
import { RedisService } from '../infra/redis/redis.service';
import { RedisService } from '../infrastructure/redis/redis.service';
import { REFRESH_TOKEN_KEY } from './constants';
import { KakaoLoginRequest } from './dtos/request/kakao-login.request.dto';
import { KakaoLoginDto } from './dtos/kakao-login.dto';
import { UserRepository } from '../domain/user/user.repository';

@Injectable()
export class OAuthService {
constructor(
private readonly jwtService: customJwtService,
private readonly userRepository: UserRepository,
@Inject(UserRepository) private readonly userRepository: UserRepository,
private readonly categoryRepository: CategoryRepository,
private readonly oauthUtil: OAuthUtil,
private readonly redisService: RedisService,
Expand All @@ -35,7 +38,11 @@ export class OAuthService {
// OAuth Login
async oauthLogin(email: string): Promise<LoginOutput> {
try {
const user: User = await this.userRepository.findOneByOrFail({ email });
const user = await this.userRepository.findByEmail(email);
if (!user) {
throw new NotFoundException('User not found');
}

if (user) {
const payload: Payload = this.jwtService.createPayload(
user.email,
Expand Down Expand Up @@ -97,7 +104,7 @@ export class OAuthService {
throw new BadRequestException('Please Agree to share your email');
}

let user = await this.userRepository.findOneByEmail(email);
let user = await this.userRepository.findByEmail(email);

// 회원가입인 경우 기본 카테고리 생성 작업 진행
if (!user) {
Expand Down Expand Up @@ -131,7 +138,7 @@ export class OAuthService {
throw new BadRequestException('Please Agree to share your email');
}

let user = await this.userRepository.findOneByEmail(email);
let user = await this.userRepository.findByEmail(email);

// 회원가입인 경우 기본 카테고리 생성 작업 진행
if (!user) {
Expand Down Expand Up @@ -161,7 +168,7 @@ export class OAuthService {
picture,
}: googleUserInfo): Promise<LoginOutput> {
try {
let user = await this.userRepository.findOneByEmail(email);
let user = await this.userRepository.findByEmail(email);

// 회원가입인 경우 기본 카테고리 생성 작업 진행
if (!user) {
Expand Down Expand Up @@ -229,7 +236,7 @@ export class OAuthService {

const { sub: id, email } = this.jwtService.decode(data.id_token);

let user = await this.userRepository.findOneByEmail(email);
let user = await this.userRepository.findByEmail(email);

if (!user) {
user = new User();
Expand Down
2 changes: 1 addition & 1 deletion src/auth/role.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SetMetadata } from '@nestjs/common';
import { UserRole } from '../users/entities/user.entity';
import { UserRole } from '../domain/user/entities/user.entity';

export type AllowedRoles = keyof typeof UserRole | 'Any';

Expand Down
2 changes: 1 addition & 1 deletion src/auth/role.guard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AllowedRoles } from './role.decorator';
import { User } from '../users/entities/user.entity';
import { User } from '../domain/user/entities/user.entity';

@Injectable()
export class RoleGuard implements CanActivate {
Expand Down
2 changes: 1 addition & 1 deletion src/categories/category.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
LoadPersonalCategoriesOutput,
LoadFrequentCategoriesOutput,
} from './dtos/load-personal-categories.dto';
import { User } from '../users/entities/user.entity';
import { User } from '../domain/user/entities/user.entity';
import { CategoryService } from './category.service';

@Controller('categories')
Expand Down
2 changes: 1 addition & 1 deletion src/categories/category.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { Content } from '../contents/entities/content.entity';
import { CoreEntity } from '../common/entities/core.entity';
import { Collection } from '../collections/entities/collection.entity';
import { User } from '../users/entities/user.entity';
import { User } from '../domain/user/entities/user.entity';

export enum IconName {
None = 'None',
Expand Down
5 changes: 3 additions & 2 deletions src/categories/category.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ import { Module } from '@nestjs/common';
import { ContentsModule } from '../contents/contents.module';
import { CategoryService } from './category.service';
import { OpenaiModule } from '../openai/openai.module';
import { UsersModule } from '../users/users.module';
import { UsersModule } from '../presentation/user/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Category } from './category.entity';
import { CategoryController } from './category.controller';
import { ContentRepository } from '../contents/repository/content.repository';
import { CategoryRepository } from './category.repository';
import { UserDomainModule } from '../domain/user/user.module';

@Module({
imports: [
TypeOrmModule.forFeature([Category]),
ContentsModule,
OpenaiModule,
UsersModule,
UserDomainModule,
],
controllers: [CategoryController],
providers: [CategoryService, ContentRepository, CategoryRepository],
Expand Down
2 changes: 1 addition & 1 deletion src/categories/category.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { Category } from './category.entity';
import { User } from '../users/entities/user.entity';
import { User } from '../domain/user/entities/user.entity';
import { generateSlug } from './utils/category.util';

@Injectable()
Expand Down
16 changes: 11 additions & 5 deletions src/categories/category.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
Injectable,
NotFoundException,
ConflictException,
Inject,
} from '@nestjs/common';
import { EntityManager } from 'typeorm';
import {
Expand All @@ -25,22 +26,23 @@ import { CategoryRepository } from './category.repository';
import { ContentRepository } from '../contents/repository/content.repository';
import { getLinkContent, getLinkInfo } from '../contents/util/content.util';
import { OpenaiService } from '../openai/openai.service';
import { User } from '../users/entities/user.entity';
import { UserRepository } from '../users/repository/user.repository';
import { User } from '../domain/user/entities/user.entity';

import {
generateCategoriesTree,
generateSlug,
loadLogs,
makeCategoryListWithSaveCount,
} from './utils/category.util';
import { Transactional } from '../common/aop/transactional';
import { UserRepository } from '../domain/user/user.repository';

@Injectable()
export class CategoryService {
constructor(
private readonly contentRepository: ContentRepository,
private readonly categoryRepository: CategoryRepository,
private readonly userRepository: UserRepository,
@Inject(UserRepository) private readonly userRepository: UserRepository,
private readonly openaiService: OpenaiService,
) {}

Expand All @@ -51,7 +53,9 @@ export class CategoryService {
entityManager?: EntityManager,
): Promise<AddCategoryOutput> {
try {
const userInDb = await this.userRepository.findOneWithCategories(user.id);
const userInDb = await this.userRepository.findByIdWithCategories(
user.id,
);

if (!userInDb) {
throw new NotFoundException('User not found');
Expand Down Expand Up @@ -417,7 +421,9 @@ export class CategoryService {
link: string,
): Promise<AutoCategorizeOutput> {
try {
const userInDb = await this.userRepository.findOneWithCategories(user.id);
const userInDb = await this.userRepository.findByIdWithCategories(
user.id,
);
if (!userInDb) {
throw new NotFoundException('User not found');
}
Expand Down
Loading