Skip to content

Instantly share code, notes, and snippets.

@mateothegreat
Last active July 20, 2023 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateothegreat/027b71bcec24603d8a4c517ae091241a to your computer and use it in GitHub Desktop.
Save mateothegreat/027b71bcec24603d8a4c517ae091241a to your computer and use it in GitHub Desktop.
Request authorization with nest.js + JWT
@Controller("/foo")
export class SomeController {
@Get("/thisisprotected")
@UseGuards(RequestGuard)
public search(@SessionDecorator() session: Session): Promise<any> {
return { foo: "bar" };
}
}
import { Injectable } from "@nestjs/common";
import { User } from "@nvr-ai/prisma/dist";
import { PrismaService } from "@nvr-ai/prisma/dist/PrismaService";
import * as bcrypt from "bcrypt";
import * as jwt from "jsonwebtoken";
import { Session } from "../../sessions/session";
import { UserCreate } from "./user-create";
import { UserLoginResult } from "./user-login-result";
import { UserStatus } from "./user-status";
@Injectable()
export class LoginService {
public static getLoginResult(userId: string): UserLoginResult {
return {
token: jwt.sign({ id: userId }, process.env.JWT_SECRET, {
expiresIn: 86400,
}),
};
}
public async login(
email: string,
password: string
): Promise<UserLoginResult> {
const user = await this.getByEmail(email);
if (!user) {
throw new Error("User not found");
}
//
// Call MS endpoint to validate user here.. <----------------------------------
// Then pass an id that corelates to the user in the MS to the JWT token below:
//
return UsersService.getLoginResult(msResultObject.userIdorWhatever);
}
}
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from "@nestjs/common";
import { Request } from "express";
import * as jwt from "jsonwebtoken";
import { Session } from "./session";
@Injectable()
export class RequestGuard implements CanActivate {
@Inject(UsersService)
private readonly usersService: UsersService;
/**
* Called before a route is executed.
*
* @param {ExecutionContext} context
* @returns {Promise<boolean>}
*/
public async canActivate(context: ExecutionContext): Promise<boolean> {
//
// Get the request object from the context.
//
const ctx = context.switchToHttp();
const request = ctx.getRequest<Request>();
if (request.headers.authorization) {
//
// Split the authorization header into the type and token.
// The type is usually "Bearer" and the token is the JWT token.
//
const split = request.headers.authorization.split(" ");
try {
//
// Verify that the JWT token wasn't tampered with and decode it.
//
const decoded = jwt.verify(split[1], process.env.JWT_SECRET);
//
// You could also query for a user record or something cool like that
// and attach it to the request object.
//
const user = await this.usersService.get(decoded["id"]);
//
// Attach the session to the request object.
//
request["session"] = {
foo: "bar",
id: decoded["id"],
};
//
// Return true to allow the request to continue.
//
return true;
} catch (e) {
//
// Return false to deny the request.
//
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment