Class: InvitesController

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

Constant Summary

Constants inherited from ApplicationController

ApplicationController::CHALLENGE_KEY, ApplicationController::HONEYPOT_KEY, 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, #login_method, #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 ThemeResolver

resolve_theme_id

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, #get_or_check_readonly_mode, #get_or_check_staff_writes_only_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



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'app/controllers/invites_controller.rb', line 111

def create
  begin
    if params[:topic_id].present?
      topic = Topic.find_by(id: params[:topic_id])
      raise Discourse::InvalidParameters.new(:topic_id) if topic.blank?
      guardian.ensure_can_invite_to!(topic)
    end

    if params[:group_ids].present? || params[:group_names].present?
      groups =
        Group.lookup_groups(group_ids: params[:group_ids], group_names: params[:group_names])
    end

    guardian.ensure_can_invite_to_forum!(groups)

    if !groups_can_see_topic?(groups, topic)
      editable_topic_groups = topic.category.groups.filter { |g| guardian.can_edit_group?(g) }
      return(
        render_json_error(
          I18n.t("invite.requires_groups", groups: editable_topic_groups.pluck(:name).join(", ")),
        )
      )
    end

    invite =
      Invite.generate(
        current_user,
        email: params[:email],
        domain: params[:domain],
        skip_email: params[:skip_email],
        invited_by: current_user,
        custom_message: params[:custom_message],
        max_redemptions_allowed: params[:max_redemptions_allowed],
        topic_id: topic&.id,
        group_ids: groups&.map(&:id),
        expires_at: params[:expires_at],
        invite_to_topic: params[:invite_to_topic],
      )

    if invite.present?
      render_serialized(
        invite,
        InviteSerializer,
        scope: guardian,
        root: nil,
        show_emails: params.has_key?(:email),
        show_warnings: true,
      )
    else
      render json: failed_json, status: 422
    end
  rescue Invite::UserExists => e
    render_json_error(e.message)
  rescue ActiveRecord::RecordInvalid => e
    render_json_error(e.record.errors.full_messages.first)
  end
end

#create_multipleObject



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

def create_multiple
  guardian.ensure_can_bulk_invite_to_forum!(current_user)
  emails = params[:email]
  # validate that topics and groups can accept invites.
  if params[:topic_id].present?
    topic = Topic.find_by(id: params[:topic_id])
    raise Discourse::InvalidParameters.new(:topic_id) if topic.blank?
    guardian.ensure_can_invite_to!(topic)
  end

  if params[:group_ids].present? || params[:group_names].present?
    groups = Group.lookup_groups(group_ids: params[:group_ids], group_names: params[:group_names])
  end

  guardian.ensure_can_invite_to_forum!(groups)

  if !groups_can_see_topic?(groups, topic)
    editable_topic_groups = topic.category.groups.filter { |g| guardian.can_edit_group?(g) }
    return(
      render_json_error(
        I18n.t("invite.requires_groups", groups: editable_topic_groups.pluck(:name).join(", ")),
      )
    )
  end

  if emails.size > SiteSetting.max_api_invites
    return(
      render_json_error(
        I18n.t("invite.max_invite_emails_limit_exceeded", max: SiteSetting.max_api_invites),
        422,
      )
    )
  end

  success = []
  fail = []

  emails.map do |email|
    begin
      invite =
        Invite.generate(
          current_user,
          email: email,
          domain: params[:domain],
          skip_email: params[:skip_email],
          invited_by: current_user,
          custom_message: params["custom_message"],
          max_redemptions_allowed: params[:max_redemptions_allowed],
          topic_id: topic&.id,
          group_ids: groups&.map(&:id),
          expires_at: params[:expires_at],
          invite_to_topic: params[:invite_to_topic],
        )
      success.push({ email: email, invite: invite }) if invite
    rescue Invite::UserExists => e
      fail.push({ email: email, error: e.message })
    rescue ActiveRecord::RecordInvalid => e
      fail.push({ email: email, error: e.record.errors.full_messages.first })
    end
  end

  render json: {
           num_successfully_created_invitations: success.length,
           num_failed_invitations: fail.length,
           failed_invitations: fail,
           successful_invitations:
             success.map do |s| InviteSerializer.new(s[:invite], scope: guardian) end,
         }
end

#destroyObject



301
302
303
304
305
306
307
308
309
310
# File 'app/controllers/invites_controller.rb', line 301

def destroy
  params.require(:id)

  invite = Invite.find_by(invited_by_id: current_user.id, id: params[:id])
  raise Discourse::InvalidParameters.new(:id) if invite.blank?

  invite.trash!(current_user)

  render json: success_json
end

#destroy_all_expiredObject



403
404
405
406
407
408
409
410
411
412
# File 'app/controllers/invites_controller.rb', line 403

def destroy_all_expired
  guardian.ensure_can_destroy_all_invites!(current_user)

  Invite
    .where(invited_by: current_user)
    .where("expires_at < ?", Time.zone.now)
    .find_each { |invite| invite.trash!(current_user) }

  render json: success_json
end

#perform_accept_invitationObject

For DiscourseConnect SSO, all invite acceptance is done via the SessionController#sso_login route



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'app/controllers/invites_controller.rb', line 314

def perform_accept_invitation
  params.require(:id)
  params.permit(
    :email,
    :username,
    :name,
    :password,
    :timezone,
    :email_token,
    user_custom_fields: {
    },
  )

  raise Discourse::NotFound if SiteSetting.enable_discourse_connect

  invite = Invite.find_by(invite_key: params[:id])
  redeeming_user = current_user

  if invite.present?
    begin
      attrs = { ip_address: request.remote_ip, session: session }

      if redeeming_user
        attrs[:redeeming_user] = redeeming_user
      else
        attrs[:username] = params[:username]
        attrs[:name] = params[:name]
        attrs[:password] = params[:password]
        attrs[:user_custom_fields] = params[:user_custom_fields]

        # If the invite is not scoped to an email then we allow the
        # user to provide it themselves
        if invite.is_invite_link?
          params.require(:email)
          attrs[:email] = params[:email]
        else
          # Otherwise we always use the email from the invitation.
          attrs[:email] = invite.email
          attrs[:email_token] = params[:email_token] if params[:email_token].present?
        end
      end

      user = invite.redeem(**attrs)
    rescue ActiveRecord::RecordInvalid,
           ActiveRecord::RecordNotSaved,
           ActiveRecord::LockWaitTimeout,
           Invite::UserExists => e
      return render json: failed_json.merge(message: e.message), status: 412
    end

    if user.blank?
      return render json: failed_json.merge(message: I18n.t("invite.not_found_json")), status: 404
    end

    log_on_user(user) if !redeeming_user && user.active? && user.guardian.can_access_forum?

    user.update_timezone_if_missing(params[:timezone])
    post_process_invite(user)
    create_topic_invite_notifications(invite, user)

    topic = invite.topics.first
    response = {}

    if user.present?
      if user.active? && user.guardian.can_access_forum?
        response[:message] = I18n.t("invite.existing_user_success") if redeeming_user

        if user.guardian.can_see?(topic)
          response[:redirect_to] = path(topic.relative_url)
        else
          response[:redirect_to] = path("/")
        end
      else
        response[:message] = if user.active?
          I18n.t("activation.approval_required")
        else
          I18n.t("invite.confirm_email")
        end

        cookies[:destination_url] = path(topic.relative_url) if user.guardian.can_see?(topic)
      end
    end

    render json: success_json.merge(response)
  else
    render json: failed_json.merge(message: I18n.t("invite.not_found_json")), status: 404
  end
end

#resend_all_invitesObject



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'app/controllers/invites_controller.rb', line 426

def resend_all_invites
  guardian.ensure_can_resend_all_invites!(current_user)

  begin
    RateLimiter.new(
      current_user,
      "bulk-reinvite-per-day",
      1,
      1.day,
      apply_limit_to_staff: true,
    ).performed!
  rescue RateLimiter::LimitExceeded
    return render_json_error(I18n.t("rate_limiter.slow_down"))
  end

  Invite
    .pending(current_user)
    .where("invites.email IS NOT NULL")
    .find_each { |invite| invite.resend_invite }

  render json: success_json
end

#resend_inviteObject



414
415
416
417
418
419
420
421
422
423
424
# File 'app/controllers/invites_controller.rb', line 414

def resend_invite
  params.require(:email)
  RateLimiter.new(current_user, "resend-invite-per-hour", 10, 1.hour).performed!

  invite = Invite.find_by(invited_by_id: current_user.id, email: params[:email])
  raise Discourse::InvalidParameters.new(:email) if invite.blank?
  invite.resend_invite
  render json: success_json
rescue RateLimiter::LimitExceeded
  render_json_error(I18n.t("rate_limiter.slow_down"))
end

#retrieveObject



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'app/controllers/invites_controller.rb', line 169

def retrieve
  params.require(:email)

  invite = Invite.find_by(invited_by: current_user, email: params[:email])
  raise Discourse::InvalidParameters.new(:email) if invite.blank?

  guardian.ensure_can_invite_to_forum!(nil)

  render_serialized(
    invite,
    InviteSerializer,
    scope: guardian,
    root: nil,
    show_emails: params.has_key?(:email),
    show_warnings: true,
  )
end

#showObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/controllers/invites_controller.rb', line 24

def show
  expires_now

  RateLimiter.new(nil, "invites-show-#{request.remote_ip}", 100, 1.minute).performed!

  invite = Invite.find_by(invite_key: params[:id])

  if invite.present? && invite.redeemable?
    show_invite(invite)
  else
    show_irredeemable_invite(invite)
  end
