Class: UserApiKey
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- UserApiKey
- Defined in:
- app/models/user_api_key.rb
Constant Summary collapse
- REVOKE_MATCHER =
RouteMatcher.new(actions: "user_api_keys#revoke", methods: :post, params: [:id])
Class Method Summary collapse
-
.allowed_scopes ⇒ Object
Scopes allowed to be requested by external services.
- .available_scopes ⇒ Object
Instance Method Summary collapse
- #allow?(env) ⇒ Boolean
- #ensure_allowed!(env) ⇒ Object
- #generate_key ⇒ Object
- #has_push? ⇒ Boolean
- #key ⇒ Object
- #key_available? ⇒ Boolean
- #update_last_used(client_id) ⇒ Object
Class Method Details
.allowed_scopes ⇒ Object
Scopes allowed to be requested by external services
57 58 59 |
# File 'app/models/user_api_key.rb', line 57 def self.allowed_scopes Set.new(SiteSetting.allow_user_api_key_scopes.split("|")) end |
.available_scopes ⇒ Object
61 62 63 |
# File 'app/models/user_api_key.rb', line 61 def self.available_scopes @available_scopes ||= Set.new(UserApiKeyScopes.all_scopes.keys.map(&:to_s)) end |
Instance Method Details
#allow?(env) ⇒ Boolean
70 71 72 |
# File 'app/models/user_api_key.rb', line 70 def allow?(env) scopes.any? { |s| s.permits?(env) } || is_revoke_self_request?(env) end |
#ensure_allowed!(env) ⇒ Object
39 40 41 |
# File 'app/models/user_api_key.rb', line 39 def ensure_allowed!(env) raise Discourse::InvalidAccess.new if !allow?(env) end |
#generate_key ⇒ Object
21 22 23 24 25 26 |
# File 'app/models/user_api_key.rb', line 21 def generate_key if !self.key_hash @key ||= SecureRandom.hex self.key_hash = ApiKey.hash_key(@key) end end |
#has_push? ⇒ Boolean
65 66 67 68 |
# File 'app/models/user_api_key.rb', line 65 def has_push? scopes.any? { |s| s.name == "push" || s.name == "notifications" } && push_url.present? && SiteSetting.allowed_user_api_push_urls.include?(push_url) end |
#key ⇒ Object
28 29 30 31 32 33 |
# File 'app/models/user_api_key.rb', line 28 def key unless key_available? raise ApiKey::KeyAccessError.new "API key is only accessible immediately after creation" end @key end |
#key_available? ⇒ Boolean
35 36 37 |
# File 'app/models/user_api_key.rb', line 35 def key_available? @key.present? end |
#update_last_used(client_id) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'app/models/user_api_key.rb', line 43 def update_last_used(client_id) update_args = { last_used_at: Time.zone.now } if client_id.present? && client_id != self.client.client_id new_client = UserApiKeyClient.create!( client_id: client_id, application_name: self.client.application_name, ) update_args[:user_api_key_client_id] = new_client.id end self.update_columns(**update_args) end |