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