Implementing a login system using react and passport local

18 Views Asked by At

Im currently trying to set up a login authentication for react using a passport local strategy. Here is the code:

The authentication code:

const passport = require('passport')
const {Strategy} = require('passport-local')
const Database = require('./../Database/Schema')
const {compareSync} = require('bcryptjs')

module.exports = passport.use(new Strategy({
        usernameField:"Username",
        passwordField:"Password"
    },async (username,password,done) => {
        try{
            const userFinder = await Database.findOne({Username:username})
            console.log(userFinder)
            if (userFinder !== null){
                if(compareSync(password,userFinder.Password)) return done(null,userFinder)
                else return new Error("Incorrect password placed inside")
            }
        }
        catch(error){
            console.log(error)
            done(error,null)
        }
    }
))

The login route:

const passport = require('passport')
const passport_local = require('passport-local')
const router = require('express').Router()
const auth = require('./../Authentication/auth')

router.get('/',passport.authenticate("local",{session:true}),(request,response) => {
    console.log("Logged in")
    return response.sendStatus(200)
})

module.exports = router

And the server:

const express = require('express')
const session = require('express-session')
const mongoose = require('mongoose')
const passport = require('passport')
const body_parser = require('body-parser')
const connect_mongo = require('connect-mongo')
const cors = require('cors')

const app = express()

app.use(cors())
app.use(express.json())
app.use(session({
    secret:'Secret for nuke and area 51',
    resave:false,
    saveUninitialized:false,
    store:connect_mongo.create({
        mongoUrl:"a-valid-url-is-here-don't worry-about-it"
    })
}))
app.use(body_parser.urlencoded({extended:false}))
app.use(passport.initialize())
app.use(passport.session())

const Database = require('./Database/Schema')

passport.serializeUser((user,done) => {
    console.log("Serializing user into session")
    return done(null,user._id)
})
passport.deserializeUser(async (userId,done) => {
    try{
        const userFinder = Database.findById(userId)
        if(userFinder !== null) return done(null,userFinder)
        else throw new Error("Incorrect credentials, user does not exist")
    }
    catch(error){
        console.log(error)
        done(error,null)
    }
    finally{
        console.log("Deserializing user Complete")
    }
})
//Routes
const signupRoute = require('./Routes/signup')
const loginRoute = require('./Routes/login')
app.use('/users/signup',signupRoute)
app.use('/users/login',loginRoute)

mongoose.connect("a-valid-url-is-here-don't worry-about-it")
    .then(() => {
        app.listen(4500,() => {
            console.log("Server is up at port 4500 and Database is running as well.")
        })
    })
    .catch(error => console.log(error))

Im expecting that I'll be able to login well since the sign up route works perfectly fine. But as I try implementing the login route I keep getting an 404 error code of: Failed to load resource: the server responded with a status of 404 (Not Found)'

For the react side application I am using vite not create-react-app and to summarise the code in the client side, I have a fetch api whose method is set to post in order to pass in the user credentials but the server side route method is set to get.

I'm honestly lost on why it isn't working since it works perfectly fine on external api's like postman, thunder client and even rest client.

Thank you for your time.

0

There are 0 best solutions below