emberjs handle 401 not authorized

后端 未结 4 2118
情书的邮戳
情书的邮戳 2020-12-29 11:24

I am building an ember.js application and am hung up on authentication. The json rest backend is rails. Every request is authenticated using a session cookie (warden).

4条回答
  •  温柔的废话
    2020-12-29 11:55

    It's not addressed by ember-data (and probably won't be), but you can reopen the DS class and extend the ajax method.

    It looks like this:

    ajax: function(url, type, hash) {
      hash.url = url;
      hash.type = type;
      hash.dataType = 'json';
      hash.contentType = 'application/json; charset=utf-8';
      hash.context = this;
    
      if (hash.data && type !== 'GET') {
        hash.data = JSON.stringify(hash.data);
      } 
    
      jQuery.ajax(hash);
    },
    

    You can rewrite it with something like this (disclaimer: untested, probably won't work):

    DS.reopen({
        ajax: function(url, type, hash) {
            var originalError = hash.error;
            hash.error = function(xhr) {
                if (xhr.status == 401) {
                    var payload = JSON.parse(xhr.responseText);
                    //Check for your API's errorCode, if applicable, or just remove this conditional entirely
                    if (payload.errorCode === 'USER_LOGIN_REQUIRED') {
                        //Show your login modal here
                        App.YourModal.create({
                            //Your modal's callback will process the original call
                            callback: function() {
                                hash.error = originalError;
                                DS.ajax(url, type, hash);
                            }
                        }).show();
                        return;
                    }
                }
                originalError.call(hash.context, xhr);
            };
            //Let ember-data's ajax method handle the call
            this._super(url, type, hash);
        }
    });
    

    What we're doing here is essentially deferring the call that received the 401 and are preserving the request to be called again when login is complete. The modal's ajax call with have the original error applied to it from the original ajax call's hash, so the original error would still work as long as it's defined :-)

    This is a modified implementation of something we're using with our own data-persistence library, so your implementation might vary a bit, but the same concept should work for ember-data.

提交回复
热议问题