Idris Hanafi Idris Hanafi - 1 year ago 132
Javascript Question

EmberJS retrieve current user from ember-simple-auth authenticator


I am trying to retrieve the current user logged in from ember-simple-auth by extending

. I just want to create a function called
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(…)


the function
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) => {
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});
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() {

works, but
will return the error mentioned above.
Please let me know how to fix this.
Also, I am using Ember 2.5.1.


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download