Skip to content

Instantly share code, notes, and snippets.

@neymarsabin
Forked from jwo/registrations_controller.rb
Created September 8, 2017 05:50
Show Gist options
  • Save neymarsabin/61877cc9efa04571454c10eab98df170 to your computer and use it in GitHub Desktop.
Save neymarsabin/61877cc9efa04571454c10eab98df170 to your computer and use it in GitHub Desktop.
API JSON authentication with Devise
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
class Api::SessionsController < Api::BaseController
prepend_before_filter :require_no_authentication, :only => [:create ]
include Devise::Controllers::InternalHelpers
before_filter :ensure_params_exist
respond_to :json
def create
build_resource
resource = User.find_for_database_authentication(:login=>params[:user_login][:login])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user_login][:password])
sign_in("user", resource)
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :login=>resource.login, :email=>resource.email}
return
end
invalid_login_attempt
end
def destroy
sign_out(resource_name)
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
warden.custom_failure!
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment