簡體   English   中英

成功注冊后登錄Ember-Simple-Auth

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

我在注冊后為用戶設置了自動身份驗證:

應用程序/庫/自動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 ?? 
        });                                                                       
      }                                                                                          
    }                                                                                            
 });

我有單獨的登錄用戶,將提供他們的用戶名和密碼。

我想要做的是,當一個新用戶在網站上注冊時,我希望該用戶直接登錄而無需進入登錄頁面並提供其用戶名/密碼? 當我從注冊過程中獲取用戶名和密碼時,我不希望用戶轉到另一條路線然后登錄。 如何調用自定義身份驗證器以使用其登錄憑據對當前已注冊的用戶進行身份驗證?

最好的解決方案可能只是重用您在注冊控制器中已有的用戶名和密碼屬性:

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

});

我們使用設計並有同樣的問題。 我對這個解決方案並不完全滿意,但我們在對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);
}

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

Marcoow的答案應該適用於大多數情況,但在我的情況下,注冊響應包括完整的身份驗證會話以及新創建的用戶的所有數據(即登錄和注冊響應相同)。 在這種情況下使用表單中的相同憑據進行登錄請求有點不太理想b / c有一個額外的網絡請求(由於網絡狀況不穩定等可能會失敗......)。

在我的情況下,響應包括一個身份驗證令牌,所以我只提供一個對象到我的自定義身份驗證器,它檢查收到的數據中的authentication_token ,如果是這樣,假設數據是一個有效的用戶會話(可以做一些更嚴格的驗證會話數據(如果需要)並使用接收的數據解析承諾,從而導致用戶會話在會話服務中使用Ember Simple Auth進行身份驗證。

如果沒有authentication_token,我嘗試使用Authenticator的authenticate()調用接收的數據對象中的emailpassword屬性進行登錄,並使用登錄嘗試的結果解析或拒絕。

我有同樣的問題,我無法從'this'或'self'獲得會話/用戶名/密碼。 所以我做的是:

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

然后我在promise(使用默認身份驗證器)中使用它們:

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

我不想使用另一個網絡請求,因為我的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驗證器:

// 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM