Skip to content

Commit

Permalink
Generate Access Key
Browse files Browse the repository at this point in the history
This provides an isolated location to create an access key for any thing
that can have an access key.
  • Loading branch information
kevin-j-m committed Sep 18, 2019
1 parent 26a26a4 commit e9444f7
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
22 changes: 22 additions & 0 deletions app/models/access_key_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class AccessKeyGenerator
def access_key(accessor_type:, acquired_company: nil)
if accessor_type == :company
if acquired_company
SecureRandom.base64
else
"CO-#{SecureRandom.hex(8)}"
end
elsif accessor_type == :user
SecureRandom.uuid
else
raise UnknownAccessorType
end

end
end

class UnknownAccessorType < StandardError
def initialize(msg="Unkown accessor to generate access key for")
super
end
end
55 changes: 55 additions & 0 deletions spec/models/access_key_generator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
require "rails_helper"

RSpec.describe AccessKeyGenerator do
UUID_REGEX = /[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}/
COMPANY_REGEX = /CO-[0-9a-fA-F]{8}/

describe "#access_key" do
it "provides a base-64 encoded key if the key is for an acquired company" do
generator = AccessKeyGenerator.new

key = generator.access_key(accessor_type: :company, acquired_company: true)

expect(key).to eq Base64.strict_encode64(Base64.decode64(key))
end

it "creates an ivory tower company access key if it's a company not acquired" do
generator = AccessKeyGenerator.new

key = generator.access_key(accessor_type: :company, acquired_company: false)

expect(key.match?(COMPANY_REGEX)).to eq true
end

it "does not provide a full UUID if the key is for a company" do
generator = AccessKeyGenerator.new

key = generator.access_key(accessor_type: :company)

expect(key.match?(UUID_REGEX)).not_to eq true
end

it "provides a UUID if the key is for a user" do
generator = AccessKeyGenerator.new

key = generator.access_key(accessor_type: :user)

expect(key.match?(UUID_REGEX)).to eq true
end

it "does not provide a company key style if the key is for a user" do
generator = AccessKeyGenerator.new

key = generator.access_key(accessor_type: :user)

expect(key.match?(COMPANY_REGEX)).not_to eq true
end

it "raises an exception if it doesn't understand the accessor type" do
generator = AccessKeyGenerator.new

expect { generator.access_key(accessor_type: :foo) }
.to raise_error UnknownAccessorType
end
end
end

0 comments on commit e9444f7

Please sign in to comment.