Giter VIP home page Giter VIP logo

angular_devise's Introduction

AngularDevise Build Status

A small AngularJS Service to interact with Devise Authentication.

Requirements

This service requires Devise to respond to JSON. To do that, simply add

# config/application.rb
module RailsApp
  class Application < Rails::Application
    # ...

    config.to_prepare do
      DeviseController.respond_to :html, :json
    end
  end
end

Additionally, if you have CSRF Forgery Protection enabled for your controller actions, you will also need to include the X-CSRF-TOKEN header with the token provided by rails. The easiest way to include this is to follow this post:

angular_rails_csrf.

Downloading

AngularDevise is registered as angular-devise in bower.

bower install --save angular-devise

You can then use the main file at angular-devise/lib/devise-min.js.

Rails Assets

To get AngularDevise via Rails Assets add to your Gemfile:

source "https://rails-assets.org" do
  gem "rails-assets-angular-devise"
end

Then bundle. Finally, to require the JS:

//= require angular-devise

Usage

Just register Devise as a dependency for your module. Then, the Auth service will be available for use.

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        // Configure Auth service with AuthProvider
    }).
    controller('myCtrl', function(Auth) {
        // Use your configured Auth service.
    });

Auth.currentUser()

Auth.currentUser() returns a promise that will be resolved into the currentUser. There are three possible outcomes:

  1. Auth has authenticated a user, and will resolve with that user.
  2. Auth has not authenticated a user but the server has a previously authenticated session, Auth will attempt to retrieve that session and resolve with its user. Then, a devise:new-session event will be broadcast with the current user as the argument.
  3. Neither Auth nor the server has an authenticated session, and a rejected promise will be returned. (see Interceptor for for custom handling.)
angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        Auth.currentUser().then(function(user) {
            // User was logged in, or Devise returned
            // previously authenticated session.
            console.log(user); // => {id: 1, ect: '...'}
        }, function(error) {
            // unauthenticated error
        });
    });

Auth._currentUser

Auth._currentUser will be either null or the currentUser's object representation. It is not recommended to directly access Auth._currentUser, but instead use Auth.currentUser().

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        console.log(Auth._currentUser); // => null

        // Log in user...

        console.log(Auth._currentUser); // => {id: 1, ect: '...'}
    });

Auth.isAuthenticated()

Auth.isAuthenticated() is a helper method to determine if a currentUser is logged in with Auth.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        console.log(Auth.isAuthenticated()); // => false

        // Log in user...

        console.log(Auth.isAuthenticated()); // => true
    });

Auth.login(creds, config)

Use Auth.login() to authenticate with the server. Keep in mind, credentials are sent in plaintext; use a SSL connection to secure them. creds is an object which should contain any credentials needed to authenticate with the server. Auth.login() will return a promise that will resolve to the logged-in user. See Auth.parse(response) to customize how the response is parsed into a user.

Upon a successful login, two events will be broadcast, devise:login and devise:new-session, both with the currentUser as the argument. New-Session will only be broadcast if the user was logged in by Auth.login({...}). If the server has a previously authenticated session, only the login event will be broadcast.

Pass any additional config options you need to provide to $http with config.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        var credentials = {
            email: '[email protected]',
            password: 'password1'
        };
        var config = {
            headers: {
                'X-HTTP-Method-Override': 'POST'
            }
        };

        Auth.login(credentials, config).then(function(user) {
            console.log(user); // => {id: 1, ect: '...'}
        }, function(error) {
            // Authentication failed...
        });

        $scope.$on('devise:login', function(event, currentUser) {
            // after a login, a hard refresh, a new tab
        });

        $scope.$on('devise:new-session', function(event, currentUser) {
            // user logged in by Auth.login({...})
        });
    });

By default, login will POST to '/users/sign_in.json' using the resource name user. The path, HTTP method, and resource name used to login are configurable using:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        AuthProvider.loginPath('path/on/server.json');
        AuthProvider.loginMethod('GET');
        AuthProvider.resourceName('customer');
    });

Auth.logout()

Use Auth.logout() to de-authenticate from the server. Auth.logout() returns a promise that will be resolved to the old currentUser. Then a devise:logout event will be broadcast with the old currentUser as the argument.

Pass any additional config options you need to provide to $http with config.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        var config = {
            headers: {
                'X-HTTP-Method-Override': 'DELETE'
            }
        };
        // Log in user...
        // ...
        Auth.logout(config).then(function(oldUser) {
            // alert(oldUser.name + "you're signed out now.");
        }, function(error) {
            // An error occurred logging out.
        });

        $scope.$on('devise:logout', function(event, oldCurrentUser) {
            // ...
        });
    });

By default, logout will DELETE to '/users/sign_out.json'. The path and HTTP method used to logout are configurable using:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        AuthProvider.logoutPath('path/on/server.json');
        AuthProvider.logoutMethod('GET');
    });

Auth.parse(response)

This is the method used to parse the $http response into the appropriate user object. By default, it simply returns response.data. This can be customized either by specifying a parse function during configuration:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        // Customize user parsing
        // NOTE: **MUST** return a truth-y expression
        AuthProvider.parse(function(response) {
            return response.data.user;
        });
    });

or by directly overwriting it, perhaps when writing a custom version of the Auth service which depends on another service:

angular.module('myModule', ['Devise']).
  factory('User', function() {
    // Custom user factory
  }).
  factory('CustomAuth', function(Auth, User) {
    Auth['parse'] = function(response) {
      return new User(response.data);
    };
    return Auth;
  });

Auth.register(creds)

Use Auth.register() to register and authenticate with the server. Keep in mind, credentials are sent in plaintext; use a SSL connection to secure them. creds is an object that should contain any credentials needed to register with the server. Auth.register() will return a promise that will resolve to the registered user. See Auth.parse(response) to customize how the response is parsed into a user. Then a devise:new-registration event will be broadcast with the user object as the argument.

Pass any additional config options you need to provide to $http with config.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        var credentials = {
            email: '[email protected]',
            password: 'password1',
            password_confirmation: 'password1'
        };
        var config = {
            headers: {
                'X-HTTP-Method-Override': 'POST'
            }
        };

        Auth.register(credentials, config).then(function(registeredUser) {
            console.log(registeredUser); // => {id: 1, ect: '...'}
        }, function(error) {
            // Registration failed...
        });

        $scope.$on('devise:new-registration', function(event, user) {
            // ...
        });
    });

By default, register will POST to '/users.json' using the resource name user. The path, HTTP method, and resource name used to register are configurable using:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        AuthProvider.registerPath('path/on/server.json');
        AuthProvider.registerMethod('GET');
        AuthProvider.resourceName('customer');
    });

Auth.sendResetPasswordInstructions(creds)

