-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathapi_key.rb
More file actions
98 lines (80 loc) · 2.08 KB
/
Copy pathapi_key.rb
File metadata and controls
98 lines (80 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# typed: strict
# frozen_string_literal: true
class ApiKey < ApplicationRecord
extend T::Sig
belongs_to :user
has_many :daily_api_usages, dependent: :destroy
has_paper_trail
validates :value, uniqueness: true
before_create :set_value
sig { params(value: String).returns(T.nilable(ApiKey)) }
def self.find_valid(value)
a = ApiKey.find_by(value:)
return unless a&.active?
a
end
sig { returns(Symbol) }
def plan
# This is a stop-gap measure until we implement a "proper" plan set-up
if commercial
# In reality this should be split out into "Standard" and "Premium"
:commercial
elsif community
:community
elsif expires_at
# We're assuming that trial licenses always have an expiry
:trial
else
# This shouldn't happen I think
:other
end
end
sig { returns(T::Boolean) }
def active?
!disabled && !expired?
end
sig { returns(T::Boolean) }
def permanent?
expires_at.nil?
end
sig { returns(T::Boolean) }
def expired?
e = expires_at
!e.nil? && e <= Time.current
end
# By default we allow up to 1000 API requests per day per API key
sig { returns(Integer) }
def self.default_daily_limit
1000
end
sig { returns(Integer) }
def self.default_daily_limit_community
1000
end
sig { returns(Integer) }
def self.default_daily_limit_commercial
50
end
sig { returns(Integer) }
def self.default_daily_limit_trial
100
end
# TODO: Should this be longer (like 28 days)?
sig { returns(Integer) }
def self.default_trial_duration_days
14
end
# Returns the daily limit for a given API key value. If no daily limit
# is set will return the default daily limit. Also, if an invalid key is given it
# will return the default daily limit as well.
sig { params(value: String).returns(Integer) }
def self.daily_limit_with_default(value)
ApiKey.find_valid(value)&.daily_limit || ApiKey.default_daily_limit
end
private
# TODO: Retry if api key value is not unique
sig { void }
def set_value
self.value = SecureRandom.base58(20)
end
end