Created
May 16, 2013 11:37
-
-
Save serek/5591131 to your computer and use it in GitHub Desktop.
Sample sessions controller for Devise APIs based on tokens.
This file contains hidden or 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 Api::V1::SessionsController < Api::V1::BaseController | |
skip_before_filter :verify_authenticity_token, only: :create | |
skip_before_filter :authenticate_user!, only: :create | |
before_filter :ensure_params_exist, only: :create | |
before_filter :ensure_token_exist, only: :destroy | |
def create | |
resource = User.find_for_database_authentication(email: params[:user][:email]) | |
return invalid_login_attempt unless resource | |
if resource.valid_password?(params[:user][:password]) | |
sign_in(:user, resource) | |
resource.ensure_authentication_token! | |
render json: { token: resource.authentication_token }, status: :ok | |
return | |
end | |
invalid_login_attempt | |
end | |
def destroy | |
resource = User.find_by_authentication_token(params[:token]||request.headers["X-AUTH-TOKEN"]) | |
if resource | |
resource.authentication_token = nil | |
resource.save | |
sign_out(:user) | |
render json: {}.to_json, :status => :ok | |
return | |
end | |
invalid_logout_attempt | |
end | |
protected | |
def ensure_params_exist | |
return unless params[:user].blank? | |
render json: { error: t('api.v1.parameters.missing') }, status: 422 | |
end | |
def ensure_token_exist | |
return unless params[:token].blank? | |
render json: { error: t('api.v1.parameters.missing') }, status: 422 | |
end | |
def invalid_login_attempt | |
render json: { error: t('api.v1.parameters.error') }, status: 401 | |
end | |
def invalid_logout_attempt | |
render json: { error: t('api.v1.parameters.error') }, status: 401 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment