Firebase - keep user signed in while localStorage object is valid - javascript

I have an app I'm building with Ionic, Angular2, and Firebase.
What I'm currently doing is that when a user log's in or registers, their auth.currentUser information is being saved in localStorage. My code is currently assuming that if a user has the user variable in localStorage set that the user is also signed in. However, I just realized that that isn't actually the case.
My localStorage variable user looks like this:
and I'm getting it like this:
ngOnInit() {
Promise.all([ //data storage get all..
this.storage.get('user')
])
.then(([user]) => {
this.userData = user; //set the user storage to this.userData
console.log(this.userData)
})
.catch(error => {
console.log("Storage Error.");
});
}
So I have all of the users information, except the fact that they aren't actually signed in... So when I do:
this.afAuth.auth.onAuthStateChanged((user) => {
if (user) {
console.log(user)
} else {
console.log("Not logged in")
}
});
It shows the user isn't logged in. Is it possible for me to keep the user logged in while I have the localStorage information?
Or maybe just have the login state always be logged in unless the user signs out? With it never expiring?
What should I do at this point? Any advice would be great! Thank you.

Firebase manger user in a different way. You should not depend on localstorage to detect if user is logged it. You should depend on firebase to check if user is logged in. Since firebase is built on web sockets, it should be really quick. So let rewrite the ngOnInit as follows:
ngOnInit() {
const user = this.afAuth.auth.currentUser;
if (user) {
this.userData = user;
} else {
// force them to reauthenticate
user.reauthenticateWithCredential(credential)
.then(function() {
// User re-authenticated.
this.userData = this.afAuth.auth.currentUser;
}).catch(function(error) {
// An error happened.
});
}
}
Read more about managing users in Firebase here: https://firebase.google.com/docs/auth/web/manage-users. Hope this helps.

Related

Getting Uncaught TypeError in Firebase Auth get current user email

I am trying to get the email of the currently signed in user in my Firebase app, but it keeps giving me an error.
This is my code for getting the current user email:
user_email = firebase.auth().currentUser.email
The error that I get is:
Error Image
It looks like firebase.auth().currentUser is null at the time when your firebase.auth().currentUser.email runs. This is quite common, as Firebase refreshes the user's authentication state when the page loads, and this requires it to make an asynchronous call to the server.
For this reason, you should not assume there is a user signed in. You should either put a check around your current code:
if (firebase.auth().currentUser) {
user_email = firebase.auth().currentUser.email
}
Or (and often better) you should use a so-called auth state listener, to have your code automatically respond to changes in the user's authentication state. From the Firebase documentation on getting the currently signed-in user, that'd be:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
user_email = firebase.auth().currentUser.email;
// TODO: execute code that needs `user_email`
} else {
// User is signed out
// ...
}
});

How can I get the uid of my users from firebase?

I am able to anonymously create a user in firebase with the below code but when I try to log the current user's 'uid' in the console it returns 'undefined'. Please advise on my below code.
firebase.initializeApp(firebaseConfig);
firebase.auth().signInAnonymously();
console.log(userID);
If you want to log the UID of the user after they sign in, you have to ways to accomplish that:
firebase.auth().signInAnonymously().then((credential) => {
console.log(credential.user.uid);
});
This will log the console when the user actively logs in.
If you instead want to respond whenever the user signs in or out, you can do:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log(user.uid);
} else {
// No user is signed in.
}
});
This second way works even if you restart the app, as Firebase will in that case automatically restore the user's authentication state.

firebase add user information while creating user (react.js)

I researched before asking this question but I couldn't find an answer.
I made a form in react js. When I click the button it creates a user with createUserWithEmailAndPassword() method. There is no problem with creating the user. I want to add extra information like; username : "Usernameeeee" to my database. The database will look like this:
users {
userUid1: {name: "Name User 1"}
userUid2: {name: "Name User 2"}
....
}
When I use createUserWithEmailAndPassword(), it creates a user and logs them in. But as you can see the above, I need the current user's id. I know how to get it normally, firebase.auth().currenUser... But while creating a user I can't catch the user's id. It returns null;
export function signUpUser({email, password}) {
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(
() => dispatch({type: USER_SIGNUP_SUCCESS})
)
.then(console.log(firebase.auth().currentUser))
.catch(error => {
dispatch({type: USER_SIGNUP_FAIL, payload: error.message});
});
}
}
When I console the current user, the creating user is complete but not logged in yet. So how can I add information while creating a user ? (not after logged in some other way)
I found the answer after a day. I hope this will be helpful to others. As you understand, the main problem is getting the user id right after creating a user, before user sign in...
So the solution is:
export function signUpUser({email, password, username}) {
const db = firebase.database();
return function (dispatch){
firebase.auth().createUserWithEmailAndPassword(email, password)
// here we get user id if creating is successful.
.then(function(user){
dispatch({type: USER_SIGNUP_SUCCESS}); // I dispatched some message.
db.ref(`users/${user.uid}`).set({name: username}); // I added user
console.log('uid:',user.uid)
})

Authentication - JavaScript - Logout issue

I need some help with my problem.
firebase.auth().onAuthStateChanged(user => {
if(user) {
console.log('log in');
window.location.href ='event_list.html'
}});
btnLogout.addEventListener('click', e => {
firebase.auth().signOut().then(function() {
console.log("not log in");
window.location.href = 'index.html';
}, function(error) {
//
});;
});
Logging in works correctly but if I'm trying logout - user probably logout correctly - back to login/signup site but immediately I'm redirecting to "event_list.html" as still logged in user.
My sign in/sign up site is - index.html
I want logout and put other data - login/pass.
One other question: How can I get email variable from this script and use it in other JavaScript script?
I want do banner - Hi (mail of user actually log in), Welcome back and insert it to all my HTML sites.
I suggest you to take a look at this code in github.
About your example, I think that the problem is with onAuthStateChanged method (user has logged out, so the auth state has changed, so it's triggered...).
Try to use signInWithEmailAndPassword what is explained here.
By other way, separated question I would, first make a search in SO, and then, if no answered meets my needs, I would asked it in a new one!
I'm also new to Firebase but firebase.auth().signOut() should do the trick for you
And in-order to identify if the user is logged in you can use the onAuthStateChanged event. If the passed parameter is null which means user is logged out if you have a valid value then you can resolve the user from that
ex: (I have not tried this but this should work)
firebase.auth().onAuthStateChanged(user => {
if(user) {
console.log('User Logged in :' + user );
window.location.href ='event_list.html'
}else{
console.log('User Not Logged in');
window.location.href = 'index.html';
}
});
btnLogout.addEventListener('click', e => {
firebase.auth().signOut();
});

How to use localStorage to store and get back user login details?

I'm building a mobile app using the Ionic framework, I need to be able to cache my user's login so they don't have to login every time.
I read a solution that recommends using HTML5 localStorage. However I'm unsure at the moment on how to implement it.
This is what my user login variables look like:
credentials Object {username: "leon", password: "sushi"}
And what my console.logs print out below:
My loginController:
// The Modernizr Code
////////////////////////////////////////////////////////////////////////////
if (Modernizr.localstorage) {
// window.localStorage is available!
console.log('localStorage is available!');
console.log('creds',creds);
} else {
console.log('no native support for HTML5 storage :(');
// no native support for HTML5 storage :(
// maybe try dojox.storage or a third-party solution
}
// The Login function
////////////////////////////////////////////////////////////////////////////
function login(credentials) {
console.log('credentials',credentials);
creds = localStorage["credentials"];
console.log('creds',creds);
AuthService.login(credentials).then(function (user) {
$rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
if (user.password_reset) {
$location.path('/password');
}
else {
AuthService.saveUser(user);
$location.path('/main');
}
}).catch(function () {
vm.errorModalClosed = false;
vm.loginError = true;
PopupFactory.saveConfig("failure", "The username and password you entered don’t match.", true);
$rootScope.$emit('open.popup');
});
}
localStorage is global in the browser you can save data and then retrieve wherever you want, you add item like this localStorage.setItem('key', 'value') and getting localStorage.getItem('key');
Remember something, localStorage only save string, you have to use JSON.stringify() for save an object y JSON.parse for parsing to json again
in you specific example in the moment you save the user
AuthService.saveUser(user);
localStorage.setItem('user', JSON.stringify(user));
$location.path('/main');
and retrieve in other place
var user = JSON.parse(localStorage.getItem('user'));
you can do that too inside your AuthServer.saveUser(user) and add some method like AuthServer.getUser() to get the user

Categories