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

Add feature authentication #6

Merged
merged 13 commits into from
Oct 17, 2021
Merged
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,16 @@
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/jwt": "^8.0.0",
"@nestjs/passport": "^8.0.1",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/typeorm": "^8.0.2",
"@types/passport-jwt": "^3.0.6",
"bcrypt": "^5.0.1",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"passport": "^0.5.0",
"passport-jwt": "^4.0.0",
"pg": "^8.7.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TasksModule } from './tasks/tasks.module';
import { AuthModule } from './auth/auth.module';

@Module({
imports: [
Expand All @@ -15,6 +16,7 @@ import { TasksModule } from './tasks/tasks.module';
autoLoadEntities: true,
synchronize: true,
}),
AuthModule,
],
})
export class AppModule {}
20 changes: 20 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Body, Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';

@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}

@Post('/signup')
signUp(@Body() authCredentialsDto: AuthCredentialsDto): Promise<void> {
return this.authService.signUp(authCredentialsDto);
}

@Post('/signin')
signIn(
@Body() authCredentialsDto: AuthCredentialsDto,
): Promise<{ accessToken: string }> {
return this.authService.signIn(authCredentialsDto);
}
}
25 changes: 25 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersRepository } from './users.repository';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt.strategy';

@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'superSecret1993',
signOptions: {
expiresIn: 3600,
},
}),
TypeOrmModule.forFeature([UsersRepository]),
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [JwtStrategy, PassportModule],
})
export class AuthModule {}
35 changes: 35 additions & 0 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { UsersRepository } from './users.repository';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './jwt-payload.interface';

@Injectable()
export class AuthService {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
private jwtService: JwtService,
) {}

async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void> {
return this.usersRepository.createUser(authCredentialsDto);
}

async signIn(
authCredentialsDto: AuthCredentialsDto,
): Promise<{ accessToken: string }> {
const { username, password } = authCredentialsDto;
const user = await this.usersRepository.findOne({ username });

if (user && (await bcrypt.compare(password, user.password))) {
const payload: JwtPayload = { username };
const accessToken: string = await this.jwtService.sign(payload);
return { accessToken };
} else {
throw new UnauthorizedException('Please check your login credentials.');
}
}
}
16 changes: 16 additions & 0 deletions src/auth/dto/auth-credentials.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { IsString, Matches, MaxLength, MinLength } from 'class-validator';

export class AuthCredentialsDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;

@IsString()
@MinLength(8)
@MaxLength(32)
@Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
message: 'Password is too weak.',
})
password: string;
}
9 changes: 9 additions & 0 deletions src/auth/get-user.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { User } from './user.entity';

export const GetUser = createParamDecorator(
(_data, context: ExecutionContext): User => {
const req = context.switchToHttp().getRequest();
return req.user;
},
);
3 changes: 3 additions & 0 deletions src/auth/jwt-payload.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface JwtPayload {
username: string;
}
31 changes: 31 additions & 0 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { User } from './user.entity';
import { UsersRepository } from './users.repository';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UsersRepository)
private usersRepository: UsersRepository,
) {
super({
secretOrKey: 'superSecret1993',
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
});
}

async validate(payload: JwtPayload): Promise<User> {
const { username } = payload;
const user: User = await this.usersRepository.findOne({ username });

if (!user) {
throw new UnauthorizedException();
}

return user;
}
}
13 changes: 13 additions & 0 deletions src/auth/user.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ unique: true })
username: string;

@Column()
password: string;
}
29 changes: 29 additions & 0 deletions src/auth/users.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import {
ConflictException,
InternalServerErrorException,
} from '@nestjs/common';
import { EntityRepository, Repository } from 'typeorm';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';

@EntityRepository(User)
export class UsersRepository extends Repository<User> {
async createUser(authCredentialsDto: AuthCredentialsDto): Promise<void> {
const { username, password } = authCredentialsDto;

const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(password, salt);
const user = this.create({ username, password: hashedPassword });

try {
await this.save(user);
} catch (error) {
if (error.code === '23505') {
throw new ConflictException('Username already exists.');
} else {
throw new InternalServerErrorException();
}
}
}
}
3 changes: 3 additions & 0 deletions src/tasks/tasks.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@ import {
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CreateTaskDto } from './dto/create-task.dto';
import { GetTasksFilterDto } from './dto/get-tasks-filter.dto';
import { UpdateTaskStatusDto } from './dto/update-task-status.dto';
import { Task } from './task.entity';
import { TasksService } from './tasks.service';

@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
constructor(private tasksService: TasksService) {}

Expand Down
3 changes: 2 additions & 1 deletion src/tasks/tasks.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from 'src/auth/auth.module';
import { TasksController } from './tasks.controller';
import { TasksRepository } from './tasks.repository';
import { TasksService } from './tasks.service';

@Module({
imports: [TypeOrmModule.forFeature([TasksRepository])],
imports: [TypeOrmModule.forFeature([TasksRepository]), AuthModule],
controllers: [TasksController],
providers: [TasksService],
})
Expand Down
Loading