Passport.js local Strategy returning error 'Missing credentials'

Asked

Viewed 46 times

0

I am trying to make a login system (authentication) using the Passport and the Express. However, it always goes back to the log page and returns the error Missing Credentials, I have tried to search the documentations, other sites too and I can’t do this authentication part. This is the code:

js router.:

const express = require('express')
const routes = express.Router()
const islogged = require('../../middleware/isLogged.js')
const User = require('../../models/User')
const UserController = require('./UserController.js')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy

passport.serializeUser(function(user, done) {
    done(null, {id: user.id, name: user.name, email: user.email, tel: user.cellphone, is_staff: is_staff})
})

passport.deserializeUser(function(user, done){
    done(null, {id: user.id, name: user.name, email: user.email, tel: user.cellphone, is_staff: is_staff})
})

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password1'
    },
    function(email, password, done){
        User.findOne({where: {email: email}}).then((user) => {

            if (user != undefined) {
                if (password == user.password) {
                    let correct = bcrypt.compareSync(password, user.password)
                } else {
                    req.flash('error', 'Senha incorreta.')
                    return done(null, false, {message: 'Senha incorreta.'})
                }
            } else {
                req.flash('error', 'Conta não encontrada.')
                return done(null, false, {message: 'Conta não encontrada.'})
            }
            return done(null, user)
        }).catch(err => done(err))
    }
))


routes.get('/register', UserController.register)
routes.post('/create-user', UserController.create)

routes.get('/login', UserController.login)
routes.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/register',
    failureFlash: true
}))
routes.get('/logout', UserController.logout)

module.exports = routes

Usercontroller.js (where the registry is configured)

const sequelize = require('sequelize')
const bcrypt = require('bcryptjs')
const User = require('../../models/User')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password1'
},

async function(email, password, done) {
    var user = await User.findOne(
        { where: {
            email: email
        }
    })
    if (user == null) {
        return done(null, false, { message: 'O email está incorreto.' });
    }
    if (!user.validPassword(password)) {
        return done(null, false, { message: 'A senha está incorreta.' });
    }
    return done(null, user)
}
))

function isValidPassword(password) {
    if (password.length >= 6) {
        return true
    }
    return false
}

function isValidEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(String(email).toLowerCase())
}

module.exports = {
    
    async register(req, res){
        res.render('users/register', { message: req.flash('error') })
    },

    async create(req, res){
        const { name, email, is_staff, tel, password1, password2 } = req.body

        if (!isValidEmail(email)) {
            req.flash('error', 'O endereço de e-mail não está formado corretamente.')
            return res.redirect('/register')
        }

        if (!isValidPassword(password1)) {
            req.flash('error', 'A senha deve ter 6 ou mais caracteres.')
            return res.redirect('/register')
        }

        if (password1 !== password2){
            req.flash('error', 'A senha não é igual.')
            return res.redirect('/register')
        }

        User.findOne({where: {email: email}}).then((user) => {
            if (user == undefined){
                let salt = bcrypt.genSaltSync(10)
                let hash = bcrypt.hashSync(password1, salt)

                User.create({
                    name: name, email: email, cellphone: tel, is_staff: is_staff, password: hash 
                }).then(() => {
                    return res.redirect('/login')
                }).catch((err) => {
                    res.flash('error', err)
                    return res.redirect('/register')
                })

            }
        })  
    }```
  • The password field in my frontend is called password1 itself and the body-parser ta configured, forgot to put in the question

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.