Skip to content

Instantly share code, notes, and snippets.

@vishalzambre
Last active October 2, 2021 02:30
Show Gist options
  • Save vishalzambre/712f031f3206474af76c to your computer and use it in GitHub Desktop.
Save vishalzambre/712f031f3206474af76c to your computer and use it in GitHub Desktop.
Using devise gem sign_in & sign_out API's with sessions
#login
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user":{"email":"<email>","password":"<passwd>"}}' http://localhost:3000/api/v1/sign_in.json
#logout
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X DELETE http://localhost:3000/api/v1/sign_out.json?auth_token=<token>
# File config/initializers/devise.rb
# append at the end of devise.rb or add in any initializer file
require 'devise/strategies/token_authenticatable'
module Devise
module Strategies
class TokenAuthenticatable < Authenticatable
def params_auth_hash
return_params = if params[scope].kind_of?(Hash) && params[scope].has_key?(authentication_keys.first)
params[scope]
else
params
end
token = ActionController::HttpAuthentication::Token.token_and_options(request)
return_params.merge!(:auth_token => token[0]) if token
return_params
end
end
end
end
# File config/routes.rb
namespace :api do
namespace :v1 do
devise_scope :user do
post '/sign_in' => 'sessions#create'
delete '/sign_out' => 'sessions#destroy'
end
end
end
# File app/controllers/api/v1/sessions_controller.rb
class Api::V1::SessionsController < Devise::SessionsController
prepend_before_filter :require_no_authentication, :only => [:create ]
# /api/v1/sign_in.json
def create
resource = warden.authenticate!(auth_options)
sign_in(resource_name, resource)
render json: {:success => true, auth_token: current_user.authentication_token }.to_json, status: :200
end
# /api/v1/sign_out.json
def destroy
signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
render json: {:success => true, auth_token: nil }.to_json, status: :200
end
def failure
render :json => {:success => false, :errors => ["Login Failed"]}, status: 401
end
protected
def auth_options
{ :scope => resource_name, :recall => "#{controller_path}#failure" }
end
end
# File app/models/user.rb
class User < ActiveRecord::Base
before_save :ensure_authentication_token
devise :token_authenticatable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment