Created
February 7, 2018 09:44
-
-
Save eidge/53ecaeb7374dba3cf20c53262e07058f 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
require 'jwt' | |
module TrackerFlow | |
module Web | |
module Auth | |
class Token | |
class InvalidToken < StandardError; end | |
PRIVATE_KEY = ENV['JWT_PRIVATE_KEY'] || fail('no private key found') | |
KEY = OpenSSL::PKey::RSA.new(PRIVATE_KEY) | |
def self.parse(token) | |
payload, _header = JWT.decode(token, KEY.public_key, true, { :algorithm => 'RS256' }) | |
new(user_id: payload['sub']) | |
rescue JWT::DecodeError => e | |
fail InvalidToken, e | |
end | |
def initialize(user: nil, user_id: nil) | |
fail ArgumentError, 'either user or user_id is required' if user.nil? && user_id.nil? | |
@user_id = user&.id || user_id | |
end | |
def user_id | |
@user_id.to_i | |
end | |
def generate | |
subject = @user_id | |
payload = { sub: subject } | |
JWT.encode(payload, KEY, 'RS256') | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment