To be used for invitation registration
516841
public function InsertForInvite($FormPostValues, $Options = array()) {
      $RoleIDs = Gdn::Config('Garden.Registration.DefaultRoles');
      if (!is_array($RoleIDs) || count($RoleIDs) == 0)
         throw new Exception(T('The default role has not been configured.'), 400);

      // Define the primary key in this model's table.
      $this->DefineSchema();

      // Add & apply any extra validation rules:
      $this->Validation->ApplyRule('Email', 'Email');

      // Make sure that the checkbox val for email is saved as the appropriate enum
      // TODO: DO I REALLY NEED THIS???
      if (array_key_exists('ShowEmail', $FormPostValues))
         $FormPostValues['ShowEmail'] = ForceBool($FormPostValues['ShowEmail'], '0', '1', '0');
      
      if (array_key_exists('Banned', $FormPostValues))
         $FormPostValues['Banned'] = ForceBool($FormPostValues['Banned'], '0', '1', '0');

      $this->AddInsertFields($FormPostValues);

      // Make sure that the user has a valid invitation code, and also grab
      // the user's email from the invitation:
      $InviteUserID = 0;
      $InviteUsername = '';
      $InvitationCode = ArrayValue('InvitationCode', $FormPostValues, '');
      $this->SQL->Select('i.InvitationID, i.InsertUserID, i.Email')
         ->Select('s.Name', '', 'SenderName')
         ->From('Invitation i')
         ->Join('User s', 'i.InsertUserID = s.UserID', 'left')
         ->Where('Code', $InvitationCode)
         ->Where('AcceptedUserID is null'); // Do not let them use the same invitation code twice!
      $InviteExpiration = Gdn::Config('Garden.Registration.InviteExpiration');
      if ($InviteExpiration != 'FALSE' && $InviteExpiration !== FALSE)
         $this->SQL->Where('i.DateInserted >=', Gdn_Format::ToDateTime(strtotime($InviteExpiration)));

      $Invitation = $this->SQL->Get()->FirstRow();
      if ($Invitation !== FALSE) {
         $InviteUserID = $Invitation->InsertUserID;
         $InviteUsername = $Invitation->SenderName;
         $FormPostValues['Email'] = $Invitation->Email;
      }
      if ($InviteUserID <= 0) {
         $this->Validation->AddValidationResult('InvitationCode', 'ErrorBadInvitationCode');
         return FALSE;
      }

      if ($this->Validate($FormPostValues, TRUE) === TRUE) {
         // Check for spam.
         $Spam = SpamModel::IsSpam('Registration', $FormPostValues);
         if ($Spam) {
            $this->Validation->AddValidationResult('Spam', 'You are not allowed to register at this time.');
            return;
         }

         $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above)
         $Username = ArrayValue('Name', $Fields);
         $Email = ArrayValue('Email', $Fields);
         $Fields = $this->Validation->SchemaValidationFields(); // Only fields that are present in the schema
         $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey);

         // Make sure the username & email aren't already being used
         if (!$this->ValidateUniqueFields($Username, $Email))
            return FALSE;

         // Define the other required fields:
         if ($InviteUserID > 0)
            $Fields['InviteUserID'] = $InviteUserID;


         // And insert the new user.
         if (!isset($Options['NoConfirmEmail']))
            $Options['NoConfirmEmail'] = TRUE;

         $Fields['Roles'] = $RoleIDs;
         $UserID = $this->_Insert($Fields, $Options);

         // Associate the new user id with the invitation (so it cannot be used again)
         $this->SQL
            ->Update('Invitation')
            ->Set('AcceptedUserID', $UserID)
            ->Where('InvitationID', $Invitation->InvitationID)
            ->Put();

         // Report that the user was created.
         $ActivityModel = new ActivityModel();
         $ActivityModel->Save(array(
             'ActivityUserID' => $UserID,
             'ActivityType' => 'Registration',
             'HeadlineFormat' => T('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'),
             'Story' => T('Welcome Aboard!')
             ),
             FALSE,
             array('GroupBy' => 'ActivityTypeID'));
      } else {
         $UserID = FALSE;
      }
      return $UserID;
   }
814695
async def register(self, request):
        """"""
        session = await get_session(request)
        user_id = session.get('user_id')
        if user_id:
            return redirect(request, 'timeline')

        error = None
        form = None
        if request.method == 'POST':
            form = await request.post()

            user_id = await db.get_user_id(self.mongo.user, form['username'])
            if not form['username']:
                error = 'You have to enter a username'
            elif not form['email'] or '@' not in form['email']:
                error = 'You have to enter a valid email address'
            elif not form['password']:
                error = 'You have to enter a password'
            elif form['password'] != form['password2']:
                error = 'The two passwords do not match'
            elif user_id is not None:
                error = 'The username is already taken'
            else:
                await self.mongo.user.insert(
                    {'username': form['username'],
                     'email': form['email'],
                     'pw_hash': generate_password_hash(form['password'])})
                return redirect(request, 'login')
        return {"error": error, "form": form}
35029
def invitation_instructions(user, token, opts = {})
      with_user(user) do
        @token = token
        @organization = user.organization
        @opts = opts

        opts[:subject] = I18n.t("devise.mailer.#{opts[:invitation_instructions]}.subject", organization: user.organization.name) if opts[:invitation_instructions]
      end

      devise_mail(user, opts[:invitation_instructions] || :invitation_instructions, opts)
    end
96560
def _send_invitation(self, enrollment, event):
        """"""

        self.log('Sending enrollment status mail to user')

        self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event)
1111593
public function postInviteUser()
    {
        try {
            execute(new InviteUserCommand(
                array_unique(array_filter((array) Binput::get('emails')))
            ));
        } catch (ValidationException $e) {
            return cachet_redirect('dashboard.team.invite')
                ->withInput(Binput::except('password'))
                ->withTitle(sprintf('%s %s', trans('dashboard.notifications.whoops'), trans('dashboard.team.invite.failure')))
                ->withErrors($e->getMessageBag());
        }

        return cachet_redirect('dashboard.team.invite')
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('dashboard.team.invite.success')));
    }
162082
def create
      new_invitation_id = super

      jss_me = ComputerInvitation.fetch(id: new_invitation_id, name: 'set_by_request')
      @name = jss_me.name
      @invitation_type = jss_me.invitation_type
      @create_account_if_does_not_exist = jss_me.create_account_if_does_not_exist
      @expiration_date_epoch = jss_me.expiration_date_epoch
      @ssh_username = jss_me.ssh_username
      @hide_account = jss_me.hide_account
      @invitation_status = jss_me.invitation_status
      @multiple_uses_allowed = jss_me.multiple_uses_allowed
    end
953837
def register():
    """"""

    if _security.confirmable or request.is_json:
        form_class = _security.confirm_register_form
    else:
        form_class = _security.register_form

    if request.is_json:
        form_data = MultiDict(request.get_json())
    else:
        form_data = request.form

    form = form_class(form_data)

    if form.validate_on_submit():
        user = register_user(**form.to_dict())
        form.user = user

        if not _security.confirmable or _security.login_without_confirmation:
            after_this_request(_commit)
            login_user(user)

        if not request.is_json:
            if 'next' in form:
                redirect_url = get_post_register_redirect(form.next.data)
            else:
                redirect_url = get_post_register_redirect()

            return redirect(redirect_url)
        return _render_json(form, include_auth_token=True)

    if request.is_json:
        return _render_json(form)

    return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
                                     register_user_form=form,
                                     **_ctx('register'))
134518
def register(self):
        
        user = {}

        print('--------------------------------------------------------------')
        print('Welcome to the user registration process.')
        print('--------------------------------------------------------------')
        print("To continue you must fill the following fields.")
        for attribute, value in self.attributes.items():

            is_required = attribute in self.required
            field_name = value['field_name']
            pattern = value['pattern']

            if attribute != 'password':
                user[attribute] = self.ask_question(field_name, pattern,
                                                    is_required)
            else:
                user[attribute] = self.ask_question(field_name, pattern,
                                                    password=True)

        return self._users_client.register(user)
285836
def on_invite(self, connection, event):
        
        sender = self.get_nick(event.source)
        invited = self.get_nick(event.target)
        channel = event.arguments[0]

        if invited == self._nickname:
            logging.info("! I am invited to %s by %s", channel, sender)
            connection.join(channel)

        else:
            logging.info(">> %s invited %s to %s", sender, invited, channel)
1031587
def send_invite    
      return if self.email.blank?
      
      application = self.applicant_answer_sheet
      
      Notifier.deliver_notification(self.email,
                                    application.email, 
                                    "Reference Invite", 
                                    {'reference_full_name' => self.name, 
                                     'applicant_full_name' => application.name,
                                     'applicant_email' => application.email, 
                                     'applicant_home_phone' => application.phone, 
                                     'reference_url' => edit_reference_sheet_url(self, :a => self.access_key, :host => ActionMailer::Base.default_url_options[:host])})
      # Send notification to applicant
      Notifier.deliver_notification(applicant_answer_sheet.email, # RECIPIENTS
                                    Questionnaire.from_email, # FROM
                                    "Reference Notification to Applicant", # LIQUID TEMPLATE NAME
                                    {'applicant_full_name' => applicant_answer_sheet.name,
                                     'reference_full_name' => self.name,
                                     'reference_email' => self.email,
                                     'application_url' => edit_answer_sheet_url(applicant_answer_sheet, :host => ActionMailer::Base.default_url_options[:host])})

      self.email_sent_at = Time.now
      self.save(:validate => false)
      
      true
    end
1331914
def accept(self, event):
        """"""

        self.log('Invitation accepted:', event.__dict__, lvl=debug)
        try:
            uuid = event.data
            enrollment = objectmodels['enrollment'].find_one({
                'uuid': uuid
            })

            if enrollment is not None:
                self.log('Enrollment found', lvl=debug)
                if enrollment.status == 'Open':
                    self.log('Enrollment is still open', lvl=debug)
                    if enrollment.method == 'Invited' and self.config.auto_accept_invited:
                        enrollment.status = 'Accepted'

                        data = 'You should have received an email with your new password ' \
                               'and can now log in to the system and start to use it. <br/>' \
                               'Please change your password immediately after logging in'
                        password = std_human_uid().replace(" ", '')

                        self._create_user(enrollment.name, password, enrollment.email, enrollment.method, uuid)
                        self._send_acceptance(enrollment, password, event)
                    elif enrollment.method == 'Enrolled' and self.config.auto_accept_enrolled:
                        enrollment.status = 'Accepted'
                        data = 'Your account is now activated.'

                        self._create_user(enrollment.name, enrollment.password, enrollment.email, enrollment.method,
                                          uuid)

                        # TODO: Evaluate if sending an acceptance mail makes sense
                        # self._send_acceptance(enrollment, "", event)
                    else:
                        enrollment.status = 'Pending'
                        data = 'Someone has to confirm your enrollment ' \
                               'first. Thank you, for your patience.'
                        # TODO: Alert admin users
                    enrollment.save()

                # Reaffirm acceptance to end user, when clicking on the link multiple times
                elif enrollment.status == 'Accepted':
                    data = 'You can now log in to the system and start to use it.'
                elif enrollment.status == 'Pending':
                    data = 'Someone has to confirm your enrollment ' \
                           'first. Thank you, for your patience.'
                else:
                    self.log('Enrollment has been closed already!', lvl=warn)
                    self._fail(event)
                    return
                packet = {
                    'component': 'hfos.enrol.enrolmanager',
                    'action': 'accept',
                    'data': {True: data}
                }
                self.fireEvent(send(event.client.uuid, packet))
            else:
                self.log('No enrollment available.', lvl=warn)
                self._fail(event)
        except Exception as e:
            self.log('Error during invitation accept handling:', e, type(e),
                     lvl=warn, exc=True)
1106341
def invite(invite)
      code = resolve_invite_code(invite)
      Invite.new(JSON.parse(API::Invite.resolve(token, code)), self)
    end
636375
def _handle_invite(self, room_id: _RoomID, state: dict):
        
        if self._stop_event.ready():
            return

        self.log.debug('Got invite', room_id=room_id)
        invite_events = [
            event
            for event in state['events']
            if event['type'] == 'm.room.member' and
            event['content'].get('membership') == 'invite' and
            event['state_key'] == self._user_id
        ]
        if not invite_events:
            self.log.debug('Invite: no invite event found', room_id=room_id)
            return  # there should always be one and only one invite membership event for us
        invite_event = invite_events[0]
        sender = invite_event['sender']

        sender_join_events = [
            event
            for event in state['events']
            if event['type'] == 'm.room.member' and
            event['content'].get('membership') == 'join' and
            event['state_key'] == sender
        ]
        if not sender_join_events:
            self.log.debug('Invite: no sender join event', room_id=room_id)
            return  # there should always be one and only one join membership event for the sender
        sender_join_event = sender_join_events[0]

        user = self._get_user(sender)
        user.displayname = sender_join_event['content'].get('displayname') or user.displayname
        peer_address = validate_userid_signature(user)
        if not peer_address:
            self.log.debug(
                'Got invited to a room by invalid signed user - ignoring',
                room_id=room_id,
                user=user,
            )
            return

        if not self._address_mgr.is_address_known(peer_address):
            self.log.debug(
                'Got invited by a non-whitelisted user - ignoring',
                room_id=room_id,
                user=user,
            )
            return

        join_rules_events = [
            event
            for event in state['events']
            if event['type'] == 'm.room.join_rules'
        ]

        # room privacy as seen from the event
        private_room: bool = False
        if join_rules_events:
            join_rules_event = join_rules_events[0]
            private_room = join_rules_event['content'].get('join_rule') == 'invite'

        # we join room and _set_room_id_for_address despite room privacy and requirements,
        # _get_room_ids_for_address will take care of returning only matching rooms and
        # _leave_unused_rooms will clear it in the future, if and when needed
        room: Room = None
        last_ex: Optional[Exception] = None
        retry_interval = 0.1
        for _ in range(JOIN_RETRIES):
            try:
                room = self._client.join_room(room_id)
            except MatrixRequestError as e:
                last_ex = e
                if self._stop_event.wait(retry_interval):
                    break
                retry_interval = retry_interval * 2
            else:
                break
        else:
            assert last_ex is not None
            raise last_ex  # re-raise if couldn't succeed in retries

        if not room.listeners:
            room.add_listener(self._handle_message, 'm.room.message')

        # room state may not populated yet, so we populate 'invite_only' from event
        room.invite_only = private_room

        self._set_room_id_for_address(address=peer_address, room_id=room_id)

        self.log.debug(
            'Joined from invite',
            room_id=room_id,
            aliases=room.aliases,
            peer=to_checksum_address(peer_address),
        )
1026682
def channels_invite(self, room_id, user_id, **kwargs):
        """"""
        return self.__call_api_post('channels.invite', roomId=room_id, userId=user_id, kwargs=kwargs)
145396
def send_invite_user_email(self, user, user_invitation):
        """"""

        # Verify config settings
        if not self.user_manager.USER_ENABLE_EMAIL: return
        if not self.user_manager.USER_ENABLE_INVITE_USER: return

        # The user param points to the inviter
        # The user_invitation param points to the invitee
        invited_by_user = user

        # Use the invitation email
        email = user_invitation.email

        # Create a dummy user object to an empty name for the invitee
        user = self.user_manager.db_manager.UserClass(email=email)

        # Generate a accept_invitation_link
        token = self.user_manager.generate_token(user_invitation.id)
        accept_invitation_link = url_for('user.register', token=token, _external=True)

        # Render email from templates and send it via the configured EmailAdapter
        self._render_and_send_email(
            email,
            user,
            self.user_manager.USER_INVITE_USER_EMAIL_TEMPLATE,
            accept_invitation_link=accept_invitation_link,
            invited_by_user=invited_by_user,
        )
554694
def invited_by?(user)
      user.friend_ids.include?(self.id) or user.pending_friend_ids.include?(self.id)
    end
873781
def accept_invitation(self, invitation):
        
        assert isinstance(invitation, github.Invitation.Invitation) or isinstance(invitation, int)

        if isinstance(invitation, github.Invitation.Invitation):
            invitation = invitation.id

        headers, data = self._requester.requestJsonAndCheck(
            "PATCH",
            "/user/repository_invitations/" + str(invitation),
            input={}
        )