Created
September 14, 2017 08:54
-
-
Save xifengzhu/b135a0eaad836f792c8507117ae3a42c to your computer and use it in GitHub Desktop.
JWT
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' | |
class JsonWebToken | |
# Encodes and signs JWT Payload with expiration | |
def self.encode(payload) | |
payload.reverse_merge!(meta) | |
JWT.encode(payload, Rails.application.secrets.secret_key_base) | |
end | |
# Decodes the JWT with the signed secret | |
def self.decode(token) | |
JWT.decode(token, Rails.application.secrets.secret_key_base) | |
end | |
# Validates the payload hash for expiration and meta claims | |
def self.valid_payload(payload) | |
if expired(payload) || payload['client'] != meta[:client] | |
return false | |
else | |
return true | |
end | |
end | |
# Default options to be encoded in the token | |
def self.meta | |
{ | |
expired_at: 7.days.from_now.to_i, | |
client: 'wechat_app' | |
} | |
end | |
# Validates if the token is expired by exp parameter | |
def self.expired(payload) | |
Time.at(payload['expired_at']) < Time.now | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment