Workflow for Ember-simple-auth, Torii and Facebook Oauth2

后端 未结 3 2030
闹比i
闹比i 2020-12-13 07:45

After my previous question about ember-simple-auth and torii, I successfully authenticate my users with their Facebook accounts.

But currently, torii\'s provider fac

3条回答
  •  忘掉有多难
    2020-12-13 08:29

    I spent a few days trying to figure out how to make it work with torii and ended up ditching it for my own authenticator. This is a mix of code from torii and ember-simple-auth so it's not the cleanest, and probably doesn't handle all the edge cases. It basically extends the ember-simple-auth oauth2 authenticator and adds the custom code to pass the access token to the API.

    app/lib/facebook-authenticator.js

    /* global FB */
    
    import OAuth2Authenticator from 'simple-auth-oauth2/authenticators/oauth2';
    import ajax from 'ic-ajax';
    
    var fbPromise;
    
    var settings = {
      appId: '1234567890',
      version: 'v2.1'
    };
    
    function fbLoad(){
      if (fbPromise) { return fbPromise; }
    
      fbPromise = new Ember.RSVP.Promise(function(resolve){
        FB.init(settings);
        Ember.run(null, resolve);
      });
    
      return fbPromise;
    }
    
    function fblogin() {
      return new Ember.RSVP.Promise(function(resolve, reject){
        FB.login(function(response){
          if (response.authResponse) {
            Ember.run(null, resolve, response.authResponse);
          } else {
            Ember.run(null, reject, response.status);
          }
        }, {scope: 'email'});
      });
    }
    
    export default OAuth2Authenticator.extend({
      authenticate: function() {
        var _this = this;
    
        return new Ember.RSVP.Promise(function(resolve, reject) {
          fbLoad().then(fblogin).then(function(response) {
            ajax(MyApp.API_NAMESPACE + '/oauth/facebook', {
              type: 'POST',
              data: {
                auth_token: response.accessToken,
                user_id: response.userId
              }
            }).then(function(response) {
              Ember.run(function() {
                var expiresAt = _this.absolutizeExpirationTime(response.expires_in);
                _this.scheduleAccessTokenRefresh(response.expires_in, expiresAt, response.refresh_token);
                if (!Ember.isEmpty(expiresAt)) {
                  response = Ember.merge(response, { expires_at: expiresAt });
                }
                resolve(response);
              });
            }).catch(function(xhr) {
              Ember.run(function() {
                reject(xhr.textStatus);
              });
            });
          });
        });
      },
    
      loadFbLogin: function(){
        fbLoad();
      }.on('init')
    });
    

提交回复
热议问题