Created
March 16, 2017 20:18
-
-
Save indyarocks/fde42a25a58838e225b907f9d36cc80b to your computer and use it in GitHub Desktop.
API Main Controller with
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
module API | |
class MainController < ApplicationController | |
protect_from_forgery with: :null_session | |
before_action :authenticate | |
attr_accessor :current_user | |
def logged_in? | |
set_current_user | |
!!@current_user | |
end | |
def current_user | |
@current_user | |
end | |
def set_current_user | |
if has_valid_auth_type? | |
user = User.find_by(auth_token: auth_secret[:auth_token]) | |
if user | |
@current_user = user | |
end | |
end | |
end | |
def authenticate | |
unless logged_in? | |
render json: { | |
success: false, | |
error: 'Invalid credentials' | |
}, status: :unauthorized | |
end | |
end | |
private | |
def auth_header | |
request.headers['Authorization'].to_s.scan(/Bearer (.*)$/).flatten.last | |
end | |
def has_valid_auth_type? | |
!!request.headers['Authorization'].to_s.scan(/Bearer/).flatten.first | |
end | |
def auth_secret | |
Auth.decode(auth_header) || {} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment