I am trying to create a tweet to the user profile using twit package. This is the code I am using. By using this code I am able to tweet to my profile because I have access_token and access_token_secret. My question is If I want to tweet to some other people's profile. What is the procedure to do it I am not able to understand? I am using passport library to get the user details.
var Twit = require('twit');
var T = new Twit({
consumer_key: '************',
consumer_secret: '**********',
access_token: '******************',
access_token_secret: '******************',
timeout_ms: 60 * 1000,
strictSSL: true,
})
T.post('statuses/update', {status: 'hello world! '}, function(err, data, response) {
console.log('post on ',data);
})
Below down is my passport authentication code
'use strict';
require('dotenv').config();
const path = require('path');
const express = require('express');
const passport = require('passport');
const { Strategy } = require('passport-twitter');
const { TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, SESSION_SECRET } = process.env;
const port = process.env.PORT || 3000;
const app = express();
const routes = require('./routes');
passport.use(new Strategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: '/return'
},
(token, tokenSecret, profile, cb) => {
console.log(token);
console.log(tokenSecret);
console.log(profile);
return cb(null, profile);
}));
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(require('express-session')({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.listen(port);
another file
'use strict';
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/', (req, res, next) => {
const { user } = req;
console.log('user details', req.user);
// res.render('home', { user });
});
router.get('/login/twitter', passport.authenticate('twitter'));
router.get('/logout', (req, res, next) => {
req.logout();
res.redirect('/');
});
router.get('/return',
passport.authenticate('twitter', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/');
});
module.exports = router;
Got the answer following these steps. https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a
Related
I was trying to learn how to use passport-local with its documentation and I could do this, however when I submit the form it does not redirect to any site
const express = require("express");
const router = express.Router();
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const UserList = [{ email: "1#1", password: "1" }];
passport.use(new localStrategy(async (email, password, done) => {
const thisUser = UserList.find(x => x.email = "email" && x.password == password);
return done(null, thisUser)
}));
router.get('/signup', (req, res) => {
res.render('auth/signup.hbs')
});
router.post('/signup', (req, res) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
})
});
module.exports = router;
You forgot to initialize passport with
app.use(passport.initialize());
and serializeUser with
passport.serializeUser(function (user, done) {
done(null, user);
});
You can view the full example below. I did a test and it worked.
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var passport = require('passport');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy;
app.use(morgan('dev')); // log tất cả request ra console log
app.use(cookieParser()); // đọc cookie (cần cho xác thực)
app.use(bodyParser()); // lấy thông tin từ html forms
app.set('view engine', 'ejs'); // cài đặt ejs là templating
app.use(passport.initialize());
const UserList = [{email: "1#1", password: "1"}];
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // cho phép chúng ta gửi reqest lại hàm callback
},
function (req, email, password, done) {
process.nextTick(function () {
const thisUser = UserList.find(x => x.email = "email" && x.password == password);
return done(null, thisUser)
});
}));
//
// routes ======================================================================
app.get('/', function (req, res) {
res.render('index.ejs'); // load the index.ejs file
});
app.get('/signup', function (req, res) {
res.render('signup.ejs');
});
app.post('/signup', passport.authenticate('local-signup', {
successRedirect: '/',
failureRedirect: '/signup',
}))
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
I am using node.js express with sequelize and database postgreSql.the problem is in passport login failureRedirect works properly sucessRedirect does not redirect to the page that I want. It still loading and not responding anything and does not come any error.
when I submit login it will check for errors if errors it will work perfectly in failureRedirect but in Success it does not work like page has loading only not goes to the destination page and if I stop the project and restart the project it will be in destination page!! i dont know what is the problem help me.
mainController.js
const express = require("express");
const sessions = require("express-session");
require("../model/MasterUser.model");
const passport = require("passport");
var session = sessions;
const router = express.Router();
router.get("/dashboard", (req, res) => {
res.render('dashboard');
});
router.get("/login", (req, res) => {
res.render("login", { layout: "login.hbs" });
});
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/main/dashboard",
failureRedirect: "/main/login",
failureFlash: true,
})
);
module.exports = router;
passport.js
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");
const sequelize = require("sequelize");
const masterUser = require("../model/MasterUser.model");
module.exports = function (passport) {
passport.use(
new LocalStrategy(
{ usernameField: "user_name" },
(user_name, password, done) => {
// Match user
masterUser.findOne({ where: { user_name: user_name } }).then((user) => {
if (!user) {
return done(null, false, {
message: "This username is not registered",
});
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: "Password incorrect" });
}
});
});
}
)
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
index.js
const express = require("express");
const Handlebars = require("handlebars");
var flash = require("connect-flash");
const app = express();
const path = require("path");
const bodyparser = require("body-parser");
const expressHandlebars = require("express-handlebars");
const passport = require("passport");
const sessions = require("express-session");
var session = sessions;
const MainController = require("./controllers/MainController");
const db = require("./config/database");
//test db
db.authenticate()
.then(() => console.log("Database Connected..."))
.catch((err) => console.log("error" + err));
//for security purpose
const cors = require("cors");
app.use(
cors()
);
//Passport Config
require("./config/passport")(passport);
app.use(cookieParser());
//use body parser
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));
const {
allowInsecurePrototypeAccess,
} = require("#handlebars/allow-prototype-access");
app.use(
bodyparser.urlencoded({
urlencoded: true,
})
);
app.use(
sessions({
secret: "secret_key",
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
})
);
// use flash for show messages
app.use(flash());
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
//flash messages
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
//setting up view Engine
app.set("views", path.join(__dirname, "/views"));
//using the hbs
app.engine(
"hbs",
expressHandlebars({
extname: "hbs",
defaultLayout: "default",
layoutsDir: __dirname + "/views/layouts",
handlebars: allowInsecurePrototypeAccess(Handlebars),
})
);
app.set("view engine", "hbs");
//route for Main
app.use("/main", MainController);
//default
app.get("/", (req, res) => {
res.render("login");
});
app.listen(3000, () => {
console.log("App listening on port 3000!");
});
the problem has been solved guys I made done wrong code in deserializeUser.
passport.js before
passport.deserializeUser((id, done) => {
masterUser.findByPk(id, (err, user) => {
done(err, user);
});
});
};
passport.js after
passport.deserializeUser(function (id, done) {
masterUser.findOne({ where: { id: id } }).then((user) => {
done(null, user);
});
});
the problem is for sequelize get the user data is different so now its worked for me.this is useful for who using express with sequelize and passport with postgresql
my passport strategy is never called. I recently added passport to my project and am using Boxes API to log a user in. I have done the example problem in another project and gotten it to work (https://github.com/smithdavedesign/OAUTH-Passport-BoxAPILogin-Example/blob/master/login/BoxLogin.js), however when I am trying to integrate it into my current project something has gone haywire. I read sessions and passport session are different and should not cause an issue, that being said I trying to figure out what middle ware is causing the issue. The box API is working correctly and returning me to my dashboard on the callback, however passport seams to be being skipped.
var products = require("../controllers/products");//get functions from product like add update delete ect
var validations = require("../controllers/validations");//get functions from product like add update delete ect
var settings = require("../config/settings");// get all things from settings we need
var Promise = require("bluebird");// adding promise mechanism
var bodyParser = require('body-parser');
var express = require('express');//web framework for node
const expressLayouts = require('express-ejs-layouts');// ejs view engine
const flash = require('connect-flash');//for error and success messages
const session = require('express-session');// holds data of users after login
const uuid = require('uuid')
var MemoryStore = require('memorystore')(session)//https://www.npmjs.com/package/memorystore
const util = require('util');
var os = require("os");
var hostname = os.hostname();//This is the users computer name
const multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage: storage })
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var BoxStrategy = require('passport-box').Strategy;
const app = express();//create instance of express
var BOX_CLIENT_ID = "**";
var BOX_CLIENT_SECRET = "**";
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
console.log("serializeUser")//NEVER BEING CALLED
done(null, user);
});
passport.deserializeUser(function (obj, done) {
console.log("deserializeUser")//NEVER BEING CALLED
done(null, obj);
});
passport.use(new BoxStrategy({
clientID: BOX_CLIENT_ID,
clientSecret: BOX_CLIENT_SECRET,
callbackURL: "http://localhost:9000/dashboard"
},
function (accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
return done(null, profile);
});
}
));
//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');//view engine
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(
session({
genid: (req) => {
console.log('Inside session middleware genid function')
console.log('Request object sessionID from client: ' + req.sessionID);
var new_sid = uuid.v4();
console.log('New session id generated: ' + new_sid);
return new_sid; // use UUIDs for session IDs
},
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
secret: 'secret',
resave: true,
httpOnly: false,
saveUninitialized: false,
cookie: {
maxAge: 24 * 60 * 60 * 1000
}
})
);
// Connect flash
app.use(flash());
// Global variables
app.use(function (req, res, next) {//diferent colors
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
//routes
app.use('/', require('./GraphRoutes'));
app.use('/', require('./dashboardRoutes'));
app.use('/', require('./index'));
app.use('/', require('./extraProccess'));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));//public folder where all templates live
app.use(express.static("."));
app.get('/', function (req, res) {
res.render('index', { user: req.user });
});
app.get('/login', function (req, res) {
res.render('login', { user: req.user });
});
app.get('/auth/box', passport.authenticate('box'), function (req, res) {
console.log("box call")
});
app.get('/auth/box/callback',
passport.authenticate('box', { failureRedirect: '/login' }),
function (req, res) {
res.redirect('/dashboard');
});
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/login');
});
I was calling my routes before initializing passport, as well as having cookie parser and other middle ware not in the correct spot.
I am using passport.js for twitter social login. In my Web app after a successful login, it will populate the tweets accordingly and will reply to the tweets as per the loggedIn user credentials. Currently, I am able to successfully redirect after login, but not able to fetch the user details which passport gives after successful login i.e (username, email). As a result, I am not able to go further.
Below is the node server.js file.
Kindly help me with this issue.
server.js
const express = require('express');
const TwitterStrategy = require('passport-twitter').Strategy;
const twitConfig = require('./config/auth').twitterAuth;
const passport = require('passport');
const path = require('path');
const bodyParser = require('body-parser');
// Create a new Express application.
const app = express();
// require('./routes/')(app);
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('cookie-parser')());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
//initialize passport strategy for twitter login.
passport.use(new TwitterStrategy({
consumerKey: twitConfig.consumer_key,
consumerSecret: twitConfig.consumer_secret,
callbackURL: twitConfig.callbackURL
}, (token, tokenSecret, profile, callback) => {
console.log('arguments in passport.use>>>>>>>>>>>>>>>', arguments);
console.log('profile in twitterStrategy>>>>>>>>>>>>>', profile,callback);
process.nextTick(() => {
if (err) {
console.log('err in passport TwitterStrategy>>>>>>>>>>>',err)
return callback()
} else {
console.log('inside the else condition no error found>>>>>>>>>>',profile)
}
})
return callback(null, profile);
}));
const twit = require('twit');
const T = new twit(twitConfig);
passport.serializeUser(function(user, callback) {
console.log('arguments in serializeUser passport.use>>>>>>>>>>>>>>>', arguments);
callback(null, user);
})
passport.deserializeUser(function (obj, callback) {
console.log('arguments in deserializeUser passport.use>>>>>>>>>>>>>>>', arguments);
callback(null, obj);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//load the routes
app.use(require('./routes/twitterApi'));
app.use(require('./routes/token'));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
console.log('user in />>>>>>>>>>>>>>', req);
res.render('index', {user: req.user})
})
app.get('/twitter/login', passport.authenticate('twitter'), (req, res) => {
console.log('consoe.log req>>>>>>>>>>>>>', req);
console.log('res >>>>>>>>>>',res);
});
app.get('/twitter/return', passport.authenticate('twitter', { failureRedirect: '/' }), function (req, res) {
console.log('inside the return failure');
res.redirect('http://localhost:8080/');
})
// listen for requests :)
const listener = app.listen(process.env.PORT || 9000, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
Here is an async/await example of how to perform a database operation on the User, after authenticating with passport strategy.
passport.use(new TwitterStrategy({
consumerKey: twitConfig.consumer_key,
consumerSecret: twitConfig.consumer_secret,
callbackURL: twitConfig.callbackURL
}, async (token, tokenSecret, profile, callback) => {
try {
// Perform some kind of db lookup/create with profile object
const user = await User.findOne({
where: {
email: profile.email
}
})
// now your user object will be passed to your callbackURL
return callback(null, user)
}
catch(error) {
return callback(error, error.message);
}
i am worked nodejs/Angular passport middleware login Authentication working fine but when I try to get login username with the help of req.authentication's not call the passport.deserializeUser function always req.authentication is shown false help how to rectify this problem any ideas.
here i pasted my tried code
Server.js
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
// const logger = require('morgan');
var cookieParser = require('cookie-parser');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const dotenv = require('dotenv');
const path = require('path');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');
const expressValidator = require('express-validator');
const http = require('http');
const app = express();
// cros origin handling method start
const cors = require('cors');
dotenv.load({ path: '.env.Config' });
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.set('views', __dirname + '\\public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//mongodb config
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on('error', () => {
console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
process.exit();
});
app.use(cookieParser(process.env.SESSION_SECRET));
app.enable('trust proxy'); // add this line
//express session config
app.use(session({
name: 'UpgradeApp.sid',
resave: true,
// saveUninitialized: true,
secret: process.env.SESSION_SECRET,
store: new MongoStore({
url: process.env.MONGODB_URI,
autoReconnect: true
}),
proxy: true, // add this line
saveUninitialized: false,
cookie: {//New
maxAge: 36000000,
httpOnly: false,
secure: false
}
}));
require('./src/SchemaConfig/PassportConfig');
//cors origin config
app.use(cors({
origin: ['http://localhost:4200', 'http://127.0.0.1:4200', 'http://192.168.1.93:4200'],
credentials: true
}));
//bodyparser config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb", extended: true, parameterLimit: 200000 }));
app.use(passport.initialize());
app.use(passport.session());
//schema config
const UserConfig = require('./src/SchemaConfig/UserSchema');
function isAuthenticated(req, res, next) {
var ss = req.isAuthenticated();//always show false
if (req.isAuthenticated()) next();
else return res.json('Un-Authenticated');
};
app.get('/logout', isAuthenticated, function (req, res) {
req.logout();
res.json("logout");
});
app.get('/GetUser', isAuthenticated, function (req, res, next) {
return res.json(req.user.UserName);
});
app.post('/login', UserConfig.loginVerify);
app.set('port', process.env.App_PORT || 3000);
app.listen(app.get('port'), () => {
console.log('%s server running on port', chalk.green('✓'), app.get('port'));
console.log(' Press CTRL-C to stop\n');
});
PassportConfig
const User = require('../SchemaConfig/UserSchema');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt-nodejs');
passport.use('local', new LocalStrategy({
usernameField: 'Email',
passwordField: 'Password'
},
function (Email, Password, done) {
debugger
User.findOne({ Email: Email }, function (err, user) {
debugger
if (err) { return done(err); }
if (!user) {
return done(null, false, {
ErrorMsg: 'Incorrect Email.'
});
}
if (user) {
GlobalUserPwd = user.Password;
}
if (!ComparePassword(Password)) {
return done(null, false, {
ErrorMsg: 'Incorrect password.'
});
}
return done(null, user);
});
}
));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
function ComparePassword(CandidatePassword) {
return bcrypt.compareSync(CandidatePassword, GlobalUserPwd)
};
Userschema
exports.loginVerify = (req, res, next) => {
passport.authenticate('local', function (err, user, info) {
debugger
if (err) { return next(err); }
if (!user) { return res.status(501).json(info); }
req.logIn(user, function (err) {
if (err) { return next(err); }
return res.status(200).json({message:'Login Success'});
});
})(req, res, next);
};
Finally i found a solution for my problem passing login header request with withCredentials:true
const httpOptions = {
observe:'body',
withCredentials:true,
headers:new HttpHeaders().append('Content-Type','application/json')
};