Search code examples
angularjsng-flow

ng-flow setting CSRF token on header


i could not find a way setting the X-XSRF-TOKEN header when using file uploads with flow.js.

Since flow.js seems to not use the $http resource to post files i need to set the header explicitly.

Here is what is did:

profile.edit.html:

<div class="row" flow-init="{target: 'rest/account/uploadImage'}" 
                        flow-file-added="processFiles($file, $event, $flow)"
                        flow-files-submitted="$flow.upload()" >
...
<img type="file" flow-btn ng-if="$flow.files.length" flow-img="$flow.files[$flow.files.length-1]" class="img-circle m-t-xs img-responsive" />

</div>

controller.js:

function profileCtrl($rootScope, $scope, $http, $location, $window, $cookies, toaster, 

    $scope.processFiles = function(file, event, flow) {
        flow.defaults.headers = function(file, chunk, isTest) {
            return {
                'X-CSRFToken': $cookies.get("csrftoken")
    };}

But unfortunally nothing is set. Any ideas?

Cheers!


Solution

  • Flow.js does not use $http service, because of this you have to set csrf token manually to each request.

    It should be:

    <div flow-init="{headers: {'XCSRF-TOKEN': csrf}}">
    </div>
    

    Or:

    html file:

    <div flow-init="setToken();">
        ...
    </div>
    

    js file:

     function profileCtrl($rootScope, $scope, $http, $location, $window, $cookies, toaster){
    
        $scope.setToken = function() {
           $scope.options = {
             headers: {
                'X-CSRFToken': $cookies.get("csrftoken");
             }
           };
        }
    

    }

    OR:

    Html File :

      <div  flow-init flow-files-submitted="uploadFiles($files, $event, $flow);"
                    flow-file-added="!!{png:1,gif:1,jpg:1,jpeg:1}[$file.getExtension()]"
    
                    flow-name="flow" flow-upload-started="uploadStart($flow);"
                    flow-file-success="fileUploadSucces($file, $message)"
                    flow-complete="fileUploadsComplete();">
    
    ....
      </div>
    

    JS file :

     function profileCtrl($rootScope, $scope, $http, $location, $window, $cookies, toaster){
    
        $scope.uploadStart = function($flow){   
            $flow.opts.target = "rest/account/uploadImage";
            $flow.opts.headers =  {'X-CSRFToken' : $cookies.get("csrftoken")};
        }
    
        $scope.fileUploadSucces = function($file, $message){
            //Upload Success
    
        };
    
        $scope.fileUploadsComplete = function(){
           //Complated Upload
    
        };
    
        $scope.uploadFiles = function($file, $message, $flow){
            //Uploading
            $rootScope.$flow = $flow;
            $rootScope.$flow.upload();
       };
    }