Idris Hanafi Idris Hanafi - 15 days ago 6
Javascript Question

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!

Answer

In your application controller, you are calling currentUser() from the session service, while you’ve defined currentUser() in your oauth2.js authenticator. Execution could be failing because you have not modified the session service to have a reference to your authenticator's currentUser function.

The other function executes successfully because the session service has the reference that is necessary to invoke the designated authenticator's invalidate() function.

You might consider using ember-simple-auth's suggestions for Managing a Current User. With this, you can explore a solution that utilizes an isolated currentUser service that works in conjunction with the session service.