Use Auth.sendResetPasswordInstructions() to send reset password mail to user. Keep in mind, credentials are sent in plaintext; use a SSL connection to secure them. creds is an object that should contain the email associated with the user. Auth.sendResetPasswordInstructions() will return a promise with no params. Then a devise:send-reset-password-instructions-successfully event will be broadcast.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        var parameters = {
            email: '[email protected]'
        };

        Auth.sendResetPasswordInstructions(parameters).then(function() {
            // Sended email if user found otherwise email not sended...
        });

        $scope.$on('devise:send-reset-password-instructions-successfully', function(event) {
            // ...
        });
    });

By default, sendResetPasswordInstructions will POST to '/users/password.json'. The path and HTTP method used to send the reset password instructions are configurable using:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        AuthProvider.sendResetPasswordInstructionsPath('path/on/server.json');
        AuthProvider.sendResetPasswordInstructionsMethod('POST');
    });

Auth.resetPassword(creds)

Use Auth.resetPassword() to reset user password. Keep in mind, credentials are sent in plaintext; use a SSL connection to secure them. creds is an object that should contain password, password_confirmation and reset_password_token. Auth.resetPassword() will return a promise that will resolve to the new user data. See Auth.parse(response) to customize how the response is parsed into a user. Then a devise:reset-password-successfully event will be broadcast.

angular.module('myModule', ['Devise']).
    controller('myCtrl', function(Auth) {
        var parameters = {
            password: 'new_password',
            password_confirmation: 'new_password',
            reset_password_token: 'reset_token',
        };

        Auth.resetPassword(parameters).then(function(new_data) {
            console.log(new_data); // => {id: 1, ect: '...'}
        }, function(error) {
            // Reset password failed...
        });

        $scope.$on('devise:reset-password-successfully', function(event) {
            // ...
        });
    });

By default, resetPassword will PUT to '/users/password.json'. The path and HTTP method used to reset password are configurable using:

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        AuthProvider.resetPasswordPath('path/on/server.json');
        AuthProvider.resetPasswordMethod('PUT');
    });

Interceptor

AngularDevise comes with a $http Interceptor that may be enabled using the interceptAuth config. Its purpose is to listen for 401 Unauthorized responses and give you the ability to seamlessly recover. When it catches a 401, it will:

  1. create a deferred
  2. broadcast a devise:unauthorized event passing:
    • the ajax response
    • the deferred
  3. return the deferred's promise

Since the deferred is passed to the devise:unauthorized event, you are free to resolve it (and the request) inside of the event listener. For instance:

angular.module('myModule', []).
    controller('myCtrl', function($scope, Auth, $http) {
        // Guest user

        // Catch unauthorized requests and recover.
        $scope.$on('devise:unauthorized', function(event, xhr, deferred) {
            // Disable interceptor on _this_ login request,
            // so that it too isn't caught by the interceptor
            // on a failed login.
            var config = {
                interceptAuth: false
            };

            // Ask user for login credentials
            Auth.login(credentials, config).then(function() {
                // Successfully logged in.
                // Redo the original request.
                return $http(xhr.config);
            }).then(function(response) {
                // Successfully recovered from unauthorized error.
                // Resolve the original request's promise.
                deferred.resolve(response);
            }, function(error) {
                // There was an error logging in.
                // Reject the original request's promise.
                deferred.reject(error);
            });
        });

        // Request requires authorization
        // Will cause a `401 Unauthorized` response,
        // that will be recovered by our listener above.
        $http.delete('/users/1', {
            interceptAuth: true
        }).then(function(response) {
            // Deleted user 1
        }, function(error) {
            // Something went wrong.
        });
    });

The Interceptor can be enabled globally or on a per-request basis using the interceptAuth setting on the AuthIntercept provider.

angular.module('myModule', ['Devise']).
    config(function(AuthInterceptProvider) {
        // Intercept 401 Unauthorized everywhere
        AuthInterceptProvider.interceptAuth(true);
    }).
    controller('myCtrl', function($http) {
        // Disable per-request
        $http({
            url: '/',
            interceptAuth: false,
            // ...
        });
    });

AuthProvider

By default, AngularDevise uses the following HTTP methods/paths:

Method HTTP Method HTTP Path
login POST /users/sign_in.json
logout DELETE /users/sign_out.json
register POST /users.json
sendResetPasswordInstructions POST /users/password.json
resetPassword ย POST /users/password.json

All credentials will be under the users namespace, and the following parse function will be used to parse the response:

function(response) {
    return response.data;
};

All of these can be configured using a .config block in your module.

angular.module('myModule', ['Devise']).
    config(function(AuthProvider, AuthInterceptProvider) {
        // Customize login
        AuthProvider.loginMethod('GET');
        AuthProvider.loginPath('/admins/login.json');

        // Customize logout
        AuthProvider.logoutMethod('POST');
        AuthProvider.logoutPath('/user/logout.json');

        // Customize register
        AuthProvider.registerMethod('PATCH');
        AuthProvider.registerPath('/user/sign_up.json');

        // Customize the resource name data use namespaced under
        // Pass false to disable the namespace altogether.
        AuthProvider.resourceName('customer');

        // Also you can change host URL for backend calls
        // (for example if it's on another server than your angular app)
        AuthProvider.baseUrl('http://localhost:3000');

        // Customize user parsing
        // NOTE: **MUST** return a truth-y expression
        AuthProvider.parse(function(response) {
            return response.data.user;
        });

        // Intercept 401 Unauthorized everywhere
        // Enables `devise:unauthorized` interceptor
        AuthInterceptProvider.interceptAuth(true);
    });

Credits

Cloudspace

AngularDevise is maintained by Cloudspace, and is distributed under the MIT License.

angular_devise's People

Contributors

aarongray avatar amirkarimi avatar benmorganio avatar bilalbash avatar eralph avatar hparfr avatar imightbeinatree avatar jridgewell avatar kkirsche avatar leomao10 avatar mjrk avatar oharrison avatar otupman avatar stevenclontz avatar theonetheonlydavidbrown avatar whitehat101 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular_devise's Issues

404 Not Found

I'm trying to use Auth.login(credentials) to connect to a Rails API through Devise but it seems that the request does not get to the server. I get Status Code: 404 Not Found
Request Method: POST
Request URL: localhost:3001/users/sign_in.json

also, in WEBrick terminal, I don't see any requests being made to the server.

Recommended way to keep track of a User throughout app?

Right now at the top of every controller I have code that checks for a current user. Is there a recommended way to set user once for a session, and access it whenever a controller needs it?

myApp.controller('myPage', ['$scope', '$routeParams', 'Auth', function($scope, $routeParams, Auth){

  Auth.currentUser().then(function(user){
    // Set the current user
    $scope.user = user;
  }, function(error){
    $location.path('/');
  });
}]);

XMLHttpRequest cannot load http://undefined:undefined.......

Not 100% sure if this is something to do with this module or just to do with $http but when I setup a full url like so

AuthProvider.loginPath('test.avin.tunnel.logicsaas-development.com:3000/users/sign_in.json');
AuthProvider.loginMethod('POST');
AuthProvider.resourceName('users');

It will change the url to

http://undefined:undefinedtest.avin.tunnel.logicsaas-development.com:3000/users/sign_in.json. 

Error:

XMLHttpRequest cannot load http://undefined:undefinedtest.avin.tunnel.logicsaas-development.com:3000/users/sign_in.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Keep getting "TypeError: string is not a function" once I put Auth.login in app.run()

As title. I want to check whether the session exists when users refresh the website, so I add

  $rootScope.isAuthenticated = Auth.isAuthenticated();
        $rootScope.currentUser = Auth._currentUser;
        $rootScope.$watch(
            function() {
                return Auth.isAuthenticated();
            },
            function(newValue, oldValue) {
                if ( newValue !== oldValue ) {
                    $rootScope.isAuthenticated = newValue;
                    $rootScope.currentUser = Auth._currentUser;
                }
            }
        );

in method app.run(). But after that, I kept getting error TypeError: string is not a function when I switch to new states.

Do you guys have any idea about this?

Could not fetch specs from https://rails-assets.org/

I have following code snippet in my Gemfile

source "https://rails-assets.org" do
  gem "rails-assets-angular-devise"
end

When I do bundle install on terminal to install dependencies, it give me following error
Could not fetch specs from https://rails-assets.org/

extending login/logout

Is there a hook for extending the basic login/logout functionality? My goal is to persist an auth token returned by the server in localStorage and set it in the $http Authorization header, and do the opposite upon logout. Right now I'm just doing it by hand everytime I use Auth.login() and Auth.logout().

I attempted to include the login functionality in the configuration of AuthProvider by defining it within the parse method, but I realized I couldn't inject $http into module.config. Thoughts/suggestions? Thanks for the great module!

405 Method Not Allowed

Why the method is not allowed? I properly config my CORS, and disable any problems with all the services in my app but this one get not allowed all the time.

Cookies

Hi,

Great addon, but it doesn't seem to have any way to resume a session. Is this the case?

I'm trying to see if the user is authenticated in a "run" angular command to check they have access to particular routes before it loads. E.g.

.run(function($rootScope, $state, Auth) {
      $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        console.log(Auth.isAuthenticated());
      })
    })

Is this something you intend to add or do you have a tutorial about how to successfully re-authenticate a user from a session cookie?

Thanks,

Rikki

angular devise registration issue

var app = angular.module('myapp', ['ui.router', 'templates', 'Devise']);
app.controller('UsersCtrl', UsersCtrl);

function UsersCtrl($scope, $http,Auth) {
//handle when user submit button is clicked
$scope.register = function() {
Auth.register($scope.employee).then(function(employee) {
console.log("inside register");
$state.go('users');
}, function(error) {
console.log('registration failed due to following errors:- ')
console.log(error)
});
}
}

Provide configurable model name

You provide a way to change the path not the model name, so if you use anything that is not named user as the model in Rails it will break. I could try to work on a fix if you want.

How can I update a user?

Hey,

how can I update a user with angular devise? I want to change a users nickname (which is not the login-name)

Thanks in advance

Keep session on refresh

When the user does a hard refresh (F5), the session is "lost". Would it be a good idea to add an option to store the session with ngCookie? Bare in mind I'm getting started with Angular and I might be doing things wrong, so it really is just a question.

edit: The other solution is probably just run Auth.currentUser() on the .run on Angular, but I would like to know your opinion on the matter. I hope I'm not bothering you guys too much.

Username in registration

I've added a userName to the Devise registration form. This works without Angular fine. Using angular_devise my form is sending the userName in the JSON request but it comes back null. Is there a way for angular_devise to handle this? The picking of a userName is done at the time of registration, not in a later step.

Respond to Json

Hello, I'm creating a Ionic app for my Rails website and I need to authenticate with Devise.
In your docs you suggest to add "respond to_json" in application controller.

Is not better to add

config.to_prepare do
   DeviseController.respond_to :html, :json
end

in application.rb as Devise suggest?

[QUESTION] Why does Auth.isAuthenticated() always return false?

Hey,

I just started using Rails with Angular and I am using angular_devise.
The problem i have is:

Logging in works (the Devise Controller redirects me when I try to enter /users/sign_in).
But then Auth.isAuthenticated() always returns false, no matter what I do.

My LoginCtrl:

angular.module('ideapl')
.controller('LoginCtrl', function($scope, Auth) {
        // Use your configured Auth service.

        $scope.login_credentials = {
            email: '',
            password: ''
        };

        $scope.signup_credentials = {
            email: '',
            password: '',
            password_confirmation: ''
        };

        console.log(Auth.isAuthenticated());

        $scope.$watch('Auth.isAuthenticated()', function(newValue) {
           $scope.loginStatus = newValue ? "loggedIn" : "loggedOut";
           console.log(newValue);
       });


        $scope.$on('devise:login', function(event, currentUser) {
            // after a login, a hard refresh, a new tab
        });

        $scope.$on('devise:logout', function(event, currentUser) {
            // after a login, a hard refresh, a new tab
        });

        $scope.$on('devise:new-registration', function(event, user) {
            // ...
        });


        $scope.login = function() {
            return Auth.login($scope.login_credentials).then(function(user) {
                console.log(user); // => {id: 1, ect: '...'}
            }, function(error) {
                // Authentication failed...
            });
        }

        $scope.checkAuth = function() {
            console.log(Auth._currentUser);
        }

        $scope.logout = function() {
            return Auth.logout().then(function(oldUser) {
                console.log(oldUser);
            }, function(error) {
                // An error occurred logging out.
            });
        }

        $scope.register = function() {
            Auth.register(credentials).then(function(registeredUser) {
                console.log(registeredUser); // => {id: 1, ect: '...'}
            }, function(error) {
                // Registration failed...
            });
        }


});

My app.js

angular
.module('ideapl', [
  'ngAnimate',
  'ui.router',
  'templates',
  'Devise'
  ])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {

    /**
     * Routes and States
     */
    $stateProvider
        .state('home', {
            url: '/',
            templateUrl: 'home.html',
            controller: 'HomeCtrl'
        })

        .state('login', {
            url: '/login',
            templateUrl: 'user/login.html',
            controller: 'LoginCtrl'
        })


        // an abstract state that just serves as a
        // parent for the below child states
        .state('dashboard', {
            abstract: true,
            url: '/dashboard',
            templateUrl: 'dashboard/layout.html'
        })
        // the default route when someone hits dashboard
        .state('dashboard.mine', {
            url: '',
            templateUrl: 'dashboard/mine.html'
        })
        // this is /dashboard/two
        .state('dashboard.participating', {
            url: '/participating',
            templateUrl: 'dashboard/participating.html'
        })
        // this is /dashboard/three
        .state('dashboard.settings', {
            url: '/settings',
            templateUrl: 'dashboard/settings.html'
        });

    // default fall back route
    $urlRouterProvider.otherwise('/');

    // enable HTML5 Mode for SEO
    $locationProvider.html5Mode(true);

});

Thanks in advance :)

logout does not work - Rails 4.1, Ruby 2.1.1, Mongoid

