Created
September 26, 2022 14:08
-
-
Save hakimkal/adb21c653611b76e9525d7243bb1f920 to your computer and use it in GitHub Desktop.
Auth helper with user entity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { | |
| HttpException, | |
| HttpStatus, | |
| Injectable, | |
| UnauthorizedException, | |
| } from '@nestjs/common'; | |
| import { Repository } from 'typeorm'; | |
| import { User } from '@/users/entities/user.entity'; | |
| import { InjectRepository } from '@nestjs/typeorm'; | |
| import { JwtService } from '@nestjs/jwt'; | |
| import * as bcrypt from 'bcrypt'; | |
| @Injectable() | |
| export class AuthHelper { | |
| @InjectRepository(User) | |
| private readonly repository: Repository<User>; | |
| private readonly jwt: JwtService; | |
| constructor(jwt: JwtService) { | |
| this.jwt = jwt; | |
| } | |
| //Decoding JWT token | |
| public async decode(token: string): Promise<any> { | |
| return this.jwt.decode(token, null); | |
| } | |
| //validate user from userID in decode() | |
| public async validateUser(decoded: any) { | |
| return this.repository.findOne({ where: { id: decoded.id } }); | |
| } | |
| //generate jwttoken | |
| public generateToken(user: User): string { | |
| return this.jwt.sign({ | |
| id: user.id, | |
| email: user.email, | |
| firstname: user.firstname, | |
| lastname: user.lastname, | |
| }); | |
| } | |
| //validate user password | |
| public isPasswordValid(password: string, userPassword: string): boolean { | |
| return bcrypt.compareSync(password, userPassword); | |
| } | |
| // encode user's password | |
| public encodePassword(password: string): string { | |
| const salt = bcrypt.genSaltSync(10); | |
| return bcrypt.hashSync(password, salt); | |
| } | |
| // Validate JWT Token, throw forbidden error if JWT Token is invalid | |
| public async validate(token: string): Promise<boolean | never> { | |
| try { | |
| const decoded: any = this.jwt.verify(token); | |
| if (!decoded) { | |
| throw new HttpException('Forbidden', HttpStatus.FORBIDDEN); | |
| } | |
| const user = await this.validateUser(decoded); | |
| if (!user) { | |
| throw new UnauthorizedException(); | |
| } | |
| return true; | |
| } catch (err) { | |
| throw new HttpException(err.message.toUpperCase(), HttpStatus.FORBIDDEN); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment