Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication error using Rails - Devise and AngularJS

I am using Devise for user authentication in a Rails application. I tried to use AngularJS instead of the default rails scaffolding in an application. The problem is that when I add the before_filter :authenticate_user! in the controller then AngularJS calls to update/save and delete a resource does not work saying Unauthorized Access (401). Here is some of the code:

The resource:

@app.factory "employeesDB", ($resource) ->
  $resource("/employees/:id", {id: "@id"}, {update: {method: "PUT"}},
    {destroy: {method: "DELETE"}}
  )

The save action:

  $scope.saveEmpl = ->
    $scope.em = new Object if !$scope.em
    employeesDB.save({}, $scope.em, (resource) ->
      $scope.employees.push(resource)
    , (response) ->
      console.log("Failed")
    )

$scope.em is the object containing the data for the record and it is bind to angular using ng-model.

Everything works perfect if I remove the before_filter :authenticate_user! from the controller

class EmployeesController < ApplicationController
  #before_filter :authenticate_user!

The problem occurs only when I try to save/update/delete the record, just reading it works OK.

Any ideas?? Are there any specific guidlines I should follow when using Angular and Devise? I am newbie to rails and angularJS so a detailed explanation will be greatly appreciated! Thanks

like image 311
jkotzi Avatar asked Mar 08 '13 09:03

jkotzi


2 Answers

You can add this to your app.js:

myApp.config([
  "$httpProvider", function($httpProvider) {
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = angular.element('meta[name=csrf-token]').attr('content');
  }
]);

Which add CSRF token to all Angular requests.

EDIT: Now jQuery independent (use jqLite).

like image 65
Hauleth Avatar answered Sep 19 '22 18:09

Hauleth


I found out that I had to use the CSRF token.

http://ngmodules.org/modules/ng-rails-csrf

like image 42
jkotzi Avatar answered Sep 22 '22 18:09

jkotzi