Passport.js Ajax login? - ajax

Is it possible to login via ajax with passport.js?
The thing is i'm creating a user via ajax and i want it to be logged in automatically (everything with json in a restful style) but the req.login() does some stuff that i don't know and that apparently sends its own status, headers and even it redirects to the home but and i need is to create my own json response.
The code where i create the user:
signup_facebook: function (req, res) {
var restponse = new Restponse();
var body = req.body;
var obj = {
display_name: body.first_name,
name: body.first_name,
surname: body.last_name,
photos: ['http://graph.facebook.com/'+ body.id+ '/picture?type=normal'],
gender: body.gender,
facebook: {
userID: body.id,
displayName: body.display_name
}
}
User.facebookSignUp(obj, function(user){
if(user !== false){
user = obj;
restponse.location = '/';
restponse.status = HTTPStatus.REST.C201_OK;
}else{
restponse.location = '/';
restponse.status = HTTPStatus.REST.C302_FOUND;
}
restponse.body = user;
req.login(user, {}, function(err) {
APIheart.respondJson(res, restponse);
});
})
Thanks for your time!

I found the answer in this post:
http://toon.io/on-passportjs-specific-use-cases/
// Manually establish the session...
req.login(user, function(err) {
if (err) return next(err);
return res.json({
message: 'user authenticated',
});
});

Related

Data are not inserted in mongodb, it gives could not get any response error in postman

I build the project using the mean stack. I insert record using postman but I get one error, I try to resolve much time but not to find where is a mistake.
Postman error
This is models user.js file.which is shows userSchema details.
Models -> user.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var config = require('../config/database');
// User Schema
var UserSchema = mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username}
User.findOne(query, callback);
}
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUSer.password = hash;
newUser.save(callback);
});
});
}
This is Routes user.js file. here router of register displays, also define add user status results that can be shown if postman value is inserted in mongo then successfully another wise unsuccessfull message.
Routes -> users.js
var express = require('express');
var router = express.Router();
var password = require('passport');
var jwt = require('jsonwebtoken');
var User = require('../models/user');
// Register
router.post('/register', function(req, res, next){
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to Register User'});
} else {
res.json({success: true, msg:'User Registered'});
}
});
});
// Authenticate
router.post('/authenticate', function(req, res, next){
res.send('Authenticate');
});
// Profile
router.get('/profile', function(req, res, next){
res.send('Profile');
});
module.exports = router;
You are sending the request wrongly from Postman. You should not use x-www-form-urlencoded. Use the Raw option at send it as a json object, like this:
{
"name": "Mark Melton",
"email": "xyz#gmail.com",
"username": "shuta",
"password": "Sunala123"
}
This is how it will work, because in your routes, you are using req.body...

Does Vue.JS work with AJAX http calls?

I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.

How to return json web token (jwt) with passport-facebook without showing it in the redirect url

I am using passport-facebook to login in a MEAN stack webapp. After successful login, I want to generate a JSON Web Token (jwt) and redirect to a page in my SPA. (res.redirect('/#/posts/'+ doc.generateJWT()); -- please see the associated code below).
My question is:
How do I send the JWT to the redirect page without showing it in the URL?
Code:
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: FACEBOOK_CALLBACKURL
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function () {
User.findOne({'fbid':profile.id},function(err, docs) {
if (err){
//console.log('Error in SignUp: '+err);
return res.status(401).json(info);
}
else {
if (docs) {
//console.log('User already exists');
globalid = profile.id;
return done(null,docs);
} else {
// if there is no user with that fbid
// create the user
var newUser = new User();
// set the user's local credentials
newUser.fbid = profile.id;
globalid = profile.id;
newUser.firstname = profile.name.givenName;
newUser.lastname = profile.name.familyName;
newUser.gender = profile.gender;
if(profile.emails){
newUser.fbemail = profile.emails[0].value;
};
newUser.fblink = profile.profileUrl;
newUser.fbverified = profile.verified;
// save the user
newUser.save(function(err) {
if (err){
//console.log('Error in Saving user: '+err);
return res.status(401).json(info);
}
//console.log('User Registration succesful');
return done(null, newUser);
});
}
}
});
});
}));
var router = express.Router();
router.get('/auth/facebook',
passport.authenticate('facebook', { scope : 'email' }
));
router.get('/auth/facebook/callback',
passport.authenticate('facebook', { session: false, failureRedirect: '/'}),
function(req, res,done) {
var redirection = true;
User.findOne({ 'fbid': globalid }, function (err, doc){
//console.log("Generating token");
doc.token = doc.generateJWT();
doc.save(function(err) {
if (err){
//console.log('Error in Saving token for old user: '+err);
return res.status(401).json(info);
}
else
{
//console.log('User Login succesful');
redirection = doc.mobileverified;
//console.log(redirection);
//return done(null, doc);
if(doc.mobileverified === true){
console.log("Token:",doc.generateJWT());
res.redirect('/#/posts/'+ doc.generateJWT());
}
else{
console.log("Token:",doc.generateJWT());
//res.json({token: doc.generateJWT()});
res.redirect('/#/register/' + doc.generateJWT());
}
}
});
});
});
Many Thanks in advance!
If you don't wanna show your token on the url you have to send the response as json
var fbOptions = {
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET,
callbackURL: FACEBOOK_CALLBACKURL
};
passport.use(new FacebookStrategy(fbOptions, function(token, refreshToken, profile, done) {
var user = profile;
// NOTE: ‘my_token’ we will use later
user.my_token = 'generate your jwt token';
done(null, user);
}));
And then on your router return the token as json
app.get('/auth/facebook/callback', passport.authenticate('facebook', {session: false, failureRedirect : '/'}), function(req, res) {
// The token we have created on FacebookStrategy above
var token = req.user.my_token;
res.json({ token: token });
});

submitAdapterAuthentication not working

I have been trying to do a specific operation once I receive the submitAdapterAuthentication from the challenge handler and I could not do any operation because my code it does not even compile through it. I am using the submitAdapterAuthentication in one method of my angular service. The method looks like this:
login: function (user, pass) {
//promise
var deferred = $q.defer();
//tempuser
tempUser = {username: user, password: pass};
userObj.user = user;
checkOnline().then(function (onl) {
if (onl) { //online
console.log("attempting online login");
var auth = "Basic " + window.btoa(user + ":" + pass);
var invocationData = {
parameters: [auth, user],
adapter: "SingleStepAuthAdapter",
procedure: "submitLogin"
};
ch.submitAdapterAuthentication(invocationData, {
onFailure: function (error) {
console.log("ERROR ON FAIL: ", error);
},
onConnectionFailure: function (error) {
console.log("BAD CONNECTION - OMAR", error);
},
timeout: 10000,
fromChallengeRequest: true,
onSuccess: function () {
console.log("-> submitAdapterAuthentication onSuccess!");
//update user info, as somehow isUserAuthenticated return false without it
WL.Client.updateUserInfo({
onSuccess: function () {
//return promise
deferred.resolve(true);
}
});
}
});
} else { //offline
console.log("attempting offline login");
deferred.resolve(offlineLogin());
}
uiService.hideBusyIndicator();
});
uiService.hideBusyIndicator();
return deferred.promise;
}
where ch is
var ch = WL.Client.createChallengeHandler(securityTest);
and checkOnline is this function that checks whether the user is online or not:
function checkOnline() {
var deferred = $q.defer();
WL.Client.connect({
onSuccess: function () {
console.log("** User is online!");
deferred.resolve(true);
},
onFailure: function () {
console.log("** User is offline!");
deferred.resolve(false);
},
timeout: 1000
});
return deferred.promise;
}
Finally this is the "submitLogin" procedure that I have in my SingleStepAuthAdapter.js. SingleStepAuthAdapter is the name of the adapter.
//-- exposed methods --//
function submitLogin(auth, username){
WL.Server.setActiveUser("SingleStepAuthAdapter", null);
var input = {
method : 'get',
headers: {Authorization: auth},
path : "/",
returnedContentType : 'plain'
};
var response = "No response";
response = WL.Server.invokeHttp(input);
WL.Logger.info('Response: ' + response.isSuccessful);
WL.Logger.info('response.responseHeader: ' + response.responseHeader);
WL.Logger.info('response.statusCode: ' + response.statusCode);
if (response.isSuccessful === true && (response.statusCode === 200)){
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("SingleStepAuthAdapter", userIdentity);
return {
authRequired: false
};
}
WL.Logger.error('Auth unsuccessful');
return onAuthRequired(null, "Invalid login credentials");
}
So I am trying to send a promise to my controller in order to redirect the user to another page but the promise is not being returned as the challenge handler is not even working.
And by the way, I have followed this tutorial: https://medium.com/#papasimons/worklight-authentication-done-right-with-angularjs-768aa933329c
Does anyone know what this is happening?
Your understanding of the Challenge Handler and mine are considerably different.
Although the
ch.submitAdapterAuthentication()
is similar in structure to the standard adapter invocation methods I have never used any callbacks with it.
I work from the IBM AdapteBasedAuthentication tutorial materials
The basic idea is that your challenge handler should have two callback methods:
isCustomResponse()
handleChallenge()
You will see these functions invoked in response to your submission.
I suggest that start by looking at those methods. I can't comment on the ionic example you reference, but I have myself used angular/ionic with the authentication framework and challenge handlers. My starting point was the IBM material I reference above.

Node.js modified AJAX insertion to MongoDB

I am succesfully posting an AJAX insert in my MondoDB database.
The user is supposed to fill in 3 fields,
Full Name
Email
Phone
What I would like to do is:
generate a random number in server-side and save it as a 4th field in my MongoDB.
Also I would like to post it as a response back to the user.
Here is my users.js file (server-side)
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var codeResponse = generateCode();
db.collection('userlist').insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '',code: codeResponse } : { msg: err }
);
});
});
function generateCode(){
var code = Math.random() *1000000;
code = Math.floor(code);
return code;
}
And this is my AJAX call(client-side)
var newUser = {
'id2': id2,
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'phone': $('#addUser fieldset input#inputUserPhone').val(),
}
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log(response);
}
else {
alert('Error: ' + response.msg);
}
});
Easy enough, add it to your object before insert and post back the object:
router.post('/adduser', function(req, res) {
var db = req.db;
var document = req.body;
var codeResponse = generateCode();
document.code = codeResponse;
db.collection('userlist').insert(document, function(err, result){
if (err) //do something
return;
else
res.send(document);
});
});

Resources