I understand that this question has been asked on here before, but the answers on those questions haven't helped me at all.
After the successful authentication of my user through passport with the "#oauth-everything/passport-discord" strategy, req.user is still undefined.
Here is the code in my main file,
// Modules
const compression = require("compression"),
cookieParser = require("cookie-parser"),
cors = require("cors"),
express = require("express"),
exphbs = require("express-handlebars"),
session = require("express-session"),
logger = require("morgan"),
path = require("path"),
createError = require("http-errors"),
mongoose = require("mongoose"),
debug = require("debug"),
flash = require("connect-flash"),
passport = require("passport");
// Local files
const setupPassport = require("./src/setupPassport");
// Passport
setupPassport(passport);
// Mongoose
mongoose.connect("mongodb://localhost/website", {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
debug("sb:mongoose")("Successfully connected to mongodb.");
}).catch(e => {
debug("sb:mongoose")("Unable to connect to mongodb\n" + e);
});
// Routers
const indexRouter = require("./routes/index");
const loginRouter = require("./routes/login");
// App setup
const app = express();
app.set("views", path.join(__dirname, "views/pages"));
// View engine
app.engine("hbs", exphbs({
defaultLayout: "user",
layoutsDir: "./views/layouts/",
partialsDir: "./views/parials/",
extname: "hbs"
}));
app.set("view engine", "hbs");
// Middleware
app.use(logger("dev"));
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
secret: "replace with env secret",
resave: false,
saveUninitialized: true,
cookie: {secure: true}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());
app.use(flash());
this is my setup passport file
const pprt = require("passport");
const { Strategy, Scope } = require("#oauth-everything/passport-discord");
const User = require("../models/user");
/**
* #param {pprt} passport
*/
module.exports = (passport) => {
passport.serializeUser((user, done) => {
return done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
User.findById(id, (err, res) => {
if (err) return done(err);
return done(null, res);
});
});
passport.use(new Strategy(
{
clientID: "no",
clientSecret: "no way",
callbackURL: "http://localhost:3000/login/auth/callback",
scope: [Scope.EMAIL, Scope.IDENTIFY]
},
(accessToken, refreshToken, profile, cb) => {
User.findOne({user_id: profile.id}, (err, res) => {
if (err) return cb(err);
if (!res) {
let newUser = new User({
user_id: profile.id,
username: profile.username,
displayName: profile.displayName,
email: profile.emails[0].value,
verified: profile.emails[0].verified,
tokens: {
access: accessToken,
refresh: refreshToken
}
});
newUser.save().then(user => {
cb(null, user);
});
} else {
res.updateOne({
user_id: profile.id,
username: profile.username,
displayName: profile.displayName,
email: profile.emails[0].value,
verified: profile.emails[0].verified,
tokens: {
access: accessToken,
refresh: refreshToken
}
}, (err, user) => {
if (err) return cb(err);
cb(null, user);
});
}
});
}
));
};
as i said req.user still returns undefined even after successful authentication does anyone have any idea why?
I should also mention that the user object is saved to mongodb perfectly which is why this perplexes me so much.
Related
I'm having some issues with setting up passport. The information gets to the console.log(req.body). and the user is being saved in the mongodb database with all the salting and hashing
passport.authenticate is not woking while signing up new users. but
and Express sessions are not being created.
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');
const session = require('express-session');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
cors({
origin: true,
credentials: true,
optionsSuccessStatus: 200
}));
mongoose.set("strictQuery", false);
app.use(session({
secret: "our little secret.",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/blogDB");
const userSchema = new mongoose.Schema(
{
name: String,
username: String,
password: String,
posts: [{
title: String,
content: String,
timestamp: Date
}]
}
);
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("user", userSchema);
passport.use(new LocalStrategy(User.authenticate()));
// passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post("/signup", function (req, res) {
User.register(
{ name:req.body.name,
username:req.body.email },
req.body.password,
function (err, user) {
if (err) {
console.log(err);
} else {
res.send(user);
passport.authenticate('local', function (err, user, info) {
if (!err) {
console.log("authenticated");
}
})(req, res)
}
})
})
i have been searching the whole web tring to find a solution, tried a so many solutions but nothing worked
I get an error TypeError: Cannot read property 'register' of undefined while attempting to register any user to the database using a post request via postman on route http:localhost:3000/signup, I searched for similar errors and tried the following:
1- installing and using bodyparser and using it on server.js
2- declaring express session before passport initialization and declaration of passport.session
and i use body to pass json data to the route on postman enter image description here
/backend/routes/signup.js
const router = require("express").Router();
const passport = require("passport");
const User = require("../models/users").default;
router.route("/signup").get((req, res) => {
res.render("/signup");
});
router.route("/signup").post((req, res) => {
const registeredUser = {
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
email: req.body.email
}
User.register(registeredUser, req.body.password, function(err, user) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function() {
res.json("User registered");
res.redirect("/notes/:username");
// redirect user or do whatever you want
});
}
// Value 'result' is set to false. The user could not be authenticated since the user is not active
});
});
// const newUser = new User({
// firstName,
// lastName,
// username,
// email,
// password
// });
// newUser.save()
// .then(() => res.json("User " + username + " is registered to database!"))
// .catch(err => res.status(400).json("Error" + err
module.exports = router;
/backend/server.js
//jshint esversion:6
const express = require("express");
const cors = require("cors");
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const User = require("./models/users");
const Note = require("./models/notes");
const notesRouter = require("./routes/notes");
const registerRouter = require("./routes/signup");
const loginRouter = require("./routes/signin");
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
app.set('view engine', 'ejs');
app.use( bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(require("express-session")({
secret:"This is keeper clone",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true});
mongoose.set("useCreateIndex", true);
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDb database connection established successfully");
});
app.use("/", notesRouter);
app.use("/", registerRouter);
app.use("/", loginRouter);
app.listen(port, () => {
console.log("Server is running on port 3000!");
});
/backend/models/users.js
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
email: {
type: String,
required: true,
unique: true,
trim: true,
},
password: {
type: String,
required: true,
minlength: 8
},
googleId: {
type: String
}
},
{
timestamps: true,
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
module.exports = User;
I have previously used the same approach in another project and it worked fine for me
//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require("passport-facebook").Strategy;
const findOrCreate = require('mongoose-findorcreate');
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: "Our little secret.",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema ({
email: String,
password: String,
googleId: String,
facebookId: String,
secret: String
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
passport.use(new FacebookStrategy({
clientID: process.env.APP_ID,
clientSecret: process.env.APP_SECRET,
callbackURL: "http://localhost:3000/auth/facebook/secrets"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ facebookId: profile.id }, function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}
));
app.get("/", function(req, res){
res.render("home");
});
app.get("/auth/google",
passport.authenticate('google', { scope: ["profile"] })
);
app.get("/auth/google/secrets",
passport.authenticate('google', { failureRedirect: "/login" }),
function(req, res) {
// Successful authentication, redirect to secrets.
res.redirect("/secrets");
});
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/secrets',
passport.authenticate('facebook', { successRedirect: '/secrets',
failureRedirect: '/login' }));
app.get("/login", function(req, res){
res.render("login");
});
app.get("/register", function(req, res){
res.render("register");
});
app.get("/secrets", function(req, res){
User.find({"secret": {$ne: null}}, function(err, foundUsers){
if (err){
console.log(err);
} else {
if (foundUsers) {
res.render("secrets", {usersWithSecrets: foundUsers});
}
}
});
});
app.get("/submit", function(req, res){
if (req.isAuthenticated()){
res.render("submit");
} else {
res.redirect("/login");
}
});
app.post("/submit", function(req, res){
const submittedSecret = req.body.secret;
//Once the user is authenticated and their session gets saved, their user details are saved to req.user.
// console.log(req.user.id);
User.findById(req.user.id, function(err, foundUser){
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.secret = submittedSecret;
foundUser.save(function(){
res.redirect("/secrets");
});
}
}
});
});
app.get("/logout", function(req, res){
req.logout();
res.redirect("/");
});
app.post("/register", function(req, res){
User.register({username: req.body.username}, req.body.password, function(err, user){
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
});
});
app.post("/login", function(req, res){
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, function(err){
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});
you use register function of User Model
User.register(registeredUser, req.body.password, function(err, user)
but you don't defined it, for defined register method in mongoose, you can use this documentation or use static method in mognoose
I have solved it by just removing .default from the User import statement in route file
const User = require("../models/users").default;
const User = require("../models/users");
I am using node.js express with sequelize and database postgreSql.the problem is in passport login failureRedirect works properly sucessRedirect does not redirect to the page that I want. It still loading and not responding anything and does not come any error.
when I submit login it will check for errors if errors it will work perfectly in failureRedirect but in Success it does not work like page has loading only not goes to the destination page and if I stop the project and restart the project it will be in destination page!! i dont know what is the problem help me.
mainController.js
const express = require("express");
const sessions = require("express-session");
require("../model/MasterUser.model");
const passport = require("passport");
var session = sessions;
const router = express.Router();
router.get("/dashboard", (req, res) => {
res.render('dashboard');
});
router.get("/login", (req, res) => {
res.render("login", { layout: "login.hbs" });
});
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/main/dashboard",
failureRedirect: "/main/login",
failureFlash: true,
})
);
module.exports = router;
passport.js
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");
const sequelize = require("sequelize");
const masterUser = require("../model/MasterUser.model");
module.exports = function (passport) {
passport.use(
new LocalStrategy(
{ usernameField: "user_name" },
(user_name, password, done) => {
// Match user
masterUser.findOne({ where: { user_name: user_name } }).then((user) => {
if (!user) {
return done(null, false, {
message: "This username is not registered",
});
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: "Password incorrect" });
}
});
});
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
index.js
const express = require("express");
const Handlebars = require("handlebars");
var flash = require("connect-flash");
const app = express();
const path = require("path");
const bodyparser = require("body-parser");
const expressHandlebars = require("express-handlebars");
const passport = require("passport");
const sessions = require("express-session");
var session = sessions;
const MainController = require("./controllers/MainController");
const db = require("./config/database");
//test db
db.authenticate()
.then(() => console.log("Database Connected..."))
.catch((err) => console.log("error" + err));
//for security purpose
const cors = require("cors");
app.use(
cors()
);
//Passport Config
require("./config/passport")(passport);
app.use(cookieParser());
//use body parser
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
const {
allowInsecurePrototypeAccess,
} = require("#handlebars/allow-prototype-access");
app.use(
bodyparser.urlencoded({
urlencoded: true,
})
);
app.use(
sessions({
secret: "secret_key",
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
})
);
// use flash for show messages
app.use(flash());
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
//flash messages
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
//setting up view Engine
app.set("views", path.join(__dirname, "/views"));
//using the hbs
app.engine(
"hbs",
expressHandlebars({
extname: "hbs",
defaultLayout: "default",
layoutsDir: __dirname + "/views/layouts",
handlebars: allowInsecurePrototypeAccess(Handlebars),
})
);
app.set("view engine", "hbs");
//route for Main
app.use("/main", MainController);
//default
app.get("/", (req, res) => {
res.render("login");
});
app.listen(3000, () => {
console.log("App listening on port 3000!");
});
the problem has been solved guys I made done wrong code in deserializeUser.
passport.js before
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
passport.js after
passport.deserializeUser(function (id, done) {
masterUser.findOne({ where: { id: id } }).then((user) => {
done(null, user);
});
});
the problem is for sequelize get the user data is different so now its worked for me.this is useful for who using express with sequelize and passport with postgresql
Currently a user can sign in with github, and i can see it gets the req.user in the callback function, and on passport github file
console.log(`frontid ${req.user.id}`) // logs user id
and passport
console.log(`backbro ${id}`); // logs an id
however, when i go on this route, the github user returns null and im not sure why. There were a few times, i see the signed in github user return in the current_user route, however its rare that i see it now. It sometimes shows, sometimes dont. Kinda wierd. Could it be a session issue ?
router.get("/current_user", (req, res) => {
if(req.user){
res.status(200).send({ user: req.user});
} else {
res.json({ user:null})
}
});
yes i looked at the following links, still no suitable answer.
Node + Express + Passport: req.user Undefined
req.user undefined after twitter authentication using express sever, passport.js
The way im accessing this link, is by explictily calling
localhost:8000/api/users/auth/github
in the address bar.
routes/users
router.get('/auth/github', passport.authenticate('github', {
scope:[ 'profile', 'id']
}));
router.get('/auth/github/callback',
passport.authenticate('github', { session:true, failureRedirect: 'http:localhost:8001/signIn' }),
function(req, res) {
// Successful authentication, redirect home.
// var token = jwt.sign({ id: req.user.id}, process.env.JWT_SECRET );
// // res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
// jwt.verify(token, process.env.JWT_SECRET, function(err, data){
// console.log(err, data);
// })
const user = req.user
req.logIn(user, err => {
models.User.findOne({
where: {
id: req.user.id,
},
}).then(user => {
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
// res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
jwt.verify(token, process.env.JWT_SECRET, function(err, data){
console.log(err, data);
})
res.redirect('http://localhost:8001');
// console.log(req.user)
});
});
console.log(`frontid ${req.user.id}`)
// res.redirect('')
// console.log('this works', token);
});
passport-github.js
const GitHubStrategy = require('passport-github2').Strategy;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const models = require("../models/");
// passport.serializeUser((user, done) => {
// // push to session
// done(null, user.id);
// console.log(user.id)
// });
// passport.deserializeUser((id, done) => {
// models.User.findOne({
// where: {
// id,
// },
// }).then(user => done(null, user))
// .catch(done);
// });
module.exports = async (passport) => {
passport.use(
new GitHubStrategy(
{
clientID: process.env.clientID,
clientSecret: process.env.secret,
callbackURL: 'http://127.0.0.1:8000/api/users/auth/github/callback',
passReqToCallback: true,
profileFields: ['id', 'login']
},
(req, accessToken, refreshToken, profile, done) => {
const { id, login, email} = profile._json;
console.log(`backbro ${id}`);
// console.log(req)
models.User.findOne({
where:{
id: id
}
}).then( user => {
// if user is found
if(user){
return done(null, user)
}
// else create new user
else{
models.User.create({
id: id,
username:login,
email: email,
createdAt: Date.now()
}).then( user => {
console.log('github user created');
return done(null, user);
})
}
})
}
)
);
passport.serializeUser((user, done) => {
// push to session
return done(null, user.id);
});
passport.deserializeUser((userId, done) => {
// console.log('calling deserial' + userId);
// // TODO: findByPk syntax? findById deprecated? Try later after sucessfully record data in DB
models.User
.findOne({ where: { id: userId } })
.then(function(user){
// console.log(user);
return done(null, userId);
}).catch(function(err){
done(err, null);
});
// return done(null, id);
});
}
app.js
const express = require('express');
const app = express();
const userRoute = require('./routes/users');
const postRoute = require('./routes/posts');
const bodyParser = require('body-parser');
const logger = require('morgan');
const session = require('express-session');
const cookieParser = require('cookie-parser') ;
const dotenv = require('dotenv');
const env = dotenv.config();
const cors = require('cors');
const models = require('./models/');
const host = '0.0.0.0';
const PORT = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
const Sequelize = require('sequelize');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const proxy = require('express-http-proxy');
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
app.use(cors({
origin: process.env.ALLOW_ORIGIN,
credentials: false,
allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}))
var sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD,{
"dialect": "sqlite",
"storage": "./session.sqlite"
});
myStore = new SequelizeStore({
db:sequelize,
})
if (!process.env.PORT) {
require('dotenv').config()
}
// console.log(process.env.DATABASE_URL);
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
// We need a store in order to save sessions, instead of the sessions clearing out on us :)
require('./config/passport')(passport); // PASSPORT Init
require('./config/passport-github')(passport); // PASSPORT Init
app.use(cookieParser());
app.use(bodyParser.json());
app.use(session({
store: myStore,
saveUninitialized: false,
resave:false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
secret : process.env.JWT_SECRET,
}));
myStore.sync();
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false}));
// this code may be useless or useful, still trying to understand cors.
app.use('/api/users', userRoute );
app.use('/api/posts', postRoute );
// In order to use REACT + EXPRESS we need the following code, alone with a build
// in the client folder we run a npm run build in the client folder then it is referred
// in the following code.
app.use(express.static(path.join(__dirname, 'client/build')));
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
//
app.get('*', (req, res) => {
res.sendfile(path.join(__dirname = 'client/build/index.html'));
})
}
//build mode
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+'/client/public/index.html'));
})
models.sequelize.sync().then(function() {
app.listen(PORT, host, () => {
console.log('[api][listen] http://localhost:' + PORT)
})
})
This is my first time doing user authentication and I think I'm nearly complete. I'm using Express with Passport.js and MongoDB/Mongoose. When I run my gulp file everything loads correctly but when I attempt to login with my credentials I'm constantly redirected to the failure page (home screen). Here's my code:
// Initialize
const bodyParser = require('body-parser')
const path = require('path')
const bcrypt = require('bcryptjs')
const express = require('express')
const session = require('express-session')
const cookieParser = require('cookie-parser')
const passport = require('passport'),
LocalStrategy = require('passport-local').Strategy
let userData = require('./models/user.js')
const app = express()
// Configuration
app.use(cookieParser())
app.use(session({ secret: 'ThisIsTheSessionSecret', resave: true, saveUninitialized: true }))
app.use(passport.initialize())
app.use(passport.session())
app.use(express.static(path.join(__dirname, '../../docs')))
app.use(express.static(path.join(__dirname, '../../src')))
app.set('port', process.env.PORT || 8080);
app.set('view engine', 'pug')
app.set('views', 'src/pages')
let urlencodedParser = bodyParser.urlencoded({ extended: false })
// Configure authentication and sessions
passport.use(new LocalStrategy(
function(username, password, done) {
user.findOne({ username: username }, function(err, user) {
if (err) { console.log(err) }
if (!user) {
return done(null, false, { message: 'Incorrect username.' })
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' })
}
return done(null, user)
})
}
));
// Session
passport.serializeUser(function(user, done) {
done(null, user.id)
});
passport.deserializeUser(function(id, done) {
user.findById(id, function(err, user) {
done(err, user)
})
})
app.listen(app.get('port'))
console.log('Listening on port: ' + app.get('port'))
// Initialize database (local or remote?)
const MongoClient = require('mongodb').MongoClient,
mongoose = require('mongoose'),
assert = require('assert')
const database = 'mongodb://localhost:27017/database'
mongoose.connect(database)
let db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error'))
db.once('open', function() {
// let testUser = new userData.UserModel({ username: 'PodcatchUser', password: 'RIPHarambe' })
// console.log(testUser.username)
})
// Routing
app.get('/', function(req, res) {
console.log('Welcome!')
res.render('index')
})
// Registration
app.post('/signup', urlencodedParser, function(req, res) {
let username = req.body.username,
password = req.body.password,
salt = bcrypt.genSaltSync(10),
hash = bcrypt.hashSync(password, salt)
let user = new userData.UserModel({
username: username,
password: hash
})
console.log(user.username)
console.log(user.password)
user.save(function(err) {
if (err) {
return console.log(err, user)
} else {
console.log('User has been saved to the database successfully')
}
})
res.end()
})
// Login
app.post('/login', passport.authenticate('local', { successRedirect: '/success',
failureRedirect: '/' }), function(req, res) {
res.end()
})
and the code in the userData module:
const mongoose = require('mongoose')
let UserSchema = mongoose.Schema({
username: String,
password: String
})
let UserModel = mongoose.model('UserModel', UserSchema)
module.exports.UserSchema = UserSchema
module.exports.UserModel = UserModel
I'm really confused as to what's happening. Mongo saves the credentials and hashed password to the database, I create a session and have a cookie parser but it doesn't authenticate. Help would be greatly appreciated :)