Newer
Older
Website-backend / lib / JWT.rb
@lukas lukas on 23 Aug 2022 888 bytes correct ruby syntax
class JWT
    attr_reader :data, :signature

    def initialize(data)
        if data.class == String
            @parts = data.split('.')
            @header = JSON.parse Base64.urlsafe_decode64(@parts[0])
            @data = JSON.parse Base64.urlsafe_decode64(@parts[1])
            @signature = @parts[2]
        else
            @header = defaultHeader
            @data = data
        end
    end

    def defaultHeader
        return {
            'alg' => 'HS256',
            'typ' => 'jwt'
        }
    end

    def toString
        string = Base64.urlsafe_encode64(@header.to_json).tr('=', '') + '.' + 
                Base64.urlsafe_encode64(@data.to_json)  .tr('=', '')
        string = string +  '.' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), 
                Rails.application.credentials.secret_key_base, string).tr('=', '')
        return string
    end
end