Authentication using passportJs is the most popular and secure module. By using passportJs, we can signin / login / authenticate very easily and quickly.
We can also twitter authenticate using passport-twitter.
Here we will discuss regarding twitter authentication.
login.html
user.js (user model) // Stored in /app/model/user.js
routes.js
From this way, we can authenticate with twitter by using passport-twitter module in nodejs.
For authenticate by email and password using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/authentication-using-passpotjs-in-nodejs.html
For facebook authenticate using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/facebook-authentication-using-passpotjs-in-nodejs.html
We can also twitter authenticate using passport-twitter.
Here we will discuss regarding twitter authentication.
login.html
<div ng-controller="UserLoginController as ctrl">
<h2>Login</h2>
Your form for login by email and password ....
<a href="javascript:void(0)" onClick="window.location.href='/user/loginByTwitter';">
<img src="images/icon/twitter.png" class="">
</a>
</div>
<h2>Login</h2>
Your form for login by email and password ....
<a href="javascript:void(0)" onClick="window.location.href='/user/loginByTwitter';">
<img src="images/icon/twitter.png" class="">
</a>
</div>
user.js (user model) // Stored in /app/model/user.js
'use strict';
/*
*Declare variables and include mongoose
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var jwt = require('jsonwebtoken');
/*
*Define structure of collection
*/
var userSchema = new Schema({
social_id: { type: String },
social_type: { type: String },
user_name: { type: String },
email: {
type: String,
index: true
},
password: String
is_active: { type: String, enum: ['1', '0'], default: "1" },
created_at: {
type: Date,
default: Date.now
},
updated_at: { type: Date },
}, { collection: 'user' });
/*
*Validations
*/
userSchema.path('email').required(true, 'email is required!');
userSchema.path('email').match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'fill a valid email address');
userSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err)
return done(err);
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
/*
*methods
*/
userSchema.methods.generateJwt = function() {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
user_name: this.user_name,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET", {
expiresIn: '7d' //7 days
}); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
/*
*Define model and export it for user in other page
*/
var User = mongoose.model('User', userSchema);
module.exports = User;
/*
*Declare variables and include mongoose
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var jwt = require('jsonwebtoken');
/*
*Define structure of collection
*/
var userSchema = new Schema({
social_id: { type: String },
social_type: { type: String },
user_name: { type: String },
email: {
type: String,
index: true
},
password: String
is_active: { type: String, enum: ['1', '0'], default: "1" },
created_at: {
type: Date,
default: Date.now
},
updated_at: { type: Date },
}, { collection: 'user' });
/*
*Validations
*/
userSchema.path('email').required(true, 'email is required!');
userSchema.path('email').match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'fill a valid email address');
userSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err)
return done(err);
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
/*
*methods
*/
userSchema.methods.generateJwt = function() {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
user_name: this.user_name,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET", {
expiresIn: '7d' //7 days
}); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
/*
*Define model and export it for user in other page
*/
var User = mongoose.model('User', userSchema);
module.exports = User;
routes.js
var passport = require('passport');
var TwitterStrategy = require('passport-twitter').Strategy;
var mongoose = require('mongoose');
var User = require('./models/user');
module.exports = function(app) {
//Start ============Twitter Passport authentication localStategy=============
passport.use(new TwitterStrategy({
consumerKey: "your twitter api client id",
consumerSecret: "your twitter api secret key",
callbackURL: "http://localhost/user/loginByTwitterCallback",//your live domain full url
includeEmail: true,
},
function (token, secreTtoken, profile, cb, done, req) {
process.nextTick(function () {
console.log(profile);
User.findOne({
social_id: profile.id,
social_media: "twitter",
is_active: 1
},
'social_id user_name email is_active',
function (err, user) {
if (!user) {
var infoData = "";
if (!!profile.id)
infoData += "social_no=" + profile.id;
if (!!profile.provider)
infoData += "&provider=" + profile.provider;
if (!!profile._json.screen_name)
infoData += "&username=" + profile._json.screen_name;
if (!!profile._json.email)
infoData += "&email=" + profile._json.email;
return cb(null, false, {profile: infoData});
} else {
return cb(null, user);
}
});
});
}
));
//End :=====================Passport authentication localStategy=============
router.get('/user/loginByTwitter', passport.authenticate('twitter'), function (req, res) {});
router.get('/api/user/loginByTwitterCallback', function (req, res) {
passport.authenticate('twitter', function (err, user, info) {
if (err) {
logger.log("error", "twitter login error : " + err);
res.json({status: 0, , message: err});
}
if (!user) {
res.redirect("Your user register path");
} else {
req.login(user, {}, function (err) {
if (err) {
res.redirect("Your user sign in path"+"/?errormessage=Could not login user");
} else {
logger.log("info", user._id + ' user logged in');
var _res = user.generateJWT(user);
res.cookie('hz-token', _res, {maxAge: 60 * 60 * 24 * 7 * 1000, httpOnly: false});
res.redirect("Your redirection url after user login");
}
});
}
})(req, res);
});
};
var TwitterStrategy = require('passport-twitter').Strategy;
var mongoose = require('mongoose');
var User = require('./models/user');
module.exports = function(app) {
//Start ============Twitter Passport authentication localStategy=============
passport.use(new TwitterStrategy({
consumerKey: "your twitter api client id",
consumerSecret: "your twitter api secret key",
callbackURL: "http://localhost/user/loginByTwitterCallback",//your live domain full url
includeEmail: true,
},
function (token, secreTtoken, profile, cb, done, req) {
process.nextTick(function () {
console.log(profile);
User.findOne({
social_id: profile.id,
social_media: "twitter",
is_active: 1
},
'social_id user_name email is_active',
function (err, user) {
if (!user) {
var infoData = "";
if (!!profile.id)
infoData += "social_no=" + profile.id;
if (!!profile.provider)
infoData += "&provider=" + profile.provider;
if (!!profile._json.screen_name)
infoData += "&username=" + profile._json.screen_name;
if (!!profile._json.email)
infoData += "&email=" + profile._json.email;
return cb(null, false, {profile: infoData});
} else {
return cb(null, user);
}
});
});
}
));
//End :=====================Passport authentication localStategy=============
router.get('/user/loginByTwitter', passport.authenticate('twitter'), function (req, res) {});
router.get('/api/user/loginByTwitterCallback', function (req, res) {
passport.authenticate('twitter', function (err, user, info) {
if (err) {
logger.log("error", "twitter login error : " + err);
res.json({status: 0, , message: err});
}
if (!user) {
res.redirect("Your user register path");
} else {
req.login(user, {}, function (err) {
if (err) {
res.redirect("Your user sign in path"+"/?errormessage=Could not login user");
} else {
logger.log("info", user._id + ' user logged in');
var _res = user.generateJWT(user);
res.cookie('hz-token', _res, {maxAge: 60 * 60 * 24 * 7 * 1000, httpOnly: false});
res.redirect("Your redirection url after user login");
}
});
}
})(req, res);
});
};
From this way, we can authenticate with twitter by using passport-twitter module in nodejs.
For authenticate by email and password using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/authentication-using-passpotjs-in-nodejs.html
For facebook authenticate using passportJs, review following link
https://laxmanchavda.blogspot.in/2018/03/facebook-authentication-using-passpotjs-in-nodejs.html
No comments:
Post a Comment