public function post($request, $response, $service, $app)
 {
     Auth::restrictAccess('anonymous');
     $app->users = new Users();
     $app->passwordResets = new PasswordResets();
     $email = $request->param('email');
     $token = $request->param('token');
     $passwordReset = self::validatePasswordResetRequest($email, $token);
     $body = json_decode($request->body());
     $newPassword = $body->newPassword;
     $confirmPassword = $body->confirmPassword;
     if (!v::length(6, 55)->validate($newPassword)) {
         return 'password 1 dont comply';
     }
     if (!v::length(6, 55)->validate($confirmPassword)) {
         return 'password 2 dont comply';
     }
     if (!v::equals($newPassword)->validate($confirmPassword)) {
         return 'passwords dont match';
     }
     // user update password
     $app->users->updatePassword($passwordReset['userId'], $newPassword);
     // delete the passwordReset row after use
     $app->passwordResets->destroy($passwordReset['id']);
 }
 /**
  * Creates a new {@link LightInstruction}, verifying the action is valid and exactly two
  * coordinates have been given.
  *
  * @param int $action {@link LightInstructionAction}
  * @param Coordinate[] $coordinatePair two coordinates
  * @return LightInstruction
  * @throws \InvalidArgumentException
  */
 public static function create($action, array $coordinatePair)
 {
     v::oneOf(v::equals(LightInstructionAction::TURN_ON), v::equals(LightInstructionAction::TURN_OFF), v::equals(LightInstructionAction::TOGGLE))->check($action);
     v::length(2, 2)->check($coordinatePair);
     v::each(v::instance('\\Hamdrew\\AdventOfCode\\Day6\\Coordinate'))->check($coordinatePair);
     return new LightInstruction($action, $coordinatePair);
 }
