简体   繁体   中英

Why Passport.JS returns empty user object after redirect?

What is my goal?

I'm creating a website using Express.JS and Node.JS that will have 3 panels :

  • User panel (account settings, contact form, etc.),
  • Admin panel (option to reply post from contact form, moderating users, etc.),
  • Dashboard (panel for owners, where You can manage website, user and admin accounts, etc.).

First I wrote a code for Admin Panel (login form, main page, full reply system), then I started to creating a Dashboard, so I decided to copy code from Admin panel, because it's working and it's all I want.

I copied the code, changed the necessary variables, etc. Then came testing part. And here is problem.


What is the problem?

As above - I copied the working code and I changed only variables like Passport > Strategy name , MongoDB Model and password encryption string . Then I tested it, and some error occured - When user provide wrong credentials - all work properly, but if user provide valid credentials and click "Submit" button - webiste tries to redirect to dashboard, but returns to login page, because req.isAuthenticated() returns false value.


What I checked?

I used console.log(req.user) method on almost every step, and everywhere on login page user object is full of correct data and req.isAuthenticated() returns true value, but when page redirect user to panel (as credentials is correct) - there user object just clears ( res.json(req.user) is just empty).

So I think is a some sort of problem with data sending on page redirect.


My parts of code:

I don't uploaded full code, because there is most part, that is not necessary for this post.

index.js - Main file:

const main = express()
const dashboard = express()

main.use(vhost(`dashboard.localhost`, dashboard))

dashboard.use(bodyParser.urlencoded({ extended: true }))

dashboard.use(cookieParser())

dashboard.use("/", session({

    secret: dashboardSecret,
    resave: false,
    saveUninitialized: false,

}))

require("./config/passport/dashboard")(passport)
dashboard.use(passport.initialize())
dashboard.use(passport.session())

dashboard.use("/", require("./routes/dashboard.routes"))

dashboard.routes.js - Routing file for dashboard:

const express = require("express")
const passport = require("passport")

const router = express.Router()

const panel = require("./../pages/dashboard/panel")
const login = require("./../pages/dashboard/login")
const logout = require("./../pages/dashboard/logout")

router.get("/", panel)

router.get("/auth", login)

router.get("/logout", logout)


router.post("/auth", (req, res, next) => {

    passport.authenticate("dashboard", {

        successRedirect: "/",
        failureRedirect: "/auth",
        successFlash: true,
        failureFlash: true,

    })(req, res, next)

})

module.exports = router

dashboard.js - File with Passport Strategy for dashboard:

const DashboardStrategy = require("passport-local").Strategy
const Cryptr = require("cryptr")

const { dashboard} = require("./../encryptionStrings")

const cryptr = new Cryptr(dashboard)

const Dashboard = require("./../../models/Dashboard")

module.exports = function(passport) {

    passport.use("managment", new DashboardStrategy({

        usernameField: "nickname",

    }, (nickname, password, done) => {

        Dashboard.findOne({

            nickname: nickname.toLowerCase()

        }).then(user => {

            if (!user) return done(null, false)

            if (password === cryptr.decrypt(user.password)) {
                
                return done(null, user)

            } else {

                return done(null, false)

            }

        })

    }))

    passport.serializeUser(function(user, done) {

        done(null, user.id)

    })

    passport.deserializeUser(async (id, done) => {

        const user = await Managment.findById(id)

        done(null, user)

    })

}

Dashboard.js - Account Model for Owners:

const mongoose = require("mongoose")

const DashboardSchema = new mongoose.Schema({

    nickname: {

        type: String,
        required: true,
        unique: true,

    },

    password: {

        type: String,
        required: true,

    }

}, {

    collection: "dashboard"

})

const Dashboard = mongoose.model("Dashboard", DashboardSchema)

module.exports = Dashboard

In dashboard.js you create local strategy with name managment , but you're trying to authenticate with strategy dashboard - as this does not exists, you can never get authenticated. Correct is:

router.post("/auth", (req, res, next) => {

    passport.authenticate("managment", {    // <-- replaced here       
        successRedirect: "/",
        failureRedirect: "/auth",
        successFlash: true,
        failureFlash: true,

    })(req, res, next)

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM