'Using failureRedirect option of passport-local with Nest.js

I need help with processing after authentication using Nest.js here do I pass the failureRedirect option for passport-local when using Nest.js for authentication?

Without Nest.js

app.post('/login', passport.authenticate('local', {
    //Passing options here.
    successRedirect: '/',
    failureRedirect: '/login'
}));

My code is. (with Nest.js)

local.strategy.ts

import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy } from "passport-local";
import { AuthService } from "./auth.service";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private authService: AuthService) {
        super({
            //I tried passing the option here. but failed.
        })
    }

    async validate(username: string, password: string): Promise<string | null> {
        const user = this.authService.validate(username, password);
        if (!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}

local.guard.ts

import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable
export class LocalAuthGuard extends AuthGuard('local') {}

auth.controller.ts

import { Controller, Get, Post, Render, UseGuards } from "@nestjs/common";
import { LocalAuthGuard } from "./local.guard";

@Controller()
export class AuthController {
    @Get("/login")
    @Render("login")
    getLogin() {}
    
    //Redirect to '/login' when authentication failed.
    @UseGuards(LocalAuthGuard)
    @Post("/login")
    postLogin() {}
}

auth.module.ts

import { Module } from "@nestjs/common";
import { PassportModule } from "@nestjs/passport";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { LocalStrategy } from "./local.strategy";
import { LocalAuthGuard } from "./local.guard";

@Module({
   controllers: [AuthController],
   imports: [PassportModule],
   providers: [AuthService, LocalStrategy, LocalAuthGuard]
})
export class AuthModule {}

I tried adding code to AuthController#postLogin to redirect on login failure, but the code seems to run only on successful login. I would like to redirect to the login page again in case of login failure with the failureRedirect option of passport-local.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source