Chase Isley
Chase Isley

Reputation: 101

Session is not Defined - Meteor 1.4 and Flow Router

I am trying to implement custom login, authorization and Roles to my Meteor app using Flow Router. I am using the latest version of Meteor. I have updated all packages as well. I get the error when I login.

Registering and creating accounts works perfectly. My credentials are saved and users are created.

I set the session variable in loggedIn.js and then retrieve it in configure.js when the login button is clicked and "should" route me to the desired route I attempted to go to before being logged in, but what I get is the "Session is not defined" error. Here are the two errors that I am receiving:

Exception in onLogin callback: TypeError: Cannot read property 'replace' of undefined
at Router.path (http://localhost:3000/packages/kadira_flow-router.js?hash=09ea12875d3801955ee70797bf8e4a70feebc570:325:18)
at Router.go (http://localhost:3000/packages/kadira_flow-router.js?hash=09ea12875d3801955ee70797bf8e4a70feebc570:360:19)
at http://localhost:3000/app/lib/routes/configure.js?hash=1ca98e9145d8b9d63189b16a8d872866175709b0:15:25
at runAndHandleExceptions (http://localhost:3000/packages/callback-hook.js?hash=fff7fdef0707c85900b21f766a4b6c65bf278ff4:162:24)
at http://localhost:3000/packages/callback-hook.js?hash=fff7fdef0707c85900b21f766a4b6c65bf278ff4:169:12
at http://localhost:3000/packages/accounts-base.js?hash=db584b046b0a64d03bfcbf1cd84a8b38f83ddc0d:290:9
at Hook.each (http://localhost:3000/packages/callback-hook.js?hash=fff7fdef0707c85900b21f766a4b6c65bf278ff4:138:15)
at http://localhost:3000/packages/accounts-base.js?hash=db584b046b0a64d03bfcbf1cd84a8b38f83ddc0d:289:25
at http://localhost:3000/packages/underscore.js?hash=27b3d669b418de8577518760446467e6ff429b1e:794:19
at loggedInAndDataReadyCallback (http://localhost:3000/packages/accounts-base.js?hash=db584b046b0a64d03bfcbf1cd84a8b38f83ddc0d:411:5)

And from the cmd line:

I20160818-21:36:28.962(-7)? Exception in onLogin callback: ReferenceError: Session is not defined
I20160818-21:36:29.266(-7)?     at app\lib\routes\configure.js:9:3
I20160818-21:36:29.267(-7)?     at runAndHandleExceptions      (packages/callback-hook/hook.js:133:1)
I20160818-21:36:29.267(-7)?     at packages/callback-hook/hook.js:140:1
I20160818-21:36:29.267(-7)?     at packages/accounts-   base/accounts_server.js:167:5
I20160818-21:36:29.267(-7)?     at [object Object]._.extend.each (packages/callback-hook/hook.js:109:1)
I20160818-21:36:29.267(-7)?     at AccountsServer.Ap._successfulLogin (packages/accounts-base/accounts_server.js:166:21)
I20160818-21:36:29.267(-7)?     at AccountsServer.Ap._attemptLogin (packages/accounts-base/accounts_server.js:356:10)
I20160818-21:36:29.267(-7)?     at [object Object].methods.login (packages/accounts-base/accounts_server.js:533:21)
I20160818-21:36:29.267(-7)?     at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1711:12)
I20160818-21:36:29.267(-7)?     at packages/ddp-server/livedata_server.js:711:19

I have removed and re-added the Sessions package several times. Here is a list of all the packages I am currently using:

[email protected]
twbs:[email protected]
fortawesome:fontawesome
[email protected]
okgrow:router-autoscroll
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
kadira:flow-router
meteorhacks:fast-render
kadira:blaze-layout
zimme:active-route
arillo:flow-router-helpers
[email protected]
alanning:roles
[email protected]
standard-minifier-css
standard-minifier-js
meteortoys:[email protected]
session

I have 3 files for Flow Router for the different routes I have created this far.

In configure.js, this is where the Session is not defined error begins:

    Accounts.onLogin(function() { // This makes sure the user goes to the route that he wanted after he successfully logged in.

  var redirect = Session.get('redirectAfterLogin');
  console.log(redirect);
  if (redirect !== null) { // added this check here because some async behaviour in either FlowRouter or onLogin hook can cause wrong redirect to the ‘ login’ page again. This explicit check solves that issue.
    if (redirect !== '/login') {
      return FlowRouter.go(redirect);
    }
  }
});

In loggedIn.js, I have created a group route for the logged in user routes:

var loggedIn = FlowRouter.group({
  name: loggedIn,
  triggersEnter: [ function() { //whenever someone enters a route in this group, the trigger will run before the route runs.
    var route;
    if (!(Meteor.loggingIn() || Meteor.userId())) { // Checks if the user is logging in or if the user is logged in already
      route = FlowRouter.current();
      if (route.route.name !== 'login') {
        Session.set('redirectAfterLogin', route.path); // we don’t use the route name, but the path. this way you can redirect the user while keeping the state in the url.
        console.log("this is the route path", route.path); // we save the route that the user wanted to go in Session.set('redirectAfterLogin')
      }
      FlowRouter.go('login');
    }
  }]
});

loggedIn.route('/admin', {
  name: 'mainLayout',
  action: function() {
    BlazeLayout.render( 'mainLayout' );
  }
});

loggedIn.route('/pageOne', {
    action: function() {
      BlazeLayout.render( 'mainLayout', {content: 'pageOne'});
    },
    name: 'pageOne'
});

loggedIn.route('/pageTwo', {
    action: function() {
      BlazeLayout.render( 'mainLayout', {content: 'pageTwo'});
    },
    name: 'pageTwo'
});

loggedIn.route('/logout', {
    name: 'logout',
    action: function () {
        Meteor.logout(function () {
            FlowRouter.go(FlowRouter.path('login'));
        });
    }
});

Here are my exposed routes in exposed.js:

var exposed = FlowRouter.group ({
  name: exposed
});

exposed.route('/', {
    action: function() {
      BlazeLayout.render( 'landing' );
    },
    name: 'landing'
});

exposed.route('/login', {
    action: function() {
      BlazeLayout.render( 'login' );
    },
    name: 'login'
});

exposed.route('/register', {
    action: function() {
      BlazeLayout.render( 'register' );
    },
    name: 'register'
});

Last but not least, in my startup folder, I have a file called default.js:

FlowRouter.wait();

//if the roles subscription is ready, start routing
//there are specific cases that this reruns, so we also check
// that FlowRouter hasn't initalized already

Tracker.autorun(function() {
  if (Roles.subscription.ready() && !FlowRouter._initialized) {
    return FlowRouter.initialize();
  }
});
// Run this when the meteor app is started
Meteor.startup(function () {

});

Has anyone else had this issue or anything similar? Any help would be greatly appreciated. To clarify, Sessions is installed and I am using the latest version 1.1.6. Thanks

Upvotes: 0

Views: 545

Answers (2)

M. Pierzchlewicz
M. Pierzchlewicz

Reputation: 1

Had a similar problem. Solved it in the following way: In the AccountsTemplates.configure I’ve setted the homeRoutePath: '/loggedin' path. This way, after login, the user will be redirected to the ‘/loggedin’ route. Then in the FlowRouter for the ‘/loggedin’ path:

loggedInGroup.route('/loggedin', {
    name: 'loggedin',
    triggersEnter: [function(context, redirect) {
        var redirectAfterLoginPath = Session.get('redirectAfterLogin');
        if(redirectAfterLoginPath){
            redirect(redirectAfterLoginPath);
            Session.set('redirectAfterLogin', undefined);
        } else {
            redirect('home');
        };
    }]
});

loggedInGroup = FlowRouter.group({
    triggersEnter: [
        function(context, redirect, stop) {
            if (Meteor.loggingIn() || Meteor.userId()) {
                route = FlowRouter.current();
            } else {
                if(context.path != '/sign-in'){
                    Session.set('redirectAfterLogin', context.path);
                };
                redirect('/sign-in');
            }
        }
    ]
});

This way the ‘/loggedin’ route is just the way of handling the problem of not being able to access the Session in the Accounts.onLogin and it redirects the user to the right route.

Upvotes: 0

MasterAM
MasterAM

Reputation: 16478

There are 2 separate issues:

  1. Session is defined only on the client, and there is no use of running the redirect code on the server (on the server the hook is normally used for different purposes, such as analytics). This leads the error you see in your console.

  2. You pass undefined to FlowRouter.go() as you are strictly comparing the returned session value against null. null and undefined are not the same. Therefore, if the 'redirectAfterLogin' session variable isn't set, you will get undefined and pass it to FlowRouter.

Upvotes: 0

Related Questions