1

I am using AngularJS routes with rails. For authencation I am using using Angular Devise directive. I am facing some issue with CSRF token.

User Controller

function userController($scope,$http,$route,$location,Auth,User) {

$scope.login = function(){
  Auth.login($scope.user).then(function(user) {
    User.setCurrentUser(user);
    $location.path("/logout");
  }, function(error) {
    // Authentication failed...
  });
}

$scope.logout = function(){
  Auth.logout().then(function() {
   $location.path("/logout");
  }, function(error) {
    // An error occurred logging out.
  });
}

} 

Angular Routes.js

myApp.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);

  $routeProvider
  .when("/login",
    { templateUrl: "/assets/user/login.html",
      controller: "userController" })
  .when("/logout",
    { templateUrl: "/assets/user/logout.html",
      controller: "userController" })
  .otherwise({ redirectTo: "/login" });
});

Templates/login.html

<div>
  <label for="user_email">Email</label><br>
  <input autofocus="autofocus" ng-model="user.email" id="user_email" name="user[email]" type="email" value="">
</div>

<div>
  <label for="user_password">Password</label><br>
  <input autocomplete="off" ng-model="user.password" id="user_password" name="user[password]" type="password">
</div>

<div>
  <input name="commit" type="submit" ng-click="login()" value="Sign in">
</div>

Templates/logout.html

<a href="#" ng-click="logout()"> LOGOUT </a>

When I click on Sign-in button which call login() function with user datas and login was successful , after that logout.html page is rendered using angular routes ($location.path) , if I click on logout button logout.html , it throws following error.

ActionController::InvalidAuthenticityToken

Since the authtoken was already used by login action and its no more valid. I am not sure how to generate new one with IN angularJS , If I refresh the page the logout is working.

Senthil
  • 946
  • 1
  • 14
  • 34

1 Answers1

1

I replaced

gem 'ng-rails-csrf'  to gem 'angular_rails_csrf'

It started working , but I am not sure why Angular devise suggested "ng-rails-csrf" , which not refreshing the token. Simply adding 'angular_rails_csrf' did the trick.

Senthil
  • 946
  • 1
  • 14
  • 34