mainmatter / ember-simple-auth

A library for implementing authentication/authorization in Ember.js applications.
https://ember-simple-auth.com
MIT License
1.92k stars 603 forks source link

authenticator.authenticate.apply(...).then is not a function #1082

Closed ynnoj closed 7 years ago

ynnoj commented 8 years ago

I'm writing a custom authenticator for an app which merely sends an ajax.request to my endpoint. The request returns the expected response, but the authenticate promise from Ember Simple Auth doesn't seem to resolve as the sessionAuthenticationSucceeded hook never fires.

return ajax.request('url', {
  method: 'POST',
  data: body
}).then((response) => {
  return RSVP.resolve(response);
}), (error) => {
  return RSVP.reject(error);
};
logIn() {
  this.get('session').authenticate('authenticator:moltin');
}
marcoow commented 8 years ago

Please share the full implementation of your authenticator. Also you'd probably want to change the above to

return ajax.request('url', {
  method: 'POST',
  data: body
});
ynnoj commented 8 years ago
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import Config from '../config/environment';

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

export default Base.extend({
  ajax: service(),

  restore() {
  },

  authenticate() {
    const ajax = this.get('ajax');

    const data = {
      client_id: Config.clientId,
      client_secret: Config.clientSecret,
      grant_type: 'client_credentials'
    };

    const body = Object.keys(data).map((key) => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`;
    }).join('&');

    return ajax.request('redacted', {
      method: 'POST',
      data: body
    }).then((response) => {
      return RSVP.resolve(response);
    }), (error) => {
      return RSVP.reject(error);
    };
  },

  invalidate() {
    return Ember.RSVP.resolve();
  }
});

@marcoow If I remove the .then() from the ajax.request then the request does not resolve.

marcoow commented 8 years ago

@marcoow If I remove the .then() from the ajax.request then the request does not resolve.

You're just returning the promise that resolves to the request's response or rejects with an error - that should be fine. Currently, you're returning a promise that resolves with a resolving promise which is most likely not what you want.

You also need to implement the restore method - otherwise the session will always be lost when reloading the page/restarting the app.

ynnoj commented 8 years ago

@marcoow I've never actually had a successful session authenticate, hence why the restore method remains empty 😢

I'll try recreate this issue in a test app and share.

ynnoj commented 8 years ago

I've created a test app that replicates the same symptoms of my working app.

https://github.com/ynnoj/esa-test