Skip to content

Commit

Permalink
add sigin and sign up
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaalanMarwan committed May 1, 2022
1 parent 881a789 commit 93052bc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export class AuthController {

@Post('/signup')
signup(@Body() authCredentialDto: AuthCredentialDto): Promise<void> {
return this.authService.signup(authCredentialDto);
return this.authService.signUp(authCredentialDto);
}
@Post('/signin')
signIn(@Body() authCredentialDto: AuthCredentialDto): Promise<string> {
return this.authService.sigIn(authCredentialDto);
}
}
15 changes: 13 additions & 2 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { AuthCredentialDto } from 'src/auth/dto/auth-credentials.dto';
import { UsersRepository } from 'src/auth/users.repository';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
Expand All @@ -10,7 +11,17 @@ export class AuthService {
private usersRepository: UsersRepository,
) {}

async signup(authCredentialDto: AuthCredentialDto): Promise<void> {
async signUp(authCredentialDto: AuthCredentialDto): Promise<void> {
return await this.usersRepository.createUser(authCredentialDto);
}

async sigIn(authCredentialDto: AuthCredentialDto): Promise<string> {
const { password, username } = authCredentialDto;
const user = await this.usersRepository.findOne({ username });
if (user && (await bcrypt.compare(password, user.password))) {
return 'success';
} else {
throw new UnauthorizedException('please check your credential ');
}
}
}
6 changes: 5 additions & 1 deletion src/auth/users.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import {
import { AuthCredentialDto } from 'src/auth/dto/auth-credentials.dto';
import { User } from 'src/auth/user.entity';
import { EntityRepository, Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';

@EntityRepository(User)
export class UsersRepository extends Repository<User> {
async createUser(authCredentialDto: AuthCredentialDto): Promise<void> {
const { username, password } = authCredentialDto;
const user = this.create({ username, password });
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) {
Expand Down

0 comments on commit 93052bc

Please sign in to comment.