Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: redirect a user if already logged in

Tags:

meteor

I'm using meteor-router, and I'd like to redirect a user to /user if he requests / and he is already logged in.

As expected, this just renders the user_index template rather than changing the URL:

Meteor.Router.add
  '/': -> if Meteor.userId() then 'user_index' else 'index'

I want to do something like this:

Meteor.Router.add
  '/': -> if Meteor.userId() then Meteor.Router.to '/user' else 'index'

update 6/4/14:

This question is no longer relevant, and iron-router should be used instead.

like image 866
David Weldon Avatar asked Jan 14 '13 19:01

David Weldon


Video Answer


2 Answers

meteor-router is now deprecated. Instead use iron-router which can redirect based on logged in status using:

Router.configure({layoutTemplate: 'mainLayout'});

Router.map(function() {
  this.route('splash', {path: '/'});
  this.route('home');
});

var mustBeSignedIn = function(pause) {
  if (!(Meteor.user() || Meteor.loggingIn())) {
    Router.go('splash');
    pause();
  }
};

var goToDashboard = function(pause) {
  if (Meteor.user()) {
    Router.go('home');
    pause();
  }
};

Router.onBeforeAction(mustBeSignedIn, {except: ['splash']});
Router.onBeforeAction(goToDashboard, {only: ['splash']});

Example taken from: Meteor.js - Check logged in status before render

--OR--

Use the accounts-entry package. From their site:

Ensuring signed in users for routes

Use AccountsEntry.signInRequired(this) to require signed in users for a route. Stick that in your before hook function and it will redirect to sign in and stop any rendering. Accounts Entry also tracks where the user was trying to go and will route them back after sign in.

like image 94
Oliver Lloyd Avatar answered Sep 18 '22 19:09

Oliver Lloyd


You're looking for a filter -- here is a sample from the docs:

Meteor.Router.filters({
    'checkLoggedIn': function(page) {
        if (Meteor.loggingIn()) {
            return 'loading';
        } else if (Meteor.user()) {
            return page;
        } else {
            return 'signin';
        }
    }
});

// applies to all pages
Meteor.Router.filter('checkLoggedIn');
like image 32
TimDog Avatar answered Sep 20 '22 19:09

TimDog