How to login to Rails 4 API via ajax using Angular
I am trying to login using Angular user instead of normal login (which atm works). Here's my method authenticate
:
def authenticate
authenticate_or_request_with_http_token do |token, options|
User.find_by(:auth_token => token)
end
end
Here's my controller:
if user && user.authenticate(params[:session][:password])
sign_in user
user.update_attribute(:last_login, DateTime.now)
if user.admin?
redirect_to admin_path
else
redirect_to user
end
else
redirect_to signin_path, notice: "Invalid email/password combination"
end
This works great using Rails based login (no Angular or Ajax).
Now when I try to implement Angular login (basic at the moment):
$http.post('/api/signin', $scope.user).success(function (data) {
console.log(data);
});
I am getting an error Invalid email/password combination
. I am assuming with a token CSRF
that is not passed through Angular $http
, but I am using protect_from_forgery with: :null_session
in a session controller.
Another point I haven't added csrf_meta_tags
to my Angular html. I need? And how would I do this if the html is not rails served?
What am I missing here?
source to share
It would be better if you return the json from rails saying that if the user is authenticated then check this with angular
# rails controller
if user && user.authenticate(params[:session][:password])
sign_in user
user.update_attribute(:last_login, DateTime.now)
render json: user
else
render json: { error: "Invalid email/password combination" }
end
# angular
$http.post('/api/signin', $scope.user).success(function (data) {
if (data.error) {
// invalid login
} else {
// logged in
}
});
something like that. Either redirect_to
works because you are not displaying anything html from rails.
source to share