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

[FEATURE] : sign-in #18

Open
wants to merge 2 commits 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
792 changes: 724 additions & 68 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 10 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,19 @@
"@nestjs/common": "^10.3.3",
"@nestjs/config": "^3.2.0",
"@nestjs/core": "^10.3.3",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.3",
"@nestjs/swagger": "^7.3.0",
"@prisma/client": "^5.10.2",
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"@prisma/client": "^5.10.2",
"helmet": "^7.1.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.2.1",
"rimraf": "^5.0.5",
"rxjs": "^7.8.1",
Expand All @@ -47,9 +53,12 @@
"@nestjs/cli": "^10.3.2",
"@nestjs/schematics": "^10.1.1",
"@nestjs/testing": "^10.3.3",
"@types/bcrypt": "^5.0.2",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.11.19",
"@types/passport-jwt": "^4.0.1",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^6.0.2",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { PrismaModule } from 'src/providers/databases/prisma/prisma.module'
import { ExampleModule } from './modules/example/example.module'
import { HealthModule } from './modules/health/health.module'
import { UsersModule } from './modules/users/users.module'
import { AuthModule } from './modules/auth/auth.module'

@Module({
imports: [
Expand All @@ -14,6 +15,7 @@ import { UsersModule } from './modules/users/users.module'
ExampleModule,
PrismaModule,
UsersModule,
AuthModule
],
})
export class AppModule {}
4 changes: 4 additions & 0 deletions src/models/signInCredential.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface signInCredentialModel {
username: string
password: string
}
3 changes: 3 additions & 0 deletions src/modules/auth/auth.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class jwtConstants {
static secret: string = 'jwt-secret-key';
}
19 changes: 19 additions & 0 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Controller, Post, Body, UseGuards} from '@nestjs/common';
import { AuthService } from './auth.service';
import { Public } from './decorators/public.decorator';
import { LocalAuthGuard } from './local/local.auth.guard';
import { SignInDto } from './dto/auth.dto';


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

@Public()
@UseGuards(LocalAuthGuard)
@Post('sign-in')
async signIn(@Body() signInDto: SignInDto) {
const result = await this.authService.signIn(signInDto);
return result;
}
}
25 changes: 25 additions & 0 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Module } from '@nestjs/common'
import { JwtModule } from '@nestjs/jwt'
import { PassportModule } from '@nestjs/passport'
import { UsersModule } from '../users/users.module'
import { jwtConstants } from './auth.constants'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import { JwtStrategy } from './jwt/jwt.strategy'

@Module({
imports: [
UsersModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
global: true,
secret: jwtConstants.secret,
signOptions: { expiresIn: '7d' },
}),
],

providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
51 changes: 51 additions & 0 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Injectable, UnauthorizedException, NotFoundException, OnApplicationBootstrap, OnApplicationShutdown } from "@nestjs/common";
import { SignInDto } from "./dto/auth.dto";
import { UsersService } from "../users/users.service";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService
) {}

async signIn(signInDto: SignInDto) {
const user = await this.usersService.findUserByUsername(signInDto.username);

if (!user) {
throw new NotFoundException('User not found');
}

if (user.password !== signInDto.password) {
throw new UnauthorizedException('Invalid credentials');
}

const payload = { username: user.username, sub: user.id };
const accessToken = await this.jwtService.signAsync(payload, { expiresIn: '1d' });
const refreshToken = await this.jwtService.signAsync(payload, { expiresIn: '7d' });

const expiryDateAccessToken = new Date();
expiryDateAccessToken.setDate(expiryDateAccessToken.getDate() + 1);

const expiryDateRefreshToken = new Date();
expiryDateRefreshToken.setDate(expiryDateRefreshToken.getDate() + 7);

return {
accessToken,
refreshToken,
expiryDateAccessToken,
expiryDateRefreshToken
};
}

async validateUser(username: string, password: string) {
const user = await this.usersService.findUserByUsername(username);

if (user && user.password === password) {
return user;
}

return null;
}
}
4 changes: 4 additions & 0 deletions src/modules/auth/decorators/public.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC_KEY = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
11 changes: 11 additions & 0 deletions src/modules/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';

export class SignInDto {
@IsNotEmpty()
@IsString()
username: string = '';

@IsNotEmpty()
@IsString()
password: string = '';
}
1 change: 1 addition & 0 deletions src/modules/auth/entities/auth.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class Auth {}
5 changes: 5 additions & 0 deletions src/modules/auth/jwt/jwt.auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {}
19 changes: 19 additions & 0 deletions src/modules/auth/jwt/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from '../auth.constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}

async validate(payload: any) {
return { id: payload.sub, username: payload.username };
}
}
6 changes: 6 additions & 0 deletions src/modules/auth/local/local.auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()

export class LocalAuthGuard extends AuthGuard('local') {}
21 changes: 21 additions & 0 deletions src/modules/auth/local/local.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { Strategy } from 'passport-local'
import { AuthService } from '../auth.service'

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'username' });
}

async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);

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

return user;
}
}
1 change: 1 addition & 0 deletions src/modules/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ import { UsersService } from './users.service'
imports: [RepositoriesModule],
controllers: [UsersController],
providers: [UsersService, UsersFactory],
exports: [UsersService],
})
export class UsersModule {}
5 changes: 5 additions & 0 deletions src/modules/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ export class UsersService {
totalRecords: count,
}
}

async findUserByUsername(username: string): Promise<UsersModel | undefined >{
const user = await this.usersRepository.findOne({ username } );
return user;
}
}
1 change: 1 addition & 0 deletions src/repositories/users/users.abstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export abstract class IUsersRepository {
abstract getList(options: GetUsersOptions): Promise<UsersModel[]>
abstract geById(id: number, returnStudent: boolean): Promise<UsersModel>
abstract count(filter: Prisma.UsersWhereInput): Promise<number>
abstract findOne(filter: Prisma.UsersWhereInput): Promise<UsersModel>
}
12 changes: 12 additions & 0 deletions src/repositories/users/users.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,16 @@ export class UsersRepository implements IUsersRepository {

return count
}

async findOne(filter: Prisma.UsersWhereInput): Promise<UsersModel> {
const user = await this.prisma.users.findFirstOrThrow({
where: filter,
include: {
Student: true,
Role: true,
},
})

return this.usersFactory.mapUsersEntityToUsersModel(user)
}
}