Class: Shakha::Session
- Inherits:
-
ApplicationRecord
- Object
- ApplicationRecord
- Shakha::Session
- Defined in:
- app/models/shakha/session.rb
Constant Summary collapse
- EXCHANGE_CODE_TTL =
60.seconds
Class Method Summary collapse
-
.exchange(code) ⇒ Object
Redeems a code for its session, atomically clearing it so a code can be used at most once even under concurrent requests.
Instance Method Summary collapse
- #expired? ⇒ Boolean
- #expires_at ⇒ Object
-
#generate_exchange_code! ⇒ Object
Issues a short-lived, single-use code the frontend swaps for the session token, so the token itself never travels in a redirect URL.
Class Method Details
.exchange(code) ⇒ Object
Redeems a code for its session, atomically clearing it so a code can be used at most once even under concurrent requests.
35 36 37 38 39 40 41 42 43 44 45 |
# File 'app/models/shakha/session.rb', line 35 def self.exchange(code) return nil if code.blank? session = active.where(exchange_code: code) .where("exchange_code_expires_at > ?", Time.current).first return nil unless session claimed = where(id: session.id).where.not(exchange_code: nil) .update_all(exchange_code: nil, exchange_code_expires_at: nil) claimed == 1 ? session : nil end |
Instance Method Details
#expired? ⇒ Boolean
15 16 17 |
# File 'app/models/shakha/session.rb', line 15 def expired? created_at < Shakha.config.session_lifetime.ago end |
#expires_at ⇒ Object
19 20 21 |
# File 'app/models/shakha/session.rb', line 19 def expires_at created_at + Shakha.config.session_lifetime end |
#generate_exchange_code! ⇒ Object
Issues a short-lived, single-use code the frontend swaps for the session token, so the token itself never travels in a redirect URL.
25 26 27 28 29 30 31 |
# File 'app/models/shakha/session.rb', line 25 def generate_exchange_code! update_columns( exchange_code: SecureRandom.urlsafe_base64(32), exchange_code_expires_at: EXCHANGE_CODE_TTL.from_now ) exchange_code end |