main
1# frozen_string_literal: true
2
3class Authorization < ApplicationRecord
4 audited associated_with: :user
5 has_secure_token :code
6 belongs_to :user
7 belongs_to :client
8 has_many :tokens, dependent: :delete_all
9 enum challenge_method: { plain: 0, sha256: 1 }
10
11 scope :active, -> { where.not(id: revoked.or(where(id: expired))) }
12 scope :revoked, -> { where('revoked_at < ?', Time.current) }
13 scope :expired, -> { where('expired_at < ?', Time.current) }
14
15 after_initialize do
16 self.expired_at = 10.minutes.from_now if expired_at.blank?
17 end
18
19 def valid_verifier?(code_verifier)
20 return true if challenge.blank?
21
22 challenge ==
23 if sha256?
24 Base64.urlsafe_encode64(Digest::SHA256.hexdigest(code_verifier))
25 else
26 code_verifier
27 end
28 end
29
30 def issue_tokens_to(client, token_types: [:access, :refresh])
31 transaction do
32 revoke!
33 token_types.map do |x|
34 tokens.create!(subject: user, audience: client, token_type: x)
35 end
36 end
37 end
38
39 def revoke!
40 raise 'already revoked' if revoked?
41
42 now = Time.current
43 update!(revoked_at: now)
44 tokens.update_all(revoked_at: now)
45 end
46
47 def revoked?
48 revoked_at.present?
49 end
50end