I am using a nodejs-express-passport solution for authentication with facebook. My goal is to automatically upload an image from a static directory the moment that a user is successfully logged in.
If my image is simply animal.png located at /images how would I modify
the following node-express server code to accomplish this?
var express = require('express');
var passport = require('passport');
var Strategy = require('passport-facebook').Strategy;
passport.use(new Strategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: 'http://localhost:3000/login/facebook/return'
},
function(accessToken, refreshToken, profile, cb) {
return cb(null, profile);
}));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.get('/login',
function(req, res){
res.render('login');
});
app.get('/login/facebook',
passport.authenticate('facebook','user_photos'));
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.listen(3000);
For res.render('profile', {user: req.user, image: 'my image string location'})
then with your html just pass in {{image}} to wherever you are trying to src the image from.
I am not super familiar with ejs templating but it'd look something like this:
<img src={{image}} alt="MyAnimal.png" style="width:304px;height:228px;">
Or did you want it to just flash on the screen? If that's the case I think you can do something like that with the flash module.
Edit:
I'll move this up here as this was a question for posting desktop data to facebook and not just popping up a picture from the server.
Passport does authentication handshakes to allow people access to your website via login, it does not however open up all the api's to Twitter/Facebook/Google, you'll need to either make them yourself, or use ones that are pre built like this Facebook API.
https://www.npmjs.com/package/fb
Related
I want to have an online map which publicly loads and shows all my activities from my Strava account.
I have found a web app on GitHub which does what I want but the user has to log in with the Strava log in screen before he than can see his own activities: https://github.com/nsynes/ActivityMap
It seems it uses Passport Strava to authenticate with Strava: https://www.passportjs.org/packages/passport-strava-oauth2/
Is it possible to adjust the script so it always logs in automatically my account and than shows my activities publicly to everyone who visits the map?
The full script is here: https://github.com/nsynes/ActivityMap/blob/master/activity-map-app.js
My STRAVA_CLIENT_ID and STRAVA_CLIENT_SECRET are from my Strava account and saved in a .env file.
const express = require('express')
const passport = require('passport')
const util = require('util')
const StravaStrategy = require('passport-strava-oauth2').Strategy
const dotenv = require('dotenv');
const path = require('path');
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser');
const session = require('express-session');
var strava = require('strava-v3');
const decode = require('geojson-polyline').decode
const geodist = require('geodist');
dotenv.config();
const port = process.env.PORT || 3000
const app = express();
// configure Express
//app.use(express.logger());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(express.methodOverride());
app.use(session({
secret: 'monkey tennis',
resave: true,
saveUninitialized: true,
maxAge: 1800 * 1000
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/css', express.static(path.join(__dirname, 'css')));
app.use('/fontawesome', express.static(path.join(__dirname, 'fontawesome')));
app.use('/js', express.static(path.join(__dirname, 'js')));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Passport session setup.
passport.serializeUser(function(user, done) { done(null, user) });
passport.deserializeUser(function(obj, done) {done(null, obj) });
passport.use(new StravaStrategy({
clientID: process.env.STRAVA_CLIENT_ID,
clientSecret: process.env.STRAVA_CLIENT_SECRET,
callbackURL: "/auth/strava/callback"
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// To keep the example simple, the user's Strava profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the Strava account with a user record in your database,
// and return that user instead.
return done(null, profile);
});
}
));
app.get('/', ensureAuthenticated, function(req, res){
pagePath = path.join(__dirname, '/index.html');
res.sendFile(pagePath);
});
app.get('/userPhoto', ensureAuthenticated, function(req, res){
if ( req.user ) {
res.json({ 'photo': req.user.photos[req.user.photos.length-1].value });
} else {
res.sendStatus(404);
}
});
// Use passport.authenticate() as route middleware to authenticate the
// request. Redirect user to strava, then strava will redirect user back to
// this application at /auth/strava/callback
app.get('/auth/strava',
passport.authenticate('strava', { scope: ['activity:read'], approval_prompt: ['force'] }),
function(req, res){
// The request will be redirected to Strava for authentication, so this
// function will not be called.
});
// GET /auth/strava/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/strava/callback',
passport.authenticate('strava', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout', function(req, res){
req.logout();
res.cookie("connect.sid", "", { expires: new Date() });
res.render('login', { user: req.user });
});
app.get('/login', function(req, res){
res.render('login', { user: req.user });
});
So I have been working with PassportJS in adding authentication to my site. I am interested in selectively displaying content that reflects whether or not a user is logged in or if he/she is an owner of a document.
I have the following files
app.js (entry point)
//Express set up
let express = require("express");
app = express();
serverPort = 8000;
io = require('socket.io')();
//BodyParser set up
bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
//Mongoose set up
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/Woof");
//Models settings
Dog = require("./models/dog");
User = require("./models/user");
//Seed file set up and run!
seed = require("./models/seed");
seed();
//Routes
app.use('/public', express.static(__dirname + '/public'));
app.use(require('./routes/dogOwners'));
app.use(require('./routes/landing'));
app.use(require('./routes/loginAndRegister'));
app.use(require('./routes/map'));
app.use(require('./routes/dog'));
//req.user avalaible to all routes
app.use(function(req,res,next){
res.locals.currentUser = req.user;
next();
});
//App settings
app.set('port', serverPort);
app.set('view engine', 'ejs');
app.set('views', 'views');
app.set('sockets', []);
//Servloger listen:
let server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
loginAndRegistration.js These are the authentication routes
let express = require('express');
router = express.Router({ mergeParams: true });
User = require("../models/user")
//AUTHENTICATION
let passport = require("passport");
LocalStratergy = require("passport-local");
//PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "I wanna go poopie",
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req,res,next){
res.locals.currentUser = req.user;
next();
});
passport.use(new LocalStratergy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
router.get('/login', function(req,res){
res.render('login');
});
router.post('/login', passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login",
}), function(req, res) {
});
router.get('/logout', function(req,res){
req.logout();
res.redirect("/");
});
router.get('/register', function(req, res) {
res.render('register', {});
});
router.post("/register", function(req, res) {
User.register(new User({ username: req.body.username }), req.body.password, function(error, newlyCreatedUser) {
if (error) {
console.log("COULD NOT REGISTER USER IN THE POST ROUTE");
res.render("register");
console.log(error);
} else {
passport.authenticate("local")(req, res, function() {
let user = req.body.user;
newlyCreatedUser.name = user.name;
newlyCreatedUser.nickname = user.nickname;
newlyCreatedUser.address = user.address;
newlyCreatedUser.email = user.email;
newlyCreatedUser.numberOfDogs = user.numberOfDogs;
newlyCreatedUser.url = "/user/" + newlyCreatedUser.id;
newlyCreatedUser.save(function(error, savedUser) {
console.log("USER REGISTERED");
res.render('maps', {
gmapsCredential: credentials.gmaps,
'authorized': true
});
});
});
}
});
});
function isLoggedIn (req,res,next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;
I wanna be able to call isLoggedIn in all my routes, but I can only use it in the auth routes. How do I selectively export that function alone to all my routes? I also wanna be able to refer to the varaible currentUser in all my .ejs files, however it only works in .ejs files associated with the auth routes. How do I check for currentUser in all my .ejs files?
The crux of your problems are you’ve got too much buried in your loginAndRegistration.js file.
First and foremost, if you want to run isLoggedIn for every route you need to make sure Passport is configured first i.e.
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req,res,next){
res.locals.currentUser = req.user;
next();
});
passport.use(new LocalStratergy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Needs to be setup before you configure any auth middleware. This will also solve your .ejs problem as user will now be getting serialised for every route and not just the auth ones.
Finally, you can configure your middleware before any routes you want to enforce authentication on
app.use(isLoggedIn);
I'm trying to access 'testpage' route. But the req.isAuthenticated() returns false only for this route. (This route was there before I started to add authentication).
I'm able to go to login page and authenticate with google. Then I can access 'signup' or 'user_profile' route without problems.
After login if I try:
localhost:8080/testpage
the server sends me to "/". But if I try:
localhost:8080/testpage#
with hash sign in the end, the page is rendered.
// routes/users.js
var express = require('express');
var router = express.Router();
module.exports = function (passport) {
router.get('/login', function (req, res) {
res.render('login', { message: req.flash('loginMessage') });
});
router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/',
failureRedirect: '/'
}));
router.get('/user_profile', isLoggedIn, function (req, res) {
res.render('user_profile');
});
router.get('/signup', isLoggedIn, function (req, res) {
res.render('signup');
});
router.get('/testpage', isLoggedIn, function (req, res) {
res.render('testpage');
});
return router;
};
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
Any ideas why this is happening?
* update *
Here my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var db = require('./mongoose');
var app = express();
require('./config/passport')(passport);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret123',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
var users = require('./routes/users')(passport);
app.use('/', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
It could be due to the express-session middleware that is needed for passport. you can fix it by using middleware in following order.
var session = require('express-session')
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'yoursecret',
resave: true,
saveUninitialized: true,
cookie: { secure: true },
// you can store your sessions in mongo or in mysql or redis where ever you want.
store: new MongoStore({
url: "mongourl",
collection: 'sessions' // collection in mongo where sessions are to be saved
})
}))
// Init passport
app.use(passport.initialize());
// persistent login sessions
app.use(passport.session());
See https://github.com/expressjs/session for more details.
Also I think so you have not config google strategy.
try some thing like following
var GoogleStrategy = require('passport-google-oauth').OAuthStrategy;
// Use the GoogleStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a token, tokenSecret, and Google profile), and
// invoke a callback with a user object.
passport.use(new GoogleStrategy({
consumerKey: GOOGLE_CONSUMER_KEY,
consumerSecret: GOOGLE_CONSUMER_SECRET,
callbackURL: "http://www.example.com/auth/google/callback"
},
function(token, tokenSecret, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}));
Finally after one entire day I just realized that when I was typing localhost:8000/testpage in the url bar it was been changed to www.localhost:8000/testpage. And the auth dos not work with www*. Another thing is that google chrome tries to predict what url you will type and this could cause this type of error, and it is annoying at debugging. So I unchecked this options at chrome's settings, preventing prediction.
Short summary of the problem: I'm using a new version of express (4.9.0) on a Node.js website which has a few public pages and a few private pages, which I'm putting behind a Google OAuth2 login, using PassportJS. When I request a page behind the sign-in, the user keeps being asked to sign-in; req.isAuthenticated() isn't "sticky". I've seen some comments online that there are can be problems with cookie parser versions being incompatible, so that could be the issue here.
Here is my (rather long) app.js:
var express = require('express');
var http = require('http');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'mysecret' }));
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('port', process.env.PORT || 3000);
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: clientId,
clientSecret: secret,
callbackURL: "http://127.0.0.1:3000/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
return done(null, profile);
});
}
));
app.get('/auth/google',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'] }),
function(req, res){
});
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
console.log("successfully authenticated with google");
res.redirect('/');
});
app.get('/login', function(req, res){
res.redirect('/auth/google');
});
app.get('/privatepage', ensureAuthenticated, function(req, res) {
var dostuff = module.listThings(function(rows) {
res.render('somepage.html', {
title : "some page",
data : rows
});
});
});
function ensureAuthenticated(req, res, next) {
console.log("in ensureAuth", req.isAuthenticated());
console.log("session data", req.session);
console.log("user data", req.user);
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
var server = app.listen(3000, function() {
var host = server.address().address
var port = server.address().port
console.log('App listening at http://%s:%s', host, port)
})
After the first login, if I visit the /privatepage URL, I get re-directed through Google and land on the homepage again. This is what's in the log from those console.log lines:
in ensureAuth false
session data { cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: {} }
user data undefined
I assume this is some session issue where it doesn't store the user's logged in state, but I'm a node newbie & am a little stuck on how to fix this. I'm running on a single computer, so it's not a multiple machines issue. Any debugging suggestions, or ideas on the conflict causing the logged-in state not to be stored?
I'm trying to create a website using expressjs.
I want to send a different page to the user if he's logged in.
I'm able to send the raw html website, but linked files like index.css are not beeing loaded!
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere', resave: false, saveUninitialized: true}));
app.use(bodyParser());
//app.use(express.static(path.join(__dirname, '../client/login')));
// disable layout
var mainPage = express.static(path.join(__dirname, '../client/main'));
var loginPage = express.static(path.join(__dirname, '../client/login'));
app.get('/', function (req, res, next) {
console.log('getting /');
if (req.session.userName) {
//app.use(express.static(path.join(__dirname, '../client/main')));
console.log("logged in");
mainPage(req, res, next);
}else {
//app.use(express.static(path.join(__dirname, '../client/login')));
console.log("not logged in");
loginPage(req, res, next);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Thanks in advance!
Yes, you can.
You can do response.render(pageName); to render the page where you want to send the user.
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere', resave: false, saveUninitialized: true}));
app.use(bodyParser());
//app.use(express.static(path.join(__dirname, '../client/login')));
// disable layout
// view engine setup
app.set('views', path.join(__dirname, '../client'));
app.set('view engine', 'jade');
app.get('/', function (req, res, next) {
console.log('getting /');
if (req.session.userName) {
//app.use(express.static(path.join(__dirname, '../client/main')));
console.log("logged in");
res.render("mainPage");
}else {
//app.use(express.static(path.join(__dirname, '../client/login')));
console.log("not logged in");
res.render("loginPage");
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I used jade templating engine, you can use any other
It looks like the code you have is just checking a session for a user name -- I'd highly recommend AGAINST doing this, as it's not a secure way to do authentication.
If you want a secure way to do auth you should look into using a tool like either passportjs or stormpath. Stormpath does a bunch of stuff (api auth, social login, etc) in addition to the normal auth stuff, while passport is a bit more bare-bones.
Here's an example using Stormpath to do what you want:
app.get('/', function(req, res) {
if (req.user) {
res.render('template');
} else {
res.render('anonymousTemplate');
}
});
Full disclosure: I work # Stormpath and am the author of that library -- but it is awesome all the same.