Search code examples
facebook-graph-apiember.jsember-clifacebook-sdk-4.0ember-addon

The fb access token always get expired in ember app


I am using ember-simple-auth and ember-cli-facebook-js-sdk.I am using the ember-cli-facebook-sdk because I want to get the user photo anytime as facebook only give the access which expires in 60 mins.So I can't save also.Ember-cli-facebook-sdk is working fine.But sometimes I am getting an error in my network console.

{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}

I am not able to think why this error is coming.I have a initializer which have facebook id and api version.And Now I am using Fb.api and others in my controller,component and other.But it fails sometimes.Please anwser where I am going wrong.Thanks in advance.

initializer/fb.js

import FB from 'ember-cli-facebook-js-sdk/fb';

export default {
  name: 'fb',
  initialize: function() {
    return FB.init({
      appId: '1234567',
      version: 'v2.3',
      xfbml: true
    });
  }
};

controller.js

usrphoto:Ember.computed('model',function(){
          var currentState = this;
          FB.api('/me/picture','Get',{'type':'large'}).then(function(response) {
            currentState.set('usrphoto', response.data.url)
            })
      }

Solution

  • I think what happens here is, that your Facebook session expires. In that case you need to handle the error and manage it. For example, you could check for a valid session and in case the session is expired, require a new token and then do your request:

    FB.getLoginStatus().then(function(response) {
      if (response.status === 'connected') {
        return Ember.RSVP.resolve();
      } else {
        return FB.login('email,user_photos'); //set your scope as needed here
      }
    }).then(function() {
      return FB.api('/me/picture','Get',{'type':'large'});
    }).then(function(response) {
      currentState.set('usrphoto', response.data.url);
    });
    

    Another possibility is to handle the error in the catch of the FB.api:

    FB.api('/me/picture','Get',{'type':'large'}).then(function(response) {
      currentStatte.set('userphoto', response.data.url);
    }).catch(function(reason) {
      ...handle your error here...
    });