Skip to content

Commit

Permalink
feat: add Bearer support
Browse files Browse the repository at this point in the history
  • Loading branch information
typeWolffo committed Jul 11, 2024
1 parent 086bf94 commit 69c8138
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { UUIDType } from "src/common/index";
import {
Body,
Controller,
Expand Down Expand Up @@ -73,16 +74,17 @@ export class AuthController {
return null;
}

@Public()
@UseGuards(RefreshTokenGuard)
@Post("refresh")
@Validate({
response: nullResponse(),
})
async refreshTokens(
@Res({ passthrough: true }) response: Response,
@Req() request: Request,
@Req() request: Request & { refreshToken: UUIDType },
): Promise<null> {
const refreshToken = request.cookies["refresh_token"];
const refreshToken = request["refreshToken"];

if (!refreshToken) {
throw new UnauthorizedException("Refresh token not found");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
ExtractJwt.fromAuthHeaderAsBearerToken(),
(request) => request?.cookies?.access_token,
]),
ignoreExpiration: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import {
Injectable,
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Reflector } from "@nestjs/core";
import { JwtService } from "@nestjs/jwt";
import { extractToken } from "src/utils/extract-token";

@Injectable()
export class JwtAuthGuard implements CanActivate {
Expand All @@ -27,7 +28,7 @@ export class JwtAuthGuard implements CanActivate {
}

const request = context.switchToHttp().getRequest();
const token = request.cookies["access_token"];
const token = extractToken(request, "access_token");

if (!token) {
throw new UnauthorizedException("Access token not found");
Expand All @@ -37,7 +38,9 @@ export class JwtAuthGuard implements CanActivate {
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>("jwt.secret"),
});

request["user"] = payload;

return true;
} catch {
throw new UnauthorizedException("Invalid access token");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import {
ExecutionContext,
UnauthorizedException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import { extractToken } from "src/utils/extract-token";

@Injectable()
export class RefreshTokenGuard implements CanActivate {
Expand All @@ -16,10 +17,10 @@ export class RefreshTokenGuard implements CanActivate {

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const refreshToken = request.cookies["refresh_token"];
const refreshToken = extractToken(request, "refresh_token");

if (!refreshToken) {
throw new UnauthorizedException("No refresh token provided");
throw new UnauthorizedException("Refresh token not found");
}

try {
Expand All @@ -28,6 +29,7 @@ export class RefreshTokenGuard implements CanActivate {
});

request["user"] = payload;
request["refreshToken"] = refreshToken;

return true;
} catch {
Expand Down
3 changes: 2 additions & 1 deletion examples/common_nestjs_remix/apps/api/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TSchema, Type } from "@sinclair/typebox";
import { Static, TSchema, Type } from "@sinclair/typebox";
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import * as schema from "src/storage/schema";

Expand All @@ -13,6 +13,7 @@ export class BaseResponse<T> {
}

export const UUIDSchema = Type.String({ format: "uuid" });
export type UUIDType = Static<typeof UUIDSchema>;

export function baseResponse(data: TSchema) {
if (data.type === "array") {
Expand Down
16 changes: 16 additions & 0 deletions examples/common_nestjs_remix/apps/api/src/utils/extract-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Request } from "express";

export function extractToken(
request: Request,
cookieName: "refresh_token" | "access_token",
): string | null {
if (request.cookies && request.cookies[cookieName]) {
return request.cookies[cookieName];
}

if (request.headers.authorization?.startsWith("Bearer ")) {
return request.headers.authorization.split(" ")[1];
}

return null;
}

0 comments on commit 69c8138

Please sign in to comment.