Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add service that generates Base(58) secure tokens #580

Merged
merged 4 commits into from
Dec 5, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions app/services/waste_carriers_engine/secure_token_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# frozen_string_literal: true

require "securerandom"

module WasteCarriersEngine

Cruikshanks marked this conversation as resolved.
Show resolved Hide resolved
# SecureTokenService generates a random base58 string of length 24.
#
# SecureRandom::base58 is used to generate the 24-character unique tokens, so
# collisions are highly unlikely.
#
# The result will contain only alphanumeric characters except 0, O, I and l
#
# p SecureRandom.base58 #=> "4kUgL2pdQMSCQtjE"
# p SecureRandom.base58(24) #=> "77TMHrHJFvFDwodq8w7Ev2m7"
#
# Copied almost verbatim from
# https://github.com/robertomiranda/has_secure_token
class SecureTokenService < BaseService
BASE58_ALPHABET = ("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a - %w[0 O I l]

def run
SecureRandom.random_bytes(24).unpack("C*").map do |byte|
idx = byte % 64
idx = SecureRandom.random_number(58) if idx >= 58
BASE58_ALPHABET[idx]
end.join
end

Cruikshanks marked this conversation as resolved.
Show resolved Hide resolved
end
end
36 changes: 36 additions & 0 deletions spec/services/waste_carriers_engine/secure_token_service_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

require "rails_helper"

module WasteCarriersEngine
RSpec.describe SecureTokenService do

describe ".run" do
context "the return value" do
it "is a string" do
expect(described_class.run).to be_a(String)
end

it "is 24 characters in length" do
expect(described_class.run.length).to eq(24)
end

it "contains only alphanumeric characters except 0, O, I and l" do
expect(described_class.run).to match(/^[a-km-zA-HJ-NP-Z1-9]*$/)
end
end

it "generates a different result each time it is called" do
results = []
10.times do
latest = described_class.run

expect(results).not_to include(latest)

results.push(latest)
end
end
end

Cruikshanks marked this conversation as resolved.
Show resolved Hide resolved
end
end