Created
November 5, 2016 13:19
-
-
Save SophieDeBenedetto/33d0efd236d796002467e0b7ce042420 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
# application controller | |
class ApplicationController < ActionController::API | |
before_action :authenticate | |
def logged_in? | |
!!current_user | |
end | |
def current_user | |
if auth_present? | |
user = User.find(auth["user"]) | |
if user | |
@current_user ||= user | |
end | |
end | |
end | |
def authenticate | |
render json: {error: "unauthorized"}, status: 404 unless logged_in? | |
end | |
private | |
def token | |
request.env["HTTP_AUTHORIZATION"].scan(/Bearer(.*)$/).flatten.last.strip | |
end | |
def auth | |
Auth.decode(token) | |
end | |
def auth_present? | |
!!request.env.fetch("HTTP_AUTHORIZATION", "").scan(/Bearer/).flatten.first | |
end | |
end | |
# auth.rb | |
# rake secret and store as AUTH_SECRET in application.yml using Figaro | |
require 'jwt' | |
class Auth | |
ALGORITHM = 'HS256' | |
def self.issue(payload) | |
JWT.encode( | |
payload, | |
auth_secret, | |
ALGORITHM) | |
end | |
def self.decode(token) | |
JWT.decode(token, | |
auth_secret, | |
true, | |
{ algorithm: ALGORITHM }).first | |
end | |
def self.auth_secret | |
ENV["AUTH_SECRET"] | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment