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();
});
Related
ok so I've built a few apps in Firebase and really enjoy using the simple API but always struggle with auth. see this code
I have a simple email and password "form" (not a form element, just two inputs)
and then a button (div) I click to call this function below
const logUserIn = () => {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((res) => {
console.log('here') // this WORKS but the history redirect below does not work :/
localStorage.setItem('authUser', JSON.stringify(res))
history.push('/account')
})
.catch((error) => {
console.log('ERROR:', error)
})
}
however when I put the lines below
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user logged in')
} else {
console.log('user not logged in')
}
})
it seemed to pick it up correctly
but my question is, what is the point of signInWithEmailAndPassword? and also, how do I use both functions together? do I need to call onAuthStateChanged in the .then part of my signInWithEmailAndPassword function?
it's really confusing how to have a consistent state. my app seems to work after I refresh the page but I want it to work without refreshes (obviously)
any ideas on the best approach?
EDIT
also when I click sign out
firebaseApp.auth().onAuthStateChanged((user) => {
if (user) {
history.push('/account')
} else {
console.log('NO USER')
}
})
NO USER logs but then I click on an authenticated route it takes me there until I refresh
The point of signInWithEmailAndPassword is to allow the implementation of classic username/password authentication for people who don't have a Google, Facebook, Twitter, etc. account. If you decide to add it, Google will handle the user accounts and everything, but you'll have to build the login form, complete with the I forgot my password and Register as new user links. Other than that it's simply another provider.
I have a very simple little project on my Github repo which implements user/password authentication along with several others, I suggest you to look into it. I made it as a test assignment for a job interview. It's Angular.
https://github.com/tomcatmwi/morbidomega
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.
I am using
firebase.auth().createUserWithEmailAndPassword(email, password1)
.then(() => {
var user_uid = firebase.auth().currentUser.uid;
db.collection(ll_collection).doc(user_uid).set({
user_review: 0,
number_of_reviews: 0
})
})
It creates a document named after the user's id right after the account creation.
I also have another function on the same file that checks if an user is logged in or not:
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
setTimeout(function() {
window.location.href = "/";
}, 400)
}
})
I had to set a timeout on this function, since the account is logged in right after the account creation. If I don't put the timeout, it is going to redirect to "/" right after the account creation without creating the document. It makes sense, since onAuthStateChanged is in realtime.
But is there another way I can redirect the logged in user on the page without interfering with the operation after the account creation?
Thanks in advance.
I typically only use onAuthStateChanged() and not the then() completion handler of the user creation.
So in that case both document creation and redirect would be in the onAuthStateChanged and you can synchronize there:
firebase.auth().createUserWithEmailAndPassword(email, password1);
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
db.collection(ll_collection).doc(user.uid).set({
user_review: 0,
number_of_reviews: 0
}).then(function() {
window.location.href = "/";
});
}
})
If you only want to create the document when the user is new, you can check if they already have a document, or reject the document (re)creation in security rules.
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.
This question is in relation to this question: FB.logout() called without an access token
I had a question i was hoping someone could help with.
I get everything in the link above, but how do you handle when someone uses a public computer and leaves themselves logged in to FB by accident? Then a new user tries to log in to an app, but it is not them. I want to have a button to log them out of FB altogether to "log in as a different user".
I cannot do that until they authorize the app, right? So they need to authorize the app under someone else's account and then log out? There has to be another way.
Any feedback would be great - tried searching for a while on this, but to no avail. I might be over thinking it, but there should be some way to "log in as a different user".
You can do something like:
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
FB.api("me", function(response2) {
// notify the user he is logged in as response2.name, and if it's not him call FB.logout
}
}
else {
// prompt the user to login
}
}
Modify your logout to something like this :-
function logout(response){
console.log("From logout" + response);
if(!response.authResponse){
window.location = "/web/login/";
return;
}
FB.logout(function(response){
FB.Auth.setAuthResponse(null,'unknown');
logout();
});
}
i.e keep on sending logout request to Facebook till the actual logout happens.
Try to use Session and save the user's ID in that session.
You can control the expiration time of that session( by default its 20 minute if the user doesn't have any activity on the page)
then in each page Load even check whether the season is still active for that user or not.
page Load event:
if(Session["LoggedIn"]==null)
{
Response.Redirect("~/Login.aspx");
}
This code above will redirect user to login page of your website if the session has expired.