discourse/app/models/invite.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

294 lines
8.6 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2013-02-06 03:16:51 +08:00
class Invite < ActiveRecord::Base
class UserExists < StandardError; end
include RateLimiter::OnCreateRecord
include Trashable
2013-02-07 23:45:24 +08:00
# TODO(2021-05-22): remove
self.ignored_columns = %w{
user_id
redeemed_at
}
BULK_INVITE_EMAIL_LIMIT = 200
rate_limit :limit_invites_per_day
2013-02-06 03:16:51 +08:00
belongs_to :user
belongs_to :topic
belongs_to :invited_by, class_name: 'User'
2013-02-06 03:16:51 +08:00
has_many :invited_users
has_many :users, through: :invited_users
has_many :invited_groups
has_many :groups, through: :invited_groups
2013-02-06 03:16:51 +08:00
has_many :topic_invites
2013-02-07 23:45:24 +08:00
has_many :topics, through: :topic_invites, source: :topic
2013-02-06 03:16:51 +08:00
validates_presence_of :invited_by_id
validates :email, email: true, allow_blank: true
validate :ensure_max_redemptions_allowed
validate :user_doesnt_already_exist
validate :ensure_no_invalid_email_invites
2013-02-06 03:16:51 +08:00
before_create do
self.invite_key ||= SecureRandom.hex
self.expires_at ||= SiteSetting.invite_expiry_days.days.from_now
2013-02-06 03:16:51 +08:00
end
2014-07-14 23:56:26 +08:00
before_validation do
self.email = Email.downcase(email) unless email.nil?
2013-02-06 03:16:51 +08:00
end
attr_accessor :email_already_exists
2013-02-07 23:45:24 +08:00
def self.emailed_status_types
@emailed_status_types ||= Enum.new(not_required: 0, pending: 1, bulk_pending: 2, sending: 3, sent: 4)
end
2013-02-06 03:16:51 +08:00
def user_doesnt_already_exist
@email_already_exists = false
return if email.blank?
user = Invite.find_user_by_email(email)
if user && user.id != self.invited_users&.first&.user_id
2013-02-06 03:16:51 +08:00
@email_already_exists = true
errors.add(:email, I18n.t(
"invite.user_exists",
email: email,
username: user.username,
base_path: Discourse.base_path
))
2013-02-06 03:16:51 +08:00
end
end
def is_invite_link?
email.blank?
end
2013-02-06 03:16:51 +08:00
def redeemed?
if is_invite_link?
redemption_count >= max_redemptions_allowed
else
self.invited_users.count > 0
end
2013-02-06 03:16:51 +08:00
end
def expired?
expires_at < Time.zone.now
2013-02-06 03:16:51 +08:00
end
def link
"#{Discourse.base_url}/invites/#{invite_key}"
end
def link_valid?
invalidated_at.nil?
end
def self.generate(invited_by, opts = nil)
opts ||= {}
email = Email.downcase(opts[:email]) if opts[:email].present?
2014-05-09 09:45:18 +08:00
if user = find_user_by_email(email)
raise UserExists.new(I18n.t(
"invite.user_exists",
email: email,
username: user.username,
base_path: Discourse.base_path
))
2014-05-09 09:45:18 +08:00
end
if email.present?
invite = Invite
.with_deleted
.where(email: email, invited_by_id: invited_by.id)
.order('created_at DESC')
.first
if invite && (invite.expired? || invite.deleted_at)
invite.destroy
invite = nil
end
end
emailed_status = if opts[:skip_email] || invite&.emailed_status == emailed_status_types[:not_required]
emailed_status_types[:not_required]
elsif opts[:emailed_status].present?
opts[:emailed_status]
elsif email.present?
emailed_status_types[:pending]
else
emailed_status_types[:not_required]
end
if invite
invite.update_columns(
created_at: Time.zone.now,
updated_at: Time.zone.now,
expires_at: opts[:expires_at] || SiteSetting.invite_expiry_days.days.from_now,
emailed_status: emailed_status
)
else
create_args = opts.slice(:email, :moderator, :custom_message, :max_redemptions_allowed)
create_args[:invited_by] = invited_by
create_args[:email] = email
create_args[:emailed_status] = emailed_status
create_args[:expires_at] = opts[:expires_at] || SiteSetting.invite_expiry_days.days.from_now
invite = Invite.create!(create_args)
end
topic_id = opts[:topic]&.id || opts[:topic_id]
if topic_id.present?
invite.topic_invites.find_or_create_by!(topic_id: topic_id)
2014-05-09 09:45:18 +08:00
end
group_ids = opts[:group_ids]
2014-05-09 09:45:18 +08:00
if group_ids.present?
group_ids.each do |group_id|
invite.invited_groups.find_or_create_by!(group_id: group_id)
2014-05-09 09:45:18 +08:00
end
end
if emailed_status == emailed_status_types[:pending]
invite.update_column(:emailed_status, emailed_status_types[:sending])
Jobs.enqueue(:invite_email, invite_id: invite.id, invite_to_topic: opts[:invite_to_topic])
end
2014-05-09 09:45:18 +08:00
invite.reload
end
def redeem(email: nil, username: nil, name: nil, password: nil, user_custom_fields: nil, ip_address: nil, session: nil)
if !expired? && !destroyed? && link_valid?
raise UserExists.new I18n.t("invite_link.email_taken") if is_invite_link? && UserEmail.exists?(email: email)
email = self.email if email.blank? && !is_invite_link?
InviteRedeemer.new(
invite: self,
email: email,
username: username,
name: name,
password: password,
user_custom_fields: user_custom_fields,
ip_address: ip_address,
session: session
).redeem
end
end
def self.redeem_from_email(email)
invite = Invite.find_by(email: Email.downcase(email))
InviteRedeemer.new(invite: invite, email: invite.email).redeem if invite
invite
end
def self.find_user_by_email(email)
User.with_email(Email.downcase(email)).where(staged: false).first
end
def self.pending(inviter)
Invite.distinct
.joins("LEFT JOIN invited_users ON invites.id = invited_users.invite_id")
.joins("LEFT JOIN users ON invited_users.user_id = users.id")
.where(invited_by_id: inviter.id)
.where('redemption_count < max_redemptions_allowed')
.where('expires_at > ?', Time.zone.now)
.order('invites.updated_at DESC')
end
def self.expired(inviter)
Invite.distinct
.joins("LEFT JOIN invited_users ON invites.id = invited_users.invite_id")
.joins("LEFT JOIN users ON invited_users.user_id = users.id")
.where(invited_by_id: inviter.id)
.where('redemption_count > max_redemptions_allowed OR expires_at < ?', Time.zone.now)
.order('invites.expires_at ASC')
end
def self.redeemed_users(inviter)
InvitedUser
.joins("LEFT JOIN invites ON invites.id = invited_users.invite_id")
.includes(user: :user_stat)
.where('invited_users.user_id IS NOT NULL')
.where('invites.invited_by_id = ?', inviter.id)
.order('invited_users.redeemed_at DESC')
.references('invite')
.references('user')
.references('user_stat')
end
def self.invalidate_for_email(email)
i = Invite.find_by(email: Email.downcase(email))
if i
i.invalidated_at = Time.zone.now
i.save
end
i
end
2014-05-28 04:14:37 +08:00
2014-10-07 02:48:56 +08:00
def resend_invite
self.update_columns(updated_at: Time.zone.now, invalidated_at: nil, expires_at: SiteSetting.invite_expiry_days.days.from_now)
2014-10-07 02:48:56 +08:00
Jobs.enqueue(:invite_email, invite_id: self.id)
end
def limit_invites_per_day
RateLimiter.new(invited_by, "invites-per-day", SiteSetting.max_invites_per_day, 1.day.to_i)
end
2014-05-28 04:14:37 +08:00
def self.base_directory
File.join(Rails.root, "public", "uploads", "csv", RailsMultisite::ConnectionManagement.current_db)
2014-05-28 04:14:37 +08:00
end
def ensure_max_redemptions_allowed
if self.max_redemptions_allowed.nil?
self.max_redemptions_allowed = 1
else
limit = invited_by&.staff? ? SiteSetting.invite_link_max_redemptions_limit
: SiteSetting.invite_link_max_redemptions_limit_users
if !self.max_redemptions_allowed.between?(1, limit)
errors.add(:max_redemptions_allowed, I18n.t("invite_link.max_redemptions_limit", max_limit: limit))
end
end
end
def ensure_no_invalid_email_invites
return if email.blank?
if SiteSetting.enable_discourse_connect?
FEATURE: Rename 'Discourse SSO' to DiscourseConnect (#11978) The 'Discourse SSO' protocol is being rebranded to DiscourseConnect. This should help to reduce confusion when 'SSO' is used in the generic sense. This commit aims to: - Rename `sso_` site settings. DiscourseConnect specific ones are prefixed `discourse_connect_`. Generic settings are prefixed `auth_` - Add (server-side-only) backwards compatibility for the old setting names, with deprecation notices - Copy `site_settings` database records to the new names - Rename relevant translation keys - Update relevant translations This commit does **not** aim to: - Rename any Ruby classes or methods. This might be done in a future commit - Change any URLs. This would break existing integrations - Make any changes to the protocol. This would break existing integrations - Change any functionality. Further normalization across DiscourseConnect and other auth methods will be done separately The risks are: - There is no backwards compatibility for site settings on the client-side. Accessing auth-related site settings in Javascript is fairly rare, and an error on the client side would not be security-critical. - If a plugin is monkey-patching parts of the auth process, changes to locale keys could cause broken error messages. This should also be unlikely. The old site setting names remain functional, so security-related overrides will remain working. A follow-up commit will be made with a post-deploy migration to delete the old `site_settings` rows.
2021-02-08 18:04:33 +08:00
errors.add(:email, I18n.t("invite.disabled_errors.discourse_connect_enabled"))
end
end
2013-02-06 03:16:51 +08:00
end
# == Schema Information
#
# Table name: invites
#
# id :integer not null, primary key
# invite_key :string(32) not null
# email :string
# invited_by_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# deleted_at :datetime
# deleted_by_id :integer
# invalidated_at :datetime
# moderator :boolean default(FALSE), not null
# custom_message :text
# emailed_status :integer
# max_redemptions_allowed :integer default(1), not null
# redemption_count :integer default(0), not null
# expires_at :datetime not null
#
# Indexes
#
# index_invites_on_email_and_invited_by_id (email,invited_by_id)
# index_invites_on_emailed_status (emailed_status)
# index_invites_on_invite_key (invite_key) UNIQUE
2019-12-30 14:13:27 +08:00
# index_invites_on_invited_by_id (invited_by_id)
#