Class: CoPlan::ApiToken

Inherits:
ApplicationRecord show all
Defined in:
app/models/coplan/api_token.rb

Constant Summary collapse

HOLDER_TYPE =
"local_agent"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.authenticate(raw_token) ⇒ Object



12
13
14
15
16
17
18
# File 'app/models/coplan/api_token.rb', line 12

def self.authenticate(raw_token)
  return nil if raw_token.blank?
  digest = Digest::SHA256.hexdigest(raw_token)
  token = active.find_by(token_digest: digest)
  token&.touch(:last_used_at)
  token
end

.create_with_raw_token(**attributes) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'app/models/coplan/api_token.rb', line 24

def self.create_with_raw_token(**attributes)
  raw_token = generate_token
  api_token = create!(
    **attributes,
    token_digest: Digest::SHA256.hexdigest(raw_token),
    token_prefix: raw_token[0, 8]
  )
  [api_token, raw_token]
end

.generate_tokenObject



20
21
22
# File 'app/models/coplan/api_token.rb', line 20

def self.generate_token
  SecureRandom.hex(32)
end

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'app/models/coplan/api_token.rb', line 42

def active?
  !revoked? && !expired?
end

#expired?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'app/models/coplan/api_token.rb', line 38

def expired?
  expires_at.present? && expires_at <= Time.current
end

#revoke!Object



46
47
48
# File 'app/models/coplan/api_token.rb', line 46

def revoke!
  update!(revoked_at: Time.current)
end

#revoked?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'app/models/coplan/api_token.rb', line 34

def revoked?
  revoked_at.present?
end