mardi 22 novembre 2016

EmberJS retrieve current user from ember-simple-auth authenticator

Issue:

I am trying to retrieve the current user logged in from ember-simple-auth by extending ember-simple-auth/authenticators/base. I just want to create a function called currentUser() that will return the username but I get the error whenever I try calling the function:

Uncaught TypeError: this.get(...).currentUser is not a function(…)

Attempt:

the function currentUser() is defined below:

// app/authenticators/oauth2.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';

const RSVP = Ember.RSVP;

export default Base.extend({
  restore() {
      // restore user session
  },
  currentUser() {
      return this.get("username");
  }),
  authenticate(username, password) {
    this.set('username', username);
    return new RSVP.Promise((resolve, reject) => {
      Ember.$.ajax({
        url: config.baseURL + "accounts/login",
        data: {
          username: username,
          password: password
        },
        type: 'POST',
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        complete: (response)=> {
          if (response.responseJSON.isAuthenticated)
            resolve({isAuthenticated: true});
          else
            reject("Wrong credentials.");
        }
      });
    });
  },
  invalidate() {
    // log out
  }
});

I called the function using:

// app/controllers/application.js
import Ember from 'ember';

export default Ember.Controller.extend({
  session: Ember.inject.service('session'),

  actions: {
    alertSession() {
      console.log("!! " + this.get('session').currentUser());
    },
    invalidateSession() {
      this.get('session').invalidate();
      this.transitionToRoute('login');
    }
  }
});

this.get('session').invalidate(); works, but this.get('session').currentUser(); will return the error mentioned above. Please let me know how to fix this. Also, I am using Ember 2.5.1.

Thanks!




Aucun commentaire:

Enregistrer un commentaire