Created
March 7, 2018 01:02
-
-
Save jasdeepsingh/1483cc80c20184e1cb198b7318e27656 to your computer and use it in GitHub Desktop.
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 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 |
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 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 |
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 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