Passport Local Strategy未成功重定向(302)

时间:2017-08-28 18:33:46

标签: javascript express authentication passport.js

我正在通过passportjs学习身份验证,目前有一个注册页面(当成功验证用户时)将呈现个人资料页面。

我的本​​地策略没有成功重定向,我无法弄清楚原因。在需要和安装的地方需要所有中间件。页面只是呈现无限循环;但是会失败正确地重定向。

配置/护照

passport.use('local', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
}, (req, username, password, done) => {

    User.findOne({username : username}, (err, user) => {
        if(err) {return done(err)}
        if(user){
            return done(null, false)
        }

        let newUser = new User()
        newUser.username = req.body.username
        newUser.password = newUser.encryptPasssword(req.body.password)

        newUser.save((err) => {
            if(err) {return done(err)}
            return done(null, newUser)
        })
    })
}))

控制器/用户

router.post('/signup', passport.authenticate('local', {

    successRedirect: '/profile',
    failureRedirect: '/index',
    failureFash: true
}))

router.get('/profile', (req, res) => {
    res.render('profile',{user: req.user})
})

视图/ signup.ejs

<form action='/signup' method='post'>
Username: <br>
<input type='text' id='username' name='username'><br>
Password: <br>
<input type='password' id='password' name='password'><br>
<button type='submit'>Submit</button>
</form>

server.js

'use strict'

const express = require('express'),
    path = require('path'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    mongoose = require('mongoose'),
    passport = require('passport'),
    ejs = require('ejs'),
    MongoStore = require('connect-mongo')(session)


const app = express()

mongoose.connect(my DaaS information is here)

let routes = require('./controllers/user')

require('./config/passport')

app.set('view engine', 'ejs')

app.set('views', path.join(__dirname, 'views'));
app.use(routes)
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static('public'))
app.use(cookieParser)

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({mongooseConnection: mongoose.connection})

}))

app.use(passport.initialize())
app.use(passport.session())



app.listen(3000, () => {
    console.log('listening on port 3000')
})

0 个答案:

没有答案