Example #3
0
 /**
  * @param string $category
  * @param string|null $subCategory
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function __construct($category, $subCategory = null)
 {
     if (!is_string($category)) {
         throw new InvalidArgumentException('category', 'type_invalid');
     }
     if (!mb_check_encoding($category, 'UTF-8')) {
         throw new InvalidArgumentException('category', 'encoding_invalid');
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($category)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     $keyword = KeywordFilter::isContainGeneric($category);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     if (!is_string($subCategory)) {
         throw new InvalidArgumentException('subCategory', 'type_invalid');
     }
     if (!mb_check_encoding($subCategory, 'UTF-8')) {
         throw new InvalidArgumentException('subCategory', 'encoding_invalid');
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($subCategory)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     $keyword = KeywordFilter::isContainGeneric($subCategory);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     $this->category = $category;
     $this->subCategory = $subCategory;
 }
Example #4
0
 /**
  * 创建主题
  *
  * @param \MongoId $topicId
  * @param int $owner
  * @param string title
  * @param string $markdown
  * @return array|null
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public static function createDiscussion(\MongoId $topicId, $owner, $title, $markdown)
 {
     if (!Validator::int()->validate($owner)) {
         throw new InvalidArgumentException('owner', 'type_invalid');
     }
     if (!is_string($title)) {
         throw new InvalidArgumentException('markdown', 'type_invalid');
     }
     if (!mb_check_encoding($title, 'UTF-8')) {
         throw new InvalidArgumentException('markdown', 'encoding_invalid');
     }
     if (!is_string($markdown)) {
         throw new InvalidArgumentException('markdown', 'type_invalid');
     }
     if (!mb_check_encoding($markdown, 'UTF-8')) {
         throw new InvalidArgumentException('markdown', 'encoding_invalid');
     }
     if (!Validator::length(VJ::COMMENT_MIN, VJ::COMMENT_MAX)) {
         throw new UserException('DiscussionUtil.content_invalid_length');
     }
     self::initParser();
     $discussionId = new \MongoId();
     $html = self::$parser->parse($markdown);
     $keyword = KeywordFilter::isContainGeneric(strip_tags($html));
     if ($keyword !== false) {
         throw new UserException('DiscussionUtil.content_forbid', ['keyword' => $keyword]);
     }
     $doc = ['_id' => $discussionId, 'owner' => (int) $owner, 'topicId' => $topicId, 'at' => new \MongoDate(), 'title' => $title, 'raw' => $markdown, 'html' => $html];
     Application::coll('Discussion')->insert($doc);
     Application::emit('discussion.create.succeeded', [$topicId, $discussionId]);
     return ['_id' => $discussionId, 'html' => $html];
 }
Example #5
0
 private function validate()
 {
     $OPEIDV = v::length(6, 6);
     if ($OPEIDV->validate($this->Input->getInput('OPEID')) == false) {
         $this->validation_errors[] = 'OPEID should not be empty and have 6 digits.';
     }
     $CIPCodeV = v::length(7);
     if ($CIPCodeV->validate($this->Input->getInput('CIPCode')) == false) {
         $this->validation_errors[] = 'CIPCode should follow xx.xxxx format.';
     }
 }
Example #6
0
   public function testKeysAsValidatorNames()
   {
       try {
           Validator::key('username', Validator::length(1, 32))->key('birthdate', Validator::date())->setName("User Subscription Form")->assert(array('username' => '', 'birthdate' => ''));
       } catch (NestedValidationExceptionInterface $e) {
           $this->assertEquals('\\-These rules must pass for User Subscription Form
 |-Key username must be valid
 | \\-"" must have a length between 1 and 32
 \\-Key birthdate must be valid
   \\-"" must be a valid date', $e->getFullMessage());
       }
   }
Example #7
0
 /**
  * @auth-groups users
  */
 public function saveAction()
 {
     if (!empty($_POST['password_new'])) {
         try {
             v::length(6)->check($_POST['password_new']);
         } catch (ValidationException $e) {
             $this->flasher->error('Please make sure new password is longer than 6 characters!');
         }
         if ($_POST['password_new'] !== $_POST['password_new_confirm']) {
             $this->flasher->error('New password fields were not identical!');
         }
         if (!Gatekeeper::authenticate(['username' => $this->user->username, 'password' => $_POST['password_old']])) {
             $this->flasher->error('Invalid password. Changes ignored.');
         } else {
             $this->user->password = $_POST['password_new'];
             $this->user->save();
             $this->flasher->success('Password updated!');
         }
     }
     if ($_POST['firstname'] != '-') {
         try {
             v::alnum(' ')->check($_POST['firstname']);
             $this->user->firstName = $_POST['firstname'];
             $this->user->save();
             $this->flasher->success('First name changed.');
         } catch (ValidationException $e) {
             $this->flasher->error('Name contains invalid characters. ' . $e->getMainMessage());
         }
     }
     if ($_POST['lastname'] != '-') {
         try {
             v::alnum(' ')->check($_POST['lastname']);
             $this->user->lastName = $_POST['lastname'];
             $this->user->save();
             $this->flasher->success('Last name changed.');
         } catch (ValidationException $e) {
             $this->flasher->error('Last name contains invalid characters. ' . $e->getMainMessage());
         }
     }
     $this->redirect('/account');
 }
Example #8
0
 public function processSignupAction()
 {
     try {
         v::email()->check($_POST['email']);
         v::length(6)->check($_POST['password']);
     } catch (ValidationException $e) {
         $this->flasher->error('Please make sure your password is longer than 6 characters, and that your username is a valid email address!');
     }
     if ($_POST['password'] !== $_POST['password_confirm']) {
         $this->flasher->error('Passwords need to be identical');
     }
     if ($this->flasher->hasMessages('error')) {
         $this->redirect('/auth');
     }
     $this->initGroups();
     // Create an account if none exists
     $user = Gatekeeper::register(['first_name' => '-', 'last_name' => '-', 'username' => $_POST['email'], 'email' => $_POST['email'], 'password' => $_POST['password'], 'groups' => Gatekeeper::countUser() ? ['users'] : ['admin', 'users']]);
     if ($user) {
         $this->flasher->success('Account successfully registered! Please log in!');
     } else {
         $this->flasher->error('Error #GK01: Account creation failed!' . Gatekeeper::getDatasource()->getLastError());
     }
     $this->redirect('/auth');
 }
