Last active
September 5, 2019 11:20
-
-
Save solutelabs-savan/6f32a9b7792e6f7ad158f38a62a2bdb4 to your computer and use it in GitHub Desktop.
Create Sign In / Sign Out API using Devise
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
# 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] |
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
# Define devise routes under version of the api | |
namespace :v1 do | |
devise_for :users, :controllers => { sessions: 'api/v1/sessions' } | |
end |
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
# 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