discourse/app/models/invite.rb

88 lines
2.5 KiB
Ruby
Raw Normal View History

2013-02-06 03:16:51 +08:00
class Invite < ActiveRecord::Base
2013-02-07 23:45:24 +08:00
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 :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 :email
validates_presence_of :invited_by_id
acts_as_paranoid
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
before_create do
self.invite_key ||= SecureRandom.hex
end
before_save do
self.email = email.downcase
2013-02-06 03:16:51 +08:00
end
validate :user_doesnt_already_exist
attr_accessor :email_already_exists
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
def user_doesnt_already_exist
@email_already_exists = false
return if email.blank?
2013-02-07 23:45:24 +08:00
if User.where("lower(email) = ?", email.downcase).exists?
2013-02-06 03:16:51 +08:00
@email_already_exists = true
errors.add(:email)
end
end
def redeemed?
redeemed_at.present?
end
def expired?
created_at < SiteSetting.invite_expiry_days.days.ago
end
def redeem
result = nil
Invite.transaction do
# Avoid a race condition
2013-02-07 23:45:24 +08:00
row_count = Invite.update_all('redeemed_at = CURRENT_TIMESTAMP',
['id = ? AND redeemed_at IS NULL AND created_at >= ?', id, SiteSetting.invite_expiry_days.days.ago])
2013-02-06 03:16:51 +08:00
if row_count == 1
# Create the user if we are redeeming the invite and the user doesn't exist
result = User.where(email: email).first
result ||= User.create_for_email(email, trust_level: SiteSetting.default_invitee_trust_level)
2013-02-06 03:16:51 +08:00
result.send_welcome_message = false
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
# If there are topic invites for private topics
topics.private_messages.each do |t|
t.topic_allowed_users.create(user_id: result.id)
end
2013-02-07 23:45:24 +08:00
# Check for other invites by the same email. Don't redeem them, but approve their
2013-02-06 03:16:51 +08:00
# topics.
Invite.where('invites.email = ? and invites.id != ?', email, id).includes(:topics).where(topics: { archetype: Archetype::private_message }).each do |i|
2013-02-06 03:16:51 +08:00
i.topics.each do |t|
t.topic_allowed_users.create(user_id: result.id)
end
end
if Invite.update_all(['user_id = ?', result.id], ['email = ?', email]) == 1
2013-02-06 03:16:51 +08:00
result.send_welcome_message = true
end
# Notify the invitee
2013-03-01 20:07:44 +08:00
invited_by.notifications.create(notification_type: Notification.types[:invitee_accepted],
data: { display_username: result.username }.to_json)
2013-02-06 03:16:51 +08:00
else
# Otherwise return the existing user
result = User.where(email: email).first
end
2013-02-07 23:45:24 +08:00
end
2013-02-06 03:16:51 +08:00
result
end
end