feat: Add Discord and JWT authentication guards

- Added `DiscordAuthGuard` to handle Discord authentication
- Added `JwtAuthGuard` to handle JWT authentication

These guards are used in the `auth.controller.ts` and `user.controller.ts` files to protect routes that require authentication.
This commit is contained in:
M1000fr 2024-11-28 16:11:16 +01:00
parent b40249fdfb
commit 61bd5cd862
4 changed files with 44 additions and 17 deletions

View File

@ -0,0 +1,13 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class DiscordAuthGuard extends AuthGuard("discord") {
handleRequest(err, user, info, context) {
if (err || !user) {
const errorMessage = info?.message || "Authentication failed";
throw new UnauthorizedException(errorMessage);
}
return user;
}
}

View File

@ -0,0 +1,5 @@
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {}

View File

@ -1,6 +1,7 @@
import { Controller, Get, Req, Res, UseGuards } from "@nestjs/common"; import { Controller, Get, Query, Req, Res, UseGuards } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { URLSearchParams } from "node:url"; import { URLSearchParams } from "node:url";
import { JwtAuthGuard } from "./Guards/jwt.guard";
import { DiscordAuthGuard } from "./Guards/discord.guard";
@Controller("auth") @Controller("auth")
export class AuthController { export class AuthController {
@ -21,7 +22,7 @@ export class AuthController {
} }
@Get("discord/callback") @Get("discord/callback")
@UseGuards(AuthGuard("discord")) @UseGuards(DiscordAuthGuard)
CallbackDiscord(@Req() req, @Res() res) { CallbackDiscord(@Req() req, @Res() res) {
const { user } = req; const { user } = req;
@ -29,7 +30,7 @@ export class AuthController {
} }
@Get("profile") @Get("profile")
@UseGuards(AuthGuard("jwt")) @UseGuards(JwtAuthGuard)
Profile(@Req() req) { Profile(@Req() req) {
return req.user; return req.user;
} }

View File

@ -1,11 +1,19 @@
import { Body, Controller, Delete, Get, Param, Post, UseGuards } from "@nestjs/common"; import {
import { AuthGuard } from "@nestjs/passport"; Body,
Controller,
import { CreateUserInput } from "./dto/create-user.input"; Delete,
Get,
Param,
Post,
UseGuards,
} from "@nestjs/common";
import { UserService } from "./user.service"; import { UserService } from "./user.service";
import { JwtAuthGuard } from "src/auth/Guards/jwt.guard";
import { CreateUserInput } from "./dto/create-user.input";
@Controller("user") @Controller("user")
@UseGuards(AuthGuard("jwt")) @UseGuards(JwtAuthGuard)
export class UserController { export class UserController {
constructor(private readonly userService: UserService) {} constructor(private readonly userService: UserService) {}