Skip to content

Commit

Permalink
Simplify encrypting and decrypting tokens
Browse files Browse the repository at this point in the history
We can use a higher level API to handle this
  • Loading branch information
jcoyne committed Jan 18, 2024
1 parent a36d8fb commit c9f0cd9
Showing 1 changed file with 2 additions and 34 deletions.
36 changes: 2 additions & 34 deletions app/controllers/concerns/blacklight/token_based_user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def token_user

# Used for #export action, with encrypted user_id.
def decrypt_user_id(encrypted_user_id)
user_id, timestamp = message_encryptor.decrypt_and_verify(encrypted_user_id)
user_id, timestamp = Rails::Secrets.decrypt(encrypted_user_id)

if timestamp < 1.hour.ago
raise Blacklight::Exceptions::ExpiredSessionToken
Expand All @@ -41,38 +41,6 @@ def decrypt_user_id(encrypted_user_id)
# as a helper method for views.
def encrypt_user_id(user_id, current_time = nil)
current_time ||= Time.zone.now
message_encryptor.encrypt_and_sign([user_id, current_time])
end

def export_secret_token
secret_key_generator.generate_key('encrypted user session key')[0..(key_len - 1)]
end

def secret_key_generator
@secret_key_generator ||= begin
app = Rails.application

secret_key_base = if app.respond_to?(:credentials)
# Rails 5.2+
app.credentials.secret_key_base
else
# Rails <= 5.1
app.secrets.secret_key_base
end
ActiveSupport::KeyGenerator.new(secret_key_base)
end
end

def message_encryptor
ActiveSupport::MessageEncryptor.new(export_secret_token)
end

# Ruby 2.4 requires keys of very particular lengths
def key_len
if ActiveSupport::MessageEncryptor.respond_to? :key_len
ActiveSupport::MessageEncryptor.key_len
else
0
end
Rails::Secrets.encrypt([user_id, current_time])
end
end

0 comments on commit c9f0cd9

Please sign in to comment.