Last active
August 29, 2015 14:06
-
-
Save dwayne/c2452c0c292501ad349e to your computer and use it in GitHub Desktop.
A secure random token generator with tests.
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
# Generating a unique auth_token for a user | |
# | |
# While a user exists with the generated token, generate a new one | |
Token.generate { |token| User.exists?(auth_token: token) } |
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
class Token | |
def self.generate | |
if block_given? | |
loop do | |
token = SecureRandom.hex | |
break token unless yield(token) | |
end | |
else | |
SecureRandom.hex | |
end | |
end | |
end |
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 'rails_helper' | |
RSpec.describe Token do | |
describe ".generate" do | |
it "returns a string of random hexadecimal of length at least 32" do | |
expect(Token.generate).to match(/[0-9a-f]{32,}/) | |
end | |
it "only returns when the given block evaluates to false" do | |
n = 16 | |
token = Token.generate do |token| | |
n = n + 1 | |
token.length > n | |
end | |
expect(token.length).to eq(n) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment