DelphiLynx
DelphiLynx

Reputation: 921

Ember.js Authenticate user from code with Ember Simple Auth

I am trying to have a user authenticated from code. I have a login form where users can login, and it works like charm.

However, when a new user sign up, and saves the form I would like to login them in in background when the form is valid.

How can I do that?

I found the following in the API at the authenticate() method:

For an application that works without an authentication route (e.g. because it opens a new window to handle authentication there), this is the method to override, e.g.:

App.ApplicationRoute = Ember.Route.extend(Ember.SimpleAuth.ApplicationRouteMixin, {
  actions: {
    authenticateSession: function() {
      this.get('session').authenticate('app:authenticators:custom', {});
    }
  }
});

Do anyone know how to implement this. When I call this.get('session').authenticate() where to put the identication and password data?

Any hints or suggestions are highly appreciated!

Edit: maybe it is possible to use the same authenticator used for logging in instead of app:authenticators:custom as in the example?

Upvotes: 1

Views: 596

Answers (1)

marcoow
marcoow

Reputation: 4062

To authenticate the session either via a regular login (probably with EmberSimpleAuth's default authenticator) or automatically after successful signup, you'd use a different authenticator for each case. For the login you'd use the default authenticator with the LoginControllerMixin etc. and for the automatic case you'd use a custom authenticator. For docs on using custom authenticators see the examples in EmberSimpleAuth's github repo an the API docs: http://ember-simple-auth.simplabs.com/api.html.

Basically what you'd do is:

App.AutoAuthenticator = Ember.SimpleAuth.Authenticators.OAuth2.extend({
  authenticate: function(credentials) {
    if (!Ember.isEmpty(credentials.access_token)) {
      return Ember.RSVP.resolve(credentials);
    } else {
      return this._super(credentials);
    }
  }
});
Ember.Application.initializer({
  name: 'authentication',
  initialize: function(container, application) {
    container.register('app:authenticators:custom', App.AutoAuthenticator);
    Ember.SimpleAuth.setup(container, application);
  }
});
this.get('session').authenticate('app:auto-authenticator', { access_token: 'secret token!' })

I did not actually test that - please regard this as pseudo code ;)

Upvotes: 5

Related Questions