Logout with Firebase - angularjs

I am trying to do a user auth, and I am in the part of the logout now
<button ng-click="logOut(user)">
GOING OUT
</button>
here is how they sign in
$scope.signIn = function (user) {
$scope.signInErrorShow = false;
if (user && user.email && user.pwdForLogin) {
auth.$authWithPassword({
email: user.email,
password: user.pwdForLogin
}).then(function (authData) {
console.log("Logged in as:" + authData.password.email);
ref.child("users").child(authData.uid).once('value', function (snapshot) {
var val = snapshot.val();
$scope.$apply(function () {
$rootScope.displayName = val;
});
});
$scope.userLogin = true;
$ionicLoading.hide();
$scope.closeModal();
$rootScope.$broadcast('');
}).catch(function (error) {
$ionicLoading.hide();
});
} else
$scope.signInErrorShow = true;
};
and I am trying to call logOut
$scope.logOut = function(user) {
ref.unauth();
};
once I call log out, I don't see any post or get in the Network section of the browser.
In the Firebase Docs, all they say about log out is this
Logging Users Out
Calling unauth() invalidates the user's token and logs them out of your application:
Copy
ref.unauth();
If you had previously used the onAuth() method to listen for authentication state, your callback would now be invoked with null for authData.
so what should I do here ?

Concerning logout not showing any network activity: on login firebase probably gives you an access token (kept by the firebase client script) when you login.
When after login your application accesses firebase it adds this token to the header of your requests (authorization header?).
When you logoff the firebase client script simply erases the token. This way the firebase backend doesn't have to keep session state on their (distributed) servers. They only have to check the validity of the token sent in each request.

Related

Angularjs : server side templating

I am very new to MEAN. And I have made an application using node.js, express and mongodb. I want to send username to dashboard after user is logged in. How can I do it using Angularjs. I don't want to use ejs templating engine. If any Middle ware is required....plzz tell me.
thank you...
this is my usercrud.js
var User = require("../../schema/user/userschema");
var bcrypt = require('bcrypt');
const userOperation={
login(userObject,response){
var username=userObject.userid;
var psw = userObject.password;
User.find({ userid:username}, function (err, user) {
if (err) {
return done(err); }
if (!user) {
return done(null, false, { message: 'no user found' });
}
if(user){
console.log("user's true password is: "+user[0].password);
console.log("password"+psw);
bcrypt.compare(psw, user[0].password, function(err, res) {
if (err){
throw err;}
if(!res) {
console.log('Ooops!. Wrong Pass!');
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
if(res){
response.redirect('dashboard');
}
});
}
});
},
}
how can I send username to the dashboard.html
this is userroute.js
router.get('/dashboard',(req,response)=>{
});
As you are using MEAN stack for your application, what you can do is check login via async call and return user object in response. Then you can store that user into localstorage.
Once user is successful in logIn and you get this "user" object in response, redirect user from login to dashboard using angular redirection not from back-end server.
After redirection use localstorge for getting user information.

Ionic Facebook Connect

I'm pretty new to developing in Ionic and I'm trying to integrate my application with Facebook login. I found this tutorial https://ionicthemes.com/tutorials/about/native-facebook-login-with-ionic-framework and I did everything the way it was shown but I'm getting the following error
TypeError: Cannot read property 'getLoginStatus' of undefined
at Scope.$scope.facebookSignIn (controllers.js:547)
at $parseFunctionCall (ionic.bundle.js:21172)
at ionic.bundle.js:53674
at Scope.$eval (ionic.bundle.js:23228)
at Scope.$apply (ionic.bundle.js:23327)
at HTMLAnchorElement.<anonymous> (ionic.bundle.js:53673)
at HTMLAnchorElement.eventHandler (ionic.bundle.js:11841)
at triggerMouseEvent (ionic.bundle.js:2865)
at tapClick (ionic.bundle.js:2854)
at HTMLDocument.tapTouchEnd (ionic.bundle.js:2977)
My Code for the controller is as follows:
.controller('WalkthroughCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
var fbLoginSuccess = function(response) {
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.feeds-categories');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log(response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.feeds-categories');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
}else{
$state.go('app.home');
}
} else {
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
Thank You in Advance.

How to get AngularJS Login form post reqest

Given the AngularJS example login form here, how can I know what post request is it sending when I click the Login button?
I try to use Chrome's Developer Tools Network tab, but all I got is a GET request.
Thanks!
If you look at the source code of the plunkr, you'll find this:
service.Login = function (username, password, callback) {
/* Dummy authentication for testing, uses $timeout to simulate api call
----------------------------------------------*/
$timeout(function(){
var response = { success: username === 'test' && password === 'test' };
if(!response.success) {
response.message = 'Username or password is incorrect';
}
callback(response);
}, 1000);
/* Use this for real authentication
----------------------------------------------*/
//$http.post('/api/authenticate', { username: username, password: password })
// .success(function (response) {
// callback(response);
// });
};
So the dummy authentication isn't sending any HTTP requests because it's a dummy timeout function which "simulates" an HTTP call.
The GET request you see there is an AJAX call to load the partial home.html view.

When I refresh my page Firebase authData becomes null

var user = null;
this.showLoginDialogGoogle = function(){
var ref = new Firebase("https://googlelogin1.firebaseio.com");
ref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
user = authData;
This.goToPage('/profile');
$rootScope.flag=true;
$rootScope.$digest();
}
});
};
I have authenticated the user with firebase google authentication. The problem is when I refresh my page, my session expires and authData becomes null. What can I do so that after refreshing the page my authData remains with the data it got at the time of authentication?
You'll want to monitor authentication state:
// Register the callback to be fired every time auth state changes
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function authDataCallback(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
}
});
Note that you're not using the AngularFire authentication wrappers. While your approach will authenticate the user, you will have to notify Angular of the updated scope yourself (see $timeout()). If you'd rather not do that yourself, look at AngularFire's auth wrappers, specifically $onAuth()

How to access userinfo in angularjs application after successful login

im developing an test application in angularjs and authenticating my user from login page,
Express Code:
exports.login = function (req, res, next) {
passport.authenticate('local', function(err, user, info) {
var error = err || info;
if (error) return res.json(401, error);
req.logIn(user, function(err) {
if (err) return res.send(err);
res.json(req);
});
})(req, res, next);
};
Service : (Auth and Session)
Auth Service code:
login: function(user, callback) {
var cb = callback || angular.noop;
return Session.Sessionlogin().save({
email: user.email,
password: user.password
}, function(user) {
$rootScope.currentUser = user;
return cb();
}, function(err) {
return cb(err);
}).$promise;
},
Session Service Code:
Sessionlogin: function(){
return $resource('/api/session/');
Controller Code:
$scope.login = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.login({
email: $scope.user.email,
password: $scope.user.password
})
.then( function(err) {
// todo : redirect to admin dashboard
$location.path('admin/dashboard');
})
.catch( function(err) {
err = err.data;
$scope.errors.other = err.message;
});
}
};
every thing work fine now my question is :
after successful login im redirecting the user to dashboard page.Now how can i access the userinfo in dashboard page.Is there any kind of session object in angularjs where i can store the response received from the express code and send it to the dashboard page.
To share data around an angular app, you can either:
Store the data in a service which can then be injected into controllers whenever you need to access that data. Services are singletons: there'll only ever be one instance of each service which is why the data is persistent across controllers.
Store data in $rootScope. It looks like you've already set the user object on the root scope, so you can access it as $rootScope.currentUser provided that you have injected $rootScope into your controller. Note that it's not usually a good idea to litter the root scope, but in this case I think it is wise to store the user object there because you will probably need to access it from a lot of views.
I usually store the user object in $rootScope (so that it's accessible from views) and in a dedicated service (so that it's accessible from controllers/etc).

Resources