Мой метод deserializeUser никогда не выполняется. Я также использую прокси-сервер, расширение CORS, а также инициализировал cors внутри моего узла сервера. Я дам вам здесь весь код из 3 файлов:
Первый, сам сервер:
// Imports
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const cors = require('cors');
const passport = require('passport');
require('./lib/passport');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const MySQLStore = require('express-mysql-session');
const { database } = require('./keys');
// Initialitzations
const app = express();
// Settings
app.set('port', process.env.PORT || 4000);
// Middlewares
app.use(morgan('dev'));
app.use(cors());
app.use(express.json());
app.use(cookieParser())
app.use(session({
secret: 'keyboardcat',
resave: false,
saveUninitialized: false,
store: new MySQLStore(database)
}))
app.use(passport.initialize());
app.use(passport.session());
// Globar Variables
app.use((req, res, next) => {
app.locals.user = req.user;
next();
})
// Routes
app.use(require('./routes'))
// Public
app.use(express.static(path.join(__dirname, 'public')))
// Starting the server
const server = app.listen(app.get('port'), () =>
console.log('Server on port', app.get('port'))
)
const pool = require('./database');
Второй файл, мой /routes/index.js:
const express = require('express');
const router = express.Router();
const path = require('path')
const passport = require('passport')
//Ruta de register per guardar usuari
router.post('/register', passport.authenticate('local.signup', {
successRedirect: 'http://localhost:3000/Help',
failureRedirect: 'http://localhost:3000/Reg',
failureFlash: true
}))
//Ruta de login per validar la autentificació de l'usuari
router.post('/login', async (req, res, next) => {
passport.authenticate('local.signin', {
successRedirect: 'http://85.56.163.142:3000/',
failureRedirect: 'http://85.56.163.142:3000/Reg',
failureFlash: true
})(req, res, next)
})
router.get('/api', (req, res, next) =>{
res.sendFile('index.html', { root: path.join(__dirname, '../public') });
})
module.exports = router;
Третий файл, паспорт. js файл:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const pool = require('../database')
const helpers = require('../lib/helpers')
let definitiveId;
passport.use('local.signin', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, async (req, email, password, done) => {
await pool.query('SELECT * FROM dades_user WHERE emailUser = ?', [email], async (err, res) => {
if (err){
console.log(err)
} else {
if (res.length > 0) {
const user = res[0]
const validPassword = await helpers.matchPassword(password, user.passwordUser);
if (validPassword){
await pool.query('SELECT idUser FROM usuari WHERE emailUser = ?', [email], (erro, resp) => {
if (erro){
console.log(erro)
} else {
definitiveId = resp[0].idUser
done(null, definitiveId)
console.log('Usuari logejat satisfactoriament')
}
})
} else {
done(null, false)
console.log('contrassenya incorrecta')
}
} else {
done(null, false)
console.log('No sha trobat lusuari')
}
}
});
}))
passport.use('local.signup', new LocalStrategy({
usernameField: 'emailUser',
passwordField: 'passwordUser',
passReqToCallback: true
}, async (req, emailUser, passwordUser, done) => {
const { nomUser } = req.body
const newUser = {
emailUser,
passwordUser,
nomUser
};
newUser.passwordUser = await helpers.encryptPassword(passwordUser)
await pool.query('INSERT INTO dades_user SET ?', [newUser], (err, res) => {
if (err){
console.log(err)
} else {
console.log('Dades de lusuari inserides')
}
})
await pool.query('INSERT INTO usuari(emailUser) VALUES(?)', [newUser.emailUser], (err, res) => {
if (err){
console.log(err)
} else {
console.log('Id de lusuari inserit en la bdd juntament amb email')
definitiveId = res.insertId
}
})
return done(null, definitiveId);
}));
passport.serializeUser((usr, done) => {
console.log('Serielized')
done(null, usr);
})
passport.deserializeUser( async (id, done) => {
console.log('hola mama XD')
await pool.query('SELECT * FROM usuari INNER JOIN dades_user ON usuari.emailUser = dades_user.emailUser WHERE idUser = ?', [id], (err, res) => {
if (err){
console.log('Unable to deserialize')
console.log(err)
} else{
console.log('Deserialized')
done(null, res[0])
}
});
})
Надеюсь, вы можете мне помочь, я потратил целый день на поиск проблемы. Я знаю, что большая часть поста - это код, но я просто старался быть максимально прямым.