Alaa-GI
Alaa-GI

Reputation: 410

Ember.JS, display views depending on the user role

I am using Ember.Js to create a web application, I have User collection in my MongoDb, in User collection there is a Role attribute which can take two values, "admin" or "customer". What I want to do is the following : When someone logs in, he is going to be redirected either to the admin dashboard or customer interface, depending on his Role.

How can I achieve this ? what is the best practice ? It is a good idea or I should better create a collection for admin and another for customer ?

Upvotes: 1

Views: 383

Answers (1)

mistahenry
mistahenry

Reputation: 8744

I would personally make use of the Application route's afterModel hook.

export default Ember.Route.extend({
    model: function(){
        //I DK if you use Ember Data. I don't but this could be a store lookup.
        return this.userService.getCurrentUser()
    },
    afterModel: function(resolvedModel, transition){
        var user = resolvedModel;
        if(user.role === 'ADMIN'){
            this.transitionTo('admin-dashboard');
        }else{
            this.transitionTo('customer-interface');
        }
    }
});

You could then have different menu structures that only link-to admin and customer routes respectively or both. I'd also have a mixin that all of my other Admin only routes extend:

import Ember from 'ember';

export default Ember.Mixin.create({
    beforeModel: function(){
        var currentUser = this.modelFor('application');
        if(currentUser.role !== 'ADMIN'){
            //handle this howerver
            this.transitionTo('unauthorized');
        }
    }
});

So your admin-dashboard route would look like:

import Ember from 'ember';
import AdminRoute from 'app_name/mixins/admin-route';

export default Ember.Route.extend(AdminRoute, {});

Upvotes: 3

Related Questions