Created
October 11, 2012 16:46
-
-
Save diminish7/3873783 to your computer and use it in GitHub Desktop.
Devise Token Auth for API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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