Validate data and log the user in.

@return  void
@throws \Nails\Common\Exception\FactoryException
776244
public function index()
    {
        //  If you're logged in you shouldn't be accessing this method
        if (isLoggedIn()) {
            redirect($this->data['return_to']);
        }

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

        //  If there's POST data attempt to log user in
        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            //  Validate input
            $oFormValidation = Factory::service('FormValidation');

            //  The rules vary depending on what login methods are enabled.
            switch (APP_NATIVE_LOGIN_USING) {

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

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

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

            //  Password is always required, obviously.
            $oFormValidation->set_rules('password', 'Password', 'required');
            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('valid_email', lang('fv_valid_email'));

            if ($oFormValidation->run()) {

                //  Attempt the log in
                $sIdentifier = $oInput->post('identifier');
                $sPassword   = $oInput->post('password');
                $bRememberMe = (bool) $oInput->post('remember');
                $oAuthModel  = Factory::model('Auth', 'nails/module-auth');

                $oUser = $oAuthModel->login($sIdentifier, $sPassword, $bRememberMe);

                if ($oUser) {
                    $this->_login($oUser, $bRememberMe);
                } else {
                    $this->data['error'] = $oAuthModel->lastError();
                }

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

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

        $oSocial                               = Factory::service('SocialSignOn', 'nails/module-auth');
        $this->data['social_signon_enabled']   = $oSocial->isEnabled();
        $this->data['social_signon_providers'] = $oSocial->getProviders('ENABLED');

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

        $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/login/form.php');

        Factory::service('View')
            ->load([
                'structure/header/blank',
                'auth/login/form',
                'structure/footer/blank',
            ]);
    }
115534
protected function validateConfig()
    {
        $this->queueDriver = $this->createQueueDriver();
        $this->requiredFields = $this->queueDriver->getRequiredConfig();
        $this->config = array_merge($this->queueDriver->getDefaultConfig(), $this->config);
        parent::validateConfig();
    }
441352
public function execute() {
        global $CFG, $DB;

        if (empty($CFG->notifyloginfailures)) {
            return;
        }

        $recip = get_users_from_config($CFG->notifyloginfailures, 'moodle/site:config');

        // Do not look back more than 1 month to avoid crashes due to huge number of records.
        $maximumlastnotifytime = time() - self::NOTIFY_MAXIMUM_TIME;
        if (empty($CFG->lastnotifyfailure) || ($CFG->lastnotifyfailure < $maximumlastnotifytime)) {
            $CFG->lastnotifyfailure = $maximumlastnotifytime;
        }

        // If it has been less than an hour, or if there are no recipients, don't execute.
        if (((time() - HOURSECS) < $CFG->lastnotifyfailure) || !is_array($recip) || count($recip) <= 0) {
            return;
        }

        // We need to deal with the threshold stuff first.
        if (empty($CFG->notifyloginthreshold)) {
            $CFG->notifyloginthreshold = 10; // Default to something sensible.
        }

        // Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
        // and insert them into the cache_flags temp table.
        $logmang = get_log_manager();
        $readers = $logmang->get_readers('\core\log\sql_internal_table_reader');
        $reader = reset($readers);
        $readername = key($readers);
        if (empty($reader) || empty($readername)) {
            // No readers, no processing.
            return true;
        }
        $logtable = $reader->get_internal_log_table_name();

        $sql = "SELECT ip, COUNT(*)
                  FROM {" . $logtable . "}
                 WHERE eventname = ?
                       AND timecreated > ?
               GROUP BY ip
                 HAVING COUNT(*) >= ?";
        $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $iprec) {
            if (!empty($iprec->ip)) {
                set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
            }
        }
        $rs->close();

        // Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
        // and insert them into the cache_flags temp table.
        $sql = "SELECT userid, count(*)
                  FROM {" . $logtable . "}
                 WHERE eventname = ?
                       AND timecreated > ?
              GROUP BY userid
                HAVING count(*) >= ?";
        $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, $CFG->notifyloginthreshold);
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $inforec) {
            if (!empty($inforec->info)) {
                set_cache_flag('login_failure_by_id', $inforec->userid, '1', 0);
            }
        }
        $rs->close();

        // Now, select all the login error logged records belonging to the ips and infos
        // since lastnotifyfailure, that we have stored in the cache_flags table.
        $namefields = get_all_user_name_fields(true, 'u');
        $sql = "SELECT * FROM (
                        SELECT l.*, u.username, $namefields
                          FROM {" . $logtable . "} l
                          JOIN {cache_flags} cf ON l.ip = cf.name
                     LEFT JOIN {user} u         ON l.userid = u.id
                         WHERE l.eventname = ?
                               AND l.timecreated > ?
                               AND cf.flagtype = 'login_failure_by_ip'
                    UNION ALL
                        SELECT l.*, u.username, $namefields
                          FROM {" . $logtable . "} l
                          JOIN {cache_flags} cf ON l.userid = " . $DB->sql_cast_char2int('cf.name') . "
                     LEFT JOIN {user} u         ON l.userid = u.id
                         WHERE l.eventname = ?
                               AND l.timecreated > ?
                               AND cf.flagtype = 'login_failure_by_info') t
             ORDER BY t.timecreated DESC";
        $params = array('\core\event\user_login_failed', $CFG->lastnotifyfailure, '\core\event\user_login_failed', $CFG->lastnotifyfailure);

        // Init some variables.
        $count = 0;
        $messages = '';
        // Iterate over the logs recordset.
        $rs = $DB->get_recordset_sql($sql, $params);
        foreach ($rs as $log) {
            $a = new \stdClass();
            $a->time = userdate($log->timecreated);
            if (empty($log->username)) {
                // Entries with no valid username. We get attempted username from the event's other field.
                $other = \tool_log\helper\reader::decode_other($log->other);
                $a->info = empty($other['username']) ? '' : $other['username'];
                $a->name = get_string('unknownuser');
            } else {
                $a->info = $log->username;
                $a->name = fullname($log);
            }
            $a->ip = $log->ip;
            $messages .= get_string('notifyloginfailuresmessage', '', $a)."\n";
            $count++;
        }
        $rs->close();

        // If we have something useful to report.
        if ($count > 0) {
            $site = get_site();
            $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
            // Calculate the complete body of notification (start + messages + end).
            $params = array('id' => 0, 'modid' => 'site_errors', 'chooselog' => '1', 'logreader' => $readername);
            $url = new \moodle_url('/report/log/index.php', $params);
            $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
                    (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
                    $messages .
                    "\n\n".get_string('notifyloginfailuresmessageend', '',  $url->out(false).' ')."\n\n";

            // For each destination, send mail.
            mtrace('Emailing admins about '. $count .' failed login attempts');
            foreach ($recip as $admin) {
                // Emailing the admins directly rather than putting these through the messaging system.
                email_to_user($admin, \core_user::get_noreply_user(), $subject, $body);
            }
        }

        // Update lastnotifyfailure with current time.
        set_config('lastnotifyfailure', time());

        // Finally, delete all the temp records we have created in cache_flags.
        $DB->delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");

    }
