Skip to content

Instantly share code, notes, and snippets.

@promisepreston
Last active September 8, 2019 05:20
Show Gist options
  • Save promisepreston/c4e4eabb25e00bcec448b36b50146b9b to your computer and use it in GitHub Desktop.
Save promisepreston/c4e4eabb25e00bcec448b36b50146b9b to your computer and use it in GitHub Desktop.
# lib/json_web_token.rb
class JsonWebToken
HMAC_SECRET = Rails.application.secrets.secret_key_base
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, HMAC_SECRET)
end
def self.decode(token)
body = JWT.decode(token, HMAC_SECRET)[0]
HashWithIndifferentAccess.new(body)
rescue JWT::DecodeError
raise 'Invalid token supplied'
rescue JWT::ExpiredSignature
raise 'Token has expired'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment