public

API JSON authentication with Devise

  • Download Gist
registrations_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Api::RegistrationsController < Api::BaseController
respond_to :json
def create
 
user = User.new(params[:user])
if user.save
render :json=> user.as_json(:auth_token=>user.authentication_token, :email=>user.email), :status=>201
return
else
warden.custom_failure!
render :json=> user.errors, :status=>422
end
end
end
sessions_controller.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
class Api::SessionsController < Api::BaseController
before_filter :authenticate_user!, :except => [:create, :destroy]
before_filter :ensure_params_exist
respond_to :json
 
def create
resource = User.find_for_database_authentication(:email => params[:user_login][:email])
return invalid_login_attempt unless resource
 
if resource.valid_password?(params[:user_login][:password])
sign_in(:user, resource)
resource.ensure_authentication_token!
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :email=>resource.email}
return
end
invalid_login_attempt
end
 
def destroy
resource = User.find_for_database_authentication(:email => params[:user_login][:email])
resource.authentication_token = nil
resource.save
render :json=> {:success=>true}
end
 
protected
def ensure_params_exist
return unless params[:user_login].blank?
render :json=>{:success=>false, :message=>"missing user_login parameter"}, :status=>422
end
 
def invalid_login_attempt
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.