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

View File

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