Authentication with emberjs and devise


#1

I am using ember js to authenticate with my rails api my devise sessions controller

module Api
class SessionsController < Devise::SessionsController

  def create
   unless params[:email] && params[:password]
  return invalid_params('You need to provide both email and password')
  end

  res = User.find_for_database_authentication(email: params[:email])

 if res && res.valid_password?(params[:password])
    user = res
  end
 unless user
   unless params[:email] && params[:password]
  return invalid_params('invalid email or password')
  else
   return invalid_params('You need to provide both email and password')
  end 
else
 sign_in user
  user.ensure_authentication_token!
 render json: user ,serializer: UserSerializer ,status: 201
   end
end

protected

 def invalid_params(errorMessage)
 warden.custom_failure!
 render json: { errorMessage: errorMessage }, status: 403
end
end
end

my emberjs auth.js

Auth =Ember.Object.extend({
auth_token: null,
current_user: null,
signIn: function(params) {

 return Ember.$.post('http://localhost:3001/api/users/sign_in',   params).then((function(_this) {
  return function(response) {
    return _this.set('auth_token', response.auth_token);
     
  };
})(this));


   },
   signUp: function(params) {
	var mypar = {'user':params};
	var that=this;
	    return Ember.$.post('/users', mypar,function(data){
   return that.set('auth_token', data.auth_token);
  });
 },
 signOut: function(){
  promise= Ember.$.ajax("/users/sign_out",{
	type: "DELETE"
});
var that =this;
promise.then(function(){
	that.set("auth_token",null);
});
return promise;
  }

  });

   Remon.Auth =Auth.create();
 $.ajaxSetup({

   beforeSend: function(xhr, options) {
    var encoded_auth_token, header;
   if (Remon.Auth.get('auth_token')) {
    encoded_auth_token = Base64.encode64(Remon.Auth.get('auth_token') + ":X");
    header = "Basic " + encoded_auth_token;
   return xhr.setRequestHeader('Authorization', header);
  }
 },
error: function(xhr) {
  if (xhr.status === 401) {
  //return window.location = '/#/login';
 
   }
 }
});

sign in and sign up working great also I got the user authentication token from sessions controler but sign in sessions not working as when I tried to get json data to another route its not working inpite in the other controller I have these method

   module Api
 class ProfilesController < ApplicationController


 before_filter :auth_only?
def index
@profiles =Profile.all
 end 
end 
end 

in devise.rb config.http_authenticatable = [:token]

and in application_controller.rb

   skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }


 def allow_ajax_request_from_other_domains
 headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Request-Method'] = '*'
  end

#2

You could have a try with ember-simple-auth. It works well with devise.

BTW, if you use a devise (>3.1.0),you may need simple_token_authentication


#3

my devise version is 2.1.2 even I migrated to lateste version of devise the problem is still the same I returned back to 2.1.2 …the problem is I can’t authenticate even Sessions create and destroy working fine but no authorization sent to the api to ckeck the current user


#4

This might be worth looking at.


#5

Take a look at the following links:

https://github.com/emberjs-cn/ember-menglifang/blob/develop/src/app/lib/devise-authenticator.coffee

https://github.com/emberjs-cn/ember-menglifang/blob/develop/src/app/lib/devise-authorizer.coffee


#6

it’s working for rails4 only no rails 3 branch


#7

the main problem is that there is no current user authenticated with devise


#8

Thanks @embermaps! I’m the author of the above plugin. In developing it we noticed that Rails will generate a new CSRF token any time you sign in/sign out. If you don’t send this new token it can result in issues. We solved this by always sending back the CSRF token in response headers & using a jQuery ajax response handler to update it in the DOM.

Here’s our SessionsController:

And here’s the response handler:

https://github.com/d-i/ember-devise-simple-auth/blob/master/config/initializers/csrf.js

Note that these are handled for you out of the box with the plugin. Hope this helps!


#10

I removed protect_from_forgery from my application controller I tried your gem but it says I must install rails 4 my main problem is that current user is not authenticated inspite sessions create action is ok and it send current user response I posted the full code of my api application on stackoverflow would you mind check it I am searching for an answer for more than a week now http://stackoverflow.com/questions/22109004/devise-authentication-with-emberjs


#11

I ended up by sending my all ajax requests with auth_token in it ,and its working now


#12

@Remon_Amin Ember Simple Auth now supports authentication with oauth2, devise, Facebook and other custom authorizers. See kagemusha and my Ember App Kit+Ember Simple Auth API Client and our companion rails+devise+doorkeeper API server for a working example that use it. Kristian Mandrup and I are working on cancan-style authorization for Ember. More info on that when its ready.