Added Simple Auth with JWT Tokens and Postgres #2

Merged
igorpropisnov merged 10 commits from feature/add-auth into main 2024-05-08 12:28:39 +02:00
3 changed files with 60 additions and 31 deletions
Showing only changes of commit af29a4682c - Show all commits

View File

@ -5,33 +5,54 @@ import { JwtService } from '@nestjs/jwt';
@Injectable() @Injectable()
export class TokenManagementService { export class TokenManagementService {
private readonly ACCESS_TOKEN_EXPIRY: string;
private readonly ACCESS_TOKEN_EXPIRY = '15m'; private readonly REFRESH_TOKEN_EXPIRY: string;
private readonly REFRESH_TOKEN_EXPIRY = '7d'; private readonly JWT_SECRET_AT: string;
private readonly JWT_SECRET_RT: string;
constructor( constructor(
private readonly jwt: JwtService, private readonly jwt: JwtService,
private readonly configService: ConfigService private readonly configService: ConfigService
) {} ) {
this.ACCESS_TOKEN_EXPIRY = this.configService.get<string>(
'ACCESS_TOKEN_EXPIRY'
);
this.REFRESH_TOKEN_EXPIRY = this.configService.get<string>(
'REFRESH_TOKEN_EXPIRY'
);
this.JWT_SECRET_AT = this.configService.get<string>('JWT_SECRET_AT');
this.JWT_SECRET_RT = this.configService.get<string>('JWT_SECRET_RT');
}
public async generateTokens(userId: number, email: string): Promise<Tokens> { public async generateTokens(userId: number, email: string): Promise<Tokens> {
const [access_token, refresh_token] = await Promise.all([ const access_token: string = await this.createAccessToken(userId, email);
this.jwt.signAsync( const refresh_token: string = await this.createRefreshToken(userId, email);
return { access_token, refresh_token };
}
private async createAccessToken(
userId: number,
email: string
): Promise<string> {
return this.jwt.signAsync(
{ sub: userId, email }, { sub: userId, email },
{ {
expiresIn: this.ACCESS_TOKEN_EXPIRY, expiresIn: this.ACCESS_TOKEN_EXPIRY,
secret: this.configService.get<string>('JWT_SECRET_AT'), secret: this.JWT_SECRET_AT,
} }
), );
this.jwt.signAsync( }
private async createRefreshToken(
userId: number,
email: string
): Promise<string> {
return this.jwt.signAsync(
{ sub: userId, email }, { sub: userId, email },
{ {
expiresIn: this.REFRESH_TOKEN_EXPIRY, expiresIn: this.REFRESH_TOKEN_EXPIRY,
secret: this.configService.get<string>('JWT_SECRET_RT'), secret: this.JWT_SECRET_RT,
} }
), );
]);
return { access_token, refresh_token };
} }
} }

View File

@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt'; import { Strategy, ExtractJwt } from 'passport-jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { Injectable } from '@nestjs/common';
import { JwtPayload } from '../models/types'; import { JwtPayload } from '../models/types';
@Injectable() @Injectable()
@ -10,13 +10,17 @@ export class AccessTokenStrategy extends PassportStrategy(
'jwt-access-token' 'jwt-access-token'
) { ) {
constructor(private readonly configService: ConfigService) { constructor(private readonly configService: ConfigService) {
super({ super(AccessTokenStrategy.getJwtConfig(configService));
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('JWT_SECRET_AT'),
});
} }
public async validate(payload: JwtPayload) { private static getJwtConfig(configService: ConfigService): any {
return {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('JWT_SECRET_AT'),
};
}
public async validate(payload: JwtPayload): Promise<JwtPayload> {
return payload; return payload;
} }
} }

View File

@ -1,7 +1,7 @@
import { Injectable, ForbiddenException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport'; import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt'; import { Strategy, ExtractJwt } from 'passport-jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { Request } from 'express'; import { Request } from 'express';
@Injectable() @Injectable()
@ -10,11 +10,15 @@ export class RefreshTokenStrategy extends PassportStrategy(
'jwt-refresh-token' 'jwt-refresh-token'
) { ) {
constructor(private readonly configService: ConfigService) { constructor(private readonly configService: ConfigService) {
super({ super(RefreshTokenStrategy.createJwtStrategyOptions(configService));
}
private static createJwtStrategyOptions(configService: ConfigService): any {
return {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get('JWT_SECRET_RT'), secretOrKey: configService.get<string>('JWT_SECRET_RT'),
passReqToCallback: true, passReqToCallback: true,
}); };
} }
public async validate(req: Request, payload: any) { public async validate(req: Request, payload: any) {