well a want to make a simple chat system, and for that i have to show
all clients witch are connected.i try sivrel techniques and it dons't work.
i tried to emit a socket when a client connect and it dons't work.
that's what i tried:
app.post('/login', (req, res)=>{
let user = req.body.username
let pass = req.body.password
console.log("le user est = " + user + " \nle password est = " + pass);
connection.query('SELECT * FROM user WHERE username = ? AND password = ?', [user,pass], function (error, results, fields) {
if (error) throw error;
console.log(results.length);
console.log(results[0]);
if (results.length==1){
const user_id = results[0]
io.sockets.emit('new_user',{user:results[1]})
req.login(user_id,(err)=>{
res.redirect('/home');
})
}else {
res.redirect('/');
}
});
});
and that the full code :
server.js:
let express = require('express');
let app = express();
let bodyParser = require('body-parser')
let server = require('http').createServer(app);
var io = require('socket.io')(server);
let session = require('express-session')
let MySQLStore = require('express-mysql-session')(session);
let passport = require('passport');
let mysql = require('mysql');
let hbs = require('hbs')
var options = {
host: 'localhost',
user: 'root',
password: '',
database: 'robot'
};
var sessionStore = new MySQLStore(options);
let connection = mysql.createConnection(options);
connection.connect(function(err) {
if (err) {
console.error('MYSQL error connecting : ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
app.use(session({
secret: 'ldifgquoqjfejg',
store: sessionStore,
//comme elle change que lorsque on modéfie la session
resave: false,
saveUninitialized: false,
//cookie: { secure: true }
}))
app.use(passport.initialize());
app.use(passport.session());
//hbs configure
app.set('view engine', 'html');
app.engine('html', hbs.__express);
hbs.registerPartials(__dirname + '/views/partials');
hbs.localsAsTemplateData(app);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res)=>{
res.render('login');
});
app.get('/home', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('index');
});
app.get('/robot', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('robot');
});
app.get('/userlist', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('listeuser');
});
app.get('/history', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('history');
});
app.get('/chat', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('chat');
});
app.get('/cam', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('cam');
});
app.get('/bras', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('bras');
});
app.get('/base', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('base');
});
app.get('/ajout', authenticationMiddleware(), (req, res)=>{
app.locals.user = req.user.username
res.render('ajout');
});
app.get('/Logout', (req, res)=>{
req.logout();
req.session.destroy();
res.redirect('/');
});
app.post('/login', (req, res)=>{
let user = req.body.username
let pass = req.body.password
console.log("le user est = " + user + " \nle password est = " + pass);
connection.query('SELECT * FROM user WHERE username = ? AND password = ?', [user,pass], function (error, results, fields) {
if (error) throw error;
console.log(results.length);
console.log(results[0]);
if (results.length==1){
const user_id = results[0]
io.sockets.emit('new_user',{user:results[1]})
req.login(user_id,(err)=>{
res.redirect('/home');
})
}else {
res.redirect('/');
}
});
});
passport.serializeUser(function(user_id, done) {
done(null, user_id);
});
passport.deserializeUser(function(user_id, done) {
done(null, user_id);
});
//socket
io.on('connection', (socket)=>{
socket.emit('user','data')
});
//socket
server.listen(8000);
app.use(express.static('./views'));
function authenticationMiddleware(){
return(req, res, next)=>{
//console.log('req.session.passport.user: ${JSON.stringify(req.session.passport)}')
if (req.isAuthenticated()) return next();
res.redirect('/')
}
}
and the chat.html
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
socket = io.connect('http://localhost:8000')
socket.on('new_user',(data)=>{
document.getElementById('ilyes').innerHTML=data.user
})
</script>
Related
So this is my code that is giving me problems with the authentification. I dont know how to get the id since is already created.
require('dotenv').config()
const express = require ("express");
const bodyParser = require ("body-parser");
const ejs = require ("ejs");
const mongoose = require ("mongoose")
const md5 = require ("md5");
const saltRounds = 10;
var bcrypt = require('bcryptjs');
const session = require('express-session');
const passport = require ("passport");
const passportLocalMongoose = require ("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require ("mongoose-findorcreate");
const app = express();
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});
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleID: 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",
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use (bodyParser.urlencoded({
extended:true
}));
app.get ("/", function (req, res) {
res.render("home");
});
app.get('/auth/google',
passport.authenticate('google', {scope: ['profile', 'email']})
);
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/profile',
failureRedirect: '/fail'
})
);
app.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/secrets');
});
app.get ("/login", function (req, res) {
res.render("login");
});
app.get ("/register", function (req, res) {
res.render("register");
});
app.get("/secrets", function (req,res) {
if (req.isAuthenticated()){
res.render("secrets");
}else {
res.rendirect("/login");
}
})
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.authenticated("local")(req,res, function() {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000")
});
So when Im trying to run my code but the same error appears all the time in my system.
ReferenceError: id is not defined
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/app.js:55:20
at pass (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/authenticator.js:291:9)
at Authenticator.serializeUser (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/authenticator.js:296:5)
at SessionManager.logIn (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/sessionmanager.js:14:8)
at IncomingMessage.req.login.req.logIn (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/http/request.js:39:26)
at Strategy.strategy.success (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/middleware/authenticate.js:256:13)
at verified (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport-oauth2/lib/strategy.js:189:20)
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/app.js:73:14
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/mongoose-findorcreate/index.js:47:11
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/mongoose/lib/model.js:4999:1
UPDATE
When I add to the code
passport.serializeUser(function(user, done, id) {
done(null, user, id);
});
The system gives me back all my data but on Hyper I get all the information.
When I try to run my code it gives me Reference Error: LocalStrategy is not defined.
This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.
I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.
/***********
Modules
***********/
//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;
/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/js', express.static(__dirname + '/js'));
/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());
/***********
Database
***********/
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + usr + ':' + pwd + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Models
***********/
//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
user_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
//Create model object
var User = mongoose.model('user', UserSchema);
/***********
Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.get('/home', function (req, res, next) {
res.sendFile(__dirname + '/home.html');
});
app.post('/login', passport.authenticate('local'),
function(req, res) {
res.redirect('/home');
});
/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if(user !== null) {
var isPasswordCorrect = bcrypt.compareSync(password, user.password);
if(isPasswordCorrect) {
console.log("Username and password correct!");
return done(null, user);
} else {
console.log("Password incorrect!");
return done(null, false);
}
} else {
console.log("Username does not exist!");
return done(null, false);
}
});
}
));
/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(err, user);
});
app.post('/register', function (req, res, next) {
var password = bcrypt.hashSync(req.body.password);
req.body.password = password;
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function() {
console.log('Server running at port ' + port);
});
The reason is you have defined var LocalStratgy, not LocalStrategy.
You're using it like this-
https://www.npmjs.com/package/passport-local-mongoose#configure-passportpassport-local
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
But I suggest you to use it like this -
https://www.npmjs.com/package/passport-local-mongoose#simplified-passportpassport-local-configuration
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
I am trying to remove the # sign on the URL using html5mode by stating the location provider html5mode to true
$locationProvider.html5Mode(true);
I also did configured my server.js file to serve my static files and my index.html as below
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
port = process.env.PORT || 8080;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen('8080');
console.log('The magic happens on port 8080');
At this point, everything works fine from localhost:8080 to other navigation such as localhost:8080/login even when I refreshed the page, it is still working fine.
It it not working during any API fetch statement is being called. Below is my routes.js
route.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db);
User = require('./models/user.js')(db);
module.exports = function(app) {
app.route('/api/user')
.get(function(req, res, next) {
User.find(function(err, user){
if(err)
res.json(err);
res.json(user);
});
})
.post(function(req, res, next) {
var error_return = [{response:'User Existed'},{response:'Invalid Username or Password'},{response:'Server Error'}];
if(req.body.type === "local"){
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
newUser.save(function(error, result){
if(error)
res.json(error_return[2]);
res.json({response:result});
});
return;
}
res.json(error_return[0]);
});
}else if(req.body.type === "login"){
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)){
res.json(error_return[1]);
return;
}
res.json({response:user});
});
}
});
};
Previously before enabling html5mode, my files in require('./app/routes.js')(app); is running smoothly, after enabling, it is not even being called. Have I missing something in my code?
All your requests are going to public/index.html right now.
Modify your code to allow /api/ requests to go to the routes
app.use('/api', bodyParser.json(), require('./app/routes.js'));
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.listen('8080');
console.log('The magic happens on port 8080');
routes.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db),
User = require('./models/user.js')(db),
router = require('express').Router();
module.exports = router;
router.route('/user')
.get(function (req, res, next) {
User.find(function (err, user) {
if (err) res.json(err);
res.json(user);
});
})
.post(function (req, res, next) {
var error_return = [{
response: 'User Existed'
}, {
response: 'Invalid Username or Password'
}, {
response: 'Server Error'
}];
if (req.body.type === "local") {
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
newUser.save(function (error, result) {
if (error) res.json(error_return[2]);
res.json({
response: result
});
});
return;
}
res.json(error_return[0]);
});
} else if (req.body.type === "login") {
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)) {
res.json(error_return[1]);
return;
}
res.json({
response: user
});
});
}
});
im working on a node passport login authentication but im stack on this error which makes it hard for me to run my node server
/home/emil/Documents/myapp/app/routes.js:14
app.post('/login', passport.authenticate('local-login', {
^
TypeError: Cannot read property 'authenticate' of undefined
how can i fix it?
my code:
server.js
var express = require('express');
var app = express();
var port = 8080;
var cookieParser = require('cookie-parser');
var session = require('express-session');
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
app.use(passport.initialize());
app.use(passport.session());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(session({
secret: 'anystringoftext',
saveUninitialized: true,
resave: true
}));
app.set('view engine', 'ejs');
//app.use('/', function(req, res){
// res.send('Our First Express program!');
// console.log(req.cookies);
// console.log('===============');
// console.log(req.session);
//});
require('./app/routes.js')(app);
app.listen(port);
console.log('Server running on port: ' + port);
routes.js:
var User = require('./models/user');
module.exports = function (app, passport) {
app.get('/', function (req, res) {
res.render('index.ejs');
});
app.get('/login', function (req, res) {
res.render('login.ejs', {
message: req.flash('loginMessage')
});
});
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile',
failureRedirect: '/login',
failureFlash: true
}));
app.get('/signup', function (req, res) {
res.render('signup.ejs', {
message: req.flash('signupMessage')
});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect: '/signup',
failureFlash: true
}));
app.get('/profile', isLoggedIn, function(req, res){
res.render('profile.ejs', { user: req.user });
});
app.get('/:username/:password', function (req, res) {
var newUser = new User();
newUser.local.username = req.params.username;
newUser.local.password = req.params.password;
console.log(newUser.local.username + " " + newUser.local.password);
newUser.save(function (err) {
if (err)
console.log(err);
});
res.send("Success!");
})
};
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
passport.js
var LocalStrategy = require('passport-local').Strategy;
var User = require('../app/models/user');
module.exports - function(passport) {
passport.serializeUser(function(usser, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){
process.nextTick(function(){
User.findOne({'local.username': email}, function(err, user){
if(err)
return done(err);
if(user){
return done(null, false, req.flash('signupMessage', 'That account exists'));
} else {
var newUser = new User();
newUser.local.username = email;
newUser.local.password = password;
newUser.save(function(err){
if(err)
throw err;
return done(null, newUser);
})
}
})
});
}));
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
function(req, email, password, done){
process.nextTick(function(){
User.findOne({ 'local.username': email}, function(err, user){
if(err)
return done(err);
if(!user)
return done(null, false, req.flash('loginMessage', 'No user found'));
if(user.local.password != password)
return done(null, false, req.flash('loginMessage', 'invalid password'));
}
return done(null, user);
})
})
}
))
You have not passed passport to the routes. require('./app/routes.js')(app); should be require('./app/routes.js')(app, passport) in server.js;
I'm sure, I'm doing something wrong coz of my lack of experience with this technologies.
So here I'm trying to authenticate my user.
in server.js I have the following :
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
//var configDB = require('./config/database.js');
require('./config/environement.js')(app, express);
require('./config/routes.client.js')(app);
//setting all modules routes
require('./api/oAuth/routes.js')(app);
app.listen(port);
In environement.js :
module.exports = function(app, express) {
app.configure(function() {
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
/* je pense que ce code n'a rien a faire ici*/
var User = require('./../models/user.js');
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({
username: username
}, function(err, user) {
if (err) {
return done(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);
});
}));
app.use(express.logger());
app.use(express.static(path.join(__dirname + '/../views')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: 'm4B1teD4nsTaG0rgE'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
/*fin*/
mongoose.connect('mongodb://localhost/passport_local_mongoose');
app.set('views', __dirname + '/../views');
app.set('view engine', 'jade'); //extension of views
console.log("config ok");
});
//development configuration
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
//production configuration
app.configure('production', function() {
app.use(express.errorHandler());
});
};
And finaly my api/oAuth/routes.js
var User = require('../../models/user.js');
var passport = require('passport');
module.exports = function(app) {
app.get('/register', function(req, res) {
res.render('../api/oAuth/views/register.page.jade');
});
//Route vers /login en get et post
app.get('/login', function(req, res) {
res.render('../api/oAuth/views/login.page.jade');
});
app.post('/api/oAuth/login', function(req, res, next) {
console.log("post login = ok");
passport.authenticate('local',function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.redirect('/users/' + req.user.username);
});
});
app.post('/api/oAuth/register', function(req, res) {
User.register(
new User({
username: req.body.username
}), req.body.password, function(err, user) {
if (err) {
res.send(err);
}
else {
res.send("Success");
}
});
});
}
Edit : Added user.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
var passport = require('passport');
var User = new Schema({
username: String,
password: String
});
User.plugin(passportLocalMongoose);
passport.serializeUser(function(user, done) {
console.log("serializeUser");
done(null, user);
});
passport.deserializeUser(function(user, done) {
console.log("deserializeUser");
done(null, user);
});
module.exports = mongoose.model('User', User);
When the app goes into passport.authenticate() it does a lot of thing then it return to passport.authenticate() in a loop way. When I use the custom callback I realize that passport.authenticate() is going smoothly but the problem seems to be in req.logIn() function. I don't know what to do in order to make this work, and I tried a lot. I feel like a blind man trying to drive a car :D.