Sha256: 9acf0e37f3500ea3769602822de7a45612c11a41f7e0c94ff0383c658bb7f6a2

Contents?: true

Size: 961 Bytes

Versions: 6

Compression:

Stored size: 961 Bytes

Contents

module Ctws
  class JsonWebToken
    require 'jwt'

    # secret to encode and decode token
    HMAC_SECRET = Rails.application.secrets.secret_key_base

    def self.encode(payload, exp = Ctws.jwt_expiration_time)
      # set expiry to 24 hours from creation time
      payload[:exp] = exp.to_i
      # sign token with application secret
      JWT.encode(payload, HMAC_SECRET)
    end

    def self.decode(token)
      # get payload; first index in decoded Array
      body = JWT.decode(token, HMAC_SECRET)[0]
      HashWithIndifferentAccess.new body
      # rescue from expiry exception
      rescue JWT::ExpiredSignature => e
        # raise custom error to be handled by custom handler
        raise Ctws::ExceptionHandler::ExpiredSignature, e.message
      rescue JWT::VerificationError => e
        # raise custom error to be handled by custom handler
        raise Ctws::ExceptionHandler::VerificationError, Ctws::Message.invalid_token

    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ctws-0.3.0.beta app/lib/ctws/json_web_token.rb
ctws-0.2.3.beta app/lib/ctws/json_web_token.rb
ctws-0.2.2.beta app/lib/ctws/json_web_token.rb
ctws-0.2.1.beta app/lib/ctws/json_web_token.rb
ctws-0.2.0.beta app/lib/ctws/json_web_token.rb
ctws-0.1.14.beta app/lib/ctws/json_web_token.rb