Example #9
0
 /**
  * @param string $name
  * @param int|null $year
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function __construct($name, $year = null)
 {
     if (!is_string($name)) {
         throw new InvalidArgumentException('name', 'type_invalid');
     }
     if (!mb_check_encoding($name, 'UTF-8')) {
         throw new InvalidArgumentException('name', 'encoding_invalid');
     }
     $keyword = KeywordFilter::isContainGeneric($name);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($name)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     if ($year !== null) {
         if (!Validator::int()->validate($year)) {
             throw new InvalidArgumentException('year', 'type_invalid');
         }
         $year = (int) $year;
     }
     $this->name = $name;
     $this->year = $year;
 }
 private function validateSoftDescriptor($parameters)
 {
     $fieldName = "soft_descriptor";
     if (array_key_exists($fieldName, $parameters)) {
         if (!v::length(1, 13, true)->validate($parameters[$fieldName]) || !v::alnum()->noWhitespace()->validate($parameters[$fieldName])) {
             $this->validationResponse->status = s::VALIDATION_ERROR;
             $this->validationResponse->errors[$fieldName] = "is invalid";
             return false;
         }
     }
     return true;
 }
/**
 * Validates that input length is greater than the expecation
 *
 * @param string           $hook       "validate:maxlength"
 * @param string           $type       "prototyper"
 * @param ValidationStatus $validation Current validation status
 * @param array            $params     Hook params
 * @return ValidationStatus
 */
function prototyper_validate_maxlength($hook, $type, $validation, $params)
{
    if (!$validation instanceof ValidationStatus) {
        $validation = new ValidationStatus();
    }
    $field = elgg_extract('field', $params);
    if (!$field instanceof Field) {
        return $validation;
    }
    $rule = elgg_extract('rule', $params);
    if ($rule != "maxlength") {
        return $validation;
    }
    $value = elgg_extract('value', $params);
    $expectation = elgg_extract('expectation', $params);
    if (!v::length(null, $expectation)->validate($value)) {
        $validation->setFail(elgg_echo('prototyper:validate:error:maxlength', array($field->getLabel(), $expectation)));
    }
    return $validation;
}
Example #12
0
 /**
  * 创建用户
  *
  * @param string $username
  * @param string $password
  * @param string $email
  * @return int UID
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function createUser($username, $password, $email)
 {
     if (!is_string($username)) {
         throw new InvalidArgumentException('username', 'type_invalid');
     }
     if (!is_string($password)) {
         throw new InvalidArgumentException('password', 'type_invalid');
     }
     if (!is_string($email)) {
         throw new InvalidArgumentException('email', 'type_invalid');
     }
     // 检查用户名
     if (!mb_check_encoding($username, 'UTF-8')) {
         throw new InvalidArgumentException('username', 'encoding_invalid');
     }
     $username = trim($username);
     if (!Validator::regex('/^\\S*$/')->length(3, 16)->validate($username)) {
         throw new InvalidArgumentException('username', 'format_invalid');
     }
     // 检查关键字
     $keyword = KeywordFilter::isContainGeneric($username);
     if ($keyword === false) {
         $keyword = KeywordFilter::isContainName($username);
     }
     if ($keyword !== false) {
         throw new UserException('UserManager.name_forbid', ['keyword' => $keyword]);
     }
     // 检查密码
     if (!Validator::length(0, 50)->validate($password)) {
         throw new InvalidArgumentException('password', 'format_invalid');
     }
     // 检查 email
     if (!Validator::email()->validate($email)) {
         throw new InvalidArgumentException('password', 'format_invalid');
     }
     // 处理用户名
     $username = VJ::removeEmoji($username);
     // 检查用户名和 Email 是否唯一
     if (UserUtil::getUserObjectByUsername($username) !== null) {
         throw new UserException('UserManager.createUser.user_exists');
     }
     if (UserUtil::getUserObjectByEmail($email) !== null) {
         throw new UserException('UserManager.createUser.email_exists');
     }
     // 生成 hash & salt
     $hashSaltPair = $this->user_credential->password_encoder->generateHash($password);
     // 插入记录
     try {
         $_id = new \MongoId();
         $doc = ['_id' => $_id, 'uid' => $_id, 'user' => $username, 'luser' => UserUtil::canonicalizeUsername($username), 'mail' => $email, 'lmail' => UserUtil::canonicalizeEmail($email), 'salt' => $hashSaltPair['salt'], 'hash' => $hashSaltPair['hash'], 'g' => $email, 'gender' => VJ::USER_GENDER_UNKNOWN, 'regat' => new \MongoDate(), 'regip' => $this->request->getClientIp()];
         Application::coll('User')->insert($doc);
     } catch (\MongoCursorException $e) {
         // 插入失败
         throw new UserException('UserManager.createUser.user_or_email_exists');
     }
     // 插入成功:更新 uid
     // 获取递增 uid
     $counterRec = Application::coll('System')->findAndModify(['_id' => 'UserCounter'], ['$inc' => ['count' => 1]], [], ['new' => true, 'upsert' => true]);
     $uid = (int) $counterRec['count'];
     try {
         // 修改 uid
         Application::coll('User')->update(['_id' => $_id], ['$set' => ['uid' => $uid]]);
     } catch (\MongoCursorException $e) {
         // 修改 uid 失败(uid 重复),则删除用户记录
         Application::critical('createUser.uidDuplicate', ['uid' => $uid]);
         Application::coll('User')->remove(['_id' => $_id], ['justOne' => true]);
         throw new UserException('UserManager.createUser.internal');
     }
     Application::emit('user.created', [$uid]);
     return $uid;
 }
Example #13
0
 public function validate($item)
 {
     $metaData = Transaction::get('array');
     foreach ($this->fieldsToCheck as $field) {
         if (is_a($this, 'Academe\\SagePay\\Validator\\Model\\Address')) {
             // I'm assuming/hoping that Billing and Delivery validation rules are identical
             $data = $metaData['Billing' . $field];
         } else {
             $data = $metaData[$field];
         }
         $value = $item->getField($field);
         if ($this->hasError($field)) {
             // We only store one error per field, so if we have already got an error for this
             // field then don't waste time checking others. This also means that we can have
             // more specific fields in the child objects which over-ride these completly.
             continue;
         }
         // State is only used when the country is US, the validation rules stores assume country is US.
         // so here we tweak them.
         if ($field == 'State' && $item->getField('Country') != 'US') {
             $data['required'] = false;
             $data['min'] = 0;
             $data['max'] = 0;
         }
         // If the item is required, check it's not empty
         if ($data['required'] && !v::notEmpty()->validate($value)) {
             if ($field == 'PostCode') {
                 // Add an exception for Postcodes when the country is one which does not have postcodes
                 if (!in_array($item->getField('Country'), $this->countriesWhichDontHavePostcodes)) {
                     $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field));
                 }
             } else {
                 if ($field == 'Amount') {
                     // 0 equates to empty, so do a special check
                     if ($item->getField('Amount') != '0' && !v::string()->notEmpty()->validate($item->getField('Amount'))) {
                         $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field));
                     }
                 } else {
                     $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field));
                 }
             }
         }
         // If there is a minimum or maximum check the length.
         // TODO: Check whether this code works well when only one or the other is set
         $min = isset($data['min']) ? $data['min'] : null;
         $max = isset($data['max']) ? $data['max'] : null;
         if ($min != null && $max != null) {
             // Check the length of the field
             if ($field == 'State') {
                 print_r("\n\nMin: {$field} : {$min}, \n\n");
                 die;
             }
             if (!v::length($min, $max, true)->validate($value)) {
                 if ($min == $max) {
                     $this->addError($field, sprintf($this->BAD_LENGTH, $field, $min));
                 } else {
                     $this->addError($field, sprintf($this->BAD_RANGE, $field, $min, $max));
                 }
             }
         }
         // Check the contents of the field
         if (isset($data['chars'])) {
             // We build two regexes, one for testing whether it matches and the other for
             // filtering out the bad characters to show the user which are not valid.
             $regex = $this->buildRegex($data['chars']);
             try {
                 if (!v::regex($regex)->validate($value)) {
                     $cleanupRegex = $this->buildRegex($data['chars'], false);
                     $badChars = preg_replace($cleanupRegex, '', $value);
                     $this->addError($field, sprintf($this->BAD_CHARACTERS, $field, $badChars, $regex));
                 }
             } catch (\Exception $e) {
                 throw new \Exception("preg_match has a problem with this regex '{$regex}'");
             }
         }
     }
     return $this;
 }
    $roleValidator = v::notEmpty();
    $companyValidator = v::notEmpty();
    $passwordValidator = v::length(6, null);
    $validators = array('email' => $emailValidator, 'password' => $passwordValidator);
    return new \DavidePastore\Slim\Validation\Validation($validators);
};
$container['registerValidation'] = function () {
    //Create the validators
    $usernameValidator = v::notEmpty()->alnum()->noWhitespace()->length(1, 10);
    $ageValidator = v::numeric()->positive()->between(1, 20);
    $emailValidator = v::email()->noWhitespace();
    $firstNameValidator = v::notEmpty();
    $lastNameValidator = v::notEmpty();
    $roleValidator = v::notEmpty();
    $companyValidator = v::notEmpty();
    $passwordValidator = v::length(8, null);
    $validators = array('email' => $emailValidator, 'password' => $passwordValidator, 'first_name' => $firstNameValidator, 'last_name' => $lastNameValidator);
    return new \DavidePastore\Slim\Validation\Validation($validators);
};
// route middleware
$container['homeRedirect'] = function ($container) {
    $uri = $container->get('request')->getUri();
    $identity = $container->get('authenticator')->getIdentity();
    die(print_r($identity));
    return true;
};
use Illuminate\Events\Dispatcher;
// route middleware
$container['events'] = function ($container) {
    $event = new Dispatcher();
    return $event;
Example #15
0
 $email = $_POST[email];
 //Validation using respect/validation
 $valid = true;
 if (!v::noWhitespace()->length(4, 20)->notEmpty()->validate($userName)) {
     $userNameError = "Por favor digite novamente o nome de usuário, entre 4 e 20 caracteres, sem espaços em branco";
     $valid = false;
 }
 if (!v::notEmpty()->validate($password)) {
     $passwordError = "Por favor digite a senha não pode ficar em branco";
     $valid = false;
 }
 if (!v::notEmpty()->length(1, 5)->validate($unidade)) {
     $unidadeError = "Por favor digite novamente o unidade, no formato A-00 (letra, traço e número)";
     $valid = false;
 }
 if (!v::length(3, 80)->notEmpty()->validate($name)) {
     $nameError = "Por favor digite novamente o nome do morador, entre 3 e 80 caracteres";
     $valid = false;
 }
 if (!v::email()->validate($email)) {
     $emailError = "O e-mail informado não é válido.";
     $valid = false;
 }
 if ($valid) {
     $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $date = date('Y-m-d H:i:s');
     //2015-10-15 15:12:23
     $slugfier = new \Slug\Slugifier();
     $slugfier->setTransliterate(true);
     $slug = $slugfier->slugify($name);
     $password_secure = sha1($password);
Example #16
0
 /**
  * @param string $source
  */
 public function setSource($source)
 {
     if (Validator::length(1, 20)->validate($source)) {
         $this->_source = $source;
     }
 }
Example #17
0
 /**
  * @param string $value
  */
 public function setVendorLeadCode($value)
 {
     if (Validator::length(1, 20)->validate($value)) {
         $this->setProperty('vendor_lead_code', $value);
     }
 }
Example #18
0
 public static function modifyMeta(\MongoId $pid, $title, array $tags, array $visibleDomains)
 {
     if (!is_string($title)) {
         throw new InvalidArgumentException('title', 'type_invalid');
     }
     if (!mb_check_encoding($title, 'UTF-8')) {
         throw new InvalidArgumentException('title', 'encoding_invalid');
     }
     if (!Validator::length(VJ::PROBLEM_TITLE_MIN, VJ::PROBLEM_TITLE_MAX)) {
         throw new UserException('ProblemUtil.title_invalid_length');
     }
     $keyword = KeywordFilter::isContainGeneric($title);
     if ($keyword !== false) {
         throw new UserException('ProblemUtil.title_forbid', ['keyword' => $keyword]);
     }
     foreach ($visibleDomains as $domain) {
         if (!$domain instanceof \MongoId) {
             throw new InvalidArgumentException('visibleDomains', 'type_invalid');
         }
     }
     foreach ($tags as $tag) {
         if (!$tag instanceof Tag) {
             throw new InvalidArgumentException('tags', 'type_invalid');
         }
     }
     $title = VJ::removeEmoji($title);
     $link = self::generateLink($title);
     try {
         $result = Application::coll('Problem')->update(['_id' => $pid], ['$set' => ['title' => $title, 'link' => $link, 'llink' => self::canonicalizeLink($link), 'tags' => array_map(function (Tag $tag) {
             return $tag->serializeForDb();
         }, $tags), 'visible' => $visibleDomains]]);
     } catch (\MongoCursorException $e) {
         throw new UserException('ProblemUtil.modifyMeta.title_exists');
     }
     return $result['n'] === 1;
 }
