简体   繁体   English

成功注册后登录Ember-Simple-Auth

[英]Login after successful signup Ember-Simple-Auth

I have set up a auto-authenticate for user after signup: 我在注册后为用户设置了自动身份验证:

app/libs/auto-authenticate.js 应用程序/库/自动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 应用程序/ 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 应用程序/控制器/ 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()的响应中返回了user.save() auth令牌,并直接调用了session#setup ,如下所示:

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: 使用新的ember-simple-auth 1.0插件,我们将此代码移动到自定义验证器中:

//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(ie sign in and sign up responses are identical). Marcoow的答案应该适用于大多数情况,但在我的情况下,注册响应包括完整的身份验证会话以及新创建的用户的所有数据(即登录和注册响应相同)。 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...). 在这种情况下使用表单中的相同凭据进行登录请求有点不太理想b / c有一个额外的网络请求(由于网络状况不稳定等可能会失败......)。

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. 在我的情况下,响应包括一个身份验证令牌,所以我只提供一个对象到我的自定义身份验证器,它检查收到的数据中的authentication_token ,如果是这样,假设数据是一个有效的用户会话(可以做一些更严格的验证会话数据(如果需要)并使用接收的数据解析承诺,从而导致用户会话在会话服务中使用Ember Simple Auth进行身份验证。

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. 如果没有authentication_token,我尝试使用Authenticator的authenticate()调用接收的数据对象中的emailpassword属性进行登录,并使用登录尝试的结果解析或拒绝。

I had the same problem, and i could not get the session/username/password from 'this' or 'self'. 我有同样的问题,我无法从'this'或'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): 然后我在promise(使用默认身份验证器)中使用它们:

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. 我不想使用另一个网络请求,因为我的API返回带有注册响应的令牌,所以我开始沿着Drew Nichols的路线,但不喜欢创建一个单独的模型。 In the end I found that you can simply extend the model's handleResponse() hook in the adapter. 最后我发现你可以简单地在适配器中扩展模型的handleResponse()钩子。 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. 这一切都在Ember 2.7中。

Here's the User model's adapter: 这是User模型的适配器:

// 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: 以及上面调用的Registration验证器:

// 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() : 然后在控制器(或任何地方)中调用,您只需执行常规save()

this.get('model').save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM