Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I pass user's login status to my Ember.js application?

I have an interactive Ember app which has a lot of options which are available only to signed in users. For example there might be a list of posts, and then there's another link to my posts, which are relevant to the user.

There are two issues that come to my mind:

  • how do I tell the app if a user is logged in, and maybe his data?
  • how do I hide specific features and items based on his login state?

Are there any best practices for approaching this? I guess the login process itself won't be that complicated, but the if logged_in? do_x else do_y is a big unknown for me atm. Where should I store the global user state?

like image 600
Jakub Arnold Avatar asked Nov 04 '22 08:11

Jakub Arnold


1 Answers

If you are using the ember router, then my suggestion would be to architect a solution like this

LoginController

App.LoginController = Ember.Controller.extend({
    login: function(params){ /* Your logic here */ },
    logout: function(params){ /* Your logic here */},

    user_data_hash: { first_name: "The", last_name: "Hobbit"},

    is_logged_in: (function() {
        /* do some logic and return true or false */
    }).property('some_item_on_user_data_hash')

    just_logged_in: (function() {
        /* do some logic and return true or false */
    }).property('some_item_on_user_data_hash')

Then in your router before you allow navigation to a protected route, you check with the LoginController object. This example is take from this answer.

root: Ember.Route.extend({
    index: Ember.Route.extend({
        enter: function(router) {
            var logged_in = router.get('loginController.is_logged_in'); /*Or in older ember builds `router.getPath('loginController.is_logged_in');`*/
            var just_logged_in = router.get('loginController.just_logged_in'); /*Or in older ember builds `router.getPath('loginController.just_logged_in');`*/
            Ember.run.next(function() {
                if (logged_in && just_logged_in) {
                    router.transitionTo('loggedIn');
                } else if (!logged_in) {
                    router.transitionTo('loggedOut');
                }
            });
        }
    }),

    loggedIn: Ember.Route.extend({
        // ...
    }),

    loggedOut: Ember.Route.extend({
        // ...
    })
})
like image 68
wmarbut Avatar answered Nov 10 '22 15:11

wmarbut