Hello, i am using Ruby on Rails with Mongoid database. I am also using your angular_devise service to help me with the authentication.
Login and Register seem to work pretty well, but when i am implementing logout, i am facing some problems.
Here is what i get in the Chrome console
DELETE http://localhost:3000/users/sign_out.json 500 (Internal Server Error)
And when going to network tab in Chrome console, and then response, here is what i get in response tab.

Moped::Errors::QueryFailure at /users/sign_out.json

The operation: #<Moped::Protocol::Query
@Length=129
@request_id=5
@response_to=0
@op_code=2004
@flags=[]
@full_collection_name="teacher_eval_development.users"
@Skip=0
@limit=-1
@selector={"$query"=>{"_id"=>{"$oid"=>BSON::ObjectId('53610f63416c650ca9000000')}}, "$orderby"=>{:_id=>1}}
@fields=nil>
failed with error 10068: "invalid operator: $oid"

See https://github.com/mongodb/mongo/blob/master/docs/errors.md
for details about this error.

moped (2.0.0.rc1) lib/moped/operation/read.rb, line 50

   45         #
   46         # @since 2.0.0
   47         def execute(node)
   48           node.process(operation) do |reply|
   49             if operation.failure?(reply)
>  50               raise operation.failure_exception(reply)
   51             end
   52             operation.results(reply)
   53           end
   54         end
   55       end

App backtrace

Full backtrace

  • moped (2.0.0.rc1) lib/moped/operation/read.rb:50:in `block in execute'
  • moped (2.0.0.rc1) lib/moped/node.rb:594:in `[]'
  • moped (2.0.0.rc1) lib/moped/node.rb:594:in `block (2 levels) in flush'
  • moped (2.0.0.rc1) lib/moped/node.rb:593:in `map'
  • moped (2.0.0.rc1) lib/moped/node.rb:593:in `block in flush'
  • moped (2.0.0.rc1) lib/moped/node.rb:617:in `block in logging'
  • activesupport (4.1.0) lib/active_support/notifications.rb:159:in `block in instrument'
  • activesupport (4.1.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  • activesupport (4.1.0) lib/active_support/notifications.rb:159:in `instrument'
  • moped (2.0.0.rc1) lib/moped/instrumentable.rb:31:in `instrument'
  • moped (2.0.0.rc1) lib/moped/node.rb:616:in `logging'
  • moped (2.0.0.rc1) lib/moped/node.rb:587:in `flush'
  • moped (2.0.0.rc1) lib/moped/node.rb:391:in `process'
  • moped (2.0.0.rc1) lib/moped/operation/read.rb:48:in `execute'
  • moped (2.0.0.rc1) lib/moped/node.rb:648:in `read'
  • moped (2.0.0.rc1) lib/moped/node.rb:411:in `query'
  • moped (2.0.0.rc1) lib/moped/query.rb:128:in `block in first'
  • moped (2.0.0.rc1) lib/moped/cluster.rb:243:in `block in with_primary'
  • moped (2.0.0.rc1) lib/moped/node.rb:204:in `block in ensure_primary'
  • moped (2.0.0.rc1) lib/moped/executable.rb:25:in `execute'
  • moped (2.0.0.rc1) lib/moped/node.rb:203:in `ensure_primary'
  • moped (2.0.0.rc1) lib/moped/cluster.rb:242:in `with_primary'
  • moped (2.0.0.rc1) lib/moped/read_preference/primary.rb:55:in `block in with_node'
  • moped (2.0.0.rc1) lib/moped/read_preference/selectable.rb:65:in `call'
  • moped (2.0.0.rc1) lib/moped/read_preference/selectable.rb:65:in `with_retry'
  • moped (2.0.0.rc1) lib/moped/read_preference/primary.rb:54:in `with_node'
  • moped (2.0.0.rc1) lib/moped/query.rb:127:in `first'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/query_cache.rb:187:in `block in first_with_cache'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/query_cache.rb:135:in `with_cache'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/query_cache.rb:186:in `first_with_cache'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual/mongo.rb:199:in `block (2 levels) in first'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual/mongo.rb:535:in `with_sorting'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual/mongo.rb:198:in `block in first'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual/mongo.rb:447:in `try_cache'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual/mongo.rb:197:in `first'
  • () home/aleksandartokarev/.rvm/gems/ruby-2.1.1/bundler/gems/mongoid-da35e0cd0fc1/lib/mongoid/contextual.rb:20:in `first'
  • orm_adapter (0.5.0) lib/orm_adapter/adapters/mongoid.rb:22:in `get'
  • devise (3.2.4) lib/devise/models/authenticatable.rb:208:in `serialize_from_session'
  • devise (3.2.4) lib/devise.rb:462:in `block (2 levels) in configure_warden!'
  • warden (1.2.3) lib/warden/session_serializer.rb:34:in `fetch'
  • warden (1.2.3) lib/warden/proxy.rb:212:in `user'
  • devise (3.2.4) lib/devise/controllers/sign_in_out.rb:73:in `block in sign_out_all_scopes'
  • devise (3.2.4) lib/devise/controllers/sign_in_out.rb:73:in `map'
  • devise (3.2.4) lib/devise/controllers/sign_in_out.rb:73:in `sign_out_all_scopes'
  • devise (3.2.4) lib/devise/controllers/sign_in_out.rb:57:in `sign_out'
  • devise (3.2.4) app/controllers/devise/sessions_controller.rb:25:in `destroy'
  • actionpack (4.1.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  • actionpack (4.1.0) lib/abstract_controller/base.rb:189:in `process_action'
  • actionpack (4.1.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
  • actionpack (4.1.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
  • actionpack (4.1.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
  • actionpack (4.1.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
  • actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  • activesupport (4.1.0) lib/active_support/notifications.rb:159:in `block in instrument'
  • activesupport (4.1.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  • activesupport (4.1.0) lib/active_support/notifications.rb:159:in `instrument'
  • actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  • actionpack (4.1.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  • actionpack (4.1.0) lib/abstract_controller/base.rb:136:in `process'
  • actionview (4.1.0) lib/action_view/rendering.rb:30:in `process'
  • actionpack (4.1.0) lib/action_controller/metal.rb:195:in `dispatch'
  • actionpack (4.1.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  • actionpack (4.1.0) lib/action_controller/metal.rb:231:in `block in action'
  • actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:80:in `call'
  • actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
  • actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:48:in `call'
  • actionpack (4.1.0) lib/action_dispatch/routing/mapper.rb:45:in `call'
  • actionpack (4.1.0) lib/action_dispatch/journey/router.rb:71:in `block in call'
  • actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in `each'
  • actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in `call'
  • actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:676:in `call'
  • warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  • warden (1.2.3) lib/warden/manager.rb:34:in `catch'
  • warden (1.2.3) lib/warden/manager.rb:34:in `call'
  • rack (1.5.2) lib/rack/etag.rb:23:in `call'
  • rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
  • rack (1.5.2) lib/rack/head.rb:11:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/flash.rb:254:in `call'
  • rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  • rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  • activesupport (4.1.0) lib/active_support/callbacks.rb:82:in `run_callbacks'
  • actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  • better_errors (1.1.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
  • better_errors (1.1.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
  • better_errors (1.1.0) lib/better_errors/middleware.rb:56:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  • railties (4.1.0) lib/rails/rack/logger.rb:38:in `call_app'
  • railties (4.1.0) lib/rails/rack/logger.rb:20:in `block in call'
  • activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  • activesupport (4.1.0) lib/active_support/tagged_logging.rb:26:in `tagged'
  • activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `tagged'
  • railties (4.1.0) lib/rails/rack/logger.rb:20:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  • rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  • rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  • activesupport (4.1.0) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  • rack (1.5.2) lib/rack/lock.rb:17:in `call'
  • actionpack (4.1.0) lib/action_dispatch/middleware/static.rb:64:in `call'
  • rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  • railties (4.1.0) lib/rails/engine.rb:514:in `call'
  • railties (4.1.0) lib/rails/application.rb:144:in `call'
  • rack (1.5.2) lib/rack/lock.rb:17:in `call'
  • rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  • rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  • () home/aleksandartokarev/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
  • () home/aleksandartokarev/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
  • () home/aleksandartokarev/.rvm/rubies/ruby-2.1.1/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'

Error 422 (Unprocessable Entity)

Can't login, instead I'm getting this error message POST http://mysite.com/login.json 422 (Unprocessable Entity)
I'm following the Readme instructions and requirements but still getting this error. I'll appreciate any help.

Config

.config(['AuthProvider', '$httpProvider', function (AuthProvider, $httpProvider) {

    $httpProvider.defaults.withCredentials = true;

    AuthProvider.loginPath('http://mysite.com/login.json');
    AuthProvider.logoutPath('http://mysite.com/logout.json');
}])

Controller

angular.module('myApp')
    .controller('MainCtrl', function ($scope, Auth) {

    var credentials = {
        email: '[email protected]',
        password: 'test1234',
        remember_me: '0'
    };
    console.log(credentials)

    Auth.login(credentials).then(function(user) {
        console.log(user); // => {id: 1, ect: '...'}
    }, function(error) {
        // Authentication failed...
    });

    console.log(Auth.isAuthenticated());
});

Rails devise route for login

HTTP Verb   Path                Controller#Action
POST        /login(.:format)    devise/sessions#create

Using a factory to parse user response

I'm using angular-rails-resource in my app, including for managing the User resource. Ideally, this code from the README would work directly to turn the response into an instance of the User resource class:

AuthProvider.parse(function(response) {
  return new User(response.data);
});

The problem: since the parsing function must be defined in the config stage, the User factory hasn't been created yet and can't be injected.

Here's a sketch of my sort-of workaround, but I figure there should be a more elegant solution:

# Coffeescript

app.factory('MyAuth', ['Auth', 'User', (Auth, User) ->
  Auth['parseUserToResource'] = (userObj) ->
    userResource = new User(userObj)
  Auth['currentUserResource'] = () ->
    @currentUser().then(
      (userObj) ->
        Auth.parseUserToResource(userObj)
    )
  return Auth
])

app.controller('SomeCtrl', ['$scope', 'MyAuth', ($scope, MyAuth) ->
    MyAuth.currentUserResource().then(
      (user) ->
        $scope.currentUser = user
    )
    # or maybe...
    $scope.login = () ->
      MyAuth.login().then(
        (userObj) ->
          $scope.currentUser = MyAuth.parseUserToResource(userObj)
      )
])

Auth.isAuthenticated() lost after refresh

Scenario:

 Do login
Auth.isAuthenticated() is true
Refresh page
Auth.isAuthenticated() is false

Why isAuthenticated method isnt handshake or 'ping' to check if user_signed_in?
Scenario2:

Do login
Request data from server
Get Error 401

It seems devise took a time to set cookie in browser to allow make data request. How I know user still logged in even after refresh or just after login??

API for Forgot Password?

How would we use angular-devise to trigger a forgot password request or change password and edit a profile?

how to get the current user variable?

Hi,
I need help on this.
I have a controller with this code

@app
  .run ->
    console.debug 'angular still running!!'
  .controller 'authCtr', (Auth, $scope)->    
    $scope.user = null
    Auth.currentUser()
      .then (user)->
        $scope.user = user
        console.debug user

in my view I try to access the user variable but I get undefined. What am I doing wrong?
I'm new with angular so my question my sound stupid, don't be too hard on me :)

Error handling for currentUser() not working

The error handling in the following code doesn't work when a 401 is encountered.

angular.module('myModule', ['Devise']).
    run(function(Auth) {
        Auth.currentUser().then(function(user) {
            // User was logged in, or Devise returned
            // previously authenticated session.
            console.log(user); // => {id: 1, ect: '...'}
        }, function(error) {
            console.log('unauthenticated') //never reached
        });
    });

Hard refresh after login

The login request is well sent, CSRF-TOKEN is written in cookies. After login, Auth.isAuthenticated() returns true. After hard refresh, it returns false. HTTP_X_CSRF_TOKEN is however sent in headers.

Angular_Devise and Grape Rails API

I've been trying to set up Angular_Devise with a rails grape api for controlling user login for an Ionic Application.

The Api has a delete method in which the users session is ended by destroying the authentication token. I had great trouble configuring the logout method of Angular_Devise to work with my api as I couldn't pass any credentials, thus didn't have the authentication token of a user to identify them with.

After a prolonged period attempting to create a solution this is what I have come up with:

In my controller:

$scope.doLogout = function(){
    var credentials = {
      authentication_token: Auth._currentUser.authentication_token
    };

    Auth.logout(credentials).then(function(user) {
      console.log(user);
    });
  };
}])

