Skip to content

Instantly share code, notes, and snippets.

@Disha-Shah
Forked from solutelabs-savan/devise.rb
Created May 10, 2016 11:39
Show Gist options
  • Save Disha-Shah/88de541ec17bc921aab821d1e07ff6ac to your computer and use it in GitHub Desktop.
Save Disha-Shah/88de541ec17bc921aab821d1e07ff6ac to your computer and use it in GitHub Desktop.
Create Sign In / Sign Out API using Devise
# Find this line config.navigational_formats = ['*/*', :html] in devise.rb file and replace it with this line inorder to accept JSON request and give JSON response.
config.navigational_formats = ["*/*", :html, :json]
# Define devise routes under version of the api
namespace :v1 do
devise_for :users, :controllers => { sessions: 'api/v1/sessions' }
end
# Override create method inorder to use json request and response.
# Accepts params user like email and password.
# After verifying authentication successfully we need to generate one AUTH TOKEN for that user and pass it in response.
class Api::V1::SessionsController < Devise::SessionsController
before_action :authenticate_user!, except: [:create]
respond_to :json
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])
render json: { success: true, auth_token: resource.authentication_token, email: resource.email }, status: :created
return
end
invalid_login_attempt
end
def destroy
current_user.reset_authentication_token
render json: { success: true }, status: :ok
end
protected
def invalid_login_attempt
render json: { success: false, message: "Error with your login or password"}, status: :unauthorized
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment