Skip to content

Instantly share code, notes, and snippets.

@diminish7
Created October 11, 2012 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diminish7/3873783 to your computer and use it in GitHub Desktop.
Save diminish7/3873783 to your computer and use it in GitHub Desktop.
Devise Token Auth for API
class AuthenticationTokensController < BaseApiController
skip_before_filter :authenticate_user!, only: :create
def create
resource = User.find_for_database_authentication(login: params[:login])
if resource && resource.valid_password?(params[:password])
resource.reset_authentication_token
resource.save(validate: false)
render :json => successful_json_with_user_information(resource)
else
warden.custom_failure!
render :json => { success: false, message: "Invalid login or password" }, status: 401
end
end
def destroy
# Clear out the auth token so they have to re-login
current_user.clear_authentication_token!
# In case we have any session saved, clear it out
sign_out(current_user)
render :json => { success: true }
end
end
class User < ActiveRecord::Base
devise :database_authenticatable, :token_authenticatable, :registerable, :recoverable, :validatable
attr_accessible :email, :login, :password, :password_confirmation
validates_presence_of :login
validates_uniqueness_of :login
before_save :reset_authentication_token, if: :encrypted_password_changed?
def clear_authentication_token!
update_attribute(:authentication_token, nil)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment