4

I am writing an ember app (using ember 2.3.0) using emberfire & torii for authentication. After a user logs in, their uid is available to me in the torii session object. I also have a user model and would like to access other data related to the current user in my templates, routes, etc.

I can get this to work in a single route by doing something like:

let uid = this.get('session').get('uid');
this.store.findRecord('user', uid).then(user => {
  console.log(user.get('firstName'));
});

but would like to prevent having to write this for each route/controller that needs to access it.

Could anyone advise on the best way to do this? Is the best way to use a service? If so, how can I ensure that the code in my service is executed after my session object is available?

Update

I managed to get my application to work with the following solution:

Create a method to login user using firebase

I created a mixin to handle the logging in behaviour. This is then used on both the login page and the sign up page.

// Mixin to handle logging in

import Ember from 'ember';

export default Ember.Mixin.create({

  user: Ember.inject.service(),

  email: null,
  errorMsg: null,

  logInUser(email, password) {

    // logout existing user if any and then login new user
    this.get('session').close()
    .then(() => {
      // if already a user logged in
      this.firebaseLogin(email, password);
    })
    .catch(() => {
      // if no user logged in
      this.firebaseLogin(email, password);
    });
  },

  firebaseLogin(email, password) {
    this.get("session").open("firebase", {
       provider: 'password',
       email: email,
       password: password
     })
     .then((data) => {
       // If successful, fetch the user and transition to home page
       console.log("Successfully logged in as ", data);
       this.get('user').loadCurrentUser().then(() => {
         this.transitionToRoute('index');
       });

     })
     .catch(error => {
       this.set('errorMsg', error);
     });
  },

});

Create a user service

This is used to associate the user model with the authentication user.

app/services/user.js

import Ember from 'ember';

export default Ember.Service.extend({

  store: Ember.inject.service(),
  session: Ember.inject.service(),

  currentUser: null,

  loadCurrentUser() {
    return new Ember.RSVP.Promise((resolve, reject) => {
      const uid = this.get('session').get('uid');
      if (!Ember.isEmpty(uid)) {
        return this.get('store').find('user', uid).then((user) => {
          this.set('currentUser', user);
          resolve();
        }, reject);
      } else {
        this.set('currentUser', null);
        resolve();
      }
    });
  }

});

Inject user service into application route

The application route is called whenever the application is loaded (when the user refreshes the page for example). Therefore, as @Deovandski mentioned in his answer, you need to inject it on the Application route in order for the user account to be available globally.

app/routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({

  user: Ember.inject.service(),

  beforeModel() {
    return this.get("session").fetch()
    .then(() => {
      // Session retrieved successfully
      console.log('session retrieved');
      return this.get('user').loadCurrentUser();
    })
    .catch(() => {
      // Session could not be retrieved
      this.transitionTo('login');
    });
  }

});

Inject the user service wherever it is needed

You can then access the current user in the following manner:

user: Ember.inject.service()
...
let currentUser = this.get('user').get('currentUser');
4

1 回答 1

3

正如评论中的锁所提到的,最好的选择是使用服务。我在会话中使用Ember-Simple-auth,这就是我实现自己的自定义会话的方式,该会话在全局范围内保存登录用户:

服务/会话帐户.js

import Ember from 'ember';

const { inject: { service }, RSVP } = Ember;

export default Ember.Service.extend({
  session: service('session'),
  store: service(),

  loadCurrentUser() {
    return new RSVP.Promise((resolve, reject) => {
      const uid = this.get('session.data.authenticated.uid');
      if (!Ember.isEmpty(userId)) {
        return this.get('store').find('user', uid).then((user) => {
          this.set('user', user);
          resolve();
        }, reject);
      } else {
        resolve();
      }
    });
  }
});

将服务注入应用程序路由

您需要将其注入到 Application 路由中才能使用户帐户在全球范围内可用。

const { service } = Ember.inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
  session: service('session'),
  sessionAccount: service('session-account'),

  beforeModel() {
    return this.get('sessionAccount').loadCurrentUser();
  }

});

将服务注入任何其他路由/控制器的示例

此示例使用会话帐户将当前登录用户与正在检索的模型进行比较。目的是只允许拥有它的用户编辑配置文件信息。

import Ember from 'ember';
const { service } = Ember.inject;

export default Ember.Route.extend ({
  session: service('session'),
  sessionAccount: service('session-account'),
  model: function() {
    return Ember.Object.create ({
      user: this.modelFor('user'),
      users: this.store.findAll('user')
    });
  },
  afterModel(model, transition) {
    if (model.user.get('id') === this.get('sessionAccount.user.id')) {
      // Allow Editing
    }
    else{
      this.transitionTo('index');
    }
  }
});
于 2016-03-15T08:20:10.667 回答