Skip to content
This repository has been archived by the owner on May 20, 2024. It is now read-only.

Extract JWT from Authorization header #59

Merged
merged 1 commit into from
Nov 23, 2023
Merged
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
33 changes: 12 additions & 21 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,22 @@ export class AuthService {
return { msg: 'Successfully registered a new account!' };
}

async login(dto: LoginDto): Promise<[string, string, object] | []> {
async login(dto: LoginDto): Promise<object> {
const user = await this.prisma.user.findUniqueOrThrow({
where: { email: dto.email },
});

if (sha512(dto.password) === user.password) {
return this.generateAuthCookie({
userId: user.id,
});
}
throw new ForbiddenException('Wrong credentials!');
if (!user || !(sha512(dto.password) === user.password))
throw new ForbiddenException('Wrong credentials!');

const jwt = await this.generateAuthJwt({
userId: user.id,
});

return {
token: jwt,
userInfo: await this.getUserPublicInfo(dto.email),
};
}

async isTaken(username: string, email: string): Promise<boolean> {
Expand All @@ -51,20 +56,6 @@ export class AuthService {
return this.jwtService.sign(payload);
}

async generateAuthCookie(
payload: JwtAuthDto,
): Promise<[string, string, object]> {
const jwt = await this.generateAuthJwt(payload);
return [
'jwt',
jwt,
{
secure: true,
sameSite: 'lax',
},
];
}

async getUserPublicInfo(email: string): Promise<object> {
const { prisma } = this;
const userPublicInfo: any = await prisma.user.findUniqueOrThrow({
Expand Down
28 changes: 3 additions & 25 deletions src/auth/login/login.controller.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,14 @@
import {
Body,
Controller,
HttpCode,
HttpStatus,
Post,
Res,
} from '@nestjs/common';
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common';
import { AuthService } from '../auth.service';
import { LoginDto } from '../dto';
import { Response } from 'express';

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

@Post()
@HttpCode(HttpStatus.OK)
async login(@Body() dto: LoginDto, @Res() res: Response) {
const jwt = await this.authService.login(dto);
if (!jwt.length) {
res.send({ has2FAEnabled: true });
return;
}
res.cookie(...jwt);
res.cookie(
'user_info',
JSON.stringify(await this.authService.getUserPublicInfo(dto.email)),
{
secure: true,
sameSite: 'lax',
},
);
res.send({ token: jwt[1] });
async login(@Body() dto: LoginDto) {
return await this.authService.login(dto);
}
}
9 changes: 2 additions & 7 deletions src/auth/strategy/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
import { JwtAuthDto } from '../dto/jwt-auth.dto';

const { SECRET = 'secret' } = process.env;

const extractFromCookie = (req: any): string | null => {
if (req && req.cookies) return req.cookies['jwt'];
return null;
};

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: extractFromCookie,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: SECRET,
});
}
Expand Down