public function validate($data) { $validator = V::key('name', V::string()->length(0, 100), true)->key('email', V::email()->length(0, 200), true)->key('password', V::string()->length(0, 100), true); try { $validator->assert($data); switch ($data['userable_type']) { case 'Designer': $this->designerCreationValidator->validate($data); $data['userable_type'] = DesignerModel::class; break; case 'Administrator': $this->adminCreationValidator->validate($data); $data['userable_type'] = AdministratorModel::class; break; case 'Buyer': $this->buyerCreationValidator->validate($data); $data['userable_type'] = BuyerModel::class; break; default: break; } } catch (AbstractNestedException $e) { $errors = $e->findMessages(['email', 'length', 'in']); throw new ValidationException('Could not create user.', $errors); } return true; }
public function testValidatorWithFilterGroups() { $allOfFilter = new AllOfFilter([new ClosureFilter('name', v::intVal()), v::key('key', v::regex('/test.+/i'))]); static::assertTrue($allOfFilter->matches(['name' => '1234', 'key' => 'test47382'])); static::assertFalse($allOfFilter->matches(['name' => 'test', 'key' => 'test47382'])); static::assertFalse($allOfFilter->matches(['name' => '1234', 'key' => 'test'])); }
private function validateField($parameters, $fieldName) { if (v::key($fieldName)->validate($parameters)) { if (v::notEmpty()->validate($parameters[$fieldName])) { return true; } } return false; }
public function validate($data) { $validator = V::key('about', V::string()->length(0, 100), false)->key('website', V::string()->length(0, 100), false)->key('twitter_username', V::string()->length(0, 100), false)->key('facebook_url', V::string()->length(0, 100), false)->key('pinterest_url', V::string()->length(0, 100), false)->key('instagram_username', V::string()->length(0, 100), false); try { $validator->assert($data); } catch (AbstractNestedException $e) { $errors = $e->findMessages(['about', 'website', 'twitter_username', 'facebook_url', 'pinterest_url', 'instagram_username']); throw new ValidationException('Could not update user.', $errors); } return true; }
public function validate($data) { $validator = V::key('retailer_id', V::int()->length(0, 100), true); try { $validator->assert($data); } catch (AbstractNestedException $e) { $errors = $e->findMessages(['retailer_id']); throw new ValidationException('Could not create user.', $errors); } return true; }
protected function validateRequired($parameters, $fieldNames) { foreach ($fieldNames as $fieldName) { if (!v::key($fieldName)->validate($parameters)) { $this->validationResponse->status = s::VALIDATION_ERROR; $this->validationResponse->errors[$fieldName] = "is required"; return false; } } return true; }
private static function validateParameters($app, $post) { if (v::key('email', v::email())->validate($post)) { return $app->render(400, array('msg' => 'Invalid email. Check your parameters and try again.')); } else { if (!v::key('name', v::stringType())->validate($post) || !v::key('subject', v::stringType())->validate($post) || !v::key('message', v::stringType())->validate($post)) { return $app->render(400, array('msg' => 'Invalid subject or message. Check your parameters and try again.')); } } return true; }
/** * Handle domain logic for an action. * * @param array $input * @return PayloadInterface */ public function __invoke(array $input) { //Authorize user to be able to view shifts $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'view', 'shifts'); //Validate input $inputValidator = v::key('startDateTime', v::stringType())->key('endDateTime', v::stringType()); $inputValidator->assert($input); //Retrieve shifts between in time period $shifts = $this->shiftRepository->getShiftsBetween(Carbon::parse($input['startDateTime']), Carbon::parse($input['endDateTime'])); $this->collection->setData($shifts)->setTransformer($this->shiftTransformer); return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->collection)->toArray()); }
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()); } }
/** * Handle domain logic for an action. * * @param array $input * @return PayloadInterface */ public function __invoke(array $input) { //Check that user has permission to edit this resource $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('entity'), 'edit', 'shifts'); //Validate input $inputValidator = v::key('id', v::intVal())->key('employee_id', v::intVal()); $inputValidator->assert($input); //Execute command to update employee on shift $shift = $this->commandBus->handle(new AssignShiftCommand($input['id'], $input['employee_id'])); $shiftItem = new Item($shift, new ShiftTransformer()); return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($shiftItem)->toArray()); }
/** * Handle domain logic for an action. * * @param array $input * @return PayloadInterface */ public function __invoke(array $input) { //Check that user is authorized to view this resource $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity'), 'view', 'users'); //Validate input $inputValidator = v::key('id', v::intVal()); $inputValidator->assert($input); //Get user from repository and transform into resource $user = $this->userRepository->getOneByIdOrFail($input['id']); $this->item->setData($user)->setTransformer($this->userTransformer); return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->createData($this->item)->toArray()); }
/** * Handle domain logic for an action. * * @param array $input * @return PayloadInterface */ public function __invoke(array $input) { //Check that user is authorized to edit this resource $this->authorizeUser($input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity'), 'edit', 'shifts'); //Validate input $inputValidator = v::key('break', v::floatVal())->key('start_time', v::stringType())->key('end_time', v::stringType())->key('id', v::intVal()); $inputValidator->assert($input); //Update shift data $shift = $this->commandBus->handle(new UpdateShiftCommand($input['id'], $input['break'], $input['start_time'], $input['end_time'])); $shiftItem = new Item($shift, new ShiftTransformer()); return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->createData($shiftItem)->toArray()); }
/** * Handle notes validation, creation and update * * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request * @param \Psr\Http\Message\ResponseInterface $response PSR7 response * @param callable $next Next middleware * * @return \Psr\Http\Message\ResponseInterface */ public function dispatch(Request $request, Response $response, $args) { $id = isset($args['id']) ? (int) $args['id'] : null; $input = $request->getParsedBody(); $validator = v::key('body', v::stringType()->notEmpty()->length(5, null, true)); $validator->assert($input); if ($id === null) { $note = $this->create($input); } else { $note = $this->update($input, $id); } return $response->write(json_encode([$note])); }
public function validateAddress($address) { //@TODO: properly check all types.. strings need to be double checked for alnum, cause of typecasting. $rules = v::key('firstname', v::notEmpty()->setName('First name'))->key('lastname', v::notEmpty()->setName('Last name'))->key('address', v::alnum(".,-'")->notEmpty()->setName('Address'))->key('secondary_address', v::when(v::notEmpty(), v::alnum(".,-'"), v::alwaysValid())->setName('Address 2'))->key('city', v::alnum()->notEmpty()->setName('City'))->key('state', v::alnum()->notEmpty()->setName('State'))->key('zip', v::when(v::notEmpty(), v::postalCode('US'), v::alwaysValid())->notEmpty()->setName('Zipcode')); if ($rules->validate($address)) { return true; } try { $rules->check($address); } catch (ValidationExceptionInterface $exception) { // $this->error = $exception->getMainMessage(); } return false; }
public function output($request, $response, $args) { $query = $request->getQueryParams(); $validator = v::key('a', v::stringType()->length(1, 32))->key('b', v::alnum()); list($ok, $message) = $this->validate($validator, $query); if (!$ok) { return $this->view->error('INPUT_ERROR', $message); } $ret = array(); for ($i = 0; $i < 4; $i++) { $ret[] = array('data' => $i); } return $this->view->render($ret); }
private static function authorizeApiToken($app) { if (!v::key('apiKey', v::stringType())->validate($app->request->post()) || !v::key('apiToken', v::stringType())->validate($app->request->post())) { return false; } $user = AuthData::selectUserByIdentifierToken($app->request->post('apiKey')); if (!$user) { return "user"; } if (!password_verify($app->request->post('apiToken'), $user->apiToken)) { return "password"; } // Go now. Be free little brother. return $user->id; }
/** * @param array $input * @return PayloadInterface * @throws UserNotAuthorized */ public function __invoke(array $input) { //Don't allow employees to view other employee's shifts //todo: figure out if managers can access all employees' shifts if ($input['id'] != $input[AuthHandler::TOKEN_ATTRIBUTE]->getMetaData('id')) { throw new UserNotAuthorized(); } //Validate input $inputValidator = v::key('id', v::intVal()); $inputValidator->assert($input); //Get shifts and transform $employee = $this->userRepository->getOneByIdOrFail($input['id']); $shifts = $this->shiftRepository->getByEmployee($employee); $this->collection->setData($shifts)->setTransformer($this->shiftTransformer); $include = array_key_exists('include', $input) ? $input['include'] : ''; return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes($include)->createData($this->collection)->toArray()); }
/** * Handle domain logic for an action. * * @param array $input * @return PayloadInterface */ public function __invoke(array $input) { //Ensure that the use has permission to create shifts $user = $input[AuthHandler::TOKEN_ATTRIBUTE]->getMetadata('entity'); $this->authorizeUser($user, 'create', 'shifts'); //If no manager_id is specified in request, default to user creating shift if (!array_key_exists('manager_id', $input)) { $input['manager_id'] = $user->getId(); } //Validate input $inputValidator = v::key('break', v::floatVal())->key('start_time', v::date())->key('end_time', v::date()->min($input['start_time']))->key('manager_id', v::intVal()); $inputValidator->assert($input); //Execute command to create shift $shift = $this->commandBus->handle(new CreateShift($input['manager_id'], $input['employee_id'], $input['break'], $input['start_time'], $input['end_time'])); $this->item->setData($shift)->setTransformer($this->shiftTransformer); return $this->payload->withStatus(PayloadInterface::OK)->withOutput($this->fractal->parseIncludes(['manager', 'employee'])->createData($this->item)->toArray()); }
static function addAction($app) { $post = $app->request->post(); // Validate parameters // Must have one or the other, or both 'action' and 'code' if (!v::key('action', v::stringType())->validate($post) && !v::key('code', v::stringType())->validate($post)) { // Validate input parameters return $app->render(400, array('msg' => 'Add action failed. Check your parameters and try again.')); } // Add the verifed action $newAction = array(":action" => v::key('action', v::stringType())->validate($post) ? $app->request->post('action') : '', ":code" => v::key('code', v::stringType())->validate($post) ? $app->request->post('code') : '', ":http_referer" => $app->request->getReferrer(), ":ip_address" => $app->request->getIp(), ":created_user_id" => APIAuth::getUserId()); $actionId = ActionData::insertAction($newAction); if ($actionId) { return $app->render(200, array('msg' => 'Action recorded.', 'action' => $actionId)); } else { return $app->render(400, array('msg' => 'Could not add new action.', 'action' => $newAction)); } }
static function quietlySaveAdditional($post, $userId = false) { $saved = false; $userId = !$userId && v::key('userId', v::stringType())->validate($post) ? $post['userId'] : $userId; if ($userId && v::key('referrer', v::stringType()->length(1, 255))->validate($post)) { $data = array(':user_id' => $userId, ':question' => "Where did you about from us?", ':answer' => $post['referrer']); $saved = InfoData::insertQuestion($data); } if ($userId && v::key('triviaLove', v::stringType()->length(1, 255))->validate($post)) { $data = array(':user_id' => $userId, ':question' => "How comitted are you?", ':answer' => $post['triviaLove']); $saved = InfoData::insertQuestion($data); } if ($userId && v::key('acceptTerms', v::stringType())->validate($post)) { $acceptTerms = $post['acceptTerms'] === 1 || $post['acceptTerms'] === '1' || $post['acceptTerms'] === true || $post['acceptTerms'] === 'true' ? 1 : 0; $data = array(':user_id' => $userId, ':accepted_terms' => $acceptTerms); $saved = InfoData::saveTerms($data); } return $saved; }
public function validate($data) { $validator = V::key('name', V::string()->length(0, 100), false)->key('email', V::email()->length(0, 200), false)->key('password', V::string()->length(0, 100), false)->key('city', V::string()->length(0, 100), false)->key('state', V::string()->length(0, 100), false)->key('language', V::string()->length(0, 100), false); try { $validator->assert($data); switch ($data['userable_type']) { case 'HOFB\\Users\\Designers\\DesignerModel': $this->designerUpdateValidator->validate($data); break; case 'HOFB\\Users\\Admins\\AdministratorModel': $this->adminUpdateValidator->validate($data); break; case 'HOFB\\Users\\Buyers\\BuyerModel': $this->buyerUpdateValidator->validate($data); break; default: break; } } catch (AbstractNestedException $e) { $errors = $e->findMessages(['email', 'length', 'in']); throw new ValidationException('Could not update user.', $errors); } return true; }
private static function hookCallHotSalsaVenueRegister($app, $apiResponse, $editFlag) { $vars = self::data_hookConfigVars('HOT_SALSA_'); if (!isset($vars['HOT_SALSA_VENUE_REGISTRATION_ENABLED']) || $vars['HOT_SALSA_VENUE_REGISTRATION_ENABLED'] !== 'true' && $vars['HOT_SALSA_VENUE_REGISTRATION_ENABLED'] !== '1') { return; } $url_var = $vars['HOT_SALSA_VENUE_REGISTRATION_URL']; if (!isset($url_var) || !isset($vars['HOT_SALSA_APP_VERSION']) || !isset($vars['HOT_SALSA_URL_CODE']) || !isset($vars['HOT_SALSA_AUTH_KEY']) || !isset($vars['HOT_SALSA_OS']) || !isset($vars['HOT_SALSA_PACKAGE_CODE'])) { self::data_logHotSalsaVenueError($apiResponse['venue']->id, "Could not attempt call. The Hot Salsa signup hook is enabled but a system variable is disabled or missing.", $vars); return; } // Get Post Data $post = $app->request->post(); $params = array('name' => $post['venue'], 'email' => v::key('email', v::email())->validate($post) ? $post['email'] : '', 'firstName' => v::key('nameFirst', v::stringType())->validate($post) ? $post['nameFirst'] : '', 'lastName' => v::key('nameLast', v::stringType())->validate($post) ? $post['nameLast'] : '', 'password' => v::key('password', v::stringType())->validate($post) ? $post['password'] : '', 'phoneNumber' => (v::key('phone_extension', v::stringType())->validate($post) ? $post['phone_extension'] : '') . (v::key('phone', v::stringType())->validate($post) ? $post['phone'] : ''), 'address1' => $post['address'], 'address2' => v::key('addressb', v::stringType())->validate($post) ? $post['addressb'] : '', 'city' => $post['city'], 'state' => $post['state'], 'postalCode' => $post['zip'], 'country' => 'US', 'triviaDay' => $post['triviaDay'], 'triviaTime' => $post['triviaTime'], 'appVersion' => $vars['HOT_SALSA_APP_VERSION'], 'code' => $vars['HOT_SALSA_URL_CODE'], 'authKey' => $vars['HOT_SALSA_AUTH_KEY'], 'os' => $vars['HOT_SALSA_OS'], 'packageCode' => $vars['HOT_SALSA_PACKAGE_CODE']); if ($editFlag == true) { $salsa_location_details = DBConn::selectOne("SELECT salsa_location_id " . "FROM " . DBConn::prefix() . "venues WHERE id = :id ORDER BY id Desc LIMIT 1;", array(':id' => $apiResponse['venue']->id)); if (!empty($salsa_location_details) && $salsa_location_details->salsa_location_id > 0) { $params['locationId'] = $salsa_location_details->salsa_location_id; } } // If it was standard signup if (isset($post['password'])) { $params['password'] = password_hash($post['password'], PASSWORD_DEFAULT); } // If it was facebook signup if (isset($post['facebookId'])) { $params['facebookId'] = $post['facebookId']; } // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, $url_var); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); /* curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); */ //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $curlOutput = curl_exec($ch); if (!$curlOutput) { // No Results = Error $error = curl_error($ch) ? curl_error($ch) : 'ERROR: No results'; $info = curl_getinfo($ch) ? json_encode(curl_getinfo($ch)) : 'ERROR: No Info'; self::data_logHotSalsaVenueError($apiResponse['venue']->id, $error, $info); } else { // Results $curlResult = json_decode($curlOutput, true); if (!isset($curlResult['status']) || $curlResult['status'] === 'failed') { $error = isset($curlResult['status']) ? $curlResult['status'] : 'ERROR: Unknown error occured'; self::data_logHotSalsaVenueError($apiResponse['venue']->id, $error, $curlOutput); } else { self::data_logHotSalsaVenueResults($curlResult, $app, $apiResponse); } } // close curl resource to free up system resources curl_close($ch); }
private function validate($input) { $validator = v::key('username', v::alnum()->notEmpty()->noWhitespace())->key('password', v::stringType()->notEmpty()->length(3, 20)); $validator->assert($input); }
static function assignRole($app) { if (!v::key('groupId', v::stringType())->validate($app->request->post()) || !v::key('roleId', v::stringType())->validate($app->request->post())) { return $app->render(400, array('msg' => 'Could not assign role from group. Check your parameters and try again.')); } $data = array(':auth_group_id' => $app->request->post('groupId'), ':auth_role_id' => $app->request->post('roleId'), ":created_user_id" => APIAuth::getUserId()); if (GroupData::insertRoleAssignment($data)) { return $app->render(200, array('msg' => 'Role has been assigned from group.')); } else { return $app->render(400, array('msg' => 'Could not assign role to group.')); } }
static function saveVariablePermissions($app, $variableId) { if (!v::intVal()->validate($variableId) || !v::key('indestructible')->validate($app->request->post()) || !v::key('locked')->validate($app->request->post())) { // Validate input parameters return $app->render(400, array('msg' => 'Update failed. Check your parameters and try again.')); } $savedConfig = ConfigData::getVariableById($variableId); if (!$savedConfig) { return $app->render(400, array('msg' => 'Variable doesnt seem to exist.')); } $indestructible = $savedConfig->indestructible; // Converting to boolean did not work well, // This allows a wider range of true false values $indestructible = $app->request->post('indestructible') === 1 || $app->request->post('indestructible') === '1' || $app->request->post('indestructible') === true || $app->request->post('indestructible') === 'true' ? 1 : 0; $locked = $savedConfig->locked; // Converting to boolean did not work well, // This allows a wider range of true false values $locked = $app->request->post('locked') === 1 || $app->request->post('locked') === '1' || $app->request->post('locked') === true || $app->request->post('locked') === 'true' ? 1 : 0; // If its locked its also indestructible $data = array(":id" => $variableId, ":indestructible" => $locked ? 1 : $indestructible, ":locked" => $locked, ":last_updated_by" => APIAuth::getUserId()); $config = ConfigData::updateVariablePermissions($data); if ($config) { $config = ConfigData::getVariableById($variableId); return $app->render(200, array('variable' => $config)); } else { return $app->render(400, array('msg' => 'Could not update system config variable permissions.')); } }
public function testShouldWorkWithSymfonyValidators() { $respectValidator = Validator::key('test', Validator::sf('Time')); $validator = new RespectValidationAdapter('failed_validator', $respectValidator); assertThat('The respect validation adapter should work with Respects Symfony validation rule.', $validator(['test' => 'Not a time.']), is('failed_validator')); }
static function updateUserPassword($app) { $post = $app->request->post(); if (!v::key('userId', v::stringType())->validate($post) || !v::key('current', v::stringType())->validate($post) || !v::key('new', v::stringType())->validate($post)) { return false; } return self::login_logoutCurrentAccount($app->request->post()); }
<?php require_once ROOT . 'models/model.php'; use Respect\Validation\Validator as v; $validateSignup = function () use($app) { $req = $app->request(); $data = $req->post(); $validator = v::key('domain', v::domain()->notEmpty())->key('username', v::string()->notEmpty()->length(1, 32))->key('email', v::email()->notEmpty())->key('nick', v::string()->notEmpty()->length(1, 32))->key('password', v::string()->notEmpty()->length(6, 20))->key('password_confirm', v::equals($data['password'])->notEmpty()); try { $validator->assert($data); } catch (\InvalidArgumentException $e) { $errors = $e->findMessages(array('domain' => '网站域名不能为空', 'username' => '账户只能是英文字符和数字', 'email' => '邮箱格式不正确', 'nick' => '用户名称不能为空', 'password' => '密码不能少于6个字符', 'password_confirm' => '两次输入的密码不一致')); $app->flash('errors', $errors); $app->redirect(SITE_URL . '/signup'); } }; /** *------------------------------------------- * User Signup *------------------------------------------- */ $app->get('/signup', function () use($app) { $app->render("signup.html"); })->name('signup'); $app->post('/signup', $validateSignup, function () use($app) { // $this->halt('500', "Signup Not Supported Now"); $req = $app->request(); $data = $req->post(); $error = null; $user = ORM::forTable('users')->where('email', $data['email'])->findOne(); if ($user) {
static function initVisibilityElement($app) { if (!v::key('fieldIdentifier', v::stringType())->validate($app->request->post())) { return $app->render(400, array('msg' => 'Could not initialize visibility field. Check your parameters and try again.')); } if (FieldData::updateVisibilityElementInit(array(':identifier' => $app->request->post('fieldIdentifier'), ":last_updated_by" => APIAuth::getUserId()))) { $field = FieldData::getByIdentifier($app->request->post('fieldIdentifier')); return $app->render(200, array('msg' => 'The visibility field has been initialized.', 'field' => $field)); } else { return $app->render(400, array('msg' => 'Could not initialize visibility field.')); } }
static function declineTeamInvite($app) { $post = $app->request->post(); if (!v::key('inviteToken', v::stringType())->validate($post) || !v::key('userId', v::intVal())->validate($post) || !v::key('teamId', v::intVal())->validate($post)) { return $app->render(400, array('msg' => 'Invalid token. Check your parameters and try again.')); } $sent = EmailData::updateDeclineInvite(array(':token' => $post['inviteToken'], ':team_id' => $post['teamId'], ':user_id' => $post['userId'])); if ($sent) { return $app->render(200, array('msg' => "Team invitation has been declined.")); } else { return $app->render(400, array('msg' => 'Could not update team invite.')); } }