Issue with passport module in Node js - node.js

i am trying to use passport in my Node js Login system which is working with mongodb.
I have included both passport module and Local strategy in my app.js file.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator=require('express-validator');
var cookieParser = require('cookie-parser');
var session= require("express-session");
var passport=require("passport");
var LocalStrategy=require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer=require("multer");
var flash=require('connect-flash');
var mongo=require('mongodb');
var mongoose=require('mongoose');
var db=mongoose.connection;
In users route file i have declared users
var express = require('express');
var router = express.Router();
var passport=require("passport");
var LocalStrategy=require('passport-local').Strategy;
var User=require('../models/users');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register',{
"title":'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login',{
"title":'Login'
});
});
router.post('/register', function(req, res, next){
//get the form values
var name = req.body.name;
var email= req.body.email;
var username= req.body.username;
var password= req.body.password;
var password2= req.body.password2;
//Check for image filed
if(req.files&&req.files.profileimage){
console.log('Uploading file....');
//File Info
var profileimageoriginalname =req.files.profileimage.originalname;
var profileimagename=req.files.profileimage.name;
var profileimageMime=req.files.profileimage.mimetype;
var profileimagePath=req.files.profileimage.path;
var profileimageExt=req.files.profileimage.extension;
var profileimageSize=req.files.profileimage.size;
}else{
//Set a default image
var profileimageName="noimage.png";
}
//Form Validation
req.checkBody('name',"nAME FILED IS REquiered").notEmpty();
req.checkBody('email',"email FILED IS REquiered").isEmail();
req.checkBody('username',"UsernamenAME FILED IS REquiered").notEmpty();
req.checkBody('password',"password FILED IS REquiered").notEmpty();
req.checkBody('password2',"password font marchjFILED IS REquiered").equals(req.body.password);
//Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors:errors,
name:name,
email:email,
username:username,
password:password,
password2:password2
});
}else{
var newUser=new User({
name:name,
email:email,
username:username,
password:password,
profileimage:profileimagename
});
//Create user
User.createUser(newUser,function(err,user){
if(err)throw err;
console.log(user);
});
//Sucess message
req.flash('success',"You are now registered and may login");
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user,done){
done(null,user.id);
});
passport.deserializeUser(function(id,done){
User.getUserbyId(id,function(err,user){
done(err,user);
});
});
passport.use(new LocalStrategy(
function(username,password,done){
User.getUserByUsername(username,function(err,user){
if(err) throw err;
if(!user){
console.log("Unknown user");
return done(null,false,{message:"unknown user"});
}
User.comparePassword(password,user.password,function(err,isMatch){
if(err) throw err;
if(isMatch){
return done(null,user);
}else{
console.log("invalid password");
return done(null,false,{message:"invalid passwors"});
}
});
});
}
));
router.post('/login',passport.authenticate('local',{failureRedirect:"/users/login/",failureFlash:"Wrong login or pass"}),function(req,res){
console.log("Authentication Successfully done");
req.flash('success',"You are loged in");
res.redirect('/');
});
module.exports = router;
And also i have created a module for my users login
var mongoose=require('mongoose');
var bcrypt=require('bcrypt');
mongoose.connect('mongodb://localhost/nodeAuth', { useMongoClient: true });
var db=mongoose.connection;
//User scheme
var UserSchema=mongoose.Schema({
usernam:{
type:String,
index:true
},
password:{
type:String,required:true,bcrypt:true
},
email:{
type:String
},
name:{
type:String
},
profileimage:{
type:String
}
});
var User=module.exports=mongoose.model('User',UserSchema);
module.exports.comparePassword=function(candidatePassword,hash,callback){
bcrypt.compare(candidatePassword,hash,function(err,isMatch){
if(err) return callback(err);
callback(null,isMatch);
});
}
module.exports.getUserById=function(id,callback){
User.findById(id,callback);
}
module.exports.getUserByUsername=function(username,callback){
var query={username:username};
User.findOne(query,callback);
}
module.exports.createUser=function(newUser,callback){
bcrypt.hash(newUser.password, 10,function(err,hash){
if(err)throw err;
//Set hashed password
newUser.password=hash;
//create User
newUser.save(callback)
});
}
But its'nt returning aboslutely nothing.
COuld anyone help?
I think it's mostly connected with passport module,but also i have absolutely nor errrors which i can debug.
I mongodb it's showing the whole of my databases.I am trying to log in with my login which is previously registered in my database and works fine but its'nt returning nothing.It's just refrashing the page.