1054269
public function run()
    {
        $this->loop = Factory::create();

        $this->errorLogger = BufferingLogger::create();
        ErrorHandler::register(new ErrorHandler($this->errorLogger));

        $this->tryConnect();
        $this->loop->run();
    }
69649
public function validate()
	{
		// reset the error container and status
		$this->errors = array();
		$this->isValid = true;

		// validation starts, call the pre-validation callback
		$this->runCallbacks('before_validation');

		// was the upload of the file a success?
		if ($this->container['error'] == 0)
		{
			// add some filename details (pathinfo can't be trusted with utf-8 filenames!)
			$this->container['extension'] = ltrim(strrchr(ltrim($this->container['name'], '.'), '.'),'.');
			if (empty($this->container['extension']))
			{
				$this->container['basename'] = $this->container['name'];
			}
			else
			{
				$this->container['basename'] = substr($this->container['name'], 0, strlen($this->container['name'])-(strlen($this->container['extension'])+1));
			}

			// does this upload exceed the maximum size?
			if ( ! empty($this->config['max_size']) and is_numeric($this->config['max_size']) and $this->container['size'] > $this->config['max_size'])
			{
				$this->addError(static::UPLOAD_ERR_MAX_SIZE);
			}

			// add mimetype information
			try
			{
				$handle = finfo_open(FILEINFO_MIME_TYPE);
				$this->container['mimetype'] = finfo_file($handle, $this->container['tmp_name']);
				finfo_close($handle);
			}
			// this will only work if PHP errors are converted into ErrorException (like when you use FuelPHP)
			catch (\ErrorException $e)
			{
				$this->container['mimetype'] = false;
				$this->addError(UPLOAD_ERR_NO_FILE);
			}

			// make sure it contains something valid
			if (empty($this->container['mimetype']) or strpos($this->container['mimetype'], '/') === false)
			{
				$this->container['mimetype'] = 'application/octet-stream';
			}

			// split the mimetype info so we can run some tests
			preg_match('|^(.*)/(.*)|', $this->container['mimetype'], $mimeinfo);

			// check the file extension black- and whitelists
			if (in_array(strtolower($this->container['extension']), (array) $this->config['ext_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_EXT_BLACKLISTED);
			}
			elseif ( ! empty($this->config['ext_whitelist']) and ! in_array(strtolower($this->container['extension']), (array) $this->config['ext_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_EXT_NOT_WHITELISTED);
			}

			// check the file type black- and whitelists
			if (in_array($mimeinfo[1], (array) $this->config['type_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_TYPE_BLACKLISTED);
			}
			if ( ! empty($this->config['type_whitelist']) and ! in_array($mimeinfo[1], (array) $this->config['type_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_TYPE_NOT_WHITELISTED);
			}

			// check the file mimetype black- and whitelists
			if (in_array($this->container['mimetype'], (array) $this->config['mime_blacklist']))
			{
				$this->addError(static::UPLOAD_ERR_MIME_BLACKLISTED);
			}
			elseif ( ! empty($this->config['mime_whitelist']) and ! in_array($this->container['mimetype'], (array) $this->config['mime_whitelist']))
			{
				$this->addError(static::UPLOAD_ERR_MIME_NOT_WHITELISTED);
			}

			// validation finished, call the post-validation callback
			$this->runCallbacks('after_validation');
		}
		else
		{
			// upload was already a failure, store the corresponding error
			$this->addError($this->container['error']);
		}

		// set the flag to indicate we ran the validation
		$this->isValidated = true;

		// return the validation state
		return $this->isValid;
	}
345948
protected function prepareForValidation(): void
    {
        $data = $this->all();

        // Calculate price
        $endsAt = new Carbon($data['ends_at']);
        $startsAt = new Carbon($data['starts_at']);
        $service = app('cortex.bookings.service')->find($data['service_id']);
        [$price, $formula, $currency] = app('cortex.bookings.service_booking')->calculatePrice($service, $startsAt, $endsAt, $data['quantity']);

        // Fill missing fields
        $data['ends_at'] = $endsAt;
        $data['starts_at'] = $startsAt;
        $data['customer_type'] = 'member';
        $data['bookable_type'] = 'service';
        $data['currency'] = $currency;
        $data['formula'] = $formula;
        $data['price'] = $price;

        $this->replace($data);
    }
1341258
public function validate()
    {
        $data = $this->wasSubmitted() === true ? $this->getSubmitted() : null;

        // Invalid selection on choice/multiple choice field
        if ($data === []) {
            $this->addError("Unrecognized choice.");
        }

        if ($this->isRequired() === true && $data === null) {
            $this->addError("This field is required.");
        }

        if ($this->getErrors() === []) {
            $this->setValidatedData($data);
        }
    }
520325
protected function validateUserLogin()
    {
        $this->setSubmitted('user', null, false);
        $this->filterSubmitted(array('email', 'password'));
        $this->validateComponent('user_login');

        return !$this->hasErrors();
    }
744681
protected static function login() :void {
		
		// look for users with this login
		$account = \Models\Accounts::getFirstEnabledWithLogin(
			Request::post( Config::get('security', 'login') )
		);
		// if the account does not exist/is not found
		if(!$account) {
			// we deny access
			self::refuse('Account does not exist or is disabled'); 
		}
		// if the account has been forced by that ip recently
		if($account->hasFailedLoginAttemptsRecentFrom(self::getSafeRemoteAddress())) {
			// extend the lock on the account
			$account->extendLoginBan();
			// refuse access
			self::refuse('Please wait '.Config::get('security', 'waiting_duration').' seconds before trying again');
		}
		// if the account has expired
		if($account->hasItsValidityExpired()) {
			// register that failure
			$account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent());
			// refuse access
			self::refuse("Your account has expired, it was valid until {$account->get('account_expiration_date')}");	
		}
		// if the posted password doesn't match the account's password
		if(!$account->hasThisPassword(Request::post(Config::get('security', 'password')))) {
			// register that failure
			$account->registerFailedLoginAttemptFrom(self::getSafeRemoteAddress(), self::getSafeUserAgent());
			// refuse access
			self::refuse('Wrong password');
		}
		// if we failed to open a session
		if(!$account->tryOpeningSession()) {
			// we report that something is wrong
			self::refuse('Your session failed to open, make sure your browser accepts cookies', 500);
		}
		// then session has been opened
		else {
			// log the loggin action
			Logger::info("Account {$account->get('login')} has logged in");
			// put the user inside of us
			self::$_account = $account;
			// set the most basic authentication block as being true/passed
			self::$_granted = true;
			// if we have an url in the session, redirect to it (and remove it)
			!Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl();
		}
		
	}
554172
public function validate() : void
    {
        if (null === $this->is_valid) {
            if (null === $this->user_value && null !== $this->default_value) {
                // There is a preset value, and its not being changed
                $this->is_valid = true;
            } elseif (in_array($this->user_value, array_keys($this->options)) && !in_array($this->user_value,
                    $this->disabled)
            ) {
                $this->is_valid = true;
            } elseif ('' == $this->user_value && $this->addBlank && !in_array('', $this->disabled)) {
                $this->is_valid = true;
            } elseif (false == $this->validator) {
                // This field does not get validated
                $this->is_valid = true;
            } else {
                $this->is_valid = false;
                $this->error = 'The provided value is not valid. Please enter a valid value.';
            }
        }

        // Check if the input is different from the default value
        if ($this->is_valid && null !== $this->user_value) {
            $this->is_changed = ($this->default_value != $this->user_value);
        }
    }
499961
protected function register()
    {
        // Make comment model for the factory.
        $this->setModel($this->makeUserModel());

        // Build comment with model.
        $this->setSingularity($this->makeUserInstance());

        // Set columns to the users, after admin init.
        if ($this->methodExist('columns')) {
            $this->registerColumns();
        }
    }
1321734
public function validate() {

		$app	= Application::getInstance();
		$value	= Input::get($this->name);
		$valid	= TRUE;

		if ($this->required) {
			
			switch ($this->type) {

				default:
				case 'text':
				case 'password':
				case 'date':
				case 'datetime':
				case 'file':
				case 'tel':
				case 'address':
				case 'color':
				case 'hidden':
					if (''==$value) {
						$app->logEvent('Control validation on field “' . $this->name . '” has failed (required)');
						$valid = FALSE;
					}
					break;

				case 'email':
					if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
						$app->logEvent('Control validation on field “' . $this->name . '” has failed (email required)');
						$valid = FALSE;
					}
					break;
					
				case 'url':
					if (!filter_var($value, FILTER_VALIDATE_URL)) {
						$app->logEvent('Control validation on field “' . $this->name . '” has failed (url required)');
						$valid = FALSE;
					}
					break;
					
				case 'number':
					if (!is_numeric($value)) {
						$app->logEvent('Control validation on field “' . $this->name . '” has failed (number required)');
						$valid = FALSE;
					}
					break;
				
				case 'bool':
					break;
					
			}
			
		}

		// set min and max value attribute for date and number only
		if (in_array($this->type, ['number','date'])) {
			
			if ($this->min and $value < $this->min) {
				$app->logEvent('Control validation on field “' . $this->name . '” has failed (min=' . $this->min . ')');
				$valid = FALSE;
			}
			
			if ($this->max and $value > $this->max) {
				$app->logEvent('Control validation on field “' . $this->name . '” has failed (max=' . $this->max . ')');
				$valid = FALSE;
			}
			
		}

		// check validity of minlength attribute
		if ($this->minLength and ''!=$value and strlen($value) < $this->minLength) {
			$app->logEvent('Control validation on field “' . $this->name . '” has failed (minLength=' . $this->minLength . ')');
			$valid = FALSE;
		}

		// check validity of minlength attribute
		if ($this->maxLength and strlen($value) > $this->maxLength) {
			$app->logEvent('Control validation on field “' . $this->name . '” has failed (maxLength=' . $this->maxLength . ')');
			$valid = FALSE;
		}
		
		return $valid;

	}
322055
public static function boot()
    {
        parent::boot();
        $instance = new static;

        //Halt saving if validation fails
        static::saving(function ($model) {
            if (!$model->validate()) {
                throw new ModelValidationException("Validation failed: " . $model->getErrors());
            }
        });

        if ($instance->userstamps) {
            static::creating(function ($model) {
                if (!Auth::guest()) {
                    $model->created_by = Auth::user()->id;
                    $model->updated_by = Auth::user()->id;
                } else {
                    $model->created_by = 1;
                    $model->updated_by = 1;
                }
            });

            static::updating(function ($model) {
                if (!Auth::guest()) {
                    $model->updated_by = Auth::user()->id;
                } else {
                    $model->updated_by = 1;
                }
            });
        }

        static::created(function ($model) use ($instance) {
            foreach ($instance->getWith() as $relationship) {
                $model->load($relationship);
            }
        });
    }
702425
private function webLogin()
    {
        if ($this->inputs['password'] == $this->config['webpassword']) {
            $_SESSION['logged_in'] = true;
            exit($this->showWebForm());
        } else {
            $error = 'Sorry your password was incorrect.';
            exit($this->showWebLoginForm($error));
        }
    }
1259424
public function validate()
    {
        $report = parent::validate();

        $password = null;
        foreach ($this->formProperties as $key => $property) {
            if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && !empty($this->formProperties[$key]['formValue'])) {
                $password = $this->formProperties[$key]['formValue'];
                break;
            }
        }

        if ($this->isNew() || ($this->doesExist() && !is_null($password))) {
            try {
                $this->validatePassword($password);
                $this->changePassword = true;
            } catch (common_exception_ValidationFailed $e) {
                $subReport = common_report_Report::createFailure($e->getMessage());
                $subReport->setData(GenerisRdf::PROPERTY_USER_PASSWORD);
                $report->add($subReport);
            }
        }

        // Validate new login availability
        if ($this->isNew()) {
            foreach($this->formProperties as $property) {
                if ( $property['uri'] == 'http://www.tao.lu/Ontologies/generis.rdf#login') {
                    if ( empty($property['formValue']) ) {
                        $subReport = common_report_Report::createFailure(__('Login is empty.'));
                    } else if ( ! $this->isLoginAvailable($property['formValue']) ) {
                        $subReport = common_report_Report::createFailure(__('Login is already in use.'));
                    }

                    if ( isset($subReport) ) {
                        $subReport->setData($property['uri']);
                        $report->add($subReport);
                    }
                }
            }
        }

        return $report;
    }
1339676
public function setupDefaultValidation() {
		$validator = $this->_table->getValidator('default');
		$validator = $this->validationUserName($validator);
		$validator = $this->validationPassword($validator);
		$validator = $this->validationConfirmPassword($validator);
		$this->validationEmail($validator);
	}
1137576
private function validate()
    {
        // Try to resolve subrules if there are any
        // as a final step before running the validator.
        $this->resolveSubrules();

        // Apply input filters.
        $filters = new Filters($this->inputs, $this->filters, $this);
        $this->inputs = $filters->apply();

        // Apply custom rules.
        $this->customRules();

        $this->validator = $this->validator->make($this->inputs, $this->rules, $this->messages);

        // Apply attributes.
        $this->validator->setAttributeNames($this->attributes);

        // Run the 'after' method, letting the
        // user execute code after validation.
        if (method_exists($this, 'after')) {
            $this->after($this->validator);
        }
    }