2

I am updating my existing code done in ember-simple-auth: 0.8.0 to ember-simple-auth: 1.0.1

There are two problems

  1. It is not persisting a session
  2. REST Calls needed to be having withCredentials: true, not sure where I can set them.

Here is my code

//config/environment.js
  ENV['ember-simple-auth'] = {
    store: 'simple-auth-session-store:local-storage',
    authorizer: 'authorizer:custom',

    routeAfterAuthentication: '/dashboard',
    routeIfAlreadyAuthenticated: '/dashboard'
  };

My authenticator

//authenticators/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';

export default Base.extend({
  restore(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      }
      else {
        reject();
      }
    });
  },

  authenticate(options) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        type: "POST",
        url: config.serverURL + '/api/users/login',
        data: JSON.stringify({
          username: options.identification,
          password: options.password
        }),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json'
      }).then(function(response) {
        Ember.run(function() {
          resolve(response);
        });
      }, function(xhr) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  },

  invalidate(data) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        type: "POST",
        url: config.serverURL + '/api/users/logout'
      }).then(function(response) {
        Ember.run(function() {
          resolve(response);
        });
      }, function(xhr) {
        Ember.run(function() {
          reject(xhr.responseJSON || xhr.responseText);
        });
      });
    });
  }
});

My authorizer (you can see that I am trying to update my old code)

//authorizers/custom.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';

export default Base.extend({
  authorize(sessionData, block) {
    if (!Ember.isEmpty(sessionData.token)) {
      block('X-CSRF-Token',  sessionData.token);
      block('Content-Type',  'application/json;charset=utf-8');
      block('withCredentials', true);
    }
  }

  //authorize(jqXHR, requestOptions) {
  //  if (!(requestOptions.data instanceof FormData)){
  //    requestOptions.contentType = 'application/json;charset=utf-8';
  //  }
  //
  //  requestOptions.crossDomain = true;
  //  requestOptions.xhrFields = {
  //    withCredentials: true
  //  };
  //
  //
  //  var token = this.get('session.token');
  //  console.error(jqXHR);
  //  if (this.get('session.isAuthenticated') ) {
  //    jqXHR.setRequestHeader('X-CSRF-Token', token);
  //  }
  //}
});

My application adapter

    import DS from 'ember-data';
    import config from '../../config/environment';
    import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

    export default DS.RESTAdapter.extend(DataAdapterMixin, {
        authorizer: 'authorizer:custom',
        namespace: 'api',
        host: config.serverURL,
    });

Dashboard

    import Ember from 'ember';

    import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

    export default Ember.Route.extend(AuthenticatedRouteMixin, {
        session: Ember.inject.service('session'),

        needs: 'application',
        setupController: function(controller, model){
            this.controllerFor('application').set('pageTitle', 'Dashboard');
            this._super(controller, model);
        }
    });

If I do console.log(this.get('session.isAuthenticated'); it returns me true, but when I use that in template it dont work

    {{#if session.isAuthenticated}}
        1
    {{else}}
        0
    {{/if}}

On my laravel end, i can see that session is created and user is logged in, on Ember side, it was previously setting the session and then resends the credentials with each request. Now when it send another request. I think it is without credentials: True and laravel returns 401. I also tried sending a garbage header and laravel CORS refused that it is not in allowed headers.

Thank you

Aamir Mahmood
  • 2,704
  • 3
  • 27
  • 47

1 Answers1

0

The authorizer config setting doesn't exist anymore in 1.0 as auto-authorization has been dropped. See the API docs for info on how to add authorization to outgoing requests:

Also your authorizer should not call the block several times but only ones, passing all authorization data at once.

Also make sure you inject the session service into all controllers and components for templates you use the session in.

marcoow
  • 4,062
  • 1
  • 14
  • 21
  • a) I have used data adapter mixin. b) i am not sure my code is calling block several times. c) my app right now have 44 routes, and it will going to have 2k + routes. why do i have to inject session in every where, while I was able to do that before without adding them – Aamir Mahmood Dec 03 '15 at 08:08
  • 1
    `block('X-CSRF-Token', sessionData.token);block('Content-Type', 'application/json;charset=utf-8');block('withCredentials', true);`. If you don't want to inject the service into each route you can also setup an auto-injection via the container in an initializer. – marcoow Dec 03 '15 at 10:03
  • Hmm i have followed what you suggested, now there is only one block call. I am able to send the ajax request using content type and with credentials as well. There are 2 things. 1) when ajax call is made, it is not passing the credentials. 2) when I reload i am logged out. means session is not persisting. – Aamir Mahmood Dec 14 '15 at 14:16