Last active
December 17, 2015 23:18
-
-
Save bplexico/5687809 to your computer and use it in GitHub Desktop.
after invited_user introduced
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
InviteRedeemer = Struct.new(:invite) do | |
def redeem | |
result = invited_user | |
Invite.transaction do | |
if mark_invite_redeemed == 1 | |
# Create the user if we are redeeming the invite and the user doesn't exist | |
result = create_user_if_missing | |
# If there are topic invites for private topics | |
allow_access_to_private_topics | |
# Check for other invites by the same email. Don't redeem them, but approve their | |
# topics. | |
approve_topic_invitations | |
send_welcome_message | |
# Notify the invitee | |
notify_invitee | |
end | |
end | |
result | |
end | |
#private | |
def invited_user | |
@invited_user ||= get_existing_user | |
end | |
def mark_invite_redeemed | |
# Avoid a race condition | |
# Return true if 1 row was updated | |
Invite.update_all('redeemed_at = CURRENT_TIMESTAMP', | |
['id = ? AND redeemed_at IS NULL AND created_at >= ?', | |
invite.id, | |
SiteSetting.invite_expiry_days.days.ago]) | |
end | |
def create_user_if_missing | |
result = invited_user | |
result ||= User.create_for_email(invite.email, trust_level: SiteSetting.default_invitee_trust_level) | |
result.send_welcome_message = false | |
result | |
end | |
def get_existing_user | |
User.where(email: invite.email).first | |
end | |
def allow_access_to_private_topics | |
invite.topics.private_messages.each do |t| | |
t.topic_allowed_users.create(user_id: invited_user.id) | |
end | |
end | |
def approve_topic_invitations | |
Invite.where('invites.email = ? and invites.id != ?', invite.email, invite.id).includes(:topics).where(topics: {archetype: Archetype::private_message}).each do |i| | |
i.topics.each do |t| | |
t.topic_allowed_users.create(user_id: invited_user.id) | |
end | |
end | |
end | |
def send_welcome_message(result) | |
if Invite.update_all(['user_id = ?', result.id], ['email = ?', invite.email]) == 1 | |
result.send_welcome_message = true | |
end | |
end | |
def notify_invitee | |
invite.invited_by.notifications.create(notification_type: Notification.types[:invitee_accepted], | |
data: {display_username: invited_user.username}.to_json) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment