Class: UserApiKeysController

Inherits:
ApplicationController show all
Defined in:
app/controllers/user_api_keys_controller.rb

Constant Summary

Constants inherited from ApplicationController

ApplicationController::LEGACY_NO_THEMES, ApplicationController::LEGACY_NO_UNOFFICIAL_PLUGINS, ApplicationController::NO_PLUGINS, ApplicationController::NO_THEMES, ApplicationController::NO_UNOFFICIAL_PLUGINS, ApplicationController::SAFE_MODE

Constants included from CanonicalURL::ControllerExtensions

CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS

Instance Attribute Summary

Attributes inherited from ApplicationController

#theme_id

Instance Method Summary collapse

Methods inherited from ApplicationController

#application_layout, #can_cache_content?, #clear_notifications, #conditionally_allow_site_embedding, #current_homepage, #discourse_expires_in, #dont_cache_page, #ember_cli_required?, #fetch_user_from_params, #guardian, #handle_permalink, #handle_theme, #handle_unverified_request, #has_escaped_fragment?, #immutable_for, #no_cookies, #perform_refresh_session, #post_ids_including_replies, #preload_json, #rate_limit_second_factor!, #redirect_with_client_support, #render_json_dump, #render_serialized, requires_plugin, #rescue_discourse_actions, #resolve_safe_mode, #secure_session, #serialize_data, #set_current_user_for_logs, #set_layout, #set_mobile_view, #set_mp_snapshot_fields, #show_browser_update?, #store_preloaded, #use_crawler_layout?, #with_resolved_locale

Methods included from VaryHeader

#ensure_vary_header

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, included, #staff_writes_only_mode?

Methods included from Hijack

#hijack

Methods included from GlobalPath

#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path

Methods included from JsonError

#create_errors_json

Methods included from CanonicalURL::ControllerExtensions

#canonical_url, #default_canonical, included

Methods included from CurrentUser

#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session

Instance Method Details

#createObject



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
99
100
101
102
103
104
105
106
107
108
109
# File 'app/controllers/user_api_keys_controller.rb', line 49

def create
  require_params

  if params.key?(:auth_redirect)
    raise Discourse::InvalidAccess if UserApiKey.invalid_auth_redirect?(params[:auth_redirect])
  end

  raise Discourse::InvalidAccess unless meets_tl?

  validate_params
  @application_name = params[:application_name]
  scopes = params[:scopes].split(",")

  # destroy any old keys we had
  UserApiKey.where(user_id: current_user.id, client_id: params[:client_id]).destroy_all

  key =
    UserApiKey.create!(
      application_name: @application_name,
      client_id: params[:client_id],
      user_id: current_user.id,
      push_url: params[:push_url],
      scopes: scopes.map { |name| UserApiKeyScope.new(name: name) },
    )

  # we keep the payload short so it encrypts easily with public key
  # it is often restricted to 128 chars
  @payload = {
    key: key.key,
    nonce: params[:nonce],
    push: key.has_push?,
    api: AUTH_API_VERSION,
  }.to_json

  public_key = OpenSSL::PKey::RSA.new(params[:public_key])
  @payload = Base64.encode64(public_key.public_encrypt(@payload))

  if scopes.include?("one_time_password")
    # encrypt one_time_password separately to bypass 128 chars encryption limit
    otp_payload = one_time_password(public_key, current_user.username)
  end

  if params[:auth_redirect]
    uri = URI.parse(params[:auth_redirect])
    query_attributes = [uri.query, "payload=#{CGI.escape(@payload)}"]
    if scopes.include?("one_time_password")
      query_attributes << "oneTimePassword=#{CGI.escape(otp_payload)}"
    end
    uri.query = query_attributes.compact.join("&")

    redirect_to(uri.to_s, allow_other_host: true)
  else
    respond_to do |format|
      format.html { render :show }
      format.json do
        instructions = I18n.t("user_api_key.instructions", application_name: @application_name)
        render json: { payload: @payload, instructions: instructions }
      end
    end
  end
end

#create_otpObject



130
131
132
133
134
135
136
137
138
139
140
141
# File 'app/controllers/user_api_keys_controller.rb', line 130

def create_otp
  require_params_otp

  raise Discourse::InvalidAccess if UserApiKey.invalid_auth_redirect?(params[:auth_redirect])
  raise Discourse::InvalidAccess unless meets_tl?

  public_key = OpenSSL::PKey::RSA.new(params[:public_key])
  otp_payload = one_time_password(public_key, current_user.username)

  redirect_path = "#{params[:auth_redirect]}?oneTimePassword=#{CGI.escape(otp_payload)}"
  redirect_to(redirect_path, allow_other_host: true)
end

#find_keyObject



163
164
165
166
167
# File 'app/controllers/user_api_keys_controller.rb', line 163

def find_key
  key = UserApiKey.find(params[:id])
  raise Discourse::InvalidAccess unless current_user.admin || key.user_id == current_user.id
  key
end

#meets_tl?Boolean

Returns:

  • (Boolean)


185
186
187
# File 'app/controllers/user_api_keys_controller.rb', line 185

def meets_tl?
  current_user.staff? || current_user.trust_level >= SiteSetting.min_trust_level_for_user_api_key
end

#newObject



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
# File 'app/controllers/user_api_keys_controller.rb', line 12

def new
  if request.head?
    head :ok, auth_api_version: AUTH_API_VERSION
    return
  end

  require_params
  validate_params

  unless current_user
    cookies[:destination_url] = request.fullpath

    if SiteSetting.enable_discourse_connect?
      redirect_to path("/session/sso")
    else
      redirect_to path("/login")
    end
    return
  end

  unless meets_tl?
    @no_trust_level = true
    return
  end

  @application_name = params[:application_name]
  @public_key = params[:public_key]
  @nonce = params[:nonce]
  @client_id = params[:client_id]
  @auth_redirect = params[:auth_redirect]
  @push_url = params[:push_url]
  @localized_scopes = params[:scopes].split(",").map { |s| I18n.t("user_api_key.scopes.#{s}") }
  @scopes = params[:scopes]
rescue Discourse::InvalidAccess
  @generic_error = true
end

#one_time_password(public_key, username) ⇒ Object



189
190
191
192
193
194
195
196
197
198
# File 'app/controllers/user_api_keys_controller.rb', line 189

def one_time_password(public_key, username)
  unless UserApiKey.allowed_scopes.superset?(Set.new(["one_time_password"]))
    raise Discourse::InvalidAccess
  end

  otp = SecureRandom.hex
  Discourse.redis.setex "otp_#{otp}", 10.minutes, username

  Base64.encode64(public_key.public_encrypt(otp))
end

#otpObject



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'app/controllers/user_api_keys_controller.rb', line 111

def otp
  require_params_otp

  unless current_user
    cookies[:destination_url] = request.fullpath

    if SiteSetting.enable_discourse_connect?
      redirect_to path("/session/sso")
    else
      redirect_to path("/login")
    end
    return
  end

  @application_name = params[:application_name]
  @public_key = params[:public_key]
  @auth_redirect = params[:auth_redirect]
end

#require_paramsObject



169
170
171
# File 'app/controllers/user_api_keys_controller.rb', line 169

def require_params
  %i[public_key nonce scopes client_id application_name].each { |p| params.require(p) }
end

#require_params_otpObject



181
182
183
# File 'app/controllers/user_api_keys_controller.rb', line 181

def require_params_otp
  %i[public_key auth_redirect application_name].each { |p| params.require(p) }
end

#revokeObject



143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/controllers/user_api_keys_controller.rb', line 143

def revoke
  revoke_key = find_key if params[:id]

  if current_key = request.env["HTTP_USER_API_KEY"]
    request_key = UserApiKey.with_key(current_key).first
    revoke_key ||= request_key
  end

  raise Discourse::NotFound unless revoke_key

  revoke_key.update_columns(revoked_at: Time.zone.now)

  render json: success_json
end

#undo_revokeObject



158
159
160
161
# File 'app/controllers/user_api_keys_controller.rb', line 158

def undo_revoke
  find_key.update_columns(revoked_at: nil)
  render json: success_json
end

#validate_paramsObject



173
174
175
176
177
178
179
# File 'app/controllers/user_api_keys_controller.rb', line 173

def validate_params
  requested_scopes = Set.new(params[:scopes].split(","))
  raise Discourse::InvalidAccess unless UserApiKey.allowed_scopes.superset?(requested_scopes)

  # our pk has got to parse
  OpenSSL::PKey::RSA.new(params[:public_key])
end