Last active
December 1, 2020 06:59
-
-
Save its-nedum/c83287243cfba317993e329380a5d9ff to your computer and use it in GitHub Desktop.
This file contains 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 < 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