Last active
July 20, 2023 07:04
-
-
Save mateothegreat/027b71bcec24603d8a4c517ae091241a to your computer and use it in GitHub Desktop.
Request authorization with nest.js + JWT
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
@Controller("/foo") | |
export class SomeController { | |
@Get("/thisisprotected") | |
@UseGuards(RequestGuard) | |
public search(@SessionDecorator() session: Session): Promise<any> { | |
return { foo: "bar" }; | |
} | |
} |
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 { 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); | |
} | |
} |
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 { | |
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