Check out your schema:
//User scheme
var UserSchema=mongoose.Schema({
usernam:{
type:String,
index:true
},
...
It should be "usernamE" :)

Related

Level 1 authentication

Good day, Please help me find the error in my code for level one authentication I could create a database, register users and store in their inputs using body parser, but I couldn't login already registered users. the login page keeps loading till it tells me a connection error, please help me out
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const app = express();
app.use(express.static("public"));
app.set('view-engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
mongoose.connect("mongodb://localhost:27017/User", {useNewUrlParser: true});
const userSchema = ({
email: String,
password: String
});
const User = new mongoose.model("User", userSchema);
const users = []
app.get("/", function(req, res){
res.render("first.ejs");
});
app.get("/login", function(req, res){
res.render("login.ejs");
});
app.get("/register", function(req, res){
res.render("register.ejs");
});
app.post("/register", function(req, res){
const newUser = new User({
email: req.body.username,
password: req.body.password
});
newUser.save(function(err){
if (err) {
console.log(err);
} else {
res.render("home.ejs");
}
});
});
app.post("/login", function(req, res){
const username = req.body.username;
const password = req.body.password;
User.findOne({email: username}, function(err, foundUser){
if (err) {
console.log(err);
} else {
if (foundUser) {
if (foundUser.password === password) {
res.send("hi");
}
}
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});

How to generate token using passport.js while signing in locally and not with any other social media channel?

I am trying to generate token while logging in locally. Let's say I am normal user and want to sign in. Will token get generated while signing in? and how? Need guidance. Thanks
As I am using mongodb I require my users schema model in my routes code.Here is my routes code user.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/schema');
var Verify = require('./verify');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
When you look at the code you will notice a verify variable.It is nothing but verification that is user is registered or not.If user registered then user will allow for login.After login user will get a successfull response along with token.So here is my veirfy code verify.js
var User=require('../models/schema');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, {
expiresIn: 3600
});
};
exports.verifyOrdinaryUser = function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secretKey, function (err, decoded) {
if (err) {
var err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
var err = new Error('No token provided!');
err.status = 403;
return next(err);
}
};
If you observe the code there is a variable like config this is nothing but connection to my mongodb.Here is the code config.js
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/conFusion'
}
And the user schema is here schema.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{
type:String,
required:true,
unique:true
},
email:{
type:String,
required:true,
unique:true
},
phone:{
type:Number,
required:true,
unique:true
},
password:{
type:String
}
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
And finally server code app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var User = require('./models/schema');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000,function(){
console.log("Server Listening on 3000");
});
module.exports = app;
project structure must be as per my code
+app.js
+config.js
+routes(directory)
++user.js
++verify.js
+models(directory)
++schema.js
run the code node app.js
When you want to register use http://localhost:3000/users/register
and for login use http://localhost:3000/users/login

.save() not inserting a data into collection without showing errors in express js

.save function is not working without error its not inserting data into collection of a table. when i was inserting data into collection using mongodb command then data is inserting. I am also checking the mongoose connection it is working fine. when i am using else case in .save function then it will come in else condition but data is not inserting. model and routes code are bellow kindly help to resolve this issue.
var express = require('express');
var router = express.Router();
var User = require('../model/User');
var bcrypt = require('bcryptjs');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.render('register', {title: 'User registrations page !'});
});
router.get('/login', function(req, res, next){
res.render('login', {title: 'User Login page !'});
});
//Register process
router.post('/register', function (req, res) {
var name = req.body.fullname;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var newUser = new User();
newUser.name = name;
newUser.email = email;
newUser.username = username;
newUser.password = password;
newUser.save(function(err, savedUser){
if (err) {
console.log(err);
return res.status(500).send();
}
return res.status(200).send();
});
});
Creating a model user under the model folder which is including in users routes file
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
username:{
type: String,
required: true
},
password:{
type: String,
required: true
}
});
var user = mongoose.model('myuser', userSchema);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/userDet',{ useMongoClient: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(err) {
if (err) {
console.log('Connection error');
}
// we're connected!
else {
console.log('We are connected !');
}
});
module.exports = user;
#NiteshSingh when you want to get the data from html form you need to do parsing. Make sure that your html form tag action must be same with post route <form method="post" action="/register">. Try this code
var express = require('express');
var bodyParser = require('body-parser');
var mongoose=require('mongoose');
var User=require('../models/User');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var userRouter = express.Router();
userRouter.use(bodyParser.json());
userRouter.post('/register',urlencodedParser,function(req, res, next){
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.use('/register',userRouter);
module.exports = userRouter;
And you can follow this link https://medium.com/#ratracegrad/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073
Read this article from top to bottom. You will get an idea. Hope this helps...

How can I do Passport Authentication on multiple users?

Here I have multiple users like Parent,Trainer,Provider.I wrote individual schemas, routes and verify codes for registration and login and for storing, collections also different for each.when I make to run the application it is properly running.And after that I opened the postman tool I registered as" parent" the response is "Registration Successfull" and login as parent I am getting token so that I can perform the functions what a Parent can do in my project.And after that I logout as parent.Next, when I try to registered as Trainer/Provider the response is "Unauthorized". But the fields what I am giving at time of registration are stored in respective collections in database.When I give same values what a parent gave at the time of registration to trainer registration and provider registration then the response is "Registration Successfull" when I give different values other than what a parent gave it shows me "Unauthorized".So, I want to know why this issue arises? And how can I fix this problem?
Here is my schema code
<!-- trainer schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var trainerUser= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
trainerUser.plugin(passportLocalMongoose);
module.exports = mongoose.model('trainerUser', trainerUser);
<!-- parent schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User = new Schema({
username: String,
email:String,
password: String,
phonenumber:Number
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('parentlog', User);
<!-- provider schema -->
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var User= new Schema({
username:{type:String,required:true,unique:true},
email:{type:String,required:true,unique:true},
phone:{type:Number,required:true,unique:true },
password:{type:String});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',User);
Here is my routes code for each module
//trainer route
<!-- trainer route -->
var express = require('express');
var router = express.Router();
var passport = require('passport');
var trainerUser = require('../models/traineruser');
var Verify = require('./trainerverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
trainerUser.register(new trainerUser({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//parent route
const AuthenticationController = require('../controllers/authentication');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/puser');
var Verify = require('./parentverify');
var mongoose=require('mongoose');
const requireLogin = passport.authenticate('local', { session: false });
router.route('/')
.get(function(req, res) {
User.find({},function(err,users){
if(err) {
return res.status(403).json({
err: 'You are not authorized to perform this operation!'
});
} else {
res.json(users);
}
});
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email:req.body.email,phonenumber:req.body.phonenumber }),
req.body.password, function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', requireLogin, AuthenticationController.login);
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
//provider route
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user');
var Verify= require('./userverify');
<!-- GET users listing. -->
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/register', function(req, res) {
User.register(new User({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password,
function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({status: 'Registration Successful!'});
});
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
var token = Verify.getToken(user);
res.status(200).json({
status: 'Login successful!',
success: true,
token: token
});
});
})(req,res,next);
});
router.get('/logout', function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
and app.js code is here
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
<!-- we're connected! -->
console.log("Connected correctly to server");
});
var users = require('./routes/users');
var trainerusers = require('./routes/trainerusers');
var pusers = require('./routes/pusers');
var contacts=require('./routes/contactRouter');
var student=require('./routes/studentRouter');
var batch=require('./routes/batchRouter');
var venue=require('./routes/venueRouter');
var trainerrouter = require('./routes/trainerrouter.js');
var report=require('./routes/reportRouter');
var attendance=require('./routes/attendanceRouter');
var app = express();
<!-- view engine setup -->
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
<!-- uncomment after placing your favicon in /public-->
<!-- app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));-->
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
<!-- passport config -->
var User = require('./models/user');
var trainerUser = require('./models/traineruser');
var Puser = require('./models/puser');
app.use(passport.initialize());
passport.use(new LocalStrategy(Puser.authenticate(),trainerUser.authenticate(),User.authenticate()));
passport.serializeUser(Puser.serializeUser(),trainerUser.serializeUser(),User.serializeUser());
passport.deserializeUser(Puser.deserializeUser(),trainerUser.deserializeUser(),User.deserializeUser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', users);
app.use('/trainerusers', trainerusers);
app.use('/pusers', pusers);
app.use('/contacts',contacts);
app.use('/student',student);
app.use('/batch',batch);
app.use('/venue',venue);
app.use('/report',report);
app.use('/trainer',trainerrouter);
app.use('/attendance',attendance);
<!-- catch 404 and forward to error handler -->
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
<!-- error handlers -->
<!-- development error handler -->
<!-- will print stacktrace -->
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
<!-- production error handler -->
<!-- no stacktraces leaked to user -->
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;

express and socket.io authentication -- how do I retrieve the cookie/session info?

Preface: I'm new to node.js, express, socket.io and all of that. I realize my code is kinda messy and needs to be separated out into modules, etc -- but I've not done that yet because I was trying to get the authentication part working first. I have searched all over stackoverflow and other sites. I've found some promising examples, but I've just not been able to make it work.
I followed a couple of tutorials to create my express app which allows a user to register, login, and view their details. I also followed a tutorial which helped me make a basic socket.io chat. What I'm trying to do is combine them and have the user log in and then be redirected to the chat app. The problem I have is that when I redirect them, I have no way to know "who they are" on the socket.io side of things. Currently I've got it set up so you have to enter your name to chat -- I would like it to grab the info from the session and use that instead.
Currently when a user logs in, it does set a cookie (I can view it in the console). So I know the cookie is there. It also sets the info into the MongoStore. I've verified that as well with db.collection.find().
Here's the code that I have so far. If any of the experts out there could help me find a way to pass the session info over to socket.io, I would very much appreciate it!
var mongo = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var bcrypt = require('bcryptjs');
var csrf = require('csurf');
var path = require ('path');
var express = require('express');
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var session = require('express-session');
var moment = require('moment');
var now = moment().format('L');
var http = require('http');
var MongoStore = require('connect-mongo')(session);
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
UserSchema = new Schema({
//id: ObjectId,
firstName: String,
lastName: String,
username: {
type: String,
unique: true,
uniqueCaseInsensitive:true
},
password: String,
email: {
type:String,
unique: true,
uniqueCaseInsensitive:true
},
accountType: String,
accountStatus: String,
acctActivation:{
type:String,
unique:true
},
joinDate: String
});
UserSchema.plugin(uniqueValidator,{ message: 'Error, {PATH} {VALUE} has already been registered.\r' });
var User = mongoose.model('User', UserSchema);
var app = express();
app.engine('ejs', require('ejs').renderFile);
app.locals.pretty = true;
//connect to mongo
mongoose.connect('mongodb://localhost/myUserDb');
//create server
var server = http.createServer(app).listen(3000);
var client = require('socket.io')(server);
console.log('listening on port 3000');
//middleware
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
app.use(session({
secret: 'mysecret!',
resave:false,
saveUninitialized: false,
stringify:true,
store: new MongoStore({
url: 'mongodb://127.0.0.1/sid2'
})
}));
app.use(csrf());
app.use(function(req,res,next){ // check to see if user already has a session, if so, query mongodb and update the user object
if(req.session && req.session.user){
User.findOne({email: req.session.user.email}, function(err, user){
if(user){
req.user = user;
delete req.user.password; // remove password field from session
req.session.user = req.user;
res.locals.user = req.user;
}
next();
});
}else{
next();
}
});
function requireLogin(req,res,next){ // check to see if user is logged in, if not, boot em
if(!req.user){
res.redirect('/login');
}else{
next();
}
};
function requireAdmin(req,res,next){ // check to see if accountType = Developer (or admin later) - if not, send them to dashboard
if(req.user.accountType !== 'Developer'){
res.redirect('/dashboard');
}else{
next();
}
};
app.get('/', function(req, res){
if(req.user){
res.render('dashboard.ejs');
}else{
res.render('index.ejs');
}
});
app.get('/register', function(req,res){
res.render('register.ejs', {csrfToken: req.csrfToken(),
error:false});
});
app.post('/register', function(req,res){
var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10));
var user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
password: hash,
email: req.body.email,
accountType: 'Standard',
accountStatus: 'Active',
joinDate: now
});
user.save(function(err){
if(err){
console.log(err);
res.render('register.ejs', {csrfToken: req.csrfToken(),
error: err});
}else{
req.session.user = user;
res.redirect('/dashboard');
}
});
});
app.get('/login', function(req,res){
res.render('login.ejs', {
csrfToken: req.csrfToken(),error:false});
});
app.post('/login', function(req, res){
User.findOne({username: {$regex: new RegExp('^' + req.body.username, 'i')}}, function(err, user){
if(!user){
res.render('login.ejs', {error: 'Invalid username or password combination.',
csrfToken: req.csrfToken()});
}else{
if(bcrypt.compareSync(req.body.password, user.password)){
req.session.user = user;
res.redirect('/chat');
}else{
res.render('login.ejs', {error: 'Invalid username or password combination.',
csrfToken: req.csrfToken()});
}
}
});
});
app.get('/dashboard', requireLogin, function(req,res){
res.render('dashboard.ejs');
});
app.get('/chat', requireLogin, function(req,res){
res.render('chat.ejs');
});
app.get('/admin', requireLogin, requireAdmin, function(req,res){ //required logged in AND admin status
// var userlist = User.find({});
User.find({},{},function(err,docs){
res.render('admin.ejs',{ "userlist": docs
});
}) ;
// res.render('admin.ejs');
});
app.get('/logout', function(req,res){
req.session.reset();
res.redirect('/');
});
mongo.connect('mongodb://127.0.0.1/chat', function(err,db){
if(err) throw err;
client.on('connection', function(socket){
var col = db.collection('messages');
sendStatus = function(s){
socket.emit('status', s);
};
//emit all messages (shows old room data)
col.find().limit(100).sort({_id: 1}).toArray(function(err, res){
if(err) throw err;
socket.emit('output',res);
});
//wait for input
socket.on('input', function(data){
var name = data.name,
message = data.message,
whitespacePattern = /^\s*$/;
if(whitespacePattern.test(name) || whitespacePattern.test(message)){
sendStatus('Name and message is required.');
}else{
col.insert({name: name, message: message}, function(){
//emit latest message to all clients
client.emit('output', [data]);
sendStatus({
message: "Message sent",
clear: true
});
});
}
});
});
});
Ok, so I've finally figured it out. I used express-session to set the cookie, and then a module called express-socket.io-session to get it over to socket.io.
From there, I was able to use:
var data = socket.handshake.session;
console.log(data.user.username);
to retrieve the values I needed. All of these days searching and it was a very simple solution. I guess I just needed some sleep!

Resources