Skip to content

Instantly share code, notes, and snippets.

@eidge
Created February 7, 2018 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eidge/53ecaeb7374dba3cf20c53262e07058f to your computer and use it in GitHub Desktop.
Save eidge/53ecaeb7374dba3cf20c53262e07058f to your computer and use it in GitHub Desktop.
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