Skip to content

Instantly share code, notes, and snippets.

@its-nedum
Last active December 1, 2020 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save its-nedum/c83287243cfba317993e329380a5d9ff to your computer and use it in GitHub Desktop.
Save its-nedum/c83287243cfba317993e329380a5d9ff to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::API
def authorize_request
token = request.headers['Authorization']
if token
token = token.split(' ').last
begin
@decoded = decode_token(token)
@current_user = User.find_by_email(@decoded[:email])
rescue ActiveRecord::RecordNotFound => e
render json: { errors: e.message }, status: :unauthorized
rescue JWT::DecodeError => e
render json: { errors: e.message }, status: :unauthorized
end
else
render json: { error: 'No authorization token found' }, status: :unauthorized
end
end
private
# token decode secret
SECRET_KEY = Rails.application.secrets.secret_key_base. to_s
# token decoder method
def decode_token(token)
decoded = JWT.decode(token, SECRET_KEY)[0]
HashWithIndifferentAccess.new decoded
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment