I am trying to show other some user's profile page to non-logged in and logged-in users. The problem is that whenever I check
if(Meteor.user() === me)
Meteor.user() returns null and code crashes since no one is logged in. How can I check whether there are logged in users?
Try this and let me know:
if (Meteor.user()) {
// code for login user
} else {
// code for non-login user
}
Related
so if a user logs into your app, you can check that by
firebase.auth().onAuthStateChanged((user)=>{});
but if the user is already logged in and his user has a property change, how do you see that?
in my case, I have the user verify his email address and when done, he should be able to see a change instantly on his app after verifying his email. So I am using react native, which is pretty much javascript with ES6 syntax in it and I am doing a firebase.auth().onAuthStateChanged(); but its not working, I even have a button on the screen that checks if verified like this:
if (!firebase.auth().currentUser.emailVerified) { firebase.auth().currentUser.sendEmailVerification(); }
else if (firebase.auth().currentUser.emailVerified) { this.setState({ showVerifier: false }); }
but even that isn't working, as if the firebase.auth().currentUser doesn't update if the email is verified, what can be done here?
As far as I understand your question, I would like to give you an idea.
I think onAuthStateChanged() gets triggered only when your Auth State Changes (login, logout) and not when the user properties change.
As they have mentioned in the documentation,
Adds an observer for changes to the user's sign-in state. Prior to
4.0.0, this triggered the observer when users were signed in, signed out, or when the user's ID token changed in situations such as token
expiry or password change. After 4.0.0, the observer is only triggered
on sign-in or sign-out.
function isVerified(){
var user = firebase.auth().currentUser;
if(user != null){
var status = user.emailVerified;
if(status)
{
// Verified
}else{
// Not Verified
}
}
else{
// User didn't login!
}
}
So, you have to manually check it by defining a function like above and you can call this function when the user clicks the button
If you are using react-native-firebase (highly recommended, since it is supports the latest firebase features), you can listen on user changes as stated in this doc
From the doc
Adds a listener to observe changes to the User object. This is a superset of everything from auth#onAuthStateChanged, auth#onIdTokenChanged and user changes. The goal of this method is to provide easier listening to all user changes, such as when credentials are linked and unlinked, without manually having to call User#reload.
onUserChanged(listener: AuthListenerCallback): () => void;
I have a web-app that allows users to sign in using their gmail account.Once the user is signed in, I am able to see it's details using result.user object like this-
function signInWithGoogle(){
var provider=new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var user=result.user;
console.log("user_provider="+user.displayName+" user_email="+user.email+" user_dp="+user.photoURL+" user_verification="+user.emailVerified+" uid="+user.uid);
}).catch(function(error){
console.log("error="+error);
});
}
After signing in, I want to keep user details in page even after reloading and refreshing for that I used User object of auth() like this-
$(document).ready(function(){
var user=firebase.auth().currentUser;
console.log(user);
});
But it's showing user as null although I can see user email address in authentication console in firebase.
P.S. I have also used onAuthStateChanged instead of currentUser , but still it's not working.
onAuthStateChanged should work. You have to listen to it correctly.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// currentUser should be available now.
} else {
// No user logged in.
}
});
Keep in mind that the state is stored in single host origin web storage. So if you navigate to a page with a different domain, the state will not propagate.
I'm using the onConnection hook and some template helpers to do some stuff with statistics. But now, I want't to exclude these operations when I'm a registered user.
The Problem, I can't use Meteor.user() in the onConnection hook, so how can i check if a user is logged in ?
Concerning code, there is not much to show
Meteor.onConnection(function(conn) {
if(Meteor.user()) {
console.log("you are logged in")
} else {
console.log("u are not logged in")
}
});
It's not the true example but it shows simple what i want to do
The Error
err [Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.]
I understand that i can just use Meteor.user() in methods, but how can i find out in the onConnection if a user is logged in ?
For statistics purposes I'd recommend to use publications. They have more sophisticated api which allows you to have more control over your connection.
Meteor.publish('users.trackPresence', function() {
// Both this.userId && this.connection are available to be called from here
this.onStop(function(){
// user went offline
});
this.ready();
});
and on the client you can check if user is present and not even subscribe if this is the case:
Tracker.autorun(function(){
if (!Meteor.userId())
Meteor.subscribe('users.trackPresence');
});
Meteor automatically handles unsubscribe/resubscribe when you subscribe from within a Tracker.autorun
read more about pubsub api here
https://docs.meteor.com/api/pubsub.html
Obviously as you stated, the Meteor docs do not provide any insight for how to achieve this. I spent a decent amount of time going thru the accounts-base source and don't see any way to do what you are asking natively.
With that said, if you could update the Users collection each time they login and save their current IP address, then you could use this as a way to see if the current connection is logged in. Here is an example.
Meteor.onConnection((connection) => {
var user = Meteor.users.findOne({
'user.profile.currentIp': connection.clientAddress
});
if (user) {
console.log("you are logged in")
} else {
console.log("u are not logged in")
}
});
Be sure to add login and logout hooks to set and remove the user's current IP. I have not tested this approach, but in theory it should work.
I am building an application using Meteor. I want to create a new Cart ID (to act as a cart where I can store items) each time a user logs into my application. However, every time I open a new page in the application, a new Cart ID is created. Does this mean that the application "logs in" every single time I click on a new page in the app? Here's my code:
Accounts.onLogin(function(user){
var newCartId = uuid.new()
Meteor.users.update({_id: user.user._id}, {$set: {'profile.cartId': newCartId}})
console.log('just created a new Cart ID at ' + Date());
});
Yes, this is true.
Every time you open a new page you are not logged in. When the localStorage token authenticates you, similar to how a cookie does, you are logged in automatically. This hook will also run when you are logged in automatically.
Its difficult to define how a user logs in. Meteor's onLogin hook fires on any type of login Method.
You can customise when you want your hook to run, though:
Accounts.onLogin(function(info) {
if(info.methodName == "createUser") {
console.log("This user logged in by signing up");
}else if(info.type == "password") {
console.log("This user logged in by using his/her password");
}else if(info.type == "resume") {
console.log("This user logged in using a localStorage token");
}
});
So here you can make the event fire only when a user logs in using his or her password. Or even when they sign up. You can use this to exclude running your hook if the user opens a new page, which uses the localStorage token to sign up.
I have been trying for days to get a list of logged in users in a Meteor chat app.
I tried many different things. I managed to add a login flag on the user profile object.
Server side:
Accounts.onCreateUser(function(options, user) {
if(!options.profile){
options.profile = {}
}
options.profile.login = false;
if (options.profile)
user.profile = options.profile;
return user;
});
In the browser console I get this:
Meteor.user().profile
Object {login: false}
So that seems to work.
Now I want to list if users are logged in:
Client side
Deps.autorun(function(){
if(Meteor.userId()){
Meteor.user().profile.login=true;
}
});
After checking the login remains false when I log in.
This template html gives me a list of all usernames but not the login flag
{{#each allUsers}}
<p>{{username}}</p><p>{{profile.login}}</p>
{{/each}
So my problems are : profile.login remains false and I cannot display profile.login but the usernames are displayed.
Thank you in advance. Greetings Joris
To change the users profile.login property you need to do Meteor.users.update(..) or call a server method that does that. Just changing the user object's property will not work.
Generally I would recommend to not persist the users state into the mondodb database but hold it in a Collection in memory.
The easiest might be to just use one of these packages:
https://github.com/dburles/meteor-presence/
https://github.com/mizzao/meteor-user-status
or study their source code to see how to propagate the user status.