9

我在注册后为用户设置了自动身份验证:

应用程序/库/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.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);                                            
    }                                                                             
 });

应用程序/控制器/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 ?? 
        });                                                                       
      }                                                                                          
    }                                                                                            
 });

我为将提供用户名和密码的用户单独登录。

我想要做的是,当新用户在网站上注册时,我希望该用户直接登录而无需进入登录页面并提供其用户名/密码?当我从注册过程中获取用户名和密码时,我不希望用户转到另一条路线然后登录。如何调用自定义身份验证器以使用其登录凭据对当前注册用户进行身份验证?

4

5 回答 5

17

最好的解决方案可能只是重用注册控制器中已有的用户名和密码属性:

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')
        });
      });                                                                       
    }                                                                                          
  }                                                                                            

});

于 2014-04-01T09:52:28.810 回答
1

我们使用设计并遇到了同样的问题。我对这个解决方案并不完全满意,但我们在响应中返回了设计身份验证令牌user.save()并直接调用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);
}

使用新的 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;
    });
  }
});

并在我们的注册表单上的提交操作中触发此验证器:

//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'));
    }
  }
}

我们的注册表单绑定到一个注册模型对象,如下所示:

//app/models/registration.js

export default DS.Model.extend(SiteModelMixin, {
  email : DS.attr("string"),
  password : DS.attr("string"),
  authToken : DS.attr("string")
});
于 2015-06-03T15:14:39.967 回答
1

Marcoow 的回答应该适用于大多数情况,但在我的情况下,注册响应包括完整的身份验证会话以及新创建用户的所有数据(即登录和注册响应是相同的)。使用表单中的相同凭据进行登录请求在这种情况下有点不太理想,因为 b/c 有一个额外的网络请求(由于网络条件不稳定等原因可能会失败)。

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

如果没有 authentication_token,我尝试使用Authenticator 调用接收到的数据对象中的属性email和属性进行登录,并使用登录尝试的结果解析或拒绝。passwordauthenticate()

于 2016-04-10T02:48:27.967 回答
0

我遇到了同样的问题,我无法从“this”或“self”获取会话/用户名/密码。所以我所做的是:

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

然后我在承诺中使用它们(使用默认身份验证器):

user.save().then(function() {
     App.session.authenticate('ember-simple-auth:authenticators:oauth2', App.credentials);
}, function(err) {
     console.log('error ..')
});
于 2014-04-12T13:04:36.537 回答
0

我不想使用另一个网络请求,因为我的 API 会返回带有注册响应的令牌,所以我沿着 Drew Nichols 的路线开始,但不喜欢创建单独的模型。最后我发现你可以简单地handleResponse()在适配器中扩展模型的钩子。然后,您只需要一个简单的身份验证器来返回输入数据(因此通过身份验证过程运行该数据以将其添加到会话中)。

这一切都在 Ember 2.7 中。

这是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);
  },
});

Registration以及上面调用的Authenticator:

// app/authenticators/registration.js

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

然后调用控制器(或任何地方),你可以简单地做一个常规save()

this.get('model').save()
于 2016-08-08T06:18:47.873 回答