문제

I have set up a auto-authenticate for user after signup:

app/libs/auto-authenticate.js

export default Ember.SimpleAuth.Authenticators.OAuth2.extend({                  
   authenticate: function(credentials) {                                                        
     if(!Ember.isEmpty(credentials.access_token)) {                               
       return Ember.RSVP.resolve(credentials);                                                  
     } else {                                                                                   
       return this._super(credentials);                                                         
     }                                                                                          
   }                                                                                            
}); 

app/app.js

import AutoAuthenticate from 'appkit/libs/auto-authenticate';
App.initializer({                                                                              
    name: 'auto',                                                                                
    initialize: function(container, application) {                                               
      container.register('app:authenticators:custom', AutoAuthenticator);         
      Ember.SimpleAuth.setup(container, application);                                            
    }                                                                             
 });

app/controllers/register.js

  export default Ember.ObjectController.extend({
    firstname: '',                                                                
    lastname: '',                                                                                
    username: '',                                                                                
    password: '',                                                                                                                                                                             
    actions: {                                                                                   
      registerUser: function(){                                                                  
        var self = this;                                                                         
        var user = this.store.createRecord('user', {                                             
          first_name: this.get('firstname'),                                       
          last_name: this.get('lastname'),                                                       
          username: this.get('username')                                                         
        });
        user.set('typedPass', this.get('password'));                                             
        user.save().then(function(){                                                             
          //How can I login this user using ember-simple-auth ?? 
        });                                                                       
      }                                                                                          
    }                                                                                            
 });

I have separate Login for users that will provide their username and password.

What I want to do is , when a new user signs up in the website I want that user to logged in directly without going to the login page and providing its username/password ? As I am getting the username and password from the registration process, I dont want the user to go to another route and then login . How to call the custom authenticator to authenticate the current signed up user with its login credentials??

도움이 되었습니까?

해결책

The best solution would probably to just reuse the username and password properties you already have in the registration controller:

export default Ember.ObjectController.extend({
  firstname: '',                                                                
  lastname: '',                                                                                
  username: '',                                                                                
  password: '',                                                                                                                                                                             
  actions: {                                                                                   
    registerUser: function(){                                                                  
      var self = this;                                                                         
      var user = this.store.createRecord('user', {                                             
        first_name: this.get('firstname'),                                       
        last_name: this.get('lastname'),                                                       
        username: this.get('username')                                                         
      });
      user.set('typedPass', this.get('password'));                                             
      user.save().then(function() {                                                             
        //this is basically what happens when you trigger the LoginControllerMixin's "authenticate" action
        this.get('session').authenticate('app:authenticators:custom', {
          identification: this.get('username'),
          password: this.get('password')
        });
      });                                                                       
    }                                                                                          
  }                                                                                            

});

다른 팁

We use devise and had this same issue. I'm not entirely happy with this solution but we returned the devise auth token in the response to user.save() and called session#setup directly as follows:

user.save().then(function(user) {
    var secure = self.session.get('secure');
    secure.token = user.get('deviseAuthToken');
    secure.email = user.get('email');
    self.session.setup('simple-auth-authenticator:devise', secure, true);
}

With the new ember-simple-auth 1.0 addon we moved this code into a custom authenticator:

//app/authenticators/registration.js

import Ember from 'ember';
import DeviseAuthenticator from 'ember-simple-auth/authenticators/devise';
const { set } = Ember;

export default DeviseAuthenticator.extend({
  authenticate: function(registration) {
    const { tokenAttributeName, identificationAttributeName } = this.getProperties('tokenAttributeName', 'identificationAttributeName');
    const data = {};

    return registration.save().then(function(response) {
      set(data, tokenAttributeName, response.get('authToken'));
      set(data, identificationAttributeName, response.get('email'));
      set(data, 'registration', response.toJSON());
      return data;
    });
  }
});

and trigger this authenticator in the submit action on our registration form:

//app/controllers/registration.js

export default Ember.Controller.extend({
  session: Ember.inject.service('session'),
  actions: {
    submit: function() {
      this.get('session')
          .authenticate('authenticator:registration', this.get('model'));
    }
  }
}

Our registration form is bound to a registration model object which looks like this:

//app/models/registration.js

export default DS.Model.extend(SiteModelMixin, {
  email : DS.attr("string"),
  password : DS.attr("string"),
  authToken : DS.attr("string")
});

Marcoow's answer should work for most cases, but in my case the sign up response includes a full authentication session as well as all data for the newly created user(i.e. sign in and sign up responses are identical). Doing a sign in request using the same credentials from the form is a little less than ideal in this case b/c there's an extra network request(which could potentially fail due to spotty network conditions, etc...).

In my case the the responses include an authentication token, so I just provide an object to my custom authenticator which checks for an authentication_token in the received data and if so assumes the data is a valid user session(could do some more rigorous validation of the session data if needed) and resolve the promise using the received data resulting in the user session being authenticated with Ember Simple Auth in the Session Service.

If there's no authentication_token, I attempt a sign in using email and password properties in the data object received by the Authenticator's authenticate() call and resolve or reject with the result of the sign in attempt.

I had the same problem, and i could not get the session/username/password from 'this' or 'self'. so what i did is:

App.session = this.get('session');
App.credentials = {
     identification: data.username,
     password: data.password
};

And then i used them in the promise (with default authenticator):

user.save().then(function() {
     App.session.authenticate('ember-simple-auth:authenticators:oauth2', App.credentials);
}, function(err) {
     console.log('error ..')
});

I didn't want to use another network request, as my API returns the token with the registration response, so I started down the route Drew Nichols had, but didn't like creating a separate model. In the end I found that you can simply extend the model's handleResponse() hook in the adapter. Then you only need a simple authenticator that will return the input data (and therefore run that data through the authentication process to add it to the session).

This is all in Ember 2.7.

Here's the User model's adapter:

// app/adapters/user.js

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

  handleResponse(status, headers, payload, requestData) {
    if (this.isSuccess(status, headers, payload) && requestData.method === 'POST') {
      this.get('session').authenticate('authenticator:registration', payload).catch((reason) => {
        console.error( 'User Adapter Error:', reason );
      });
    }

    this._super(...arguments);
  },
});

And the Registration Authenticator that's being called above:

// app/authenticators/registration.js

export default Base.extend({
  authenticate(response) {
    return new Ember.RSVP.Promise((resolve) => {
      Ember.run.join(null, resolve, response);
    });
  },
});

Then to call in the controller (or wherever), you can simply do a regular save():

this.get('model').save()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top