Activate an existing user (validate their email confirmation)
191414
def activate():
    ''''''
    email = click.prompt('Email')
    user = User.objects(email=email).first()
    if not user:
        exit_with_error('Invalid user')
    if user.confirmed_at is not None:
        exit_with_error('User email address already confirmed')
        return
    user.confirmed_at = datetime.utcnow()
    user.save()
    success('User activated successfully')
715354
def send_email_confirmation_instructions(self, user):
        
        token = self.security_utils_service.generate_confirmation_token(user)
        confirmation_link = url_for('security_controller.confirm_email',
                                    token=token, _external=True)
        self.send_mail(
            _('flask_unchained.bundles.security:email_subject.email_confirmation_instructions'),
            to=user.email,
            template='security/email/email_confirmation_instructions.html',
            user=user,
            confirmation_link=confirmation_link)
        confirm_instructions_sent.send(app._get_current_object(), user=user,
                                       token=token)
226261
function user_confirm($username, $confirmsecret = null) {
        global $DB;

        $user = get_complete_user_data('username', $username);

        if (!empty($user)) {
            if ($user->confirmed) {
                return AUTH_CONFIRM_ALREADY;
            } else {
                $DB->set_field("user", "confirmed", 1, array("id"=>$user->id));
                return AUTH_CONFIRM_OK;
            }
        } else  {
            return AUTH_CONFIRM_ERROR;
        }
    }
189692
def send_activation_email(self, user, profile, password, site):
        
        ctx_dict = { 'password': password, 
                     'site': site, 
                     'activation_key': profile.activation_key,
                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS}
                     
        subject = render_to_string(
            'registration/email/emails/password_subject.txt',
            ctx_dict)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        
        message = render_to_string('registration/email/emails/password.txt',
                                   ctx_dict)
                                   
        try:
            user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
        except:
            pass
144407
public function emailAddSendVerify($email_id, $iUserId = null)
    {
        //  Fetch the email and the user's group
        $oDb = Factory::service('Database');
        $oDb->select(
            [
                $this->tableEmailAlias . '.id',
                $this->tableEmailAlias . '.code',
                $this->tableEmailAlias . '.is_verified',
                $this->tableEmailAlias . '.user_id',
                $this->tableAlias . '.group_id',
            ]
        );

        if (is_numeric($email_id)) {
            $oDb->where($this->tableEmailAlias . '.id', $email_id);
        } else {
            $oDb->where($this->tableEmailAlias . '.email', $email_id);
        }

        if (!empty($iUserId)) {
            $oDb->where($this->tableEmailAlias . '.user_id', $iUserId);
        }

        $oDb->join(
            $this->table . ' ' . $this->tableAlias,
            $this->tableAlias . '.id = ' . $this->tableEmailAlias . '.user_id'
        );

        $oEmailRow = $oDb->get($this->tableEmail . ' ' . $this->tableEmailAlias)->row();

        if (!$oEmailRow) {
            $this->setError('Invalid Email.');
            return false;
        }

        if ($oEmailRow->is_verified) {
            $this->setError('Email is already verified.');
            return false;
        }

        // --------------------------------------------------------------------------

        $oEmailer                = Factory::service('Emailer', 'nails/module-email');
        $oEmail                  = new \stdClass();
        $oEmail->type            = 'verify_email_' . $oEmailRow->group_id;
        $oEmail->to_id           = $oEmailRow->user_id;
        $oEmail->data            = new \stdClass();
        $oEmail->data->verifyUrl = site_url('email/verify/' . $oEmailRow->user_id . '/' . $oEmailRow->code);

        if (!$oEmailer->send($oEmail, true)) {

            //  Failed to send using the group email, try using the generic email template
            $oEmail->type = 'verify_email';

            if (!$oEmailer->send($oEmail, true)) {
                //  Email failed to send, for now, do nothing.
                $this->setError('The verification email failed to send.');
                return false;
            }
        }

        return true;
    }
255933
public function validateemailAction() {
        $this->view->title = __('activate email page title');
        $auth = Garp_Auth::getInstance();
        $authVars = $auth->getConfigValues();
        $request = $this->getRequest();
        $activationCode = $request->getParam('c');
        $activationEmail = $request->getParam('e');
        $emailValidColumn = $authVars['validateemail']['email_valid_column'];

        if (!$activationEmail || !$activationCode) {
            throw new Zend_Controller_Action_Exception('Invalid request.', 404);
        }

        $userModel = new Model_User();
        // always collect fresh data for this one
        $userModel->setCacheQueries(false);
        $activationCodeClause = 'MD5(CONCAT(' .
                $userModel->getAdapter()->quoteIdentifier(
                    $authVars['validateemail']['token_column']
                ) . ',' .
                'MD5(email),' .
                'MD5(' . $userModel->getAdapter()->quote($authVars['salt']) . '),' .
                'MD5(id)' .
            ')) = ?'
        ;
        $select = $userModel->select()
            // check if a user matches up to the given code
            ->where($activationCodeClause, $activationCode)
            // check if the given email address is part of the same user record
            ->where('MD5(email) = ?', $activationEmail);

        $user = $userModel->fetchRow($select);
        if (!$user) {
            $this->view->error = __('invalid email activation code');
        } else {
            $user->{$emailValidColumn} = 1;
            if (!$user->save()) {
                $this->view->error = __('activate email error');
            } elseif ($auth->isLoggedIn()) {
                // If the user is currently logged in, update the cookie
                $method = $auth->getStore()->method;
                $userData = $auth->getUserData();
                // Sanity check: is the user that has just validated his email address
                // the currently logged in user?
                if ($userData['id'] == $user->id) {
                    $userData[$emailValidColumn] = 1;
                    $auth->store($userData, $method);
                }
            }
            $this->view->user = $user;
        }
    }
1069746
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs):
    
    if user:
        return {'user': user}
    if not username:
        return None
    email = details.get('email')
    original_email = None
    # email is required
    if not email:
        message = _("""your social account needs to have a verified email address in order to proceed.""")
        raise AuthFailed(backend, message)
    # Avoid hitting field max length
    if email and len(email) > 75:
        original_email = email
        email = ''
    return {
        'user': UserSocialAuth.create_user(username=username,
                                           email=email,
                                           sync_emailaddress=False),
        'original_email': original_email,
        'is_new': True
    }
479394
protected function secureEmailChange() {
    $this->defaultEmailChange();
    /** @var Token $token */
    $token = Yii::createObject([
      'class' => Token::className(),
      'userId' => $this->user->id,
      'type' => Token::TYPE_CONFIRM_OLD_EMAIL,
    ]);
    $token->save(false);
    $this->mailer->sendReconfirmationMessage($this->user, $token);

    // unset flags if they exist
    $this->user->flags &= ~User::NEW_EMAIL_CONFIRMED;
    $this->user->flags &= ~User::OLD_EMAIL_CONFIRMED;
    $this->user->save(false);

    Yii::$app->session->setFlash('info', Yii::t('users', 'We have sent confirmation links to both old and new email addresses. You must click both links to complete your request'));
  }
760181
def create_user(email, password, active, confirmed_at, send_email):
    
    if confirmed_at == 'now':
        confirmed_at = security.datetime_factory()
    user = user_manager.create(email=email, password=password, active=active,
                               confirmed_at=confirmed_at)
    if click.confirm(f'Are you sure you want to create {user!r}?'):
        security_service.register_user(user, allow_login=False, send_email=send_email)
        user_manager.save(user, commit=True)
        click.echo(f'Successfully created {user!r}')
    else:
        click.echo('Cancelled.')
1030446
def verify_email(request, code, redirect_to=None):
    
    success = False

    valid_code = EmailConfirmation.is_valid(code)
    if valid_code:
        valid_code.activate()
        success = True

    if success:
        messages.success(request, SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT, 'success')
    else:
        messages.error(request, SIGNUP_VERIFY_EMAIL_ERROR_TEXT, 'danger error')

    if redirect_to is None:
        redirect_to = '/'

    return redirect(redirect_to)
162683
public function sendActivationMail($user)
    {
        if ($user->activated || !$this->shouldSend($user)) {
            return;
        }
        $userToken = $this->createActivation($user);
        //$userToken = User::find($user->id);
        $user->notify(new ConfirmEmailNotification($userToken));
    }
1041879
def register_user(self, data):
        
        error = False
        msg = ""

        email_re = re.compile(
            r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
            r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"'  # quoted-string
            r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE)  # domain

        # Check input format
        if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None:
            error = True
            msg = _("Invalid username format.")
        elif email_re.match(data["email"]) is None:
            error = True
            msg = _("Invalid email format.")
        elif len(data["passwd"]) < 6:
            error = True
            msg = _("Password too short.")
        elif data["passwd"] != data["passwd2"]:
            error = True
            msg = _("Passwords don't match !")

        if not error:
            existing_user = self.database.users.find_one({"$or": [{"username": data["username"]}, {"email": data["email"]}]})
            if existing_user is not None:
                error = True
                if existing_user["username"] == data["username"]:
                    msg = _("This username is already taken !")
                else:
                    msg = _("This email address is already in use !")
            else:
                passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest()
                activate_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest()
                self.database.users.insert({"username": data["username"],
                                            "realname": data["realname"],
                                            "email": data["email"],
                                            "password": passwd_hash,
                                            "activate": activate_hash,
                                            "bindings": {},
                                            "language": self.user_manager._session.get("language", "en")})
                try:
                    web.sendmail(web.config.smtp_sendername, data["email"], _("Welcome on INGInious"),
                                 _("""Welcome on INGInious !

To activate your account, please click on the following link :
""")
                                 + web.ctx.home + "/register?activate=" + activate_hash)
                    msg = _("You are succesfully registered. An email has been sent to you for activation.")
                except:
                    error = True
                    msg = _("Something went wrong while sending you activation email. Please contact the administrator.")

        return msg, error
616112
def activate_user(query):
    
    user = _query_to_user(query)
    if click.confirm(f'Are you sure you want to activate {user!r}?'):
        user.active = True
        user_manager.save(user, commit=True)
        click.echo(f'Successfully activated {user!r}')
    else:
        click.echo('Cancelled.')
74627
def user(context, name, email):
    """"""
    existing_user = context.obj['store'].user(email)
    if existing_user:
        click.echo(existing_user.to_dict())
    elif name:
        new_user = context.obj['store'].add_user(name, email)
        click.echo(click.style(f"New user added: {email} ({new_user.id})", fg='green'))
    else:
        click.echo(click.style('User not found', fg='yellow'))
1341806
def activate_users(self, request, queryset):
        
        n = 0
        for user in queryset:
            if not user.is_active:
                user.activate()
                n += 1
        self.message_user(
            request,
            _('Successfully activated %(count)d %(items)s.') %
            {'count': n, 'items': model_ngettext(self.opts, n)},  messages.SUCCESS)
1107950
def check_user(self, username, email):
        ''''''
        users = self.router.user
        avail = yield users.filter(username=username).count()
        if avail:
            raise FieldError('Username %s not available' % username)
        if email:
            avail = yield users.filter(email=email).count()
            if avail:
                raise FieldError('Email %s not available' % email)
425262
def require_email_confirmation(self):
        
        self.email_confirmed = False
        self.email_link = self.generate_hash(50)
        now = datetime.datetime.utcnow()
        self.email_link_expires = now + datetime.timedelta(hours=24)