I am using Angularfire for my login system and trying to get current logged in user's username for purpose of using in controller. Firts getting uid from $getAuth and sync it with data in database. But what I am trying below is not working.
.factory("Auth", function($firebaseAuth) {
var ref = new Firebase("URL");
return $firebaseAuth(ref);
})
.factory("Konusma", function($firebaseObject) { //When you give user's uid to this factory its gives you user data in database.
return function(xm) {
var ref = new Firebase("URL");
var userdata = ref.child('users').child(xm);
return $firebaseObject(userdata);
}})
.controller("chatCtrl", function(Auth, Konusma) {
var userx = Auth.$getAuth(); //Current logged in user's uid and email
var chatci = function() { //Trying to get current logged in user's username and other data according to uid which is comes from Auth.$getAuth.
Konusma(userx.uid).$loaded().then(function(data){
return data.username;
});
};
As mentioned in comments -
You are trying to get the data before user is authenticated.
So in your controller , instead of :
var userx = Auth.$getAuth();
you can use this :
var userx = {};
Auth.$onAuth(function(authData) {
var userx = authData;
// or bind to scope -
// $scope.authData = authData;
});
this will also update your authData variable every time auth status is change.
Anyway - you still need to call: currentUser = chatci() only after user is loggedIn ,
and not evrey time that auth is change.
The best way is to use it with router, see here : https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html#section-routers
So the controller is loaded only after auth is success.
But for your example - you can add this to your controller:
Auth.$waitForAuth().then(function(authData){
if (authData){
currentUser = chatci()
}
});
Related
I am relatively new to Ionic and I'm having issues doing a Facebook login with ionic framework on the android platform. It does work perfectly on browser (sometimes when I try to do the login the first attempt doesn't work) but when I run the project on Android it just redirects and doesn't pass to the next page.
I think that the issue could be that the first login attempt doesn't fetch the Facebook user data.
Here is my code:
.controller('LoginCtrl', function (Backand, $state, $rootScope, $scope, LoginService, ID, name) {
$scope.bgs = ["img/welcome-bg.jpg"];
$scope.firebaseFacebookLogIn = function(){
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');
provider.addScope('public_profile');
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
var user = result.user;
var uid = user.providerData[0].uid;
var nombre = user.providerData[0].displayName;
localStorage.setItem("Usuario", user);
localStorage.setItem("ID", uid);
localStorage.setItem("Nombre", nombre);
$state.go('app.feed');
}
//var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
alert(errorCode);
var errorMessage = error.message;
alert(errorMessage);
// The email of the user's account used.
var email = error.email;
alert(email);
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
alert(credential);
// ...
});
};
$scope.ID = localStorage.getItem("ID");
$scope.name = localStorage.getItem("name");
$scope.facebookLogOut = function(token){
firebase.auth().signOut().then(function() {
// Sign-out successful.
$state.go('auth.walkthrough');
}, function(error) {
// An error happened.
});
};
})
Solved it!
Turns out that I was just missing a firebase tag inside config.xml of the project.. Pretty dumb to be honest, hope it helps to somebody with the same issue.
I'm making a single page app in AngularJS using Firebase and using the side nav bar on index.html.
And after login, I want the username should be on the side nav bar but the $scope is working for the current page on the controller is working.
scotchApp.controller('mainController', function($scope) {
$scope.validateLogin = function()
{
var email = $scope.login.userName + "#xyz.co";
var password = $scope.login.password;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
$scope.message = "please enter the correct details";
});
firebase.auth().onAuthStateChanged(function(user)
{
if(user)
{
$scope.usermobile = $scope.login.userName;
window.location.assign("/#/equipment");
}
});
}
$scope.message = '';
});
The current user is available in firebase.auth().currentUser as described in the docs so in your mainController you don't need to listen for auth changes.
In your code you are attaching a new listener each time the user tries to login, but what you actually want is to respond to one successful login, so just add a then to your sign in call:
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function (user) {
console.log('the logged in user: ', user);
// Go to the other route here.
// It is recommended to use the router instead of "manually" changing `window.location`
})
.catch(function(error) {
$scope.message = "please enter the correct details";
});
Trying to authenticate an user using firebase. Started my app using firebase 2.xx but even after upgrading to Firebase 3.xx, throwing
error "onAuthStateChanged is not a function".
This is how my login function looks like-
.controller('HomeCtrl', ['$scope','$location','CommonProp','$firebaseAuth', '$firebaseObject',function($scope,$location,CommonProp,$firebaseAuth,$firebaseObject) {
var firebaseObj = $firebaseObject(rootRef);
var loginObj = $firebaseAuth(firebaseObj);
$scope.SignIn = function($scope, user) {
event.preventDefault(); // To prevent form refresh
var username = user.email;
var password = user.password;
loginObj.$signInWithEmailAndPassword({
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
$location.path("/welcome");
CommonProp.setUser(user.password.email);
}, function(error) {
// Failure callback
console.log(error);
});
}
}]);
Your problem is that you are passing a $firebaseObject to $firebaseAuth().
So make sure you are initializing your [$firebaseAuth][1] object like the following and then your code should work properly.
var loginObj = $firebaseAuth();
Working jsFiddle for demonstrating.
You can check here the documentation for AngularFire2
I have been working for authentication for each $http request and url changes. Therefore i have implemented peace of codes for url changing authentication as bellows
/** login-controller.js file **/
//when the form is submitted
$scope.submit = function() {
console.log("enter login submit");
$scope.submitted = true;
if (!$scope.loginForm.$invalid) {
$scope.login($scope.credentials);
} else {
$scope.error = true;
$scope.error_des = '';
return;
}
};
// if a session exists for current user (page was refreshed)
// log him in again
if ($window.sessionStorage["userInfo"]) {
var credentials = JSON.parse($window.sessionStorage["userInfo"]);
$scope.login(credentials);
};
//Performs the login function, by sending a request to the server with the Auth service
$scope.login = function(credentials) {
$scope.error = false;
Auth.login(credentials, function(user) {
//success function
$mdDialog.hide();
$state.go("admin-panel.default.home");
}, function(err) {
console.log("error");
$scope.error_des = err.msg;
$scope.error = true;
});
};
Everything is working as i expected but while reloding the same page it'l always redirect to home(http://localhost:3000/#/home).i know that it happens because of
$state.go("admin-panel.default.home");
trouble is , i want to redirect the page according to login way let'say if user login via form submitted which will be redirected to $state.go("admin-panel.default.home");
As well if user login via session exists for current user which will be redirected to $state.go("admin-panel.default."+$current_page);
how to achieve it? please help me????
If form submit : var formsubmitted = true;
if login via session : formsubmitted = false
and while routing you can check condition
if(formsubmitted == true)
$state.go("admin-panel.default.home");
else
$state.go("admin-panel.default."+$current_page);
//to get current page path you can use $location.path();
So I have some code that authenticates the user to my app using google which works out fine. What I want to do is then save that user info to the firebase and then have that user be able add data specifically under their account that will then reload the next time they log in. What's the best way to do that? I'm getting very lost.
(function() {
'use strict';
angular.module('life-of-a-story')
.controller('UserController', function($scope, $firebaseAuth) {
var ref = new Firebase('https://life-of-a-story.firebaseio.com/');
// create an instance of the authentication service
var auth = $firebaseAuth(ref);
// login with Google
this.login = function() {
auth.$authWithOAuthPopup("google").then(function(authData) {
console.log(authData);
console.log("Logged in as:", authData.uid);
var user = {
'name': authData.google.displayName,
'image': authData.google.profileImageURL,
'uid': authData.uid
}
console.log(user);
}).catch(function(error) {
console.log("Authentication failed:", error);
});
};
});
})();
AngularFire is a (relatively) thin UI binding library on top of Firebase's regular JavaScript SDK. So when something is not explicitly documented in the AngularFire documentation, you can sometimes find the answer in the documentation for the regular Firebase JavaScript SDK.
Most Firebase Authentication developers store each user's data under a /users node. If that is what you're trying to do, you can read how to accomplish it in the section called Storing user data in the Firebase documentation for JavaScript.
The relevant code from there:
// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
// find a suitable name based on the meta info given by each provider
function getName(authData) {
switch(authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'twitter':
return authData.twitter.displayName;
case 'facebook':
return authData.facebook.displayName;
}
}