Skip to content

Instantly share code, notes, and snippets.

@jasdeepsingh
Created March 7, 2018 01:02
Show Gist options
  • Save jasdeepsingh/1483cc80c20184e1cb198b7318e27656 to your computer and use it in GitHub Desktop.
Save jasdeepsingh/1483cc80c20184e1cb198b7318e27656 to your computer and use it in GitHub Desktop.
class ApplicationController
before_action :authenticate_user
def authenticate_user
response = TokenAuthService.call(token: request.headers['Api-Token'] || params[:api_token])
if response.failure?
render json: {
error: 'Not Authorized',
message: response.error
}, status: :unauthorized
elsif
@current_user = response.user
Current.user = @current_user
end
end
def current_user
@current_user
end
end
class TokenAuthService
include Interactor
before :verify_token_presence
# {
# token: user api token
# }
def call
if user = User.find_by(api_token: context.token)
context.user = user
else
context.fail!(error: 'Invalid API token!')
end
end
def verify_token_presence
if !context.token.present?
context.fail!(error: "Api Token must be present for this request.")
end
end
end
class User < ApplicationRecord
authenticates_with_sorcery!
def generate_api_token
self.api_token = SecureRandom.hex(24)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment