Im trying to display flash messages from passport.js but for some reason they are not showing - It is however showing "credentials not found" (but thats not the error message i want)
The code below - App,config and ejs (respectively)
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
app.set('view engine', 'ejs')
const initializePassport = require('./passport-config')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const accounts = [
]
app.use(passport.initialize())
initializePassport(passport, accounts.find(user => user.email === email))
app.use(express.urlencoded({ extended: true }))
app.use(passport.session())
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}))
app.use(flash())
app.get('/login', (req, res) => {
res.render('login')
})
app.post('/login', passport.authenticate(('local'), {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}))
app.get('/register', (req, res) => {
res.render('register')
})
app.post('/register', async (req, res) => {
const { name, email, password } = req.body
accounts.push({ id: Date.now().toString(), name, email, password: await bcrypt.hash(password, 10) })
console.log(accounts);
res.render('login')
})
app.listen(3000, () => {
console.log('server is running ');
})
//////////
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const initializePassport = (passport, getUserByEmail) => {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, { message: "email is not on our db" })
}
try {
if (await bcrypt.compare(password), user.password) {
return done(null, user)
} else {
return done(null, false, { message: 'wrong password ' })
}
} catch (error) {
return done(error)
}
}
passport.use(new LocalStrategy(({ usenameField: 'email' }), authenticateUser))
}
module.exports = initializePassport
//////////
<h1>Login</h1>
<% if(messages.error){ %>
<p><%=messages.error%></p>
<% } %>
<form action="/login" method="POST">
<label for="email">email</label>
<input id="email" name="email" type="text">
<label for="password">password</label>
<input id="password" name="password" type="text">
<button>Log in</button>
</form>
<p> register</p>
Can anyone see the issue? I am following a tutorial and this seems to match exactly with his code
The documentation states that it requires cookieParser in order to work. I would add the following to your file:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Documentation: https://github.com/RGBboy/express-flash#usage
You could also potentially look at the source project for this extension called connect-flash. There is a wealth of information on implementing this package which should transfer well to the express-flash extension.
Working example: https://gist.github.com/vesse/9e23ff1810089bed4426
Related
Working with Registration in a Site. For the register Form,Validation is done using mongoose models and trying to Use Flash to display the error message in the Form.
In my nodejs app it shows an error like:
TypeError: req.flash is not a function
I have installed connection-flash npm it is throwing an error like:
TypeError: req.flash is not a function at
E:\node-course\apnadukan\src\routes\index.js:21:24
app.js
const express = require('express');
const path = require('path');
const hbs = require('hbs');
const flash = require("connect-flash");
const passport = require("passport");
const db = require('./connection/db');
// Express Use
const app = express()
const port = 3000;
// Form Data Get
app.use(express.json());
app.use(express.urlencoded({extended:false}));
// HBS Handlebar use
app.set('view engine', 'hbs');
// Router Use
app.use('/', require(path.join(__dirname, 'routes/index.js')))
// Publics assess link (HBS)
const static_path = path.join(__dirname, '../publics');
app.use(express.static(static_path));
// View Set (HBS)
const views = path.join(__dirname, '../src/views');
const partials_path = path.join(__dirname, '../src/views/partials');
app.set('views', views);
hbs.registerPartials(partials_path);
//
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
index.js
const express = require('express');
const addUser = require('../models/register');
let passport = require("passport");
let LocalStrategy = require("passport-local").Strategy;
// const passport = require('../config/passport');
const {validationRegister, validationRegisterMsg} = require('../config/validator');
// const router = express.Router()
const router = require('express').Router()
router.get('/' , (req , res)=>{
res.render('index', {
title: "Welcome To Apna Dukan"
})
})
router.get('/welcome-to-apnadukan', (req , res)=>{
var errorMsg = req.flash('error')[0];
res.render('register', {
title: "Register | Welcome To Apna Dukan",
errorMsg,
page_name: "Register"
});
});
router.post('/welcome-to-apnadukan',
[
validationRegister(),
validationRegisterMsg,
passport.authenticate("local.register", {
successRedirect: "/login",
failureRedirect: "/welcome-to-apnadukan",
failureFlash: true,
}),
],
async (req , res)=>{
try {
if (req.session.oldUrl) {
let oldUrl = req.session.oldUrl;
req.session.oldUrl = null;
res.redirect(oldUrl);
} else {
res.redirect("/welcome-to-apnadukan");
}
} catch (error) {
req.flash("error", error.message);
res.status(400).send(error);
return res.redirect("/");
}
})
router.get('/login' , (req , res)=>{
res.render('login', {
title: "Login | Welcome To Apna Dukan",
page_name: "Login"
})
})
router.post('/login' , (req , res)=>{
req.send("Update");
})
router.get('/recover-password', (req, res)=>{
res.render('recoverpassword',{
title: "Recover Password | Welcome To Apna Dukan",
page_name: "Recover Password"
})
})
router.post('/recover-password', (req, res)=>{
res.render('recoverpassword',{
title: "Recover Password | Welcome To Apna Dukan",
page_name: "Recover Password"
})
})
router.get('/page' , (req , res)=>{
res.send('Hello World!')
})
module.exports = router
Validator.js
const { check, validationResult } = require("express-validator");
const validationRegister = (()=>{
return [
check('name', 'Name is required').not().isEmpty(),
check('username', 'Username is required').not().isEmpty().matches('/^(?![0-9]*$)[a-zA-Z0-9]+$/').withMessage('Only AlphaNumeric character is allowed').isLength({min:6,max:6}).withMessage('Minimum 6 characters required'),
check('email', 'Email is required').not().isEmpty().isEmail().withMessage('Email must be a valid email address.'),
check('password', 'Password is required').not().isEmpty().matches('/^(?=(.*[a-zA-Z].*){2,})(?=.*\d.*)(?=.*\W.*)[a-zA-Z0-9\S]{6,}$/').withMessage('Strong passwords with min 6 characters, at least two letters (not case sensitive), one number, one special character, space is not allowed'),
];
});
const validationRegisterMsg = (req, res, next)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
let messages = [];
errors.array().forEach((error)=>{
messages.push(error.msg)
});
req.flash('error', messages);
// req.flash({error: messages})
return res.redirect('/register');
}
next();
};
module.exports = {validationRegister,validationRegisterMsg};
passport.js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/register");
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
"local.register",
new LocalStrategy(
{
nameField: 'name',
usernameField: 'username',
emailField: 'email',
passwordField: 'password',
passReqToCallBack: true
},
async (req, username, email, done) => {
try {
const username = await Customer_users.findOne({ username: username });
if (username) {
return done(null, false, { message: "Username already exists" });
}
const user = await Customer_users.findOne({ email: email });
if (user) {
return done(null, false, { message: "Email already exists" });
}
const newUser = await new User();
newUser.name = name;
newUser.username = username;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
await newUser.save();
return done(null, newUser);
} catch (error) {
console.log(error);
return done(error);
}
}
)
);
You are configuring flash in your app after configuring the routes.
Moving this line app.use(flash()); before line app.use('/', require(path.join(__dirname, 'routes/index.js'))); will resolve the issue.
I'm serving my login form but for some reason can't POST to login and actually log in. I think it has something to do with my route folders, but I've tried several iterations of the routing and can't seem to figure it out. I keep receiving error POST http://localhost:3000/login 404 (Not Found).
My app runs on port 3000.
CRUD path: "Routes" folder-> artists.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const Artist = require('../models/artist');
const catchAsync = require('../utils/catchAsync');
const ExpressError = require('../utils/ExpressError');
/* lists artists from database */
router.get('/', async (req, res) => {
const artists = await Artist.find({});
res.render('artists/index', { artists })
});
router.get('/new', (req, res) => {
res.render('artists/new');
});
router.get('/login', (req, res) => {
res.render('artists/login');
})
/* shows specific artists that exist in database */
/* link - show.ejs */
router.get('/:id', catchAsync(async(req, res,) => {
const artist = await Artist.findById(req.params.id);
if (!artist) {
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
}
res.render('artists/show', { artist });
}));
/* artist edits form*/
router.get('/:id/edit', catchAsync(async (req, res) => {
const artist = await Artist.findById(req.params.id);
if (!artist) {
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
}
res.render('artists/edit', { artist });
}))
router.put('/:id', catchAsync(async (req, res) => {
const { id } = req.params;
const artist = await Artist.findByIdAndUpdate(id, { ...req.body.artist });
res.redirect(`/artists/${artist._id}`);
}))
/* creating a new artist */
router.post('/new', catchAsync(async(req, res) => {
try {
const { email, username, password, location, genre, about, size } = req.body;
const artist = new Artist({ email, username, location, genre, about, size });
const registeredArtist = await Artist.register(artist, password);
req.flash('success', 'Successfully signed up!');
res.redirect(`/artists/${artist._id}`)
} catch (e) {
req.flash('error', 'Sorry, an artist with that email already exists');
res.redirect('/artists');
}
}));
/** Where I'm encountering my error **/
router.post('/login', passport.authenticate('local', { failureFlash: true, failureRedirect: '/login' }), (req, res) =>{
req.flash('success', 'Welcome back!');
res.redirect('/artists');
})
/* delete a post */
router.delete('/:id', catchAsync(async (req, res) => {
const{ id } = req.params;
await Artist.findByIdAndDelete(id);
res.redirect('/artists');
}))
router.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404))
})
router.use((err, req, res, next) => {
const { statusCode = 500, message = 'Something went wrong' } = err;
res.status(statusCode).render('error');
})
module.exports = router;
Here's the ejs form w/ path: "Views" folder-> "artists" folder-> login.ejs
<% layout('layouts/boilerplate')%>
<div class="container d-flex justify-content-center align-items-center mt-5">
<div class="row">
<div class="col-md-6 offset-md-3 col-xl-4 offset-xl-4">
<div class="card shadow">
<img src="https://images.unsplash.com/photo-1571863533956-01c88e79957e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1267&q=80"
alt="" class="card-img-top" />
<div class="card-body">
<h5 class="card-title">Login</h5>
<form action="/login" method="POST" class="validated-form" novalidate>
<div class="mb-3">
<label class="form-label" for="artist[username]">Username</label>
<input class="form-control" type="text" id="artist[username]" name="artist[username]" required autofocus>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label class="form-label" for="artist[password]">Password</label>
<input class="form-control" type="password" id="artist[password]" name="artist[password]" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<button class="btn btn-success btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
Below is my app.js to display all routes. I also have "users" and "events". Only Users and Artists can login.
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const ejsMate = require('ejs-mate');
const catchAsync = require('./utils/catchAsync');
const methodOverride = require('method-override');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const session = require('express-session');
const Artist = require('./models/artist');
const Event = require('./models/event');
const User = require('./models/user');
const flash = require('connect-flash');
const eventRoutes = require('./routes/events');
const userRoutes = require('./routes/users');
const artistRoutes = require('./routes/artists');
const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/macro-tickets';
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express();
app.engine('ejs', ejsMate);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
/* method override allows to serve put requests into the database */
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
const sessionConfig = {
secret: 'thisshouldbeabettersecret!',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(flash());
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.use(new LocalStrategy(Artist.authenticate()));
passport.serializeUser(User.serializeUser());
passport.serializeUser(Artist.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.deserializeUser(Artist.deserializeUser());
app.use('/events', eventRoutes)
app.use('/users', userRoutes);
app.use('/artists', artistRoutes)
app.listen(3000, () => {
console.log('Serving on port 3000')
})
The form is POSTing to '/login' but nothing is going through. Any ideas what I'm doing wrong?
If to use this router you are calling it with
app.use("/your-route", require("../routes/artists.js")
the correct address would be http://localhost:3000/your-route/login.
In your case it seems I can think what you do:
app.use("/artists", require("../routes/artists.js")
then the post request would be http://localhost:3000/artists/login.
You can try this,
Update this in your app.js file
app.use(require('./routes/artists'))
then your request link will be like http://localhost:3000/login
I am using the following dependencies:
express session
passport
passport-local
passport-local-mongoose
When I try to register a user and they post the data. The data get saved to the database but it give a bad request. Also when I try to use req.user.id in the Tweet.find() it gives undefined and I also console.log(req.user) and it give me undefined. And once a error came that failed to serialize session one or two time. Can anybody help me. Here is some code sorry in advance if this is to much code as I was not sure that which part of the code was important.
//-----------------------//Require---------------------
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ejs = require("ejs");
const session = require("express-session");
const passport = require("passport");
const LocalStratagy= require("passport-local").Strategy;
const passportLocalMongoose = require("passport-local-mongoose");
const mongoose = require("mongoose");
//-----------------------//App.use---------------------
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
//-----------------------//Passport---------------------
app.use(passport.initialize());
app.use(passport.session());
//-----------------------//Mongoose---------------------
mongoose.connect('mongodb://localhost/Twitter', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
const tweetschema = new mongoose.Schema({
username: String,
password: String,
tweets: String
});
//-----------------------//Schema Plgin---------------------
tweetschema.plugin(passportLocalMongoose);
//-----------------------//New Model---------------------
const Tweet = new mongoose.model("Tweet", tweetschema);
//-----------------------//Local Strategy-------------------
passport.use(new LocalStratagy(Tweet.authenticate()));
//-----------------------//Seralize Passport---------------------
passport.serializeUser(function(user, done) {
console.log(user);
done(null, user.id);
});
//-----------------------//Desarlize Passport---------------------
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post("/tweets", bodyParser.urlencoded({extended: true}), (req, res)=>{
const Gottweets= req.body.tweet;
console.log(Gottweets);
console.log(req.user);
/* Tweet.findById(req.tweet.id, (err, foundUser)=>{
if(err){
console.log(err);
res.redirect("/tweets");
}else{
if(foundUser){
foundUser.tweets = Gottweets;
foundUser.save(()=>{
res.redirect("/");
})
}
}
})
*/
});
app.post("/regsiter",bodyParser.urlencoded({extended: true}), (req, res)=>{
console.log(req.body.email);
Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
if(err){
console.log(err);
res.redirect("/regsiter");
}else{
if(user){
passport.authenticate("local")(req, res, function(){
res.redirect("/regsiter");
})
}
}
})
});
<%- include('partials/header') %>
<form action="/regsiter" method="post" class="login">
<label for="emial" class="email">
Email
<input type="email" name="email" id="email">
</label>
<label for="password">
Password
<input type="password" name="password" id="password">
</label>
<div class="soicalLogin">
Facebook
Google
</div>
<button type="submit">Register</button>
</form>
<%- include('partials/footer') %>
You can try rewriting your POST /register endpoint with this example
app.post("/register",bodyParser.urlencoded({extended: true}), (req, res, next) => {
console.log(req.body.email);
Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
if(err){
console.log(err);
res.redirect("/regsiter");
return;
}
if(!user){ // also handle the case where user is undefined
return res.status(500).json({ yourMessage: 'error' });
}
next();
})
}, passport.authenticate("local", { successRedirect: '/', failureRedirect: '/register' }));
It's not a good idea to override the next function given to passport.authenticate("local")
Now the error should be gone, let me know if this code sample doesn't work.
Hope it helps
On my web site I stuck in the change password part.
I send an email to the user to change the password, on this link I pass a token on the URL to use is to find the user with findOne.
My problem is the following I was able to get the URL on the router.get but I cannot get it on router.post. I need too get it on router.post because I receive the password from the user on router.post.
Here is my code :
server.js
if(process.env.NODE_ENV !== 'production') {
const dotenv = require('dotenv')
dotenv.config();
}
const express = require('express')
const expressLayouts = require('express-ejs-layouts')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const dotenv = require('dotenv')
const app = express()
require('./passport-config')(passport);
const indexRouter = require('./routes/index')
const registerRouter = require('./routes/register')
const loginRouter = require('./routes/login')
const parentRouter = require('./routes/parent')
const animatorRouter = require('./routes/animator')
const confirmationRouter = require('./routes/confirmation')
const activateRouter = require('./routes/activate')
const cguRouter = require('./routes/cgu')
const confidentialiteRouter = require('./routes/confidentialite')
const lost_passwordRouter = require('./routes/lost_password')
const Change_passwordRouter = require('./routes/change_password')
app.set('view engine','ejs')
app.set('views', __dirname + '/views')
app.set('layout', 'layouts/layout')
app.use(expressLayouts)
app.use(express.static('public'))
app.use(express.json())
app.use(express.urlencoded({ extended : false }))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_URL, {
useNewUrlParser: true, useUnifiedTopology: true}).then(()=>{
console.log('Successfully connected to the mongoDB Atlas!')
}).catch((error)=>{
console.log('impossible to connect to the mondoDB Atlas !')
console.error(error);
});
app.use('/', indexRouter)
app.use('/register', registerRouter)
app.use('/login', loginRouter)
app.use('/animator', animatorRouter)
app.use('/parent', parentRouter)
app.use('/confirmation', confirmationRouter)
app.use('/activate', activateRouter)
app.use('/cgu', cguRouter)
app.use('/confidentialite', confidentialiteRouter)
app.use('/lost_password', lost_passwordRouter)
app.use('/change_password',Change_passwordRouter)
app.listen(process.env.PORT || 3000)
change_password.js
const express = require('express')
const router = express.Router()
const Users = require('../models/register')
router.get('/:token', async (req, res) =>{
let {token} = req.params
console.log(token)
let user = await Users.findOne({resetPasswordToken: token})
user.save()
console.log(user)
res.render('change_password/change_password')
res.send(token)
})
router.post('/', async (req, res)=>{
let {token} = req.params
console.log(token)
// const user = await Users.findOne({ Users.resetPasswordToken })
// console.log(user)
// console.log(user)
// user.password = req.body.password
// await user.save()
})
module.exports = router
change_password.ejs
<form action="/change_password" method="POST">
<div>
<label for="password">New Password</label>
<input type="password" name="password" id="password" required>
</div>
<button type="submit">Login</button>
lost_password.js
const express = require('express')
const router = express.Router()
const Users = require('../models/register')
const nodemailer = require('nodemailer');
const flash = require('express-flash')
const jwt = require('jsonwebtoken')
const secret = require('crypto').randomBytes(64).toString('hex')
router.get('/', (req, res) =>{
res.render('lost_password/lost_password', {message : req.flash('success')})
})
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '',
pass: ''
}
});
router.post('/', async (req,res)=>{
const user = await Users.findOne({email: req.body.email})
if(!user) {
return res.status(401).json({
success: false,
message: "This email do not exist in our base"
})
}
user.resetPasswordToken = jwt.sign({ email: user.email}, secret, { expiresIn: '1h'})
user.save()
req.flash('success', 'An e-mail has been sent to ' + user.email + ' with further instructions.')
console.log(user.resetPasswordToken)
const mailOptions = {
from: '',
to: user.email,
subject: 'Localhost activation link',
text: 'http://localhost:3000/change_password/'+ user.resetPasswordToken,
html:'link'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.redirect('/lost_password')
})
module.exports = router
lost_password.ejs
<h1>Lost Password</h1>
<form action="/lost_password" method="POST">
<div>
<label for="email">Indiquez votre email</label>
<input type="email" name="email" id="email" required>
</div>
<button type="submit">Register</button>
</form>
<%= message %>
Thank you for your help.
Just change your
router.post('/')
with router.post('/:token')
I am making a authentication form were users can register and login.
if (process.env.Node_ENV !== 'production') {
require('dotenv').config()
}
const express = require('express');
const app = express();
const bcrypt = require('bcrypt')
const passport = require("passport")
const flash = require("express-flash")
const sessions = require("express-session")
const methodOverride = require("method-override")
const fs = require('fs')
const initializePassport = require("./passport-config")
initializePassport(
passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
)
const users = []
app.set("view-engine", "ejs")
app.use('/public', express.static('public'))
app.use(express.urlencoded({extended: false}))
app.use(flash())
app.use(sessions({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.get("/", checkAuthenticated, (req,res)=> {
res.render("index.ejs", { name: req.user.name})
})
app.get("/login", checkNotAuthenticated, (req, res) => {
res.render("login.ejs")
})
app.post("/login", checkNotAuthenticated, passport.authenticate('local', {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}))
app.get("/register", checkNotAuthenticated, (req,res)=> {
res.render("register.ejs")
})
app.post("/register", checkNotAuthenticated, async (req,res) => {
try{
//encrypt the Uses password, so "we" cant see it
const hashedPassword = await bcrypt.hash(req.body.password, 10)
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
})
//if all the above is right, than redirect the user to login page
res.redirect("/login")
}catch{
//if for some reason there is a failure, redirect back to register
res.redirect("/register")
}
//if there is user that is added, it is possible to see ind the console
//console.log(users)
localStorage.setItem('user', JSON.stringify(users));
})
app.delete('/logout', (req,res) => {
req.logOut()
res.redirect('/login')
})
function checkAuthenticated(req, res, next){
if (req.isAuthenticated()) {
return next()
}
res.redirect('/login')
}
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return res.redirect('/')
}
next()
}
The problem is that I need to implement localStorage, and the user needs to be able to delete the account once they are logged in.
To register the user only needs "Name", "email" and "password"
here is some of my passport-config if necessary:
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require("bcrypt")
function initialize(passport, getUserByEmail, getUserById){
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, {message: "No user with that Email"})
}
try{
if(await bcrypt.compare(password, user.password)) {
return done(null, user)
} else{
return done(null, false, {message: "Passwrod incorrect"})
}
}catch(error){
return done(error)
}
}
passport.use(new LocalStrategy({usernameField: 'email'}, authenticateUser))
passport.serializeUser((user,done) => done(null, user.id))
passport.deserializeUser((id,done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize;
Everything works fine, so there is no error in the code it's self, I just don't seem to find an answer to what I need to do anywhere, I can only find mongoDB which I don't want to use. The most important for me is to implement the localStorage, then it comes the delete part.
I hope some of you can help me!
Thanks a lot.