Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Make LoginToken generation frozen string compatible

Jan Sandbrink54055ffa5b15
diff --git a/modules/two_factor_authentication/app/models/two_factor_authentication/login_token.rb b/modules/two_factor_authentication/app/models/two_factor_authentication/login_token.rb
index 4ce92b14236..2856a6952be 100644
--- a/modules/two_factor_authentication/app/models/two_factor_authentication/login_token.rb
+++ b/modules/two_factor_authentication/app/models/two_factor_authentication/login_token.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module TwoFactorAuthentication
class LoginToken < ::Token::HashedToken
include ::Token::ExpirableToken
@@ -8,9 +10,7 @@ module TwoFactorAuthentication
def self.generate_token_value
chars = ("0".."9").to_a
- password = ""
- 6.times { |_i| password << chars[rand(chars.size - 1)] }
- password
+ Array.new(6) { chars[SecureRandom.rand(chars.size)] }.join
end
end
end
diff --git a/modules/two_factor_authentication/spec/models/login_token_spec.rb b/modules/two_factor_authentication/spec/models/login_token_spec.rb
index ad5d37d8744..0993139166b 100644
--- a/modules/two_factor_authentication/spec/models/login_token_spec.rb
+++ b/modules/two_factor_authentication/spec/models/login_token_spec.rb
@@ -25,4 +25,21 @@ RSpec.describe TwoFactorAuthentication::LoginToken, :with_2fa_ee do
expect(described_class.find_by(id: token.id)).to be_nil
expect(described_class.find(new_token.id)).not_to be_nil
end
+
+ describe ".generate_token_value" do
+ subject { described_class.generate_token_value }
+
+ it "generates tokens consisting of 6 numerical digits" do
+ expect(subject).to match(/\A[0-9]{6}\z/)
+ end
+
+ it "generates tokens that can contain any digit (regression test)" do
+ generated_digits = ""
+ 100.times { generated_digits += described_class.generate_token_value }
+
+ (0..9).each do |digit|
+ expect(generated_digits).to include(digit.to_s)
+ end
+ end
+ end
end