Skip to content

Instantly share code, notes, and snippets.

@cmdr-rohit-bang
Created February 5, 2021 11:40
Show Gist options
  • Save cmdr-rohit-bang/f13744accc7787cd2f164f13cea8a7e8 to your computer and use it in GitHub Desktop.
Save cmdr-rohit-bang/f13744accc7787cd2f164f13cea8a7e8 to your computer and use it in GitHub Desktop.
API Only application controller
# Project API application controller module
class ApplicationController < ActionController::API
before_action :authorized
def encode_token(payload)
JWT.encode(payload, ENV['APP_SECRET_TOKEN'])
end
def auth_header
# { Authorization: 'Bearer <token>' }
request.headers['Authorization']
end
def decoded_token
if auth_header
token = auth_header.split(' ')[1]
# header: { 'Authorization': 'Bearer <token>' }
begin
JWT.decode(token, ENV['APP_SECRET_TOKEN'], true, algorithm: 'HS256')
rescue JWT::DecodeError
nil
end
end
end
def logged_in_user
if decoded_token
user_id = decoded_token[0]['user_id']
@user = User.find_by(id: user_id)
end
end
def logged_in?
!!logged_in_user
end
def authorized
render json: { message: 'Please log in' }, status: :unauthorized unless logged_in?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment