So recently I came across a problem, which is happening when i try to authenticate using google oauth2 from mobile, but when i try to authenticate via computer, it works fine. I am using it with passportjs in node/express project.
project link: https://rhubarb-tart-18821.herokuapp.com/
You guys can see code here:
https://ide.c9.io/saijax/www
just whole authentication is so big that i can not put everything here...
EDIT:
here are some main files
passport.js
const GoogleStrategy = require("passport-google-oauth2")
.Strategy;
const mongoose = require("mongoose");
const keys = require("./keys");
module.exports = (passport) => {
passport.use(
new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: "/auth/google/callback",
proxy: true
}, (accessToken, refreshToken, profile, done) => {
const image = profile.photos[0].value.substring(0, profile.photos[0].value.indexOf("?"));
const newUser = {
googleID: profile.id,
email: profile.emails[0].value,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
image: image
}
// CHECK FOR USER
User.findOne({
googleID: profile.id
}).then(user => {
if(user){
done(null, user);
} else {
// CREATE USER
new User(newUser)
.save()
.then(user => done(null,user));
}
})
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => done(null, user));
});
}
auth.js
const express = require("express");
const passport = require("passport");
const router = express.Router();
router.get("/google", passport.authenticate("google", {
scope: [
"profile",
"email"
]
}));
router.get("/google/callback", passport.authenticate("google", {
failureRedirect: "/"
}), (req, res) => {
req.flash("success_msg", "Successfully Logged In");
res.redirect("/dashboard");
});
router.get("/verify", (req, res) => {
if(req.user){
console.log(req.user);
} else {
console.log("Not auth");
}
});
router.get('/logout', (req, res) => {
req.logout();
req.flash("success_msg", "Successfully Logged Out");
res.redirect('/');
});
module.exports = router;
app.js
// SETUP
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const exphbs = require("express-handlebars");
const bodyParser = require("body-parser");
const methodOverride = require("method-override");
const flash = require("connect-flash");
// LOAD GOOGLE AND MONGO KEYS
const keys = require("./config/keys");
// LOAD MODELS
require("./models/story");
require("./models/user");
// PASSPORT CONFIG
require("./config/passport")(passport);
// LOAD ROUTES
const auth = require("./routes/auth");
const index = require("./routes/index");
const stories = require("./routes/stories");
// HANLEBARS HELPERS
const {
truncate,
stripTags,
formatDate,
select,
editIcon
} = require("./helpers/hbs");
// MONGOOSE CONNECT
mongoose.connect(keys.mongoURI)
.then(() => {
console.log("MongoDB Connected...");
}).catch(err => console.log(err));
// USE APP
const app = express();
// CSS CONFIG
app.use(express.static(__dirname + "/public"));
// VIEW ENGINE
app.engine("handlebars", exphbs({
helpers: {
truncate: truncate,
stripTags: stripTags,
formatDate: formatDate,
select: select,
editIcon: editIcon
},
defaultLayout: "main"
}));
app.set("view engine", "handlebars");
// BODY PARSER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// METHOD OVERRIDE
app.use(methodOverride("_method"));
// FLASH
app.use(flash());
// COOKIE PARSER
app.use(cookieParser());
// SESSION MIDDLEWARE
app.use(session({
secret: "KAPPA",
resave: false,
saveUninitialized: false
}));
// PASSPORT MIDDLEWARE
app.use(passport.initialize());
app.use(passport.session());
// SET GLOBAL VARS
app.use((req, res, next) => {
res.locals.user = req.user || null;
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
next();
});
// ROUTES
app.use("/", index);
app.use("/auth", auth);
app.use("/stories", stories);
UPDATE: well, i dont know if it was silly mistake or not, but it seems like mobile can not read
callbackURL: "/auth/google/callback"
instead i changed following line with
callbackURL: keys.callback + "/auth/google/callback"
where keys.callback is url for my app(from c9/heroku) ... now it works perfectly!
Related
i was trying to track if the user is logged in or not and if not and try to make a new post he will redirected to login page then i store the url he was trying to go to (the new post url) so when he log in he will be redirected there, i used express session to store that and have passport local to do the auth thing anyway the (new post) url is in the session but when i log in (doing post request) it just got deleted altho i tried other post requests to see if that the prob but it only reset on this post
the middleware to check and store the url in the session
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl
console.log(req.session.returnTo)
req.flash('error', 'You must be signed in first!');
return res.redirect('/login');
}
next();
}
module.exports.isNotLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
return res.redirect('/campgrounds')
}
next();
}
the login routes
const express = require('express');
const router = express.Router();
const passport = require('passport');
const catchAsync = require('../utils/catchAsync');
const User = require('../models/user');
const { isNotLoggedIn } = require('../middleware')
router.get('/register', isNotLoggedIn, (req, res) => {
res.render('users/register');
});
router.post('/register', isNotLoggedIn, catchAsync(async (req, res, next) => {
try {
const { email, username, password } = req.body;
const user = new User({ email, username });
const registeredUser = await User.register(user, password);
req.login(registeredUser, err => {
if (err) return next(err);
req.flash('success', 'Welcome to Yelp Camp!');
res.redirect('/campgrounds');
})
} catch (e) {
req.flash('error', e.message);
res.redirect('register');
}
}));
router.get('/login', isNotLoggedIn, (req, res) => {
console.log(req.session)
res.render('users/login');
})
router.post('/login', isNotLoggedIn, passport.authenticate('local', { failureFlash: true, failureRedirect: '/login' }), (req, res) => {
req.flash('success', 'welcome back!');
const returnTo = req.session.returnTo || '/campgrounds';
console.log('this thsisdifsdk')
console.log(req.session) //todo this req.session is getting reset for some reason and i cannot return to what page i was goin for
res.redirect(returnTo);
})
router.get('/logout', (req, res) => {
req.logout((err) => {
if (err) { return next(err); }
req.flash('success', "Goodbye!");
res.redirect('/campgrounds');
});
})
module.exports = router;
the app.js
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const ejsMate = require('ejs-mate');
const session = require('express-session')
const flash = require('connect-flash')
const ExpressError = require('./utils/ExpressError')
const methodOverride = require('method-override')
const passport = require('passport');
const LocalStrategy = require('passport-local')
const User = require('./models/user')
const userRoutes = require('./routes/user')
const campgroundRoutes = require('./routes/campgrounds')
const reviewRoutes = require('./routes/reviews');
mongoose.connect('mongodb://localhost:27017/yelp-camp');
const db = mongoose.connection //?shortcut
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Database Connected');
})
const app = express();
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
const sessionConfig = {
secret: 'meowmeowthecatsounduwu',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next) => {
console.log(req.session)
res.locals.currentUser = req.user;
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
app.use('/', userRoutes);
app.listen(3000, () => {
console.log('Serving on port 3000')
})
things i tried
remove the cookie, add for cookie secure: true, change secure: false, change the secret, make resave true and false, make saveUninitialized true and false, change the session name, nothing worked, i suspect that the passport is the problem but idk how to solve it
passport.authenticate('local', {failureFlash:true, failureRedirect:'/login', keepSessionInfo:true})
router.post('/#',
passport.authenticate('local', {
failureFlash: true,
failureRedirect: '/login',
keepSessionInfo: true
})
);
i'm using a localhost to test the passport-facebook authentication, i've been trying to implement the Auth and im getting the error mentioned above i've reviewed similar questions but none seem to help me, i've changed my dns address but to no avail,
this is my passport.js code for facebook authentication
const mongoose = require("mongoose");
const FacebookStrategy = require('passport-facebook').Strategy;
const passport = require('passport');
const User = module.exports = mongoose.model('User', facebookSchema)
var facebookSchema = mongoose.Schema
module.exports = function (_passport) {}
//serialize the user for the session
passport.serializeUser(function (user, done) {
done(null, user.id);
});
//deserialize the user
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('facebook', new FacebookStrategy({
clientID: 'XXXXXXXXXX',
clientSecret: 'YYYYYYYYYYYYYYY',
callbackURL: " http://localhost:3000/auth/facebook/callback",
enableProof: true,
profileFields: ['id', 'displayName', 'photos', 'email']
},
function (accessToken, refreshToken, profile, done)
{ let newUser = new User();
// set the user's facebook credentials
newUser.facebook.email = profile.emails[0].value,
newUser.facebook.fullName = profile.displayName,
User.findOne({email:newUser.facebook.email }, function(err, user) {
if(!user) {
newUser.save(function(err, newUser) {
if(err) return done(err);
done(null,newUser);
});
} else {
done(null, user);
}
});
}
));
this is my index.js code for initiallizing app
const rfc = require('rfc-3986');
const express = require('express');
const bodyParser = require('body-parser');
var routes = require('./routes/routes'); //importing route
require('./models/userModel')
app = express();
port = 3000;
require("./config/db"); app.get('/success', (req, res) => res.send("You have successfully logged in"));
app.get('/error', (req, res) => res.send("error logging in"));
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.set(rfc)
routes(app, passport);
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.listen(port,()=>{
console.log('server listening on localhost:' + port)
});
and this is my routes.js for app routing
app.get('/auth/facebook',
passport.authenticate('facebook', {scope:"email"}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/success');`module.exports = function(app, passport) {
app.get('/auth/facebook',
passport.authenticate('facebook', {scope:"email"}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/success');
});
}
});
}
this is the error i get on browser
this is the same error on terminal
I am trying to make a "Connect with Twitter" feature for my website, and it is the first time that I use Passport.js.
I have a problem since a while now : when trying the api, the passport.authenticate function of the /twitter/callback page gets stucks and I can't do anything to solve this problem
I am running my app on my localhost system. Here is my code for the index.js page. The home.ejs just contains a template for EJS where I show the username.
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser('thissecretrocks'));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const session = require('express-session');
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'bla bla bla'
}));
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://Something', {useNewUrlParser: true, useUnifiedTopology: true});
const db = {};
db.users = require('./db/users');
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
const Twitter = require('passport-twitter');
var Strategy = require('strategy');
const TwitterStrategy = Twitter.Strategy;
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
db.users.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new TwitterStrategy({
consumerKey: '5KSomethingMx',
consumerSecret: 'tld1Something6M2q',
callbackURL: "http://127.0.0.1:3000/auth/twitter/callback",
},
function(token, tokenSecret, profile, cb) {
console.log(profile);
/*const newUser = new db.users({
twitter: profile.id
});
newUser.save();*/
}
));
app.use('/cdn', express.static('cdn'));
app.get('/', function(req, res) {
res.render('home.ejs', {username: req.user.username});
});
app.get('/fail', function(req, res) {
console.log('FAIL');
res.render('home.ejs', {username: 'req.user.username'});
});
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/fail' }), function(req, res) {
res.redirect('/');
});
app.listen(3000);
I am new to NodeJS. And I am trying to create a simple web server.
I am only using NodeJS and Passport.js (using a google strategy) right now.
Currently, all the app.get("") calls are working when I am not authenticated, but once I authenticate with google and the callback happens, I can no longer access any of the app.get routes. I try and put a break point in the arrow function and it is never calls, and just hangs when loading from the browser with auth cookie.
Here is my current code:
Index.js
const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require("cookie-session");
const passport = require("passport");
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000, //30 days
keys: [keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
require('./routes/authRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
authRoutes.js
const passport = require('passport');
module.exports = (app) => {
app.get(
"/auth/google",
passport.authenticate('google', {
scope: ['profile', 'email']
})
);
app.get(
'/auth/google/callback',
passport.authenticate('google')
);
app.get("/api/logout", (req, res) => {
req.logout();
res.send(req.user);
});
app.get("/api/current_user", (req, res) => {
res.send("test");//req.user); //Tried as a test, is called when
//not authenticated, but does not get
//called when authenticated
});
}
passport.js
const passport = require('passport');
const googleStrategy = require('passport-google-oauth20');
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model("users");
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done)=> {
User.findById(id)
.then(user =>{
doen(null, user);
});
});
passport.use(new googleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleclientSecret,
callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
User.findOne({ googleId: profile.id })
.then((existingUser) => {
if (existingUser){
//we already have a user
done(null, existingUser);
}
else{
new User({ googleId: profile.id })
.save()
.then (user => done(null, user));
}
});
})
);
this probably wont help anyone besides for the fact to check for TYPOS!
I found my problem here:
passport.deserializeUser((id, done)=> {
User.findById(id)
.then(user =>{
doen(null, user);
});
});
notice doen should be done
I got no error messages that helped me on this one.
Been having some trouble for the past week getting this link to work. Feel like I'm misunderstanding something from the flow.
What I'm struggling with was implementing the passport with passport-facebook. I want to include the passport.authenticate inside the same route as the account linking. Currently only managed to separate the two processes and having two logins. Looking to merge them.
As can be seen here http://recordit.co/osdMl0MUCL
Is there no way to do the passport.authenticate inside the link route ? Been trying with no success.
Tried to move the passport.authenticate inside app.get('/authorize but don't know how to handle the const redirectURISuccess = ${redirectURI}&authorization_code=${authCode};
res.redirect(redirectURISuccess);
I'm thinking would need to do this inside the app.get(/auth/fb/callback' ... but not sure how.
This is what I have currently
'use strict';
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const http = require('http');
const port = '3000';
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const fbConfig = require('./oauth');
const cookieParser = require('cookie-parser');
const session = require('express-session');
// used to serialize the user for the session
// Not using these yet
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
const Botly = require('botly');
const botly = new Botly({
accessToken: process.env.ACCESS_TOKEN,
verifyToken: '123123321' // the verification token you provided when defining the webhook in facebook
});
const app = express();
// Listen on the account link event
botly.on('account_link', (sender, message, link) => {
// Continue conversation
console.log('CONFIRMED AUITH', link);
botly.sendText({
id: sender,
text: (link.status === 'unlinked') ? 'sorry to see you go' : 'Welcome'
});
botly.sendButtons({
id: sender,
text: 'Please Login Again :-) This time for real',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/auth/fb/?senderId=' + sender/`) ]
});
});
botly.on('message', (senderId, message, data) => {
const text = `echo: ${data.text}`;
botly.sendText({
id: senderId,
text: text
});
botly.sendButtons({
id: senderId,
text: 'Please Login :)',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/authorize/`), botly.createAccountUnLinkButton() ]
});
});
app.use(bodyParser.json());
app.use('/', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'its_my_secret', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/webhook', botly.router());
app.set('port', port);
/*
* This path is used for account linking. The account linking call-to-action
* (sendAccountLinking) is pointed to this URL.
*
*/
app.get('/authorize', function (req, res) {
// Passport setup
passport.use('facebook', new FacebookStrategy({
clientID: fbConfig.facebook.clientID,
clientSecret: fbConfig.facebook.clientSecret,
callbackURL: fbConfig.facebook.callbackURL,
profileFields: [ 'id', 'displayName', 'email' ]
},
// facebook will send back the tokens and profile
function (request, access_token, refresh_token, profile, done) {
// asynchronous
process.nextTick(function () {
console.log('WATCH THIS: ', profile);
return done(null, profile);
});
}));
console.log('%%%%%%%% AccountLinking Testing');
const accountLinkingToken = req.query.account_linking_token;
const redirectURI = req.query.redirect_uri;
console.log('%%%%%%%% /authorize called with accountLinkingToken %s, redirectURI %s', accountLinkingToken, redirectURI);
// Authorization Code should be generated per user by the developer. This will
// be passed to the Account Linking callback.
const authCode = '1234567890';
// Redirect users to this URI on successful login
const redirectURISuccess = `${redirectURI}&authorization_code=${authCode}`;
res.redirect(redirectURISuccess);
});
app.get('/auth/fb', (req, res, next) => {
req.session.senderId = req.query.senderId;
passport.authenticate('facebook', { scope: [ 'email' ] },
{
state: {
senderId: req.query.senderId // senderId will be used after auth to reply to the user
}
})(req, res, next);
});
// Redirection after login
app.get('/auth/fb/callback',
passport.authenticate('facebook', {
successRedirect: `https://m.me/${process.env.app_name}`, // The webview I want to open if user logs in
failureRedirect: '/somePage' // redirect to Messenger if failure
}));
const server = http.createServer(app);
server.listen(port);
I solved it I think. Probably not the best way to go about it though. I'm passing the account linked redirect URI to the callback route and resolving the passport.authenticate in there redirecting if needed.
'use strict';
require('dotenv').config();
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const LINKED = {};
const http = require('http');
const port = '3000';
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const fbConfig = require('./oauth');
const cookieParser = require('cookie-parser');
const session = require('express-session');
// used to serialize the user for the session
// Not using these yet
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
const Botly = require('botly');
const botly = new Botly({
accessToken: process.env.ACCESS_TOKEN,
verifyToken: '123123321' // the verification token you provided when defining the webhook in facebook
});
const app = express();
// Listen on the account link event
botly.on('account_link', (sender, message, link) => {
// Continue conversation
console.log('CONFIRMED AUITH', link);
botly.sendText({
id: sender,
text: (link.status === 'unlinked') ? 'sorry to see you go' : 'Welcome'
});
});
botly.on('message', (senderId, message, data) => {
const text = `echo: ${data.text}`;
botly.sendText({
id: senderId,
text: text
});
botly.sendButtons({
id: senderId,
text: 'Please Login :)',
buttons: [ botly.createAccountLinkButton(`https://${process.env.LOGIN_DOMAIN}/authorize/?senderId=' + senderId/`), botly.createAccountUnLinkButton() ]
});
});
app.use(bodyParser.json());
app.use('/', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'its_my_secret', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/webhook', botly.router());
app.set('port', port);
// Passport setup
passport.use('facebook', new FacebookStrategy({
clientID: fbConfig.facebook.clientID,
clientSecret: fbConfig.facebook.clientSecret,
callbackURL: fbConfig.facebook.callbackURL,
profileFields: [ 'id', 'displayName', 'email' ]
},
// facebook will send back the tokens and profile
function (request, access_token, refresh_token, profile, done) {
// asynchronous
process.nextTick(function () {
return done(null, profile);
});
}));
/*
* This path is used for account linking. The account linking call-to-action
* (sendAccountLinking) is pointed to this URL.
*
*/
app.get('/authorize', function (req, res, next) {
req.session.senderId = req.query.senderId;
console.log('%%%%%%%% AccountLinking Testing');
const accountLinkingToken = req.query.account_linking_token;
const redirectURI = req.query.redirect_uri;
console.log('%%%%% /authorize called with accountLinkingToken %s, redirectURI %s', accountLinkingToken, redirectURI);
// Authorization Code should be generated per user by the developer. This will
// be passed to the Account Linking callback.
const authCode = '1234567890';
// Redirect users to this URI on successful login
const redirectURISuccess = `${redirectURI}&authorization_code=${authCode}`;
LINKED.redirect = redirectURISuccess;
console.log('redirect to this ', redirectURISuccess);
passport.authenticate('facebook', { scope: [ 'email' ] },
{
state: {
senderId: req.query.senderId // senderId will be used after auth to reply to the user
}
})(req, res, next);
});
// Redirection after login
app.get('/auth/fb/callback', (req, res, next) => {
passport.authenticate('facebook', (err, user, info) => {
if (err) { return next(err); }
if (!user) {
console.log('bad', info);
return res.redirect(LINKED.redirect);
}
console.log('good');
LINKED.user = user;
})(req, res, next);
res.redirect(LINKED.redirect);
});
const server = http.createServer(app);
server.listen(port);