rescue RateLimiter::LimitExceeded => e
  flash.now[:error] = e.description
  render layout: "no_ember"
end

#updateObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'app/controllers/invites_controller.rb', line 187

def update
  invite = Invite.find_by(invited_by: current_user, id: params[:id])
  raise Discourse::InvalidParameters.new(:id) if invite.blank?

  if params[:topic_id].present?
    topic = Topic.find_by(id: params[:topic_id])
    raise Discourse::InvalidParameters.new(:topic_id) if topic.blank?
    guardian.ensure_can_invite_to!(topic)
  end

  if params[:group_ids].present? || params[:group_names].present?
    groups = Group.lookup_groups(group_ids: params[:group_ids], group_names: params[:group_names])
  end

  guardian.ensure_can_invite_to_forum!(groups)

  Invite.transaction do
    if params.has_key?(:topic_id)
      invite.topic_invites.destroy_all
      invite.topic_invites.create!(topic_id: topic.id) if topic.present?
    end

    if params.has_key?(:group_ids) || params.has_key?(:group_names)
      invite.invited_groups.destroy_all
      if groups.present?
        groups.each { |group| invite.invited_groups.find_or_create_by!(group_id: group.id) }
      end
    end

    if !groups_can_see_topic?(invite.groups, invite.topics.first)
      editable_topic_groups =
        invite.topics.first.category.groups.filter { |g| guardian.can_edit_group?(g) }
      return(
        render_json_error(
          I18n.t("invite.requires_groups", groups: editable_topic_groups.pluck(:name).join(", ")),
        )
      )
    end

    if params.has_key?(:email)
      old_email = invite.email.presence
      new_email = params[:email].presence

      if new_email
        if Invite
             .where.not(id: invite.id)
             .find_by(email: new_email.downcase, invited_by_id: current_user.id)
             &.redeemable?
          return(
            render_json_error(
              I18n.t("invite.invite_exists", email: CGI.escapeHTML(new_email)),
              status: 409,
            )
          )
        end
      end

      if old_email != new_email
        invite.emailed_status =
          if new_email && !params[:skip_email]
            Invite.emailed_status_types[:pending]
          else
            Invite.emailed_status_types[:not_required]
          end
      end

      invite.domain = nil if invite.email.present?
    end

    if params.has_key?(:domain)
      invite.domain = params[:domain]

      if invite.domain.present?
        invite.email = nil
        invite.emailed_status = Invite.emailed_status_types[:not_required]
      end
    end

    if params[:send_email]
      if invite.emailed_status != Invite.emailed_status_types[:pending]
        begin
          RateLimiter.new(current_user, "resend-invite-per-hour", 10, 1.hour).performed!
        rescue RateLimiter::LimitExceeded
          return render_json_error(I18n.t("rate_limiter.slow_down"))
        end
      end

      invite.emailed_status = Invite.emailed_status_types[:pending]
    end

    begin
      invite.update!(
        params.permit(:email, :custom_message, :max_redemptions_allowed, :expires_at),
      )
    rescue ActiveRecord::RecordInvalid => e
      return render_json_error(e.record.errors.full_messages.first)
    end
  end

  if invite.emailed_status == Invite.emailed_status_types[:pending]
    invite.update_column(:emailed_status, Invite.emailed_status_types[:sending])
    Jobs.enqueue(:invite_email, invite_id: invite.id, invite_to_topic: params[:invite_to_topic])
  end

  render_serialized(
    invite,
    InviteSerializer,
    scope: guardian,
    root: nil,
    show_emails: params.has_key?(:email),
    show_warnings: true,
  )
end

#upload_csvObject



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'app/controllers/invites_controller.rb', line 449

def upload_csv
  guardian.ensure_can_bulk_invite_to_forum!(current_user)

  hijack do
    begin
      file = params[:file] || params[:files].first

      csv_header = nil
      invites = []

      CSV.foreach(file.tempfile, encoding: "bom|utf-8") do |row|
        # Try to extract a CSV header, if it exists
        if csv_header.nil?
          if row[0] == "email"
            csv_header = row
            next
          else
            csv_header = %w[email groups topic_id]
          end
        end

        invites.push(csv_header.zip(row).map.to_h.filter { |k, v| v.present? }) if row[0].present?

        break if invites.count >= SiteSetting.max_bulk_invites
      end

      if invites.present?
        Jobs.enqueue(:bulk_invite, invites: invites, current_user_id: current_user.id)

        if invites.count >= SiteSetting.max_bulk_invites
          render json:
                   failed_json.merge(
                     errors: [
                       I18n.t(
                         "bulk_invite.max_rows",
                         max_bulk_invites: SiteSetting.max_bulk_invites,
                       ),
                     ],
                   ),
                 status: 422
        else
          render json: success_json
        end
      else
        render json: failed_json.merge(errors: [I18n.t("bulk_invite.error")]), status: 422
      end
    end
  end
end