I need some input from the Meteor community.
I use the Meteor.UserId() to check if the user has logged in or not. This works well when the user is not logged in(Meteor.userId()
is null) and when the user has logged in(Meteor.userId()
is not null) however if the user is logged in and the browser is refreshed Meteor.userId()
is lost.
What are the community recommendations to keep track of whether the user has logged in or not? Should I redirect the user to the login page if the user has logged in and the browser is refreshed? Should I keep the Meteor.UserId() in local storage work after the user has logged in(I don’t think it will work)?
Update 1: The MainNavBar shows if the user is logged in or not based on Meteor.userId().
in a method call to App.vue.
MainNavBar.vue
<li class="nav-item d-xl-block" v-if="(this.$root.currentUserId==null)">
<router-link class="nav-link" v-bind:to="{ name: 'register' }">Register</router-link>
</li>
<li class="nav-item d-xl-block" v-else>
<a class="nav-link" href='' data-cy="logout" v-on:click="Logout()">Log out</a>
</li>
App.vue:
<script>
import { mapGetters } from 'vuex';
import { Meteor } from 'meteor/meteor';
export default
{
computed: {
...mapGetters('layout', ['showCart',]),
},
meteor:
{
$subscribe:
{
'currentUserId': function()
{
return [Meteor.userId()];
},
},
currentUser()
{
return Meteor.user();
},
currentUserId()
{
return Meteor.userId();
},
},
}
</script>
Update 2:
src\imports\server.js:
import { Meteor } from 'meteor/meteor';
import './server/accountsBase';
import { Accounts } from 'meteor/accounts-base';
const isDev = process.env.NODE_ENV !== 'production'
Meteor.publish('currentUserId', function ()
{
return this.userId;
});
Meteor.startup(() =>
{
Accounts.config({loginExpirationInDays: 0.0006});
});
src\imports\api\publications.js
import { Meteor } from 'meteor/meteor';
Meteor.publish('currentUserId', function ()
{
return this.userId;
});
Meteor.publish(null, function ()
{
if (this.userId)
{
return Meteor.users.find({ '_id': this.userId });
}
else
{
this.ready();
}
})
Login.Vue:
<template>
<form role="form">
<button type="button" v-on:click="LoginUserForDomain()">
Sign in
</button>
</form>
</template>
<script>
import { Meteor } from 'meteor/meteor';
export default
{
methods:
{
LoginUserForDomain()
{
this.disableButton=true;
Meteor.loginWithPassword(email, this.user.password, (error2)=>
{
this.disableButton=false;
if(error2)
{
this.failureMessage='There was an error logging you in. Our administrators have been notified of the issue and we will have a look.';
return;
}
else
{
root.setValue(StateVariables.SelectedDomain, 'ClearCrimson');
router.push({ name: 'dashboard', params: { domain: 'ClearCrimson' }});
return;
}
});
},
},
}
</script>
Update 3:
I am using vue-meteor and i was asked to check the following issue on stackoverflow.