Last active
April 3, 2017 20:28
-
-
Save rreinhardt9/307dc53ac4b81851f0444da8052fb290 to your computer and use it in GitHub Desktop.
Securely hashed request
This file contains hidden or 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
| ## | |
| # Forms a tokenized request payload | |
| class Tokenizer | |
| ## | |
| # Initialize with a secret and a message to encode | |
| # Tokenizer.new(secret: String, message: Hash) | |
| def initialize(args) | |
| @secret = args[:secret] | |
| @message = args[:message] | |
| end | |
| ## | |
| # Creates a signed token of the request | |
| def tokenize | |
| Base64.strict_encode64(signed_message.to_json) | |
| end | |
| private | |
| def signature | |
| OpenSSL::HMAC.hexdigest("sha256", @secret, encoded_message) | |
| end | |
| def encoded_message | |
| Base64.strict_encode64(message: @message.to_json , expires_at: 30.seconds.from.now) | |
| end | |
| def signed_message | |
| { data: encoded_message, secret: signature } | |
| end | |
| end | |
| # Use it like: | |
| message = { username: "[email protected]" } | |
| signed_message = Tokenizer.new(secret: "my_super_secret_key", message: message).tokenize | |
| # Now we have a signed message that we can send along; that will expire after 30 seconds. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment