Skip to content

Instantly share code, notes, and snippets.

@dwayne
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwayne/c2452c0c292501ad349e to your computer and use it in GitHub Desktop.
Save dwayne/c2452c0c292501ad349e to your computer and use it in GitHub Desktop.
A secure random token generator with tests.
# 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) }
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
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