In my app.js

.config(function($httpProvider) {
  //$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  $httpProvider.defaults.headers.delete = { 'Content-Type' : 'application/json' };
})


.config(['AuthProvider', 'AuthInterceptProvider', function(AuthProvider, AuthInterceptProvider) {
    // Customize login
    var URL = "http://localhost:3000/api"
    AuthProvider.loginMethod('POST');
    AuthProvider.loginPath(URL + '/sessions');

    // Customize logout
    AuthProvider.logoutMethod('DELETE');
    AuthProvider.logoutPath(URL + '/sessions');

    // Customize register
    AuthProvider.registerMethod('POST');
    AuthProvider.registerPath(URL + '/users');

    // Customize the resource name data use namespaced under
    // Pass false to disable the namespace altogether.
    AuthProvider.resourceName(false);

    // Customize user parsing
    // NOTE: **MUST** return a truth-y expression
    AuthProvider.parse(function(response) {
        return response.data;
    });

    // Intercept 401 Unauthorized everywhere
    // Enables `devise:unauthorized` interceptor
    AuthInterceptProvider.interceptAuth(true);
}])

Then I changed the default logout in devise.js

logout: function(creds) {
                var returnOldUser = constant(service._currentUser);

                creds = creds || {};
                return $http(httpConfig('logout', creds))
                    .then(reset)
                    .then(returnOldUser)
                    .then(broadcast('logout'));

            },

It took me a very long time to figure out and I'm not sure it's the correct solution.
Is this how I go about passing the authentication token when logging out?

Auth.register() gives an "ActionController::UnknownFormat" error

When I try to use Auth.register(), I get this error in Rails: ActionController::UnknownFormat (ActionController::UnknownFormat).

This usually happens in Rails when an action isn't recognized. It seems likely that the Devise controller does not support the .json method. When I edit the default paths in devise.js to not JSON, the method works successfully, but returns an HTML page response instead of JSON (not surprising since I dropped the .json in the URL).

Was there extra configuration needed for Devise to support .json? Or is everyone doing something after including angular-devise in their JS that isn't in the angular-devise docs?

My controller:

myApp.controller('register', ['$scope', '$http', '$log', '$routeParams', 'Auth', function($scope, $http, $log, $routeParams, Auth){

  $scope.createAccount = function(){
    console.log('creating account');

    var credentials = {
      email: $scope.user.email,
      password: $scope.user.password
    };

    Auth.register(credentials).then(function(registeredUser){
      console.log('Registration succeeded');
      console.log(registeredUser);
    }, function(error){
      console.log('Registration failed');
      console.log(error);
    });
  }
}]);

My routes (no changes after installing Devise):

Rails.application.routes.draw do
  devise_for :users
  resources :users
  ...
end

The error:

Started POST "/users.json" for 127.0.0.1 at 2015-01-26 14:45:28 -0800
Processing by Devise::RegistrationsController#create as JSON
  Parameters: {"user"=>{"email"=>"boop.com", "password"=>"[FILTERED]"}, "registration"=>{"user"=>{"email"=>"boop.com", "password"=>"[FILTERED]"}}}
   (0.1ms)  BEGIN
  User Exists (0.4ms)  SELECT  1 AS one FROM "users"  WHERE "users"."email" = 'boop.com' LIMIT 1
   (0.1ms)  ROLLBACK
Completed 406 Not Acceptable in 79ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  actionpack (4.1.4) lib/action_controller/metal/mime_responds.rb:440:in `retrieve_collector_from_mimes'
  actionpack (4.1.4) lib/action_controller/metal/mime_responds.rb:396:in `respond_with'
  devise (3.4.1) app/controllers/devise/registrations_controller.rb:37:in `create'
  actionpack (4.1.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.4) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.4) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.4) lib/active_support/callbacks.rb:149:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.4) lib/active_support/callbacks.rb:86:in `call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.4) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.4) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.4) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.1.4) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.1.4) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.1.4) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.1.4) lib/abstract_controller/base.rb:136:in `process'
  actionview (4.1.4) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.1.4) lib/action_controller/metal.rb:196:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.1.4) lib/action_controller/metal.rb:232:in `block in action'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:82:in `call'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:50:in `call'
  actionpack (4.1.4) lib/action_dispatch/routing/mapper.rb:45:in `call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:59:in `each'
  actionpack (4.1.4) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.1.4) lib/action_dispatch/routing/route_set.rb:678:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `catch'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/flash.rb:254:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.1.4) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.1.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
  activerecord (4.1.4) lib/active_record/migration.rb:380:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.1.4) lib/active_support/callbacks.rb:82:in `run_callbacks'
  actionpack (4.1.4) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.4) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.4) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.4) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.1.4) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.4) lib/rails/engine.rb:514:in `call'
  railties (4.1.4) lib/rails/application.rb:144:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/donaldpinkus/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
  /Users/donaldpinkus/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
  /Users/donaldpinkus/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'


  Rendered /Users/donaldpinkus/.rvm/gems/ruby-2.1.5/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)
  Rendered /Users/donaldpinkus/.rvm/gems/ruby-2.1.5/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (0.8ms)
  Rendered /Users/donaldpinkus/.rvm/gems/ruby-2.1.5/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.7ms)
  Rendered /Users/donaldpinkus/.rvm/gems/ruby-2.1.5/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (11.3ms)

Handling flash messages

I have to admit I'm new to Angular but I'm an old hand at rails. How do you handle flash messages sent back by devise?

Thanks

angular_devise + rails-api is vulnerable to CSRF attacks

Because rails-api strips out rails' CSRF protection - protect_from_forgery - assuming that everyone using rails-api will use token authentication, and because angular_devise relies on cookie authentication, using rails-api with angular_devise means that you are vulnerable to CSRF. At the very least, it might be good to have a one-line comment in the angular_devise Readme section on CSRF making a clear warning to people, because rails-api is becoming very common, and has been merged into Rails.

Please correct me if I'm wrong here, but I think this is a possible vulnerability worth highlighting.

Using AngularDevise with SpreeAuthDevise

Currently, I am trying to get my custom spree application to work with AngularDevise.

In my ApplicationController:

class ApplicationController < ActionController::Base
  respond_to :html, :json

  protect_from_forgery with: :exception
end

Module setup via:

var DeviseModule = angular.module('DeviseModule', ["Devise"]);

$(document).on("ready page:load", function() {
  return angular.bootstrap("#devise", ["DeviseModule"]);
});

Configuration as so:

DeviseModule.config (AuthProvider, AuthInterceptProvider) ->
  # Customize login
  AuthProvider.loginMethod "POST"
  AuthProvider.loginPath "/user/spree_user/sign_in.json"

  # Customize logout
  AuthProvider.logoutMethod "GET"
  AuthProvider.logoutPath "/user/spree_user/logout.json"

  # Customize register
  AuthProvider.registerMethod "PATCH"
  AuthProvider.registerPath "/user/spree_user.json"

  # Intercept 401 Unauthorized everywhere
  # Enables `devise:unauthorized` interceptor
  AuthInterceptProvider.interceptAuth true
  return

Rails routes:

                        Prefix Verb   URI Pattern                              Controller#Action
                          root GET    /                                        spree/home#index
        new_spree_user_session GET    /user/spree_user/sign_in(.:format)       spree/user_sessions#new
            spree_user_session POST   /user/spree_user/sign_in(.:format)       spree/user_sessions#create
    destroy_spree_user_session GET    /user/spree_user/logout(.:format)        spree/user_sessions#destroy
           spree_user_password POST   /user/spree_user/password(.:format)      spree/user_passwords#create
       new_spree_user_password GET    /user/spree_user/password/new(.:format)  spree/user_passwords#new
      edit_spree_user_password GET    /user/spree_user/password/edit(.:format) spree/user_passwords#edit
                               PATCH  /user/spree_user/password(.:format)      spree/user_passwords#update
                               PUT    /user/spree_user/password(.:format)      spree/user_passwords#update
cancel_spree_user_registration GET    /user/spree_user/cancel(.:format)        spree/user_registrations#cancel
       spree_user_registration POST   /user/spree_user(.:format)               spree/user_registrations#create
   new_spree_user_registration GET    /user/spree_user/sign_up(.:format)       spree/user_registrations#new
  edit_spree_user_registration GET    /user/spree_user/edit(.:format)          spree/user_registrations#edit
                               PATCH  /user/spree_user(.:format)               spree/user_registrations#update
                               PUT    /user/spree_user(.:format)               spree/user_registrations#update
                               DELETE /user/spree_user(.:format)               spree/user_registrations#destroy

And the Login Controller currently looks like this:

DeviseModule.controller "LoginController", ["$scope", "Auth", ($scope, Auth) ->
  credentials = {
    email: '[email protected]',
    password: 'spree123'
  }

  Auth.login(credentials).then ((user) ->
    console.log(user); # => {id: 1, ect: '...'}
  ), (error) ->
    # Authentication failed...
]

And the html its working with:

#devise
  %section{"ng-controller" => "LoginController"}

The issue that I'm seeing is the response from Devise:

17:49:50 web.1    | Started POST "/user/spree_user/sign_in.json" for 127.0.0.1 at 2015-01-06 17:49:50 -0500
17:49:50 web.1    | Processing by Spree::UserSessionsController#create as JSON
17:49:50 web.1    |   Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}, "user_session"=>{"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}}
17:49:50 web.1    | Completed 406 Not Acceptable in 12ms
17:49:50 web.1    |
17:49:50 web.1    | ActionController::UnknownFormat - ActionController::UnknownFormat:
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/mime_responds.rb:440:in `retrieve_collector_from_mimes'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/mime_responds.rb:256:in `respond_to'
17:49:50 web.1    |    () Users/benmorgan/.rvm/gems/ruby-2.2.0/bundler/gems/spree_auth_devise-4342275c04f0/lib/controllers/frontend/spree/user_sessions_controller.rb:32:in `create'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/abstract_controller/base.rb:189:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/rendering.rb:10:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:113:in `call'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:229:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:229:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:229:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:166:in `block in halting'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:86:in `run_callbacks'
17:49:50 web.1    |   actionpack (4.1.9) lib/abstract_controller/callbacks.rb:19:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/rescue.rb:29:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/notifications.rb:159:in `block in instrument'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/notifications.rb:159:in `instrument'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
17:49:50 web.1    |   activerecord (4.1.9) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
17:49:50 web.1    |   actionpack (4.1.9) lib/abstract_controller/base.rb:136:in `process'
17:49:50 web.1    |   actionview (4.1.9) lib/action_view/rendering.rb:30:in `process'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal.rb:196:in `dispatch'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_controller/metal.rb:232:in `block in action'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/routing/route_set.rb:82:in `dispatch'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/routing/route_set.rb:50:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/routing/mapper.rb:45:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/journey/router.rb:73:in `block in call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/journey/router.rb:59:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/routing/route_set.rb:685:in `call'
17:49:50 web.1    |   bullet (4.13.2) lib/bullet/rack.rb:12:in `call'
17:49:50 web.1    |   meta_request (0.3.4) lib/meta_request/middlewares/app_request_handler.rb:13:in `call'
17:49:50 web.1    |   meta_request (0.3.4) lib/meta_request/middlewares/meta_request_handler.rb:13:in `call'
17:49:50 web.1    |   warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
17:49:50 web.1    |   warden (1.2.3) lib/warden/manager.rb:34:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/etag.rb:23:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/head.rb:11:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/flash.rb:254:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
17:49:50 web.1    |   rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/cookies.rb:562:in `call'
17:49:50 web.1    |   activerecord (4.1.9) lib/active_record/query_cache.rb:36:in `call'
17:49:50 web.1    |   activerecord (4.1.9) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
17:49:50 web.1    |   activerecord (4.1.9) lib/active_record/migration.rb:380:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/callbacks.rb:82:in `run_callbacks'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/reloader.rb:73:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
17:49:50 web.1    |   better_errors (2.0.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
17:49:50 web.1    |   better_errors (2.0.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
17:49:50 web.1    |   better_errors (2.0.0) lib/better_errors/middleware.rb:57:in `call'
17:49:50 web.1    |   rack-contrib (1.1.0) lib/rack/contrib/response_headers.rb:17:in `call'
17:49:50 web.1    |   meta_request (0.3.4) lib/meta_request/middlewares/headers.rb:16:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
17:49:50 web.1    |   railties (4.1.9) lib/rails/rack/logger.rb:38:in `call_app'
17:49:50 web.1    |   railties (4.1.9) lib/rails/rack/logger.rb:20:in `block in call'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/tagged_logging.rb:68:in `block in tagged'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/tagged_logging.rb:26:in `tagged'
17:49:50 web.1    |   activesupport (4.1.9) lib/active_support/tagged_logging.rb:68:in `tagged'
17:49:50 web.1    |   railties (4.1.9) lib/rails/rack/logger.rb:20:in `call'
17:49:50 web.1    |   request_store (1.1.0) lib/request_store/middleware.rb:8:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/request_id.rb:21:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/runtime.rb:17:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/lock.rb:17:in `call'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:136:in `forward'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:143:in `pass'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:155:in `invalidate'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:71:in `call!'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:51:in `call'
17:49:50 web.1    |   actionpack (4.1.9) lib/action_dispatch/middleware/static.rb:84:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
17:49:50 web.1    |   railties (4.1.9) lib/rails/engine.rb:514:in `call'
17:49:50 web.1    |   railties (4.1.9) lib/rails/application.rb:144:in `call'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:136:in `forward'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:143:in `pass'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:155:in `invalidate'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:71:in `call!'
17:49:50 web.1    |   rack-cache (1.2) lib/rack/cache/context.rb:51:in `call'
17:49:50 web.1    |   rack (1.5.2) lib/rack/content_length.rb:14:in `call'
17:49:50 web.1    |   puma (2.9.1) lib/puma/server.rb:490:in `handle_request'
17:49:50 web.1    |   puma (2.9.1) lib/puma/server.rb:361:in `process_client'
17:49:50 web.1    |   puma (2.9.1) lib/puma/server.rb:254:in `block in run'
17:49:50 web.1    |   puma (2.9.1) lib/puma/thread_pool.rb:92:in `block in spawn_thread'
17:49:50 web.1    |   logging (1.8.2) lib/logging/diagnostic_context.rb:323:in `block in create_with_logging_context'

So, I decided to make Spree::UserSessionsController respond to JSON:

Spree::UserSessionsController.class_eval do
  respond_to :html, :json
end

Still no luck. The create method can be seen here. It does seem to be able to respond to JSON.

Auth.currentUser()

I'm paraphrasing from a few stackoverflow posts as it's unanswered and I have the same question:

http://stackoverflow.com/questions/27302932/getting-previous-session-using-angular-devise

I am using the cloudspace angularjs-devise library on the client. When I try to login/register I get a 200 ok response with the plain user object visible in the chrome js console. Refreshing the page seems to lose this information even though I assumed that the service would store this at some point since it also has logout and currentUser methods.

How do you recommend the rails api be setup to authenticate a post, with an empty user object, to the path defined at AuthProvider.loginPath

Is there a prefered method that uses a cookie, or simply passes in the rails current_user object?

Please advise.

Regression: Intercepting 401 on all $http requests not possible anymore

Before the recent ignoreAuth -> interceptAuth switch it possible to intercept all $http requests and react on 401.

Now interceptAuth defaults to false and has to be set. But setting it only applies to requests made within angular_devise (login, etc.) and does not apply to regular $http requests.

I can set interceptAuth on individual $http requests as the README advises. But there is no way to set interceptAuth on all requests to restore the previous functionality.

Devise version?

Hi, does this work with the latest version of Devise after adding the respond to json to the application controller, or does it require the deprecated branch with token auth?

According to issue #7 it uses cookies, so I am guessing that it is using cookies on the latest version not token?

angular devise registration issue

i am building an application using Rails with angular JS. am using angular devise for authentication. i implemented login functionality. The problem is as a admin , i can able to create users . So when i am trying to do, the current user logged in ( admin ) is changing to newly creating user.

var app = angular.module('myapp', ['ui.router', 'templates', 'Devise']);
app.controller('UsersCtrl', UsersCtrl);

function UsersCtrl($scope, $http,Auth) {
//handle when user submit button is clicked
$scope.register = function() {
Auth.register($scope.employee).then(function(employee) {
console.log("inside register");
$state.go('users');
}, function(error) {
console.log('registration failed due to following errors:- ')
console.log(error)
});
}
}

login error handling

First, thanks a lot for your great work!

In the readme your define

Auth.login(credentials).then(function(user) {
            console.log(user); // => {id: 1, ect: '...'}
        }, function(error) {
            // Authentication failed...
        });

However, if I provide invalid email or password, the error function is not executed but the devise:unauthorized event is thrown.

401 {"error":"You need to sign in or sign up before continuing."}

Am I doing something wrong? Usually you would like to provide user feedback "invalid email or password" etc. to the user here. Now I implemented some workaround with the event, looks quite hacky.

How to share currentUser for all controller ?

I have many controller AboutCtrl, MainCtrl, UserCtrl.
I have written login code in UserCtrl , the Auth.isAuthenticated() only available in UserCtrl, but AboutCtrl and MainCtrl
How to share Auth.isAuthenticated() for all controllers ? or write a helper like devise helper user_sign_in?

Add note re: setting $httpProvider.defaults.withCredentials = true

When I attempted using this to fully separate my Angular app and Rails API, I spent ages trying to figure out why angular would authenticate, then immediately make an unauthorized request, eventually I figured out the cookies weren't being set on the request and then finally figured out I had to set

.config([
    '$httpProvider',
    function($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
    }
])

in my app config.

This might be obvious or it might mean I'm doing something wrong, in which case my apologies (and in the case of the latter - help would be appreciated). Otherwise hopefully this saves someone some headache and it might be worth mentioning in the README (I didn't want to do a presumptive PR...).

How to handle devise:unauthorized in a global way

Hi,
I'm new to angular, so I hope my question is relevant.
I try to handle devise:unauthorized following this article : https://github.com/cloudspace/angular_devise#interceptor
I have a lot of controller. And if want to handle devise:unauthorized the same way for every controller.
Is there any way to handle it globally instead of duplicate the code everywhere?

I was thinking about something like this :

angular.module('myModule', ['Devise']).
    config(function(AuthProvider) {
        // Customize login
        AuthProvider.loginMethod('GET');
        AuthProvider.loginPath('/admins/login.json');

        //Handle unauthorized
        AuthProvider.onUnauthorized=function(event, xhr, deferred) {
            //....
        }
    });

Auth.isAuthenticated() โ€” service._currentUser is null

Hey guys,

So we are using angular_devise with our application and are trying to utilize the service.isAuthenticated function in devise.js beginning on line 183. The problem is that service._currentUser is null.

In an attempt to debug this on our end, I found that save which is supposed to be called on login line 158 in the then. The problem is that save expects the user argument. If I add save(user) in next .then block, isAuthenticated works.

E.g. Doesn't work:

return $http(httpConfig('login', creds)).then(service.parse).then(save).then(function (user) {
    if (withCredentials && !loggedIn) {
        return broadcast('new-session')(user);
    }
    return user;
    }).then(broadcast('login'));
},

Works:

return $http(httpConfig('login', creds)).then(service.parse).then(save).then(function (user) {
    save(user);
    if (withCredentials && !loggedIn) {
        return broadcast('new-session')(user);
    }
    return user;
    }).then(broadcast('login'));
},

Is there something we are doing wrong or is this an issue with angular_devise?

Cannot read property 'interceptAuth' of undefined

Hi there, I have been getting this error lately:

TypeError: Cannot read property 'interceptAuth' of undefined
    at devise.provider.$get.responseError (devise.js?body=1:22)
    at processQueue (angular.js?body=1:13190)
    at angular.js?body=1:13206
    at Scope.$get.Scope.$eval (angular.js?body=1:14402)
    at Scope.$get.Scope.$digest (angular.js?body=1:14218)
    at Scope.$get.Scope.$apply (angular.js?body=1:14507)
    at done (angular.js?body=1:9660)
    at completeRequest (angular.js?body=1:9850)
    at XMLHttpRequest.requestLoaded (angular.js?body=1:9791)

[Feature Request] Update user functionality

Hi guys,

It would be nice if the framework would support the update User functionality. This is the only thing I am missing in this great library. Or am I wrong?

Cheers,
Karens

Auth.login is using OPTIONS Method

Hi,

i followed the instructions on https://github.com/cloudspace/angular_devise#authlogincreds-config

But on my rails server I get:

Started OPTIONS "/clients/sign_in.json" for 127.0.0.1 at 2015-09-02 14:45:58 +0200
ActionController::RoutingError (No route matches [OPTIONS] "/clients/sign_in.json")

In my Rails routes.rb I got

devise_for :clients, controllers: { sessions: "clients/sessions" }

My Rails SessionsController:

class Clients::SessionsController < Devise::SessionsController
  after_filter :cors_set_access_control_headers
# before_filter :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  def new
     super
  end

  # POST /resource/sign_in
  def create
     super
  end

  # DELETE /resource/sign_out
  # def destroy
  #   super
  # end

  # protected

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.for(:sign_in) << :attribute
  # end

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = request.headers["HTTP_ORIGIN"]
    headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token'
    headers['Access-Control-Max-Age'] = "1728000"
  end
end

The AuthProvider Config:

  .config(function(AuthProvider){
    AuthProvider.resourceName('client');
    AuthProvider.loginMethod('GET');
    AuthProvider.loginPath('http://localhost:3000/clients/sign_in.json');
  });

And my login function:

  $scope.loginUser = function () {
    var credentials = {
      email: '[email protected]',
      password: 'password'
    };
    var config = {
      headers: {
        'X-HTTP-Method-Override': 'POST'
      }
    };
    Auth.login(credentials, config).then(function(user) {
      console.log(user); // => {id: 1, ect: '...'}
    }, function(error) {
      // Authentication failed...
    });

  };

What am I missing?

Can anyone push me in the right direction please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.