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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API token tweaks #388

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion app/models/access_token.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
class AccessToken < ApplicationRecord
validates :token_digest, :owner, presence: true
validates :token_digest, uniqueness: { conditions: -> { active } }

scope :active, -> { where(deactivated_at: nil) }

def generate_token
users_token = SecureRandom.uuid
users_token = "forms_#{SecureRandom.uuid}"
self.token_digest = Digest::SHA256.hexdigest(users_token)
users_token
end
Expand Down
20 changes: 18 additions & 2 deletions spec/models/access_token_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@
expect(access_token).to be_invalid
expect(access_token.errors[:token_digest]).to include("can't be blank")
end

it "is invalid to have two active tokens with the same digest" do
access_token_1 = described_class.create!(owner: "test1", token_digest: "baabaa")
expect(access_token_1).to be_valid

access_token_2 = described_class.new(owner: "test2", token_digest: "baabaa")
expect(access_token_2).not_to be_valid
end

it "is valid to reuse the same token digest" do
access_token_1 = described_class.create!(owner: "test1", token_digest: "baabaa")
access_token_1.update!(deactivated_at: Time.zone.now)

access_token_2 = described_class.new(owner: "test2", token_digest: "baabaa")
expect(access_token_2).to be_valid
end
end

describe "scopes" do
Expand All @@ -50,12 +66,12 @@
let(:result) { access_token.generate_token }

it "generates a user token before validation" do
expect(result).to eq("testing-123")
expect(result).to eq("forms_testing-123")
end

it "generates a sha-256 token before validation" do
result
expect(access_token.token_digest).to eq("8d9754db9759ab1785644440dbf19f88ab45ae326e421da6c1cb6e45140d534f")
expect(access_token.token_digest).to eq("f3aed9ecfc2db207800ca641f45e24d2f6de030487b7270871c04046808c1b22")
end
end
end