Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton model for logged-in user

Tags:

ember.js

I handle user login/registration without ember for now, but I'd like to handle user profile within ember (edit the profile). What would be the best course of action to have a singleton model that would handle current user? I defined a simple user as:

App.User = DS.Model.extend({
    email: DS.attr('string'),
    name: DS.attr('string'),
});

I could populate it in App.ready but I am not quite sure how to do it with anything other than App.User.find(id) - and I don't know the id. My server can return just currently logged in user from this session, but how to use that in this case? Or am I handling this in a wrong way?

Thanks

like image 683
Marin Avatar asked Feb 18 '23 00:02

Marin


2 Answers

Discourse embeds the current user's information into the base HTML page and preloads it into a User model in the application route:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/routes/application_route.js

The User model then has enough information to access the users's profile/etc:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/models/user.js

The session specific items (such as logging out) access a separate /session/ URL:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse.js#L169

If you are using sessions and you want to avoid embedding the current user information in your base HTML page (if you are serving content statically, etc) you could also manually access a session specific URL (such as /session/) that returns the currently logged in user's information according to the current session.

like image 186
CraigTeegarden Avatar answered Feb 22 '23 03:02

CraigTeegarden


I basically do what you are describing. I use the code below to make a call to the backend to get the currently logged in user and set it in the Ember application.

var App = Ember.Application.create({
    LOG_TRANSITIONS: true,
});

App.deferReadiness();

$.ajax({
    url: 'http://localhost:3000/login',
    dataType: 'json',
    success: function (resp) {
        console.log(resp.user);

        App.store.load(App.User, resp.user._id, resp.user);
        App.store.load(App.Company, resp.company._id, resp.company);

        var user = App.User.find(resp.user._id);
        var company = App.Company.find(resp.company._id);

        App.CurrentUserController.reopen({
            content: user
        });

        App.CurrentCompanyController.reopen({
            content: company
        });

        App.advanceReadiness();
    },
    error: function (resp) {
        console.log('failed: ' + resp);
        App.advanceReadiness();
    }
});

App.initialize();
like image 38
Fred Jiles Avatar answered Feb 22 '23 04:02

Fred Jiles