Skip to content

Commit

Permalink
add user module
Browse files Browse the repository at this point in the history
  • Loading branch information
amrtgaber committed Jun 16, 2024
1 parent e009534 commit 0cbce31
Show file tree
Hide file tree
Showing 18 changed files with 259 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- DropForeignKey
ALTER TABLE "drafts" DROP CONSTRAINT "drafts_ownerId_fkey";

-- AddForeignKey
ALTER TABLE "drafts" ADD CONSTRAINT "drafts_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ model Draft {
desc String?
private Boolean @default(true)
owner User @relation(fields: [ownerId], references: [id])
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
ownerId Int
civs Civ[]
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { TechModule } from './tech/tech.module';
import { AgeModule } from './age/age.module';
import { VersionModule } from './version/version.module';
import { DraftModule } from './draft/draft.module';
import { UserModule } from './user/user.module';

@Module({
imports: [
Expand All @@ -25,6 +26,7 @@ import { DraftModule } from './draft/draft.module';
AgeModule,
VersionModule,
DraftModule,
UserModule,
],
})
export class AppModule {}
5 changes: 2 additions & 3 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { ApiCreatedResponse, ApiTags } from '@nestjs/swagger';
import { ApiCreatedResponse, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { AuthService, JwtAccessToken } from './auth.service';
import { AuthDto } from './dto/auth.dto';

Expand All @@ -9,13 +9,12 @@ export class AuthController {
constructor(private authService: AuthService) {}

@ApiCreatedResponse({ type: JwtAccessToken })
@HttpCode(HttpStatus.OK)
@Post('signup')
signup(@Body() dto: AuthDto): Promise<JwtAccessToken> {
return this.authService.signup(dto);
}

@ApiCreatedResponse({ type: JwtAccessToken })
@ApiOkResponse({ status: HttpStatus.OK, type: JwtAccessToken })
@HttpCode(HttpStatus.OK)
@Post('login')
login(@Body() dto: AuthDto): Promise<JwtAccessToken> {
Expand Down
12 changes: 4 additions & 8 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import {
ForbiddenException,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { ApiProperty } from '@nestjs/swagger';
import { User } from '@prisma/client';
import * as argon from 'argon2';

import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
import { PrismaService } from '../prisma/prisma.service';
import { AuthDto } from './dto/auth.dto';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';

export class JwtAccessToken {
@ApiProperty()
Expand Down Expand Up @@ -79,13 +75,13 @@ export class AuthService {
}

async signToken(userId: number, email: string): Promise<JwtAccessToken> {
const payload: object = {
const payload = {
sub: userId,
email,
};

const token = await this.jwt.signAsync(payload, {
expiresIn: '7d',
expiresIn: '15m',
secret: this.config.get('JWT_SECRET') || process.env.JWT_SECRET,
});

Expand Down
3 changes: 1 addition & 2 deletions src/auth/jwt-strategy/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface JwtPayload {

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private config: ConfigService, private prisma: PrismaService) {
constructor(config: ConfigService, private prisma: PrismaService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get('JWT_SECRET') || process.env.JWT_SECRET,
Expand All @@ -32,7 +32,6 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
throw new ForbiddenException('User not found for authorization');
}

// TODO: clean this up
// delete password before returning the user object
user.hash = '';

Expand Down
8 changes: 7 additions & 1 deletion src/draft/draft.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import {
Body,
ClassSerializerInterceptor,
Controller,
Delete,
Get,
Param,
Patch,
Post,
UseInterceptors,
} from '@nestjs/common';
import { ApiNoContentResponse, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { DraftService } from './draft.service';
Expand All @@ -14,29 +16,33 @@ import { UpdateDraftDto } from './dto/update-draft.dto';
import { DraftEntity } from './entities/draft.entity';

@ApiTags('Drafts')
@Controller('draft')
@Controller('drafts')
export class DraftController {
constructor(private readonly draftService: DraftService) {}

@ApiOkResponse({ type: DraftEntity })
@UseInterceptors(ClassSerializerInterceptor)
@Post()
create(@Body() createDraftDto: CreateDraftDto) {
return this.draftService.create(createDraftDto);
}

@ApiOkResponse({ type: [DraftEntity] })
@UseInterceptors(ClassSerializerInterceptor)
@Get()
findAll() {
return this.draftService.findAll();
}

@ApiOkResponse({ type: DraftEntity })
@UseInterceptors(ClassSerializerInterceptor)
@Get(':id')
findOne(@Param('id') id: string) {
return this.draftService.findOne(+id);
}

@ApiOkResponse({ type: DraftEntity })
@UseInterceptors(ClassSerializerInterceptor)
@Patch(':id')
update(@Param('id') id: string, @Body() updateDraftDto: UpdateDraftDto) {
return this.draftService.update(+id, updateDraftDto);
Expand Down
2 changes: 2 additions & 0 deletions src/draft/draft.module.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* istanbul ignore file */

import { Module } from '@nestjs/common';
import { DraftController } from './draft.controller';
import { DraftService } from './draft.service';
Expand Down
1 change: 1 addition & 0 deletions src/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export class PrismaService extends PrismaClient {
});
}

// FOR TESTING ONLY
async cleanDb() {
await this.user.deleteMany();
await this.unit.deleteMany();
Expand Down
1 change: 1 addition & 0 deletions src/user/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class CreateUserDto {}
4 changes: 4 additions & 0 deletions src/user/dto/update-user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreateUserDto } from './create-user.dto';

export class UpdateUserDto extends PartialType(CreateUserDto) {}
1 change: 1 addition & 0 deletions src/user/entities/user.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class User {}
20 changes: 20 additions & 0 deletions src/user/user.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';

describe('UserController', () => {
let controller: UserController;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService],
}).compile();

controller = module.get<UserController>(UserController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});
});
36 changes: 36 additions & 0 deletions src/user/user.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
Body,
Controller,
Delete,
Get,
Patch,
UseGuards,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { User } from '@prisma/client';
import { GetUser } from '../auth/decorator/get-user.decorator';
import { JwtGuard } from '../auth/guard/jwt.guard';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserService } from './user.service';

@ApiTags('Users')
@UseGuards(JwtGuard)
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}

@Get()
getSelf(@GetUser() user: User) {
return user;
}

@Patch()
update(@Body() updateUserDto: UpdateUserDto, @GetUser('id') id: number) {
return this.userService.update(id, updateUserDto);
}

@Delete()
remove(@GetUser('id') id: number) {
return this.userService.remove(id);
}
}
11 changes: 11 additions & 0 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* istanbul ignore file */

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
18 changes: 18 additions & 0 deletions src/user/user.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';

describe('UserService', () => {
let service: UserService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();

service = module.get<UserService>(UserService);
});

it('should be defined', () => {
expect(service).toBeDefined();
});
});
26 changes: 26 additions & 0 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Injectable()
export class UserService {
create(createUserDto: CreateUserDto) {
return 'This action adds a new user';
}

findAll() {
return `This action returns all user`;
}

findOne(id: number) {
return `This action returns a #${id} user`;
}

update(id: number, updateUserDto: UpdateUserDto) {
return `This action updates a #${id} user`;
}

remove(id: number) {
return `This action removes a #${id} user`;
}
}
Loading

0 comments on commit 0cbce31

Please sign in to comment.