#javascript #node.js #express #passport.js
#язык JavaScript #node.js #экспресс #passport.js
Вопрос:
Я новичок в node, express и node, и я создаю функцию аутентификации с помощью passport.js. В своих маршрутах я использую функцию промежуточного программного обеспечения под названием «Проверка подлинности», чтобы проверить, не аутентифицирован ли пользователь, но я получаю эту ошибку: «Ошибка типа: req.IsAuthenticated не является функцией»
В чем здесь может быть проблема?
Мои маршруты:
const express = require('express') const router = express.Router() const bcrypt = require('bcrypt') const passport = require('passport') const flash = require('express-flash') const session = require('express-session') const methodOverride = require('method-override') const User = require('../models/user.model') const initializePassport = require('../passport-config') initializePassport(passport) const app = express() app.use(flash()) app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session()) app.use(methodOverride('_method')) /* Middleware function to check if user is authenticated */ function checkNotAuthenticated(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/') } next() } /* ------- Routes ------- */ /* Create new user */ router.post('/register', checkNotAuthenticated, async (req, res) =gt; { /* Check if the email isn't already taken */ const emailIsTaken = await User.findOne({email: req.body.email}) if (emailIsTaken) return res.status(500).send('Email already used') try { const hashedPassword = await bcrypt.hash(req.body.password, 10) const user = new User({ name: req.body.name, password: hashedPassword, email: req.body.email, title: req.body.title, about: req.body.about }) user.save() res.send('Success - User created') } catch (err) { res.status(500).send(err) } }) /* Login user */ router.post('/login', checkNotAuthenticated, passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true })) /* Logout */ router.delete('/logout', (req, res) =gt; { req.logOut() res.redirect('/login') }) module.exports = router
passport-config.js:
const User = require('./models/user.model') const LocalStrategy = require('passport-local').Strategy const bcrypt = require('bcrypt') function initializePassport(passport) { const authenticateUser = async done =gt; { /* Check if there's a user account created with that email */ const userFound = await User.findOne({email: req.body.email}) if (!userFound) return done(null, false, {message: 'Cannot find user with that email'}) /* Validate password */ try { const checkPassword = await bcrypt.compare(req.body.password, userFound.password) if (checkPassword) { return done(null, userFound) } else { return done(null, false, {message: 'Incorrect password'}) } } catch (err) { return done(err) } } passport.use(new LocalStrategy( { usernameField: 'email' }, authenticateUser) ) passport.serializeUser(done =gt; { done(null, userFound.id) }) passport.deserializeUser(done =gt; { done(null, userFound) }) } module.exports = initializePassport
Полная ошибка:
TypeError: req.isAuthenticated is not a function at checkNotAuthenticated (/home/German/Desktop/ger/code/projects/helpr/helpr-back/routes/users.route.js:27:11) at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5) at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5) at /home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:335:12) at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:275:10) at Function.handle (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:174:3) at router (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:47:12)
Ответ №1:
function checkNotAuthenticated(req, res, next) { if (req.isAuthenticated()) { return res.redirect('/') } next() }
поместите эту функцию промежуточного программного обеспечения в нижней части вашего сценария непосредственно перед
module.exports = router;