Example #19
0
 /**
  * 修改回复
  *
  * @param \MongoId $commentId
  * @param string $ref
  * @param \MongoId $replyId
  * @param string $markdown
  * @return array|null
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public static function modifyReply(\MongoId $commentId, $ref, \MongoId $replyId, $markdown)
 {
     if (!is_string($ref)) {
         throw new InvalidArgumentException('ref', 'type_invalid');
     }
     if (!mb_check_encoding($ref, 'UTF-8')) {
         throw new InvalidArgumentException('ref', 'encoding_invalid');
     }
     if (!is_string($markdown)) {
         throw new InvalidArgumentException('markdown', 'type_invalid');
     }
     if (!mb_check_encoding($markdown, 'UTF-8')) {
         throw new InvalidArgumentException('markdown', 'encoding_invalid');
     }
     if (!Validator::length(VJ::COMMENT_MIN, VJ::COMMENT_MAX)) {
         throw new UserException('CommentUtil.content_invalid_length');
     }
     self::initParser();
     $html = self::$parser->parse($markdown);
     $keyword = KeywordFilter::isContainGeneric(strip_tags($html));
     if ($keyword !== false) {
         throw new UserException('CommentUtil.content_forbid', ['keyword' => $keyword]);
     }
     $result = Application::coll('Comment')->update(['_id' => $commentId, 'ref' => $ref, 'deleted' => false, 'replies' => ['$elemMatch' => ['_id' => $replyId, 'deleted' => false]]], ['$set' => ['replies.$.raw' => $markdown, 'replies.$.html' => $html, 'replies.$.modifyat' => new \MongoDate()]]);
     if ($result['n'] === 1) {
         Application::emit('comment.reply.modify.succeeded', [$ref, $commentId, $replyId]);
         return ['_id' => $replyId, 'html' => $html];
     } else {
         return null;
     }
 }