ReferenceError: User is not defined on callback - node.js

I'm implementing a google login with node, express, and passport. After I click sign in, I get a User is not defined error when it's calling back to the page. It worked before but for some reason it doesn't now. Since the user isn't found, the session data is also not going to the database either. After sign in, the user is correctly signed into chrome.
Any suggestions on how to fix this issue?
User.findOne({ "google.id": profile.id }, function (err, user) {
^
ReferenceError: User is not defined
app.js on localhost:3000
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var passport = require("passport");
var bodyParser = require("body-parser");
var passport = require("passport");
var session = require("express-session");
var DynamoDBStore = require("connect-dynamodb")(session);
var GoogleStrategy = require("passport-google-oauth2").Strategy;
var AWS = require("aws-sdk");
var cors = require("cors");
require("dotenv").config({ path: __dirname + "/.env" });
var GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
var GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
var app = express();
passport.use(
new GoogleStrategy(
{
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback",
passReqToCallback: true,
},
function (request, accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
User.findOne({ "google.id": profile.id }, function (err, user) {
if (err) return done(err);
if (user) {
// if a user is found, log them in
return done(null, user);
} else {
// if the user isnt in our database, create a new user
var newUser = new User();
// set all of the relevant information
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value; // pull the first email
// save the user
newUser.save(function (err) {
if (err) throw err;
return done(null, newUser);
});
}
});
});
}
)
);
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
console.log(obj);
done(null, obj);
});
AWS.config.update({
accessKeyId: process.env.ACCESS_KEY,
secretAccessKey: process.env.ACCESS_KEY_SECRET,
region: "us-west-1",
});
var dynamodb = new AWS.DynamoDB();
var server = require("http").createServer(app);
var userDrinksRouter = require("./routes/userDrinks");
var drinksRouter = require("./routes/drinks");
var ingredientsRouter = require("./routes/ingredients");
var liquorRouter = require("./routes/liquors");
var justIngredients = require("./routes/justIngredients");
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3001");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(logger("dev"));
var options = {
table: "app-sessions",
AWSConfigJSON: {
accessKeyId: process.env.ACCESS_KEY,
secretAccessKey: process.env.ACCESS_KEY_SECRET,
region: "us-west-1",
},
client: dynamodb,
};
//initialzie session
app.use(
session({
store: new DynamoDBStore(options),
secret: "new user",
resave: true,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
// serialized and deserialized.
app.use((req, res, next) => {
console.log(req.user);
next();
});
app.get("/", function (req, res) {
res.status(200).send({ user: req.user });
});
app.get("/account", ensureAuthenticated, function (req, res) {
res.status(200).send({ user: req.user });
});
app.get("/login", function (req, res) {
res.status(200).send({ user: req.user });
});
app.get("/users", function (req, res) {
res.send({ user: req.user });
});
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email", "openid"],
})
);
app.get(
"/auth/google/callback",
passport.authenticate("google", {
failureRedirect: "/login",
}),
function (req, res) {
res.redirect("http://localhost:3001/");
}
);
app.get("/logout", function (req, res) {
req.logout();
res.redirect("http://localhost:3001/");
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/login");
}
//app.use(ensureAuthenticated);
//app.use("/userDrinks", userDrinksRouter);
app.use("/drinks", drinksRouter);
app.use("/ingredients", ingredientsRouter);
app.use("/liquors", liquorRouter);
app.use("/justIngredients", justIngredients);
server.listen(3000, () => console.log("Drinks API listening on port 3000!"));

If I saw correctly, appears that you didn't import User, take a look on your requires.

Related

I keep getting "Login sessions require session support" when I try to use tokens

So I am following a tutorial on how to use JSON tokens and I am getting an error, it was working fine using sessions but I can't figure out why I am having trouble, it is the exact code
this is my authenticate.js file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/user");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const jwt = require("jsonwebtoken"); // used to create, sign, and verify tokens
const config = require("./config.js");
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, { expiresIn: 3600 });
}; // config.secretKey is a string of random numbers
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload:", jwt_payload);
User.findOne({ _id: jwt_payload._id }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
exports.verifyUser = passport.authenticate("jwt", { session: false });
This is my app.js file (the main file):
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const config = require("./config");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const mongoose = require("mongoose");
const passport = require("passport");
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
() => console.log("Connected correctly to server"),
(err) => console.log(err)
);
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser("12345-67890-09876-54321"));
app.use(passport.initialize());
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(express.static(path.join(__dirname, "public")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// 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");
});
module.exports = app;
this is the routes/users.js file (I believe the problem is here because I can sign-up (create new users) but I can't login with the same users)
const express = require("express");
const User = require("../models/user");
const passport = require("passport");
const authenticate = require("../authenticate");
const router = express.Router();
/* GET users listing. */
router.get(
"/",
function (req, res, next) {
res.send('send users')
}
);
router.post("/signup", (req, res) => {
User.register(
new User({ username: req.body.username }),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstname) {
user.firstname = req.body.firstname;
}
if (req.body.lastname) {
user.lastname = req.body.lastname;
}
user.save((err) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
status: "Registration Successful!",
});
});
});
}
}
);
});
// I tried to add a console.log inside of the .post() route but it never reach it
router.post(
"/login",
passport.authenticate("local"),
(req, res) => {
const token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
token: token,
status: "You are successfully logged in!",
});
}
);
router.get("/logout", (req, res, next) => {
if (req.session) {
req.session.destroy();
res.clearCookie("session-id");
res.redirect("/");
} else {
const err = new Error("You are not logged in!");
err.status = 401;
return next(err);
}
});
module.exports = router;
Basically, every time that i go to localhost:3000/users/login and send a POST request with the username and password, it tells me that I need to use express-session but I am trying to use tokens instead of session
The problem is caused when passport.authenticate('local') is called in routes/users.js file. It is a middleware that automatically calls req.login function in case correct username and password is provided.
The req.login() in turn, implements sessions in order to serialise the user in the session.
You can solve the issue by adding another parameter to passport.authenticate() as passport.authenticate('local', {session: false}. This ensures sessions are not implemented in the 'local' strategy and subsequently login can be performed.
Thanks, it helped me. You have to remove app.use(passort.session) from app.js and do
router.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
var token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, token: token, status: 'You are successfully logged in!' });
});

Bad Request in Node Js using passport Js

I am trying to build a registration and login page using passport-local-mongoose.
When I click on submit signup button I get an error which says bad request.
I am getting "Bad Request" while registering, but the details are being stored in MongoDB. Not sure where I am making a mistake.
Please help me out.
Here is my register POST API.
let express = require('express');
let mongoose = require('mongoose');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const passportLocalMongoose = require('passport-local-mongoose');
var expressValidator = require('express-validator');
const bodyParser = require('body-parser')
const { check, validationResult } = require('express-validator');
const Admin = require('../models/admin-model');
let router = express.Router();
const app = express();
//Creating a Secret Key to Hash Password
router.use(require('cookie-session')({
secret: 'jdkjhLGUL#^&%^%(*)&^%#!gkjh', // Encode/Decore Session
resave: false,
saveUninitialized: false
}));
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
}, Admin.authenticate()));
//Encrypting and Decrypting the Password for Security
passport.serializeUser(Admin.serializeUser()); //session Encoding
passport.deserializeUser(Admin.deserializeUser());
// passport.use(new LocalStrategy(Admin.authenticate()));
//Setting the View Engine to take EJS Pages
app.set('view engine', "ejs");
app.set('views', "./views")
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(__dirname + '/public'));
mongoose.connect("mongodb://localhost:27017/node-auth-db", { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to node-auth-db successfully....!'))
.catch(err => console.log(err))
router.get('/', (req, res) => {
res.render('home');
});
router.get('/login', (req, res) => {
res.render('signin');
});
router.post('/login', passport.authenticate("local", {
successRedirect: '/admin/addnews',
failureRedirect: '/login'
}));
//Registration
router.get('/register', (req, res) => {
res.render('signup');
});
router.post('/register', (req, res) => {
Admin.findOne({ username: req.body.email }, (err, result) => {
if (err) throw err;
if (!result) {
Admin.register(new Admin({ name: req.body.name, username: req.body.email }),
req.body.password, function (err, admin) {
if (err) throw err;
passport.authenticate("local")(req, res, function () {
res.redirect('/admin/login');
})
}
)
}
else {
res.redirect('/admin/register');
}
});
});
//Add News
router.get('/addnews', isLoggedIn, (req, res) => {
res.render('addnews');
});
router.post('/addnews', (req, res) => {
News.create(req.body, (err, data) => {
if (err) throw err;
const htmlMsg = encodeURIComponent('Added News DONE !');
res.redirect('/admin/addnews');
})
});
//Creating a Authentication Token to secure the logging and Logout.
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/admin/login');
}
router.get('/logout', (req, res) => {
req.logOut();
res.redirect('/admin');
});
module.exports = router;[]
Might be the issue is here you are passing req.body.password outside admin module
Admin.register(new Admin({ name: req.body.name, username: req.body.email, req.body.password}), function (err, admin) {
if (err) throw err;
passport.authenticate("local")(req, res, function () {
res.redirect('/admin/login');
})
}
)

My passport auth doesnt work on Heroku, user is not returned

My app and auth is working perfectly localy, however after deploying the server to heroku I am unable to login, because user object is not returned.
Here is my passport file:
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('users');
passport.serializeUser((user, done) => {
// console.log({user})
done(null, user._id)
})
passport.deserializeUser((id, done) =>
User.findById(id).then((user) => {
if (user) {
done(null, user)
} else {
}
})
);
passport.use(new localStrategy((username, password, done) => {
// console.log({username}, {password})
User.findOne({ username: username }, (err, user) => {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Username not found' });
}
if (!user.comparePassword(password, user.password)) {
return done(null, false, { message: 'Incorrect password.' });
}
// console.log('user', user)
return done(null, user);
});
}));
Routes:
const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('users');
module.exports = (app) => {
app.post('/login',
passport.authenticate('local', {
successRedirect: '/loginSuccess',
failureRedirect: '/loginFailed',
})
);
app.get('/loginSuccess', (req, res) => {
res.send({ success: true, test:'test', user: req.user })
})
app.get('/loginFailed', (req, res) => {
res.send({ success: false, error: "Incorrect credentials" })
})
};
And I dont know if its helpful, but my index file:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const cookieSession = require('cookie-session');
const keys = require('./config/keys');
require('./models/user');
require('./services/passport');
mongoose.connect(keys.mongoUri, { useNewUrlParser: true })
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cookieSession({
maxAge: 30 * 24 + 60 * 60 * 1000, //30 days
keys: [keys.cookieKey]
})
);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
app.use(passport.initialize());
app.use(passport.session());
//ROUTES
require('./routes/auth')(app);
require('./routes/game')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
After login is successfull I send back object containing 3 other objects, success bool value, user object with user info and for the sake of testing, test object containing a string.
Everything is returned, except for user object. What could be the issue?

How to make signup function in nodejs using passportjs?

I am trying to make a signup and signin app in node.js. I am using passport.js for authentication purpose.
My main problem here is whenever i submit my signup form with valid form data, its automatically log user in. Other functions are working properly. Login works perfectly but whenever i submit signup form it submits without any errors and shows successful message too. But main drawback is along with singup it also log user in which i don`t want.
Here is my 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');
const validator = require('express-validator');
const passport = require('passport');
const expressHbs = require('express-handlebars');
const flash = require('connect-flash');
const session = require('express-session');
const mongoose = require('mongoose');
const configDB = require('./config/database.js');
//db configuration
mongoose.connect(configDB.url, (err) => {
if(err) {
console.log('Error connecting to databse');
} else {
console.log('Connection Successful');
}
});
require('./config/passport');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
// 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(validator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'node_modules')));
//required for passport
app.use(session({
secret: 'mysecret',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
app.use('/users', users);
app.use('/', index);
// 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');
});
module.exports = app;
passport.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
var fullname = req.body.name;
var address = req.body.address;
req.checkBody('name', 'Name is Required').notEmpty();
req.checkBody('email', 'Invalid email').notEmpty().isEmail();
req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach((error) => {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({ 'email': email }, (err, user) => {
if (err) {
return done(err);
}
if (user) {
return done(null, false, {message: 'That email is already taken.'});
} else {
var newUser = new User();
newUser.fullname = fullname;
newUser.email = email;
newUser.password = newUser.encryptPassword(password);
newUser.address = address;
newUser.isAdmin = false;
//saving the user
newUser.save((err) => {
if (err) {
return done(err);
}
return done(null, newUser, req.flash('info', 'Signup Completed, pleases login to continue'));
});
}
});
}));
passport.use('local-signin', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) =>{
req.checkBody('email', 'Invalid email').notEmpty().isEmail();
req.checkBody('password', 'Invalid password').notEmpty().isLength({ min: 4 });
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach((error) => {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
User.findOne({'email': email}, (err, user) => {
if(err) {
return done(err);
}
if(!user) {
return done(null, false, {message: 'No User Found'});
}
if(!user.validPassword(password)) {
return done(null, false, {message: "Wrong Password"});
}
return done(null, user);
});
}));
user.js
var express = require('express');
var router = express.Router();
const passport = require('passport');
const User = require('../models/user');
/* GET users listing. */
router.get('/admin/dashboard', isLoggedIn, isAdmin, (req, res) => {
var user = req.user;
User.find({}, (err, users) => {
if(err) {
throw err;
} else {
res.render('admin/dashboard', {
successMsg: 'Hello' + ' ' + user.fullname,
users: users
});
}
});
});
//router.use('/', notLoggedIn, (req, res, next) => {
// next();
//});
router.get('/login', (req, res) => {
var messages = req.flash('error');
var infoMsg = req.flash('info');
res.render('users/login', { infoMsg: infoMsg, messages: messages, hasErrors: messages.length > 0 });
});
router.post('/login', passport.authenticate('local-signin', {// successRedirect: '/users/profile',
failureRedirect: '/users/login',
failureFlash: true
}), (req, res, next) => {
user = req.user;
role = user.isAdmin;
if(role) {
return res.redirect('/users/admin/dashboard');
} else {
return res.redirect('/users/profile');
}
});
router.get('/signup', (req, res, next) => {
var messages = req.flash('error');
res.render('users/signup', { messages: messages, hasErrors: messages.length > 0 });
});
router.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/users/login',
failureRedirect: '/users/signup',
failureFlash: true
}));
router.get('/profile', isLoggedIn, (req, res) => {
var user = req.user;
var role = user.isAdmin;
res.render('users/profile', {
user: user,
role: role,
successMsg: 'Welcome' + ' ' + user.fullname
});
});
router.get('/logout', isLoggedIn, (req, res, next) => {
req.logout();
res.redirect('/users/login');
});
//route middleware to make sure a use is logged in
function isLoggedIn(req, res, next) {
//if user is authenticated in the session, carry on
if(req.isAuthenticated()) {
return next();
}
res.redirect('/users/login');
}
function isAdmin(req, res, next) {
var user = req.user;
if(user.isAdmin == true) {
return next();
}
res.redirect('/users/profile');
}
function notLoggedIn(req, res, next) {
if(!req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
module.exports = router;
You can use session configuration as per passport documentation
.post(passport.authenticate('local-signup', {
successRedirect: '/users/login',
failureRedirect: '/users/signup',
badRequestMessage: "You must fill in all of the form fields.",
failureFlash: true, // allow flash,
session: false // prevent auto-login
})
or you can give a callback to passport call and prevent session storing so it will not perform login
router.post('/signup', function(req, res, next) {
passport.authenticate('local-signup', function(err, user) {
if (err) { return next(err) }
if (!user) { return res.redirect('/users/signup') }
res.redirect('/users/login');
})(req, res, next);
});

NodeJS Express req[user] undefined on multiple refresh

My Question is similar to this.I am using express version 4.14.0 and I have implemented OAuth2 SSO using "passport-ping" module. For getting new Access token from refresh token which we have on successful login I am using "passport-oauth2-refresh" module. No problem with these modules. Everything works fine as expected. But the problem is with request.user object. Below is my code
var express = require('express');
var async = require('async');
var cookieParser = require('cookie-parser');
var request = require('request');
var passport = require('passport');
var OAuth2Strategy = require('passport-ping').Strategy;
var refresh = require('passport-oauth2-refresh');
var session = require('express-session');
var bodyParser = require('body-parser');
var Client = require('node-rest-client').Client;
var client = new Client();
var _outputpath = "/build",
_templatePath = "./templates";
var app = express();
app.use(express.static(__dirname + "/"));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: "session secret",
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
var port = process.env.port || 8080;
// Allow cross orgin
app.all('*', function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
} else {
next();
}
});
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (id, done) {
done(null, id);
});
var strategy = new OAuth2Strategy({
authorizationURL: 'xxx',
tokenURL: 'xxx',
clientID: 'xxx',
clientSecret: 'xxx',
callbackURL: 'http://localhost:8080'
},
function (accessToken, refreshToken, profile, done) {
done(null, { accessToken: accessToken, refreshToken: refreshToken });
}
);
passport.use('oauth-provider', strategy);
refresh.use('oauth-provider', strategy);
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/');
}
}
/***************** GET BASE PAGE ************/
app.get('/guide', isAuthenticated, function (req, res) {
async.series({
one: function (callback) {
newAccessToken(req, res, true, function (reqQuery) {
var _reqQuery = reqQuery;
res.cookie('userAccessToken', req["user"].refreshToken, { maxAge: 1 * 24 * 3600000, httpOnly: false });
res.sendFile(__dirname + _outputpath + '/index.html');
callback(null, req["user"]);
})
},
two: function (callback) {
callback(null, 2);
}
},
function (err, results) {
console.log('Completed Guide Page');
});
});
app.get('/', passport.authenticate('oauth-provider', {
successRedirect: '/guide',
failureRedirect: '/error',
pfidpadapterid: 'OAuthAdapterCCDS'
})
);
function newAccessToken(req, res, isParent, callback) {
refresh.requestNewAccessToken('oauth-provider', req["user"].refreshToken, function (err, accessToken, refreshToken) {
var expireAccessToken = new Date();
expireAccessToken.setMinutes(expireAccessToken.getMinutes() + 59);
req["user"].refreshToken = refreshToken;
req["user"].accessToken = accessToken;
req["user"].accessTokenTime = new Date();
req["user"].expireAccessToken = expireAccessToken;
callback(req);
});
}
/***************** START THE SERVER ************/
app.listen(port, function () {
console.log('Server started & listening on port: ' + port);
});
On successful login OAuth2Strategy done function is adding below object to req.user.
{ accessToken: accessToken, refreshToken: refreshToken }
On every request I am hitting newAccessToken function to get new Access token for refresh token we have and updating the req.user object with new Access token and refresh token manually as shown below. Is there any better way to update the req["user"]?
req["user"].refreshToken = refreshToken;
req["user"].accessToken = accessToken;
req["user"].accessTokenTime = new Date();
req["user"].expireAccessToken = expireAccessToken;
If the user hits refresh continuously from browser, I am getting as req.user undefined. Tried few things by seeing forum but it dint worked. Any help is much appreciated.
I dint handled the error properly while getting the new access token. I changed new Access token function as below
function newAccessToken(req, res, isParent, callback) {
refresh.requestNewAccessToken('oauth-provider', req["user"].refreshToken, function (err, accessToken, refreshToken) {
var expireAccessToken = new Date();
expireAccessToken.setMinutes(expireAccessToken.getMinutes() + 59);
req["user"].refreshToken = refreshToken;
req["user"].accessToken = accessToken;
req["user"].accessTokenTime = new Date();
req["user"].expireAccessToken = expireAccessToken;
callback(req);
});
}

Resources