Validate registration.

@Route("/recovery/{email}/{hash}")
@Method({"GET", "POST"})
@Template("CoreBundle:RecoveryPassword:new.html.twig")
960857
public function recoveryPasswordFormAction(Request $request, $email, $hash)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('CoreBundle:BaseActor')->findOneByEmail($email);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find user.');
        }

        if ($user instanceof BaseActor && $user->getSalt() == $hash) {
            $options = array('hash'=>$hash);
            $form = $this->createForm('CoreBundle\Form\RecoveryPasswordType', null, $options);
            $form->handleRequest($request);
            
            if ($form->isSubmitted() && $form->isValid()) {
                //Encode pass
                $factory = $this->get('security.encoder_factory');
                $recovery = $form->getData();
                $newPassword = $recovery['password'];
                $hash = $recovery['hash'];
                $user = $em->getRepository('CoreBundle:BaseActor')->findOneBySalt($hash);
                $encoder = $factory->getEncoder(new BaseActor());

                if (!$user) {
                    throw $this->createNotFoundException('Unable to find user.');
                }
                $newSalt = md5(uniqid(null, true));
                $password = $encoder->encodePassword($newPassword, $newSalt);
                $user->setSalt($newSalt);
                $user->setPassword($password);
                $em->flush();

                $this->get('core.mailer')->sendRecoveryPasswordConfirmation($user);

                $this->get('session')->getFlashBag()->add('success', 'recovery.change.success');

            }
            
            return array('form' => $form->createView());
            
        } else {
            throw $this->createNotFoundException('Invalid parameters. {'.$hash.'}');
        }

    }
565265
public function validateEmailInactive()
    {
        // check for valid user
        $user = $this->getUser();
        if (!$user) {
            $this->addError("email", Yii::t("user", "Email not found"));
        } elseif ($user->status == $user::STATUS_ACTIVE) {
            $this->addError("email", Yii::t("user", "Email is already active"));
        } else {
            $this->user = $user;
        }
    }
159532
public function password(Request $request): Response
    {
        $this->denyAccessUnlessLoggedIn();

        if ($request->isMethod(Request::METHOD_POST)) {
            // @todo : send recovery email
            return $this->renderStorefront('@Storefront/page/account/password-reset/hash-sent.html.twig', ['page' => []]);
        }

        return $this->renderStorefront('@Storefront/page/account/password-reset/index.html.twig', ['page' => []]);
    }
393108
public function postReset()
    {
        $credentials = Input::only(
            'email', 'password', 'password_confirmation', 'token'
        );

        $response = Password::reset($credentials, function($user, $password)
        {
            $user->password = Hash::make($password);
            $user->save();
        });

        switch ($response)
        {
            case Password::INVALID_PASSWORD:
            case Password::INVALID_TOKEN:
            case Password::INVALID_USER:
                return Redirect::back()->with('error', 'Something was wrong with the input you provided.');

            case Password::PASSWORD_RESET:
                return Redirect::route('bumble.login');
        }
    }
967633
public function validate()
    {
        $valid = true;
        $message = null;
        $type = $this->Type;

        // Check if empty strings
        switch ($type) {
            case 'URL':
            case 'Email':
            case 'Phone':
                if ($this->{$type} == '') {
                    $valid = false;
                    $message = _t(
                        __CLASS__ . '.VALIDATIONERROR_EMPTY'.strtoupper($type),
                        'You must enter a {TypeLabel}',
                        [
                            'TypeLabel' => $this->TypeLabel
                        ]
                    );
                }
                break;
            case 'File':
            case 'SiteTree':
                if ($type && empty($this->{$type.'ID'})) {
                    $valid = false;
                    $message = _t(
                        __CLASS__ . '.VALIDATIONERROR_OBJECT',
                        'Please select a {TypeLabel}',
                        [
                            'TypeLabel' => $this->TypeLabel
                        ]
                    );
                }
                break;
        }
        // if its already failed don't bother checking the rest
        if ($valid) {
            switch ($type) {
                case 'URL':
                    $allowedFirst = ['#', '/'];
                    if (!in_array(substr($this->URL, 0, 1), $allowedFirst) && !filter_var($this->URL, FILTER_VALIDATE_URL)) {
                        $valid = false;
                        $message = _t(
                            __CLASS__ . '.VALIDATIONERROR_VALIDURL',
                            'Please enter a valid URL.  Be sure to include http:// for an external URL. or begin your internal url/anchor with a "/" character'
                        );
                    }
                    break;
                case 'Email':
                    if (!filter_var($this->Email, FILTER_VALIDATE_EMAIL)) {
                        $valid = false;
                        $message = _t(
                            __CLASS__ . '.VALIDATIONERROR_VALIDEMAIL',
                            'Please enter a valid Email address'
                        );
                    }
                    break;
                case 'Phone':
                    if (!preg_match("/^\+?[0-9a-zA-Z\-\s]*[\,\#]?[0-9\-\s]*$/", $this->Phone)) {
                        $valid = false;
                        $message = _t(
                            __CLASS__ . '.VALIDATIONERROR_VALIDPHONE',
                            'Please enter a valid Phone number'
                        );
                    }
                    break;
            }
        }

        $result = ValidationResult::create();
        if (!$valid) {
            $result->addError($message);
        }

        $this->extend('updateValidate', $result);

        return $result;
    }
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;
        }
    }
1122625
public function actionRegister() {

		$coreProperties = $this->getCoreProperties();

		// Create Form Model
		$model = new Register();

		// Load and Validate Form Model
		if( $coreProperties->isRegistration() && $model->load( Yii::$app->request->post(), 'Register' ) && $model->validate() ) {

			// Register User
			$user = $this->userService->register( $model );

			if( isset( $user ) ) {

				// Add User to current Site
				$this->siteMemberService->create( $user );

				// Send Register Mail
				Yii::$app->coreMailer->sendRegisterMail( $user );

				// Trigger Ajax Success
				return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REGISTER ) );
			}
		}

		// Generate Errors
		$errors = AjaxUtil::generateErrorMessage( $model );

		// Trigger Ajax Failure
		return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_REQUEST ), $errors );
	}
197046
public function postRegister()
    {
        if (!Config::get('credentials.regallowed')) {
            return Redirect::route('account.register');
        }

        $input = Binput::only(['first_name', 'last_name', 'email', 'password', 'password_confirmation']);

        $val = UserRepository::validate($input, array_keys($input));
        if ($val->fails()) {
            return Redirect::route('account.register')->withInput()->withErrors($val->errors());
        }

        $this->throttler->hit();

        try {
            unset($input['password_confirmation']);

            $user = Credentials::register($input);

            if (!Config::get('credentials.activation')) {
                $mail = [
                    'url'     => URL::to(Config::get('credentials.home', '/')),
                    'email'   => $user->getLogin(),
                    'subject' => Config::get('app.name').' - Welcome',
                ];

                Mail::queue('credentials::emails.welcome', $mail, function ($message) use ($mail) {
                    $message->to($mail['email'])->subject($mail['subject']);
                });

                $user->attemptActivation($user->getActivationCode());
                $user->addGroup(Credentials::getGroupProvider()->findByName('Users'));

                return Redirect::to(Config::get('credentials.home', '/'))
                    ->with('success', 'Your account has been created successfully. You may now login.');
            }

            $code = $user->getActivationCode();

            $mail = [
                'url'     => URL::to(Config::get('credentials.home', '/')),
                'link'    => URL::route('account.activate', ['id' => $user->id, 'code' => $code]),
                'email'   => $user->getLogin(),
                'subject' => Config::get('app.name').' - Welcome',
            ];

            Mail::queue('credentials::emails.welcome', $mail, function ($message) use ($mail) {
                $message->to($mail['email'])->subject($mail['subject']);
            });

            return Redirect::to(Config::get('credentials.home', '/'))
                ->with('success', 'Your account has been created. Check your email for the confirmation link.');
        } catch (UserExistsException $e) {
            return Redirect::route('account.register')->withInput()->withErrors($val->errors())
                ->with('error', 'That email address is taken.');
        }
    }
483814
public function PasswordRequest() {
      Gdn::Locale()->SetTranslation('Email', T(UserModel::SigninLabelCode()));
      if ($this->Form->IsPostBack() === TRUE) {
         $this->Form->ValidateRule('Email', 'ValidateRequired');

         if ($this->Form->ErrorCount() == 0) {
            try {
               $Email = $this->Form->GetFormValue('Email');
               if (!$this->UserModel->PasswordRequest($Email)) {
                  $this->Form->SetValidationResults($this->UserModel->ValidationResults());
               }
            } catch (Exception $ex) {
               $this->Form->AddError($ex->getMessage());
            }
            if ($this->Form->ErrorCount() == 0) {
               $this->Form->AddError('Success!');
               $this->View = 'passwordrequestsent';
            }
         } else {
            if ($this->Form->ErrorCount() == 0)
               $this->Form->AddError("Couldn't find an account associated with that email/username.");
         }
      }
      $this->Render();
   }
1129719
public function index()
    {
        //  If user is logged in they shouldn't be accessing this method
        if (isLoggedIn()) {
            $oSession = Factory::service('Session', 'nails/module-auth');
            $oSession->setFlashData('error', lang('auth_no_access_already_logged_in', activeUser('email')));
            redirect('/');
        }

        //  If there's POST data attempt to validate the user
        if ($this->input->post() || $this->input->get('identifier')) {

            //  Define vars
            $_identifier = $this->input->post('identifier');

            /**
             * Override with the $_GET variable if POST failed to return anything. Populate
             * the $_POST var with some data so form validation continues as normal, feels
             * hacky but works.
             */

            if (!$_identifier && $this->input->get('identifier')) {

                $_POST['identifier'] = $this->input->get('identifier');
                $_identifier         = $this->input->get('identifier');
            }

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

            /**
             * Set rules.
             * The rules vary depending on what login method is enabled.
             */

            $oFormValidation = Factory::service('FormValidation');

            switch (APP_NATIVE_LOGIN_USING) {

                case 'EMAIL':
                    $oFormValidation->set_rules('identifier', '', 'required|trim|valid_email');
                    break;

                case 'USERNAME':
                    $oFormValidation->set_rules('identifier', '', 'required|trim');
                    break;

                default:
                    $oFormValidation->set_rules('identifier', '', 'trim');
                    break;
            }

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

            //  Override default messages
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

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

            //  Run validation
            if ($oFormValidation->run()) {

                /**
                 * Some apps may want the forgotten password tool to always return as successful,
                 * even if it wasn't. Bad UX, if you ask me, but I'm not the client.
                 */

                $oConfig       = Factory::service('Config');
                $alwaysSucceed = $oConfig->item('authForgottenPassAlwaysSucceed');

                //  Attempt to reset password
                $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth');
                if ($oUserPasswordModel->setToken($_identifier)) {

                    //  Send email to user
                    $oUserModel = Factory::model('User', 'nails/module-auth');
                    switch (APP_NATIVE_LOGIN_USING) {

                        case 'EMAIL':
                            $this->data['reset_user'] = $oUserModel->getByEmail($_identifier);

                            //  User provided an email, send to that email
                            $sendToEmail = $_identifier;
                            break;

                        case 'USERNAME':
                            $this->data['reset_user'] = $oUserModel->getByUsername($_identifier);

                            /**
                             * Can't email a username, send to their ID and let the email library
                             * handle the routing
                             */

                            $sendToId = $this->data['reset_user']->id;
                            break;

                        default:
                            if (valid_email($_identifier)) {

                                $this->data['reset_user'] = $oUserModel->getByEmail($_identifier);

                                //  User provided an email, send to that email
                                $sendToEmail = $_identifier;

                            } else {

                                $this->data['reset_user'] = $oUserModel->getByUsername($_identifier);

                                /**
                                 * Can't email a username, send to their ID and let the email library handle
                                 * the routing
                                 */

                                $sendToId = $this->data['reset_user']->id;
                            }
                            break;
                    }

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

                    if (!$alwaysSucceed && isset($sendToEmail) && !$sendToEmail) {

                        //  If we're expecting an email, and none is available then we're kinda stuck
                        $this->data['error'] = lang('auth_forgot_email_fail_no_email');

                    } elseif (!$alwaysSucceed && isset($sendToId) && !$sendToId) {

                        //  If we're expecting an ID and it's empty then we're stuck again
                        $this->data['error'] = lang('auth_forgot_email_fail_no_id');

                    } elseif ($alwaysSucceed) {

                        //  Failed, but we always succeed so, yeah, succeed
                        $this->data['success'] = lang('auth_forgot_success');

                    } else {

                        //  We've got something, go go go
                        $_data       = new stdClass();
                        $_data->type = 'forgotten_password';

                        if (isset($sendToEmail) && $sendToEmail) {

                            $_data->to_email = $sendToEmail;

                        } elseif (isset($sendToId) && $sendToId) {

                            $_data->to_id = $sendToId;
                        }

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

                        //  Add data for the email view
                        $_code = explode(':', $this->data['reset_user']->forgotten_password_code);

                        $_data->data             = new \stdClass();
                        $_data->data->resetUrl   = site_url('auth/password/forgotten/' . $_code[1]);
                        $_data->data->identifier = $_identifier;

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

                        //  Send user the password reset email
                        if ($this->emailer->send($_data)) {

                            $this->data['success'] = lang('auth_forgot_success');

                        } elseif ($alwaysSucceed) {

                            $this->data['success'] = lang('auth_forgot_success');

                        } else {

                            $this->data['error'] = lang('auth_forgot_email_fail');
                        }
                    }

                } elseif ($alwaysSucceed) {

                    $this->data['success'] = lang('auth_forgot_success');

                } else {

                    switch (APP_NATIVE_LOGIN_USING) {

                        case 'EMAIL':
                            $this->data['error'] = lang('auth_forgot_code_not_set_email', $_identifier);
                            break;

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

                        case 'USERNAME':
                            $this->data['error'] = lang('auth_forgot_code_not_set_username', $_identifier);
                            break;

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

                        default:
                            $this->data['error'] = lang('auth_forgot_code_not_set');
                            break;
                    }
                }

            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

        //  Load the views
        $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/password/forgotten.php');
        $oView = Factory::service('View');
        $oView->load('structure/header/blank', $this->data);
        $oView->load('auth/password/forgotten', $this->data);
        $oView->load('structure/footer/blank', $this->data);
    }
663505
public function postRegister(Request $request)
	{
		$validator = $this->registrar->validator($request->all());

		if ($validator->fails())
		{
			$this->throwValidationException(
				$request, $validator
			);
		}

		$this->auth->login($this->registrar->create($request->all()));

		return redirect($this->redirectPath());
	}
774737
public function authenticate($request = [])
    {
        if ($request) {
            $this->email = clean($request['email']);
            $this->password = $this->getPasswordHelper()->hash(clean($request['password']));
        } else {
            $this->password = $this->getPasswordHelper()->hash(clean($this->password));
        }

        $query = $this->getManager()->newQuery();

        $query->where("email = ?", $this->email);
        $query->where("password = ?", $this->password);

        /** @var User $user */
        $user = $this->getManager()->findOneByQuery($query);

        if ($user) {
            $this->writeData($user->toArray());
            $this->doAuthentication();
        }

        return $this->authenticated();
    }
1106717
public function registerAction(Request $request)
    {
        if ($this->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED)) {
            return $this->redirectToRoute($this->getParameter('darvin_user.already_logged_in_redirect_route'));
        }

        $widget = $request->isXmlHttpRequest();

        $form = $this->getSecurityFormFactory()->createRegistrationForm()->handleRequest($request);

        if (!$form->isSubmitted()) {
            return new Response($this->getSecurityFormRenderer()->renderRegistrationForm($widget, $form));
        }

        $successMessage = 'security.action.register.success';

        $needConfirm = $this->getParameter('darvin_user.confirm_registration');
        if (!$this->getSecurityFormHandler()->handleRegistrationForm($form, !$widget, $successMessage, $needConfirm)) {
            $html = $this->getSecurityFormRenderer()->renderRegistrationForm($widget, $form);

            return $widget
                ? new AjaxResponse($html, false, FlashNotifierInterface::MESSAGE_FORM_ERROR)
                : new Response($html);
        }

        $url = $needConfirm ?
            $this->generateUrl('darvin_user_security_confirm_registration') :
            $this->generateUrl($this->getParameter('darvin_user.already_logged_in_redirect_route'))
        ;

        return $widget
            ? new AjaxResponse('', true, $successMessage, [], $url)
            : $this->redirect($url);
    }
1051908
public function validateAction()
    {
        // Check for a valid POST request
        if (!$this->getRequest()->isPost()) {
            // Return a "405 Method Not Allowed" response
            $this->getResponse()->setHttpResponseCode(405);
            return;
        }

        $data = $this->getRequest()->getPost();

        // Check that all of the required fields are present
        if (empty($data) || !isset($data['country_id'], $data['region_id'], $data['street'], $data['city'], $data['postcode'])) {
            // Return a "400 Bad Request" response
            $this->getResponse()->setHttpResponseCode(400);
            return;
        }

        $country = Mage::getModel('directory/country')->load($data['country_id'])->getName();
        $region = Mage::getModel('directory/region')->load($data['region_id'])->getCode();

        $result = Mage::helper('australia/address')->validate(
            $data['street'],
            $region,
            $data['city'],
            $data['postcode'],
            $country
        );

        $this->getResponse()->setHeader('Content-type', 'application/json');
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
152405
public function recoveryAction(Request $request)
    {
        $form = $this->createForm('CoreBundle\Form\RecoveryEmailType');
        $form->handleRequest($request);
        
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getNormData();
            if(isset($data['email'])){
                $em = $this->getDoctrine()->getManager();
                $user = $em->getRepository('CoreBundle:BaseActor')->findOneByEmail($data['email']);
                
                if ($request->isXmlHttpRequest()) {
                    $returnValues = new stdClass();
                    if ($user instanceof BaseActor) {
                        $this->get('core.mailer')->sendRecoveryPasswordMessage($user);
                        $returnValues->status = 'success';
                        $returnValues->message = $this->get('translator')->trans('recovery.email.success');
                    } else {
                        $returnValues->status = 'error';
                        $returnValues->message = $this->get('translator')->trans('recovery.email.error');
                    }
                    $response = new Response();
                    $response->setContent(json_encode(array(
                        'answer' => $returnValues
                    )));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }else{
                    if ($user instanceof BaseActor) {
                        $this->get('core.mailer')->sendRecoveryPasswordMessage($user); 
                        $this->get('session')->getFlashBag()->add('success', 'recovery.email.success');
                    } else {
                        $this->get('session')->getFlashBag()->add('danger', 'recovery.email.error');
                    }
                }
            }
            
        }
        
        return array('form' => $form->createView());
    }
354864
public function postRegister(Request $request)
    {
        $this->validate($request, $this->validateCreating());

        $user = $this->create($request->all());
        if (config('taki.confirm_after_created')) {
            $token              = app('auth.password.tokens')->createNewToken();
            $user->is_activated = 0;
            $user->token        = $token;
            $user->save();
            Mail::queue(config('taki.emails.activate'), compact('token', 'user'), function ($m) use ($user, $token) {
                $m->subject(config('taki.emails.activate_subject'));
                $m->to($user->getEmailForPasswordReset());
            });
        } else {
            Auth::login($user);
        }

        if (method_exists($this, 'userRegistered')) {
            $this->userRegistered($request, $user);
        }


        return redirect($this->getPostRegisterRedirectPath());
    }
870112
public function actionRegisterByEmail()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $rr = new RequestResponse();
        $model = new SignupForm();

        $model->scenario = SignupForm::SCENARION_ONLYEMAIL;


        //Запрос на валидацию ajax формы
        if ($rr->isRequestOnValidateAjaxForm()) {
            return $rr->ajaxValidateForm($model);
        }
        //Запрос ajax post
        if ($rr->isRequestAjaxPost()) {

            $t = \Yii::$app->db->beginTransaction();

            try {

                if ($model->load(\Yii::$app->request->post()) && $registeredUser = $model->signup()) {

                    $t->commit();

                    $rr->success = true;
                    $rr->message = 'Для дальнейших действий, проверьте вашу почту.';

                    return $rr;

                } else {
                    $rr->message = 'Не удалось зарегистрироваться';
                }

            } catch (\Exception $e) {
                $t->rollBack();
                throw $e;
            }


            return (array)$rr;

        }

        return $this->render('register', [
            'model' => $model,
        ]);
    }