HOWTO access `currentUser` within the `model()` hook with ember-simple-auth?


#1

I am using ember-simple-auth as my authentication library.

I have a situation where I need to access the currentUser‘s ID to retrieve a record in the model() hook of a route handler. However, from what I understand, I’m not able to access the session service because it is injected into the controller, not into the route handler.

Is there a way to actually do this?


#2

You can inject it in the route like you would any other service. There is nothing special about it.

Also, somewhere in the simple-auth docs, there is a write-up called “managing current user” or something like that. It provides a basic cookbook for what you are attempting. We have been using that pattern successfully.


#3

Thanks, Chris! I’ll take a look.


#4

@johnnyicon you can create the currentUser service as explained in the docs ESA - Managing a Current User

and then just use it in your route like this, given you want to get all the bookings of the current user in the following example:

import Ember from 'ember';

const { inject: { service } } = Ember;

export default Ember.Route.extend({
  currentUser: service(),
    
  model() {
    let userId = this.get('currentUser.user.id');
    return this.store.query('booking', { user_id: userId });
  }
});