регистрация пользователя через форму консольной регистрации
@param SignUpFormConsole $sign_up_form_console
@return bool
@throws \yii\db\Exception
@throws \yii\web\ServerErrorHttpException
339121
public function createFromConsole(SignUpFormConsole $sign_up_form_console): bool
    {
        return (new actions\CreateFromConsole($this->user, null, null, $sign_up_form_console))->execute();
    }
1350572
public function signup()
    {
        //Checks if signup is enabled
        if (!getConfig('users.signup')) {
            $this->Flash->error(I18N_DISABLED);

            return $this->redirect(['_name' => 'homepage']);
        }

        $user = $this->Users->newEntity();

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());

            $user->group_id = getConfigOrFail('users.default_group');
            $user->active = (bool)!getConfig('users.activation');

            //Checks for reCAPTCHA, if requested
            if (!getConfig('security.recaptcha') || $this->Recaptcha->verify()) {
                if ($this->Users->save($user)) {
                    switch (getConfig('users.activation')) {
                        //The account will be enabled by an administrator
                        case 2:
                            $this->Flash->success(__d('me_cms', 'Account created, but it needs to be activated by an admin'));
                            break;
                        //The account will be enabled by the user via email
                        //  (default)
                        case 1:
                            //Sends the activation mail
                            $this->sendActivationMail($user);

                            $this->Flash->success(__d('me_cms', 'We send you an email to activate your account'));
                            break;
                        //No activation required, the account is immediately active
                        default:
                            $this->Flash->success(__d('me_cms', 'Account created. Now you can login'));
                            break;
                    }

                    return $this->redirect(['_name' => 'homepage']);
                }

                $this->Flash->error(__d('me_cms', 'The account has not been created'));
            } else {
                $this->Flash->error(__d('me_cms', 'You must fill in the {0} control correctly', 'reCAPTCHA'));
            }
        }

        $this->set(compact('user'));
        $this->viewBuilder()->setLayout('login');
    }
63889
async function connectUser(form) {
  if (!form.login.value || !form.password.value) {
    document.getElementById('login-errors').innerHTML += `<p>Login and password are required</p>`;
    return;
  }

  await client.setCredentials({ login: form.login.value, password: form.password.value });
  client
    .connect()
    .then(() => {
      displayMessage('Login success', 'Welcome to wonderful service', 'is-success');
      goTo('home');
    })
    .catch((e) => {
      displayMessage(
        'Login failed',
        'Your account is not validated, have you clicked on the link in the email ?',
        'is-warning'
      );
    });
}
490599
public function signup()
    {
        if (!$this->validate()) {
            return null;
        }

        $this->user = new UserModel();
        $this->user->setAttributes($this->attributes);
        $this->user->setPassword($this->password);
        $this->user->setLastLogin(time());
        $this->user->generateAuthKey();

        return $this->user->save() ? $this->user : null;
    }
1336752
public function signupAction()
    {
        $form = new SignUpForm();

        if ($this->request->isPost()) {

            if ($form->isValid($this->request->getPost()) != false) {

                $user = new Users([
                    'name' => $this->request->getPost('name', 'striptags'),
                    'email' => $this->request->getPost('email'),
                    'password' => $this->security->hash($this->request->getPost('password')),
                    'profilesId' => 2
                ]);

                if ($user->save()) {
//                    return $this->dispatcher->forward([
//                        'namespace' => 'Modules\Frontend\Controllers',
//                        'controller' => 'index',
//                        'action' => 'index'
//                    ]);
                    return $this->response->redirect('index');
                }

                $this->flash->error($user->getMessages());
            }
        }

        $this->view->form = $form;
    }
945308
public function insertModel(): bool
    {
        $this->getFromForm();
        if (!$this->insert()) {
            throw new Exception(\Yii::t('app', 'Ошибка при добавлении в БД'));
        }
        return true;
    }
493732
def signup(request, **kwargs):
    
    if not ALLAUTH:
        return http.HttpResponse(_('allauth not installed...'))
    if request.method == "POST" and 'login' in request.POST:
        form_class = LoginForm
        form = form_class(request.POST)
        redirect_field_name = "next"
        success_url = get_default_redirect(request, redirect_field_name)
        if form.is_valid():
            return form.login(request, redirect_url=success_url)
    response = allauth_signup(request, **kwargs)
    return response
1124723
def signup_handler(remote, *args, **kwargs):
    
    # User already authenticated so move on
    if current_user.is_authenticated:
        return redirect('/')

    # Retrieve token from session
    oauth_token = token_getter(remote)
    if not oauth_token:
        return redirect('/')

    session_prefix = token_session_key(remote.name)

    # Test to see if this is coming from on authorized request
    if not session.get(session_prefix + '_autoregister', False):
        return redirect(url_for('.login', remote_app=remote.name))

    form = create_registrationform(request.form)

    if form.validate_on_submit():
        account_info = session.get(session_prefix + '_account_info')
        response = session.get(session_prefix + '_response')

        # Register user
        user = oauth_register(form)

        if user is None:
            raise OAuthError('Could not create user.', remote)

        # Remove session key
        session.pop(session_prefix + '_autoregister', None)

        # Link account and set session data
        token = token_setter(remote, oauth_token[0], secret=oauth_token[1],
                             user=user)
        handlers = current_oauthclient.signup_handlers[remote.name]

        if token is None:
            raise OAuthError('Could not create token for user.', remote)

        if not token.remote_account.extra_data:
            account_setup = handlers['setup'](token, response)
            account_setup_received.send(
                remote, token=token, response=response,
                account_setup=account_setup
            )
            # Registration has been finished
            db.session.commit()
            account_setup_committed.send(remote, token=token)
        else:
            # Registration has been finished
            db.session.commit()

        # Authenticate the user
        if not oauth_authenticate(remote.consumer_key, user,
                                  require_existing_link=False):
            # Redirect the user after registration (which doesn't include the
            # activation), waiting for user to confirm his email.
            return redirect(url_for('security.login'))

        # Remove account info from session
        session.pop(session_prefix + '_account_info', None)
        session.pop(session_prefix + '_response', None)

        # Redirect to next
        next_url = get_session_next_url(remote.name)
        if next_url:
            return redirect(next_url)
        else:
            return redirect('/')

    # Pre-fill form
    account_info = session.get(session_prefix + '_account_info')
    if not form.is_submitted():
        form = fill_form(form, account_info['user'])

    return render_template(
        current_app.config['OAUTHCLIENT_SIGNUP_TEMPLATE'],
        form=form,
        remote=remote,
        app_title=current_app.config['OAUTHCLIENT_REMOTE_APPS'][
            remote.name].get('title', ''),
        app_description=current_app.config['OAUTHCLIENT_REMOTE_APPS'][
            remote.name].get('description', ''),
        app_icon=current_app.config['OAUTHCLIENT_REMOTE_APPS'][
            remote.name].get('icon', None),
    )
1276975
public static function signup($user_id, $info) {
	if (empty($info['github_username']) || empty($info['oauth_token']) || empty($info['scope'])) {
		$exception = bootstrap::get_library('exception');
		throw new $exception('all info from ::is_valid() is needed for signup');
	}
	
	$mysql = bootstrap::get_library('mysql');
	
	$sql = "INSERT INTO `login_github` SET
		`user_id` = %d,
		`github_username` = '%s',
		`oauth_token` = '%s',
		`scope` = '%s'
	;";
	$binds = [$user_id, $info['github_username'], $info['oauth_token'], $info['scope']];
	$mysql::query($sql, $binds);
	
	return new static($mysql::$insert_id);
}
155518
public function login(?FormInterface $form = null)
    {
        if (!$form) {
            throw new \RuntimeException('This provider require a form');
        }

        $url = $this->config['login']['url'] ?? null;
        if ($this->router->getRouteCollection()->get($url)) {
            $url = $this->router->generate($url, [], Router::ABSOLUTE_URL);
        }

        $opts = [
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => [],
        ];

        $paramsIn = $this->config['login']['parameters_in'] ?? 'form';
        if ('header' === $paramsIn) {
            $opts[CURLOPT_HEADER] = true;
            $headers = [];
            foreach ($form->getData() as $key => $value) {
                $headers[] = sprintf('%s: %s', $key, $value);
            }
            $opts[CURLOPT_HTTPHEADER] = array_merge(["Accept: application/json"], $headers);
        } elseif ('query' === $paramsIn) {
            $url .= '?'.http_build_query($form->getData(), null, '&');
        } else {
            $opts[CURLOPT_POSTFIELDS] = http_build_query($form->getData(), null, '&');
            $opts[CURLOPT_POST] = true;
        }

        $opts[CURLOPT_URL] = $url;

        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result = curl_exec($ch);

        // Split the HTTP response into header and body.
        try {
            list($headers, $body) = explode("\r\n\r\n", $result);
            $headers = explode("\r\n", $headers);
        } catch (\ErrorException $exception) {
            throw new AuthenticationFailedException('Authentication Failed');
        }

        // We catch HTTP/1.1 4xx or HTTP/1.1 5xx error response.
        if (strpos($headers[0], 'HTTP/1.1 4') !== false || strpos($headers[0], 'HTTP/1.1 5') !== false) {
            $result = [
                'code' => 0,
                'message' => '',
            ];

            if (preg_match('/^HTTP\/1.1 ([0-9]{3,3}) (.*)$/', $headers[0], $matches)) {
                $result['code'] = $matches[1];
                $result['message'] = $matches[2];
            }

            // In case retrun with WWW-Authenticate replace the description.
            foreach ($headers as $header) {
                if (preg_match("/^WWW-Authenticate:.*error='(.*)'/", $header, $matches)) {
                    $result['message'] = $matches[1];
                }
            }

            throw new AuthenticationFailedException($result['message'] ?: 'Authentication Failed', $result['code'] ?: 401);
        }

        $tokenPath = $this->config['login']['response_token_path'] ?? 'token';
        $token = $body;

        if ($tokenPath) {
            $token = search($tokenPath, @json_decode($body));
        }

        if (!$token) {
            throw new AuthenticationFailedException('Authentication Failed');
        }

        $this->session->set(self::SESSION_PATH, $token);
    }
694512
function save ($commit = true)
    {
        if (! $this->isValid()) {
            throw new Exception(
                    __('Cannot save the model from an invalid form.'));
        }
        return Pluf::f('url_base') . Pluf_HTTP_URL_urlForView(
                'IDF_Views_User::changeEmailDo', 
                array(
                        $this->cleaned_data['key']
                ));
    }
328307
protected function createComponentSignInForm()
    {
        $form = new Form();
        $form->setRenderer(new BootstrapRenderer());
        $form->addProtection();
        $form->addText('username', $this->translator->translate('users.frontend.sign_in.username.label'))
            ->setType('email')
            ->setAttribute('autofocus')
            ->setRequired($this->translator->translate('users.frontend.sign_in.username.required'))
            ->setAttribute('placeholder', $this->translator->translate('users.frontend.sign_in.username.placeholder'));

        $form->addPassword('password', $this->translator->translate('users.frontend.sign_in.password.label'))
            ->setRequired($this->translator->translate('users.frontend.sign_in.password.required'))
            ->setAttribute('placeholder', $this->translator->translate('users.frontend.sign_in.password.required'));

        $form->addCheckbox('remember', $this->translator->translate('users.frontend.sign_in.remember'));

        $form->addSubmit('send', $this->translator->translate('users.frontend.sign_in.submit'));

        $form->setDefaults([
            'remember' => true,
        ]);

        $form->onSuccess[] = [$this, 'signInFormSucceeded'];
        return $form;
    }
956399
public function buildForm(array $form, FormStateInterface $form_state, $token = null)
    {
        if ($token === null) {
            return [];
        }

        /* @var Token $token */
        $token = $this->tokenManager->loadToken($token);
        if ($token === null) {
            drupal_set_message(
                $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
            return [];
        }

        $currentUser = $this->currentUser();
        $userStorage = $this->entityManager->getStorage('user');

        if ($currentUser->id()) {
            // The existing user is already logged in.
            if ($currentUser->id() == $token->uid) {
                drupal_set_message($this->t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', [
                    '%user' => $currentUser->getAccountName(),
                    '!user_edit' => url('user/password'),
                ]));
            }
            // A different user is already logged in on the computer.
            else {
                /* @var UserInterface $user */
                $tokenUser = $userStorage->load($token->uid);

                drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', [
                    '%other_user' => $currentUser->getAccountName(),
                    '%resetting_user' => $tokenUser->getAccountName(),
                    '!logout' => url('user/logout'),
                ]), 'warning');
            }

            drupal_goto();
        }
        else {
            /* @var UserInterface $user */
            $user = $userStorage->load($token->uid);

            if ($user->isBlocked() && $user->getLastLoginTime() > 0) {
                drupal_access_denied();
                drupal_exit();
            }

            if ($token->isValid()) {
                $form_state->setTemporaryValue('token', $token);
                $form_state->setTemporaryValue('user', $user);

                $form['#form_horizontal'] = true;

                $form['password'] = [
                    '#type' => 'password_confirm',
                    '#size' => 20,
                    '#required' => true,
                    '#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]),
                ];

                $form['actions'] = [
                    '#type' => 'actions',
                    'submit' => [
                        '#type' => 'submit',
                        '#value' => $this->t('Save my password'),
                    ],
                ];
            }
            else {
                drupal_set_message(
                    $this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');
                drupal_goto('user/password');
            }
        }

        return $form;
    }
948553
public function buildForm(array $form, FormStateInterface $form_state) {

    // Redirect the user to the homepage if they are already logged in.
    if ($this->commerceUserManager->isAuthenticated()) {
      return $this->redirect('<front>');
    }

    $request = $this->requestStack->getCurrentRequest();
    $password_token = $request->query->get('token');
    $email = $request->query->get('email');

    $form['email'] = [
      '#type' => 'email',
      '#title' => $this->t('Email Address'),
      '#default_value' => $email,
      '#disabled' => isset($email) ? TRUE : FALSE,
      '#required' => TRUE,
    ];

    $form['new_password'] = [
      '#type' => 'password_confirm',
      '#required' => TRUE,
    ];

    $form['password_token'] = [
      '#type' => 'hidden',
      '#value' => $password_token,
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Update password'),
    ];

    return $form;
  }
208732
public function actionRegisterNewUser()
    {
        $model = new RegisterForm();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post())) {
            try {
                if (($result = $model->register()) === true) {
                    Yii::$app->session->setFlash(Module::SESSION_KEY_RESULT, Module::RESULT_SUCCESS);
                    Yii::$app->session->setFlash(Module::SESSION_KEY_MESSAGE, '(' . $model->model->getID() . ') ' . $this->registerSuccessMessage);
                    return $this->redirect($model->continue ? '' : ['index']);
                }
                if ($result instanceof \Exception) {
                    throw $result;
                }
            } catch (\Exception $ex) {
                Yii::error($ex->getMessage(), __METHOD__);
                Yii::$app->session->setFlash(Module::SESSION_KEY_RESULT, Module::RESULT_FAILED);
                Yii::$app->session->setFlash(Module::SESSION_KEY_MESSAGE, $ex->getMessage());
            }
        }
        return $this->render('register-new-user', ['model' => $model]);
    }
784570
def authorized_signup_handler(resp, remote, *args, **kwargs):
    
    # Remove any previously stored auto register session key
    session.pop(token_session_key(remote.name) + '_autoregister', None)

    # Store token in session
    # ----------------------
    # Set token in session - token object only returned if
    # current_user.is_autenticated().
    token = response_token_setter(remote, resp)
    handlers = current_oauthclient.signup_handlers[remote.name]

    # Sign-in/up user
    # ---------------
    if not current_user.is_authenticated:
        account_info = handlers['info'](resp)
        account_info_received.send(
            remote, token=token, response=resp, account_info=account_info
        )

        user = oauth_get_user(
            remote.consumer_key,
            account_info=account_info,
            access_token=token_getter(remote)[0],
        )

        if user is None:
            # Auto sign-up if user not found
            form = create_csrf_disabled_registrationform()
            form = fill_form(
                form,
                account_info['user']
            )
            user = oauth_register(form)

            # if registration fails ...
            if user is None:
                # requires extra information
                session[
                    token_session_key(remote.name) + '_autoregister'] = True
                session[token_session_key(remote.name) +
                        '_account_info'] = account_info
                session[token_session_key(remote.name) +
                        '_response'] = resp
                db.session.commit()
                return redirect(url_for(
                    '.signup',
                    remote_app=remote.name,
                ))

        # Authenticate user
        if not oauth_authenticate(remote.consumer_key, user,
                                  require_existing_link=False):
            return current_app.login_manager.unauthorized()

        # Link account
        # ------------
        # Need to store token in database instead of only the session when
        # called first time.
        token = response_token_setter(remote, resp)

    # Setup account
    # -------------
    if not token.remote_account.extra_data:
        account_setup = handlers['setup'](token, resp)
        account_setup_received.send(
            remote, token=token, response=resp, account_setup=account_setup
        )
        db.session.commit()
        account_setup_committed.send(remote, token=token)
    else:
        db.session.commit()

    # Redirect to next
    next_url = get_session_next_url(remote.name)
    if next_url:
        return redirect(next_url)
    return redirect(url_for('invenio_oauthclient_settings.index'))
901231
private function stepOneValidation(array &$form, FormStateInterface $form_state) {
    $campaignID = $form_state->getValue('campaign_id');
    $membershipID = $form_state->getValue('membership_id');

    /** @var \Drupal\node\Entity\Node $campaign Current campaign. */
    $campaign = $this->nodeStorage->load($campaignID);
    $extended_registration = $campaign->field_campaign_ext_registration->value;

    $config = $this->config('openy_campaign.general_settings');
    $errorDefault = $config->get('error_msg_default');
    // Get error from Campaign node.
    if (!empty($campaign->field_error_default->value)) {
      $errorDefault = check_markup($campaign->field_error_default->value, $campaign->field_error_default->format);
    }

    // Check MemberCampaign entity.
    $memberCampaignID = MemberCampaign::findMemberCampaign($membershipID, $campaignID);

    // If the member is already registered, there will be a basic error message “This member has already registered”.
    if ($memberCampaignID) {
      $form_state->setErrorByName('membership_id', $this->t('This member has already registered.'));
      return;
    }

    /** @var \Drupal\openy_campaign\Entity\Member $member Load or create Temporary Member entity. Will be saved by submit. */
    $member = Member::loadMemberFromCRMData($membershipID);
    // Membership ID must be valid Personify entry only if extended registration is disabled.
    // Because for enabled extended registration it could be also invite code, not membership ID.
    if (!$extended_registration && (($member instanceof Member === FALSE) || empty($member))) {
      $form_state->setErrorByName('membership_id', $errorDefault);
      return;
    }

    // If member was found in Personify - process they as usual.
    if ($member instanceof Member) {
      $isInactiveMember = empty($member->order_number->value);
      if ($isInactiveMember) {
        $msgMemberInactive = $config->get('error_msg_member_is_inactive');
        $errorMemberInactive = check_markup($msgMemberInactive['value'], $msgMemberInactive['format']);
        // Get error from Campaign node.
        if (!empty($campaign->field_error_member_is_inactive->value)) {
          $errorMemberInactive = check_markup($campaign->field_error_member_is_inactive->value, $campaign->field_error_member_is_inactive->format);
        }
        $form_state->setErrorByName('membership_id', $errorMemberInactive);
        return;
      }

      // If User does not have an assigned branch he is now allowed to register.
      $isEmptyBranch = empty($member->branch->entity);
      if ($isEmptyBranch) {
        $msgAudienceMessages = $config->get('error_msg_target_audience_settings');
        $errorAudience = check_markup(
          $msgAudienceMessages['value'],
          $msgAudienceMessages['format']
        );
        // Get error from Campaign node.
        if (!empty($campaign->field_error_target_audience->value)) {
          $errorAudience = check_markup(
            $campaign->field_error_target_audience->value,
            $campaign->field_error_target_audience->format
          );
        }
        $form_state->setErrorByName('membership_id', $errorAudience);
        return;
      }
      else {
        $form_state->set('branch', $member->branch->entity);
      }

      /** @var \Drupal\openy_campaign\Entity\MemberCampaign $memberCampaign Create temporary MemberCampaign entity. Will be saved by submit. */
      $memberCampaign = MemberCampaign::createMemberCampaign($member, $campaign, 'portal');
      if (($memberCampaign instanceof MemberCampaign === FALSE) || empty($memberCampaign)) {
        $form_state->setErrorByName('membership_id', $errorDefault);
        return;
      }

      // Check Target Audience Settings from Campaign.
      $validateAudienceErrorMessages = $memberCampaign->validateTargetAudienceSettings();
      // Member is ineligible due to the Target Audience Setting.
      if (!empty($validateAudienceErrorMessages)) {
        $errorText = implode('<br>', $validateAudienceErrorMessages);
        $form_state->setErrorByName('membership_id',
          $this->t('This member is not eligible for the campaign for the following reasons:<br>@errors', ['@errors' => $errorText]));
        return;
      }

      $personifyEmail = $member->getPersonifyEmail();
      if (!empty($personifyEmail)) {
        $form_state->setTemporaryValue('personify_email', $personifyEmail);
      }
    }
    else {
      // This was an invite code.
      $member = Member::loadMemberFromInvite($membershipID);

      /** @var \Drupal\openy_campaign\Entity\MemberCampaign $memberCampaign Create temporary MemberCampaign entity. Will be saved by submit. */
      $memberCampaign = MemberCampaign::createMemberCampaign($member, $campaign, 'portal');
      if (($memberCampaign instanceof MemberCampaign === FALSE) || empty($memberCampaign)) {
        $form_state->setErrorByName('membership_id', $errorDefault);
        return;
      }
    }

    // Save Member and MemberCampaign entities in storage to save by submit.
    $form_state->set('member', $member);
    $form_state->set('campaign', $campaign);
    $form_state->set('member_campaign', $memberCampaign);
  }