MSK
MSK

Reputation: 401

Marionette JS multiple route ,controller and session management

So my Marionette application has folowing 2 routes and controllers

  1. AuthRoute and AuthController for user login and logout
  2. UserRoute and UserControler for user listing, new user and edit user

In AuthController when user login I need to save the user session somewhere so that it can be acceable to both these routes, So next time when user hits user listing page I can check for user session and then load the user listing page.

How can I achieve this?

Also, what will be the best way to check if user session is valid or not? My plan is to create a service which will return user details if the session is valid or else will return 401, but till the time service returns the response I can't load the route specific views.

Can someone help me on these?

Thanks in Advance MSK

Upvotes: 1

Views: 397

Answers (2)

Federico Baron
Federico Baron

Reputation: 997

I usually save session data in a singleton Beckbone.Model referenced by the Marionette.Application.

Session Model:

var SessionModel = Backbone.Model.extend({
    initialize: function () {

        this.listenTo(this, 'change', function (model) {
            // Manage cookies storage
            // ex. using js.cookie
            Cookies.set('session', model.toJSON(), {expires: 1});
        });
    },
    checkAuth: function () {
        ...
    },
    login: function (user, password, remember) {
        ...
    },
    logout: function () {
        ...
    }
});

Application:

var app = new Marionette.Application({
    session: new SessionModel(),
    ...
})
app.reqres.setHandlers({
    session: function () {
        return app.session;
    }
});

Then you can access session model from any point through "global channel":

Backbone.Wreqr.radio.channel('global').reqres.request('session').checkAuth()

So you can implement all your session procedures in the session model class that can be accessed from the whole application. Using cookies you will also save the user session in the browser.

Upvotes: 1

Alexander Shlenchack
Alexander Shlenchack

Reputation: 3869

If you use backend API for Backbone then:

How can I achieve this?

The best way for saving a user session is cookies. Use it for storing and retrieving the user authentication_token.

Also, what will be the best way to check if user session is valid or not?

You have to store authentication_token on the backend side. For login, logout, signup you should iterate with your API.

Upvotes: 0

Related Questions