Can't get socket.io to work - javascript

The client library js file is not loading. Trying to load socket.io into my project but the client is not detecting the javascript library that is supposed to be served automatically. here is my code.
var express = require('express')
, passport = require('passport')
, util = require('util')
, session = require('express-session')
, SteamStrategy = require('../../').Strategy
, Steam = require('machinepack-steam')
, path = require('path')
, app = express()
, http = require('http')
, socket = require('socket.io')
;
app.set('port', process.env.PORT || 2053);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socket.listen(server);
io.sockets.on('connection', function () {
console.log('hello world im a hot socket');
});
var steamkey = 'redacted';
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new SteamStrategy({
returnURL: 'https://get-a.team/auth/steam/return',
realm: 'https://get-a.team',
apiKey: steamkey
},
function(identifier, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(session({
secret: 'your secret',
name: 'name of session id',
resave: true,
saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join('public')));
app.get('/', function(req, res){
if(req.user){
res.redirect('/account');
} else {
res.render('index', { user: req.user });
}
});
app.get('/search/:appid', ensureAuthenticated, function(req, res){
if(Number.isInteger(+req.params.appid)){
res.render('search', { user: req.user, appid: req.params.appid });
} else {
res.render('error', { user: req.user, error: "Wrong url format "+req.params.appid });
}
})
app.get('/account', ensureAuthenticated, function(req, res){
Steam.getOwnedGames({
steamid: req.user.id,
key: steamkey,
include_appinfo: 1,
include_played_free_games: 1,
appids_filter: [],
}).exec({
// An unexpected error occurred.
error: function(err) {
console.error(err);
},
// OK.
success: function(result) {
//console.log(result);
// save every game that isnt already saved
res.render('account', { user: req.user, games: result });
},
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/auth/steam',
passport.authenticate('steam', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/');
});
app.get('/auth/steam/return',
passport.authenticate('steam', { failureRedirect: '/' }),
function(req, res) {
res.redirect('/account');
});
app.listen(3000);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/');
}
Any help will be greatly appreciated
I've tried many different ways to include the socket library online but none works, even code copied directly from the socket.io website.
I tried localhost:2053/socket.io/socket.io.js and it still won't work. Not sure what im doing wrong

Figured it out. Had to reload socket.io to a different port:
...
, app2 = require('express')()
, http2 = require('http').Server(app2)
;
var io = require('socket.io')(http2);
io.on('connection', function(socket){
console.log('a user connected');
});
app2.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
http2.listen(2085, function(){
console.log('listening on *:2085');
});
the create a nginx rule to serve the lib from that port:
location /route/ {
rewrite ^/route/?(.*)$ /$1 break;
proxy_pass http://127.0.0.1:2085;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
and finally load it from the client end:
<script src="/route/socket.io/socket.io.js"></script>
if anyone knows the correct way of doing it, please let me know. This works though, feels quite like forcing a round peg in a square hole.

Related

nodejs expressjs ERR_TOO_MANY_REDIRECTS

I have error with "ERR_TOO_MANY_REDIRECTS" in browser.
On linux server it looks like:
Error: Can't set headers after they are sent.
This is my app.js:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const session = require('express-session');
const {getHomePage} = require('./routes/index');
const {getmain, addUserPage, addUser, deleteUser, editUser, editUserPage, addTemplates, getHistory} = require('./routes/user');
const port = 5000;
var auth = function(req, res, next) {
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
// create connection to database
// the mysql.createConnection function takes in a configuration object which contains host, user, password and the database name.
const db = mysql.createConnection ({
host: 'localhost',
user: '*****',
password: '*****',
database: '*****',
charset : 'utf8mb4'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.locals.moment = require('moment');
app.use(session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1800000}
}));
// routes for the app
app.get('/', getHomePage);
app.get('/main', auth, getmain);
app.get('/add', auth, addUserPage);
app.get('/edit/:id', auth, editUserPage);
app.get('/delete/:id', auth, deleteUser);
app.get('/addtemp/:login', auth, addTemplates);
app.get('/history', auth, getHistory)
app.post('/add', auth, addUser);
app.post('/edit/:id', auth, editUser);
app.post('/addtemp/:login', auth, addTemplates);
// Login endpoint
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amy") {
req.session.user = "amy";
req.session.admin = true;
res.redirect('/main');
}
});
// Logout endpoint
app.get('/logout', function (req, res) {
req.session.destroy();
res.redirect("/");
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
I know I have some problems in
app.get('login...
Theres everything ok with success login using correct username and password but when I use incorrect nothing happend.
This is my module getmain (after correct login):
getmain: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/main');
}
res.render('main.ejs', {
title: "blablabla"
,users: result
});
});
},
And this is index.js:
module.exports = {
getHomePage: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: "blablabla"
,users: result
});
});
},
};
I read that's all because by looping but I can not figure it out.
I will be grateful for directing me to the source of the problem.

how to delete cookie on logout in express + passport js?

I want to "delete cookies on logout". I am not able to do that. I googled for answer and found following ways:
Assign new date of expiration to cookie
res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });
Delete cookie using below lines
res.clearCookie('connect.sid', { path: '/' });
I tried both ways individually but they do not delete the cookie.
Here is my code:
routes.js
module.exports = function(app, passport, session){
app.get('/', function(req, res)
{
res.render('index.ejs');
});
app.get('/login', function(req,res){
res.render('login.ejs',{message:req.flash('loginMessage')});
});
app.get('/signup',checkRedirect , function(req, res) {
res.render('signup.ejs',{message: req.flash('signupMessage')});
});
app.get('/profile', isLoggedIn, function(req,res) {
res.render('profile.ejs', {
user :req.user
});
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile',
failureRedirect : '/signup',
failureFlash : true
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash :true
}));
app.get('/logout',function(req,res){
res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });
req.logOut();
res.clearCookie('connect.sid', { path: '/' });
res.redirect('/');
});
function isLoggedIn(req, res, next){
if(req.isAuthenticated())
return next();
console.log("hiii");
res.redirect('/');
}
};
server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var passport = require('passport');
var flash=require('connect-flash');
var morgan=require('morgan');
var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
//
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require("redis");
var redis_client = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var configDb=require('./config/database.js');
mongoose.connect(configDb.url);
require('./config/passport')(passport);
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.set('view engine', 'ejs');
app.use(session({
store: new RedisStore({
host: '127.0.0.1',
port: 6379,
client: redis_client
}),
secret : 'foo',
resave: false,
saveUninitialized: false
}));
app.use(function (req, res, next) {
if (!req.session) {
return next(new Error('oh no')); // handle error
}
next();
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./app/routes')(app, passport, session);
app.listen(port, function(){
console.log('server is at port' + port);
});
Please try this:
router.get('/logout', function (req, res) {
req.logOut();
res.status(200).clearCookie('connect.sid', {
path: '/'
});
req.session.destroy(function (err) {
res.redirect('/');
});
});
I was struggling with this issue myself. Previously I tried logout and session.destroy, and none worked for me. Then I found the above answers with the clearCookie addition, and that did the trick.
However, I was wondering if those functions are at all having any effect, given that without clearCookie they didn't. So I omitted them.
Also, as status(200) is overridden by redirect (which sets status to 302), I reckoned I'd omit that too.
As for the options to clearCookie in Will59's solution, they looked like they could be the defaults anyhow, so I tried omitting them as well.
I ended up with two lines of code bellow. They worked for me with Chrome, Firefox and Safari (the most recent versions at time of this writing).
router.get('/logout', function (req, res) {
res.clearCookie('connect.sid');
res.redirect('/');
});
You can use req.session.destroy in logout route to destroy the session below is the code for reference :)
app.get('/logout', function(req,res){
req.logOut();
req.session.destroy(function (err) {
res.redirect('/'); //Inside a callback… bulletproof!
});
});
res.clearCookies is kind of messed up. As an alternative, call res.cookie again with whatever options you used to create the cookie in the first place, along with expires: new Date(1), like this:
// Use the same httpOnly, secure, sameSite settings to "delete" the cookie
res.cookie("jwt", "", {
httpOnly: true,
secure: true,
sameSite: "none",
expires: new Date(1)
});
Essentially you are replacing the old cookie with a new one that expires immediately.
pjiaquan's did not work with chromium for me, the cookie was still around.
The issue comes from the res.clearCookie method, as explained in http://expressjs.com/en/api.html:
Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.
In my case, the solution ended up being:
router.get('/logout', function (req, res) {
req.logOut();
res.status(200).clearCookie('connect.sid', {
path: '/',
secure: false,
httpOnly: false,
domain: 'place.your.domain.name.here.com',
sameSite: true,
});
req.session.destroy(function (err) {
res.redirect('/');
});
});
So none of the suggestions here worked for me, until I realized I was doing a dumb:
Using Github, I set up an OAuth app (you can do this in your profile settings), and used that for authentication.
Worked a charm! But it was always sending me back the same profile, even when I logged out from my app. Clearing all browser storage didn't fix it.
Then it dawned on me that I was still logged into my github account (and that was the profile I was always getting)... once I logged out of that, then the OAuth app prompted me for my user/pw again.

Simple authentification with passport.js turning into infinite loop

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.

Passport.js only redirect to failure page, without calling the LocalStrategy

I have a persistent problem with Passport.js in my Express.js small application : whatever I put in the LocalStrategy, I'm always redirected to the failureRedirect, apparently without even pass by the LocalStrategy...
What did I wrong ? And how can I print/display the largest error log to follow the execution ?
var express = require('express'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
http = require('http'),
path = require('path'),
mysql = require('mysql'),
flash = require('connect-flash');
var app = express();
// SQL connexion
var sqlInfo = {
host: 'localhost',
user: 'root',
password: '',
database: 'mex'
};
global.client = mysql.createConnection(sqlInfo);
client.connect(function(err) {
if(err)
console.log(err);
});
app.configure(function(){
app.set('views', __dirname+'/views');
app.set('port', process.env.PORT || 85);
//app.engine('ejs', engine);
app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
// 1 - Session express
app.use(express.session({ secret: 'secretpass' }));
// 2 - Init et session Passeport
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.logger());
app.use(app.router);
});
// Simple logger
app.use(function(req, res, next){
console.log('%s %s', req.method, req.url);
next();
passport.use(new LocalStrategy(
function(username, password, done) {
console.log("localstrategy ---");
var user = {username: 'w#j.fr', password: 'pwd'};
return done(null, user);
}));
passport.serializeUser(function(user, done) {
// JUST 4 TEST
done(null, user);
});
passport.deserializeUser(function(user, done) {
// JUST 4 TEST
done(null, user);
});
// Home
app.get('/', function(req, res){
//check user session value, is logged in
if(req.user)
res.render('menu_log.ejs', function(err, html){
var data = {
title: 'Home',
menu: html
//req.user['Prenom'] -- à afficher
};
res.render('index.ejs', data);
console.log("index logué");
});
else
res.render('menu_nolog.ejs', function(err, html){
var data = {
title: 'Home',
menu: html
};
res.render('index.ejs', data);
console.log("index PAS logué");
});
});
// Passport's authentication
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
successFlash: 'Bienvenue !',
failureRedirect: '/wrong',
failureFlash: "Email ou mot de passe incorrect." })
);
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
})
.get('/inscription', function(req, res){
res.render('menu_nolog.ejs', function(err, html){
var data = {
title: 'Register',
menu: html
};
res.render('inscription.ejs', data);
});
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
LocalStrategy requires two parameters (either passed as POST data, or in a query string) to exist: username and password. If you're not passing those two, Passport doesn't even bother to call the strategy handler.
The field names are configurable by passing an object as first argument to the LocalStrategy constructor:
passport.use(new LocalStrategy({
usernameField : 'username',
passwordField : 'password'
}, function(username, password, done) { ... }));

Cannot GET /auth/twitter/callback while using twitter oauth in nodejs

I'm trying to do twitter oauth in nodejs using passportjs but getting error
Cannot GET /auth/twitter/callback?oauth_token=alksdkalsjdsjd23232378skjdfjsdhf&oauth_verifier=234jjh23j4k234k23h4j2h342k34hj
Here is my node js code
var express = require('express')
, passport = require('passport')
, util = require('util')
, GoogleStrategy = require('passport-google').Strategy
, TwitterStrategy = require('passport-twitter').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new TwitterStrategy({
consumerKey: 'xxxxxxxxxxxxxxxxxxxx',
consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'
},
function(token, tokenSecret, profile, done) {
process.nextTick(function () {
return done(null, profile);
});
}
));
var app = express();
// configure Express
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/../../public'));
});
app.get('/', function(req, res){
res.render('index', { user: req.user });
});
app.get('/login', function(req, res){
res.sendfile('./views/auth.html');
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('auth/twitter/callback',
passport.authenticate('twitter', { successRedirect: '/success',
failureRedirect: '/login' }));
app.get('/success', function(req, res){
res.send("success logged in");
});
app.listen(process.env.PORT || 3000);
EDIT
There is missing / in auth/twitter/callback route definition.
Also for the routers /auth/twitter and auth/twitter/callback, passport.authenticate() as middleware will do the authentication, and you should have route handling functions.
So the definition of your routes should look something like:
app.get('/auth/twitter',
passport.authenticate('twitter'),
function(req, res) {}); // empty route handler function, it won't be triggered
app.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect: '/success',
failureRedirect: '/login' }),
function(req, res) {}); // route handler
You don't need the empty route handler function(req, res) {} - you can just leave the argument out and express will understand you don't plan on ever using the handler

Categories