Class: UserApiKey

Inherits:
ActiveRecord::Base
  • Object
show all
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

Instance Method Summary collapse

Class Method Details

.allowed_scopesObject

Scopes allowed to be requested by external services



55
56
57
# File 'app/models/user_api_key.rb', line 55

def self.allowed_scopes
  Set.new(SiteSetting.allow_user_api_key_scopes.split("|"))
end

.available_scopesObject



59
60
61
# File 'app/models/user_api_key.rb', line 59

def self.available_scopes
  @available_scopes ||= Set.new(UserApiKeyScopes.all_scopes.keys.map(&:to_s))
end

.invalid_auth_redirect?(auth_redirect) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
# File 'app/models/user_api_key.rb', line 72

def self.invalid_auth_redirect?(auth_redirect)
  SiteSetting
    .allowed_user_api_auth_redirects
    .split("|")
    .none? { |u| WildcardUrlChecker.check_url(u, auth_redirect) }
end

Instance Method Details

#allow?(env) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'app/models/user_api_key.rb', line 68

def allow?(env)
  scopes.any? { |s| s.permits?(env) } || is_revoke_self_request?(env)
end

#ensure_allowed!(env) ⇒ Object



36
37
38
# File 'app/models/user_api_key.rb', line 36

def ensure_allowed!(env)
  raise Discourse::InvalidAccess.new if !allow?(env)
end

#generate_keyObject



18
19
20
21
22
23
# File 'app/models/user_api_key.rb', line 18

def generate_key
  if !self.key_hash
    @key ||= SecureRandom.hex
    self.key_hash = ApiKey.hash_key(@key)
  end
end

#has_push?Boolean

Returns:

  • (Boolean)


63
64
65
66
# File 'app/models/user_api_key.rb', line 63

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

#keyObject



25
26
27
28
29
30
# File 'app/models/user_api_key.rb', line 25

def key
  unless key_available?
    raise ApiKey::KeyAccessError.new "API key is only accessible immediately after creation"
  end
  @key
end

#key_available?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'app/models/user_api_key.rb', line 32

def key_available?
  @key.present?
end

#update_last_used(client_id) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/models/user_api_key.rb', line 40

def update_last_used(client_id)
  update_args = { last_used_at: Time.zone.now }
  if client_id.present? && client_id != self.client_id
    # invalidate old dupe api key for client if needed
    UserApiKey
      .where(client_id: client_id, user_id: self.user_id)
      .where("id <> ?", self.id)
      .destroy_all

    update_args[:client_id] = client_id
  end
  self.update_columns(**update_args)
end