/**
  * Validates a AJAX validation request and returns a JsonResponse
  *
  * @param \Illuminate\Http\Request $request
  * @param array                    $rules
  * @param array                    $messages
  * @return \Illuminate\Http\JsonResponse
  */
 public function validate(Request $request, array $rules = [], array $messages = [])
 {
     $rules = $this->getRules()->merge($rules)->toArray();
     if ($singleField = $request->has($this->singleFieldReferenceKey)) {
         $fields = [$request->get($this->singleFieldReferenceKey)];
     } else {
         $fields = Arr::keys($this->getRules()->toArray());
     }
     $data = $request->only($fields);
     $rules = Arr::only($rules, $fields);
     $validator = $this->validationFactory->make($data, $rules, $messages);
     if ($validator->fails()) {
         $messages = $validator->getMessageBag();
         if ($singleField) {
             $fieldName = $request->get($this->singleFieldReferenceKey);
             return $this->jsonResponse([$fieldName => $messages->first($fieldName)]);
         } else {
             $response = [];
             foreach ($messages->keys() as $key) {
                 $response[$key] = $messages->first($key);
             }
             return $this->jsonResponse($response);
         }
     } else {
         return $this->jsonResponse('true');
     }
 }
Beispiel #2
0
 /**
  * Injects validator with rules and data if validation is required
  *
  * @param Factory $factory
  *
  * @return Validator
  */
 public function validator(Factory $factory)
 {
     if (!$this->shouldBeValidated()) {
         return $factory->make([], []);
     }
     $rules = $this->container->call([$this, 'rules']);
     return $factory->make($this->all(), $rules, $this->messages(), $this->attributes());
 }
Beispiel #3
0
 /**
  * Make sure the given attributes comply to our rules.
  *
  * Throws an exception if validation fails.
  *
  * @param array $attributes
  * @return $this
  * @throws \FluxBB\Server\Exception\ValidationFailed
  */
 protected function ensureValid(array $attributes)
 {
     $validation = $this->validation->make($attributes, $this->rules());
     if ($validation->fails()) {
         throw new ValidationFailed($validation->getMessageBag());
     }
     return $this;
 }
 /**
  * Validate the data and the rules to the validator
  *
  * @return boolean
  */
 public function validate()
 {
     $validator = $this->validator->make($this->data, $this->rules, $this->messages);
     if ($validator->fails()) {
         $this->errors = $validator->messages();
         return false;
     }
     return true;
 }
 /**
  * Creates JsValidator instance based on FormRequest
  *
  * @param $formRequest
  * @param null $selector
  * @return Manager
  * @throws FormRequestArgumentException
  */
 public function formRequest($formRequest, $selector = null)
 {
     if (!is_subclass_of($formRequest, "Illuminate\\Foundation\\Http\\FormRequest")) {
         $className = is_object($formRequest) ? get_class($formRequest) : (string) $formRequest;
         throw new FormRequestArgumentException($className);
     }
     $formRequest = is_string($formRequest) ? new $formRequest() : $formRequest;
     $validator = $this->validator->make([], $formRequest->rules(), $formRequest->messages(), $formRequest->attributes());
     return $this->createValidator($validator, $selector);
 }
 public function update($id, array $attribute)
 {
     $attribute['id'] = $id;
     $rules = array_merge($this->rules['common'], $this->rules['update']);
     $validator = $this->validation->make($attribute, $rules);
     if ($validator->fails()) {
         throw new ValidationException($validator);
     }
     return $this->model->update($id, $attribute);
 }
 /**
  * Validate the command.
  *
  * @param object $command
  *
  * @throws \AltThree\Validator\ValidationException
  *
  * @return void
  */
 protected function validate($command)
 {
     if (method_exists($command, 'validate')) {
         $command->validate();
     }
     $messages = property_exists($command, 'validationMessages') ? $command->validationMessages : [];
     $validator = $this->factory->make($this->getData($command), $command->rules, $messages);
     if ($validator->fails()) {
         throw new ValidationException($validator->getMessageBag());
     }
 }
Beispiel #8
0
 /**
  * Execute validation service.
  *
  * @param  array  $input
  * @param  string|array  $events
  * @param  array  $phrases
  *
  * @return \Illuminate\Contracts\Validation\Validator
  */
 public function runValidation(array $input, $events = [], array $phrases = [])
 {
     if (is_null($this->validationScenarios)) {
         $this->onValidationScenario('any');
     }
     $this->runQueuedOn();
     list($rules, $phrases) = $this->runValidationEvents($events, $phrases);
     $validationResolver = $this->validationFactory->make($input, $rules, $phrases);
     $this->runQueuedExtend($validationResolver);
     return $validationResolver;
 }
 /**
  * Validate the given model.
  *
  * @param \Illuminate\Database\Eloquent\Model $model
  *
  * @throws \AltThree\Validator\ValidationException
  *
  * @return void
  */
 protected function validate(Model $model)
 {
     $attributes = $model->getAttributes();
     $messages = isset($model->validationMessages) ? $model->validationMessages : [];
     $validator = $this->factory->make($attributes, $model->rules, $messages);
     if ($validator->fails()) {
         throw new ValidationException($validator->getMessageBag());
     }
     if (method_exists($model, 'validate')) {
         $model->validate();
     }
 }
Beispiel #10
0
 /**
  * check if the input is valid
  *
  * @param array  $attributes
  * @param string $rules
  * @return bool
  */
 public function isValid(array $attributes, $rules = 'rules')
 {
     //validator
     $validator = $this->factory->make($attributes, static::${$rules});
     //passes validation
     if (!$validator->fails()) {
         return true;
     }
     //set errors
     $this->errors = $validator->getMessageBag();
     //return
     return false;
 }
Beispiel #11
0
 /**
  * Get the validator instance.
  *
  * @return \Illuminate\Contracts\Validation\Validator
  */
 public function getValidator()
 {
     if (!$this->validator) {
         $this->validator = static::$validatorFactory->make([], static::getCreateRules(), static::getValidationMessages(), static::getValidationAttributes());
     }
     return $this->validator;
 }
 /**
  * Execute the command.
  *
  * @param ContentType $contentType
  * @param Validator $validator
  * @param Dispatcher $dispatcher
  * @return CommandResult
  */
 public function handle(ContentType $contentType, Validator $validator, Dispatcher $dispatcher)
 {
     // validate authorization
     if (!$this->disablePermissionChecking) {
         if (!$this->user->hasAnyPermission(['contentBuilder.manage'])) {
             return new CommandResult(false, CommandResult::$responseForbiddenMessage, null, 403);
         }
     }
     // validate data
     $validationResult = $validator->make(array('taxonomy' => $this->taxonomy, 'content_type_id' => $this->contentTypeId), ContentTypeTaxonomy::$rules);
     if ($validationResult->fails()) {
         return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400);
     }
     // prepare the data to be stored
     $taxonomyToBeCreated = array('taxonomy' => $this->taxonomy, 'description' => $this->description);
     // fire creating event
     $dispatcher->fire('contentTypeTaxonomy.creating', array($taxonomyToBeCreated));
     // store
     try {
         $contentType = $contentType->findOrFail($this->contentTypeId);
         $createdContentTypeTaxonomy = $contentType->taxonomies()->create($taxonomyToBeCreated);
     } catch (\Exception $e) {
         return new CommandResult(false, "Invalid Content Type.", null, 400);
     }
     // fire creating event
     $dispatcher->fire('contentTypeTaxonomy.created', array($createdContentTypeTaxonomy));
     // return
     return new CommandResult(true, "Content type taxonomy successfully created.", $createdContentTypeTaxonomy, 201);
 }
 /**
  * @param Factory $validator
  * @param Dispatcher $dispatcher
  * @param ContentType $contentType
  * @param ContentTypeFormGroup $contentTypeFormGroup
  * @return CommandResult
  */
 public function handle(Factory $validator, Dispatcher $dispatcher, ContentType $contentType, ContentTypeFormGroup $contentTypeFormGroup)
 {
     // check if user has permission
     if (!$this->disablePermissionChecking) {
         if (!$this->user->hasAnyPermission(['contentBuilder.manage'])) {
             return new CommandResult(false, "Not enough permission.", null, 403);
         }
     }
     // validate data
     $validationResult = $validator->make(array('name' => $this->name, 'form_name' => $this->formName, 'fields' => $this->fields, 'content_type_id' => $this->contentTypeId), ContentTypeFormGroup::$rules);
     if ($validationResult->fails()) {
         return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400);
     }
     // fire event creating
     $dispatcher->fire('formGroup.creating', array($this->args));
     // begin create
     if (!($cType = $contentType->find($this->contentTypeId))) {
         return new CommandResult(false, "Content Type Not Found.", null, 400);
     }
     $createdFormGroup = $cType->formGroups()->create(array('name' => $this->name, 'form_name' => $this->formName, 'conditions' => $this->conditions, 'fields' => $this->fields, 'content_type_id' => $this->contentTypeId));
     // fire event creating
     $dispatcher->fire('formGroup.created', array($createdFormGroup));
     // all good
     return new CommandResult(true, "Form group successfully created.", $createdFormGroup, 201);
 }
 /**
  * handle group creation logic
  *
  * @param Validator $validator
  * @param Dispatcher $dispatcher
  * @param Group $group
  * @return CommandResult
  */
 public function handle(Validator $validator, Dispatcher $dispatcher, Group $group)
 {
     // check user permission
     if (!$this->disablePermissionChecking) {
         if (!$this->user->hasAnyPermission(['user.manage'])) {
             return new CommandResult(false, CommandResult::$responseForbiddenMessage, null, 403);
         }
     }
     // validate data
     $validationResult = $validator->make(array('name' => $this->name, 'permissions' => $this->permissions), Group::$rules);
     if ($validationResult->fails()) {
         return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400);
     }
     // prepare data to be store
     $groupToBeCreated = array('name' => $this->name, 'permissions' => $this->transform($this->permissions));
     // fire creating
     $dispatcher->fire('group.creating', array($groupToBeCreated));
     // create
     $createdGroup = $group->create($groupToBeCreated);
     if (!$createdGroup) {
         return new CommandResult(false, "Failed to create user.", null, 400);
     }
     // fire created user
     $dispatcher->fire('group.created', array($createdGroup));
     // return response
     return new CommandResult(true, "Group successfully created.", $createdGroup, 201);
 }
 public function handle(Navigation $navigation, Factory $validator, Dispatcher $dispatcher)
 {
     // check if user has permission
     if (!$this->disablePermissionChecking) {
         if (!$this->user->hasAnyPermission(['navigationBuilder.manage'])) {
             return new CommandResult(false, "Not enough permission.", null, 403);
         }
     }
     // validate data
     $validationResult = $validator->make(array('name' => $this->name, 'data' => $this->data), Navigation::$rules);
     if ($validationResult->fails()) {
         return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400);
     }
     if (!($nav = $navigation->find($this->id))) {
         return new CommandResult(false, 'Navigation does not exist.', null, 400);
     }
     // fire before create event
     $dispatcher->fire('navigationBuilder.updating', array($nav, $this->args));
     $nav->name = $this->name;
     $nav->data = $this->data;
     $nav->save();
     // fire after create
     $dispatcher->fire('navigationBuilder.updated', array($nav, $this->args));
     // all good
     return new CommandResult(true, "Navigation successfully updated.", $nav, 200);
 }
Beispiel #16
0
 /**
  * Update handler.
  *
  * @param $clientId
  *
  * @return \Illuminate\Http\Response|\Laravel\Passport\Client
  * @throws \Illuminate\Validation\ValidationException
  */
 public function update($clientId)
 {
     if (!$this->request->user()->clients->find($clientId)) {
         return new Response('', 404);
     }
     $this->validation->make($this->request->all(), ['name' => 'required|max:255', 'redirect' => 'required|url'])->validate();
     return $this->clients->update($this->request->user()->clients->find($clientId), $this->request->name, $this->request->redirect);
 }
Beispiel #17
0
 public function isValid()
 {
     if (!is_array($this->rules()) || count($this->rules()) === 0) {
         return true;
     }
     $this->validatorInstance = $this->validator->make($this->request->all(), $this->rules(), $this->messages(), $this->attributes());
     return $this->validatorInstance->passes();
 }
 /**
  * Validate the form
  *
  * @param array $validationRules
  * @param array $messages
  * @return Validator
  */
 public function validate($validationRules = [], $messages = [])
 {
     $fieldRules = $this->formHelper->mergeFieldsRules($this->fields);
     $rules = array_merge($fieldRules['rules'], $validationRules);
     $this->validator = $this->validatorFactory->make($this->getRequest()->all(), $rules, $messages);
     $this->validator->setAttributeNames($fieldRules['attributes']);
     return $this->validator;
 }
Beispiel #19
0
 public function it_should_prevent_saving_is_validation_fails(Factory $factory, Validator $validator)
 {
     $rules = ['name' => 'required'];
     $this->setRules($rules);
     // Invalid
     $factory->make($this->getAttributes(), $rules)->shouldBeCalled()->willReturn($validator);
     $validator->fails()->shouldBeCalled()->willReturn(true);
     $validator->failed()->shouldBeCalled()->willReturn(["name" => ["Required" => []]]);
     $this->shouldThrow('\\Pisa\\GizmoAPI\\Exceptions\\ValidationException')->duringSave();
 }
 /**
  * Get parameters for sending the message
  *
  * @param \Illuminate\Contracts\Validation\Factory $validator
  * @param array $messageParameters
  * @return array
  * @throws \Exception
  */
 protected function getMessageParameters(Validator $validator, $messageParameters)
 {
     $messageParameters['from'] = $this->formatMessageParameter($messageParameters['from'], 'From');
     $messageParameters['to'] = $this->formatMessageParameter($messageParameters['to'], 'To');
     $validation = $validator->make($messageParameters, ['from.address' => 'email', 'to.address' => 'email']);
     if ($validation->fails()) {
         throw new \Exception($validation->getMessageBag()->first());
     }
     return $messageParameters;
 }
Beispiel #21
0
 /**
  * @param array $data
  * @param array $rules
  *
  * @return array
  */
 protected function runValidation(array $data, array $rules)
 {
     $validation = $this->validator->make($data, $rules, $this->model->validationMessages());
     if ($validation->fails()) {
         $validation->setAttributeNames($this->model->frontEndAttributeNames());
         $messagesArray = $validation->messages()->getMessages();
         return $this->model->forwardTransformAttributeKeyNames($messagesArray);
     }
     return null;
 }
Beispiel #22
0
 /**
  * @param Dictionary $metaBag
  */
 protected function validateBag(Dictionary $metaBag)
 {
     if (empty($this->rules)) {
         return;
     }
     $validator = self::$validator->make($metaBag->toArray(), $this->rules);
     if ($validator->fails()) {
         throw new InvalidMetaException($validator->getMessageBag());
     }
 }
 /**
  * @param string $type
  * @param int $count
  * @throws ValidationException
  */
 protected function validateTagCount($type, $count)
 {
     $min = $this->settings->get('flarum-tags.min_' . $type . '_tags');
     $max = $this->settings->get('flarum-tags.max_' . $type . '_tags');
     $key = 'tag_count_' . $type;
     $validator = $this->validator->make([$key => $count], [$key => ['numeric', $min === $max ? "size:{$min}" : "between:{$min},{$max}"]]);
     if ($validator->fails()) {
         throw new ValidationException([], ['tags' => $validator->getMessageBag()->first($key)]);
     }
 }
 public function isValid(Request $request) : bool
 {
     $this->errors = new ErrorCollection();
     /** @var \Illuminate\Contracts\Validation\Validator $validator */
     $validator = $this->validatorFactory->make($request->json(), $this->rules(), $this->messages());
     if ($validator->fails()) {
         // @todo put this somewhere else, this is getting messy
         // @see https://jsonapi.org/examples/#error-objects-basic
         foreach ($validator->errors()->toArray() as $field => $errorMessages) {
             // get the pointer for an array so we can pinpoint the section
             // of json where the error occurred
             $field = '/' . str_replace('.', '/', $field) . '/';
             foreach ($errorMessages as $message) {
                 $this->errors->add(new Error(null, null, 422, null, 'Invalid Attribute', $message, ['pointer' => $field]));
             }
         }
         return false;
     }
     return true;
 }
 /**
  * @param RequestPasswordReset $command
  * @return \Flarum\Core\User
  * @throws ModelNotFoundException
  */
 public function handle(RequestPasswordReset $command)
 {
     $email = $command->email;
     $validation = $this->validatorFactory->make(compact('email'), ['email' => 'required|email']);
     if ($validation->fails()) {
         throw new ValidationException($validation);
     }
     $user = $this->users->findByEmail($email);
     if (!$user) {
         throw new ModelNotFoundException();
     }
     $token = PasswordToken::generate($user->id);
     $token->save();
     $data = ['{username}' => $user->username, '{url}' => $this->url->toRoute('resetPassword', ['token' => $token->id]), '{forum}' => $this->settings->get('forum_title')];
     $body = $this->translator->trans('core.email.reset_password.body', $data);
     $this->mailer->raw($body, function (Message $message) use($user, $data) {
         $message->to($user->email);
         $message->subject('[' . $data['{forum}'] . '] ' . $this->translator->trans('core.email.reset_password.subject'));
     });
     return $user;
 }
Beispiel #26
0
 /**
  * @param RegisterUser $command
  * @throws PermissionDeniedException if signup is closed and the actor is
  *     not an administrator.
  * @throws \Flarum\Core\Exception\InvalidConfirmationTokenException if an
  *     email confirmation token is provided but is invalid.
  * @return User
  */
 public function handle(RegisterUser $command)
 {
     $actor = $command->actor;
     $data = $command->data;
     if (!$this->settings->get('allow_sign_up')) {
         $this->assertAdmin($actor);
     }
     $username = array_get($data, 'attributes.username');
     $email = array_get($data, 'attributes.email');
     $password = array_get($data, 'attributes.password');
     // If a valid authentication token was provided as an attribute,
     // then we won't require the user to choose a password.
     if (isset($data['attributes']['token'])) {
         $token = AuthToken::validOrFail($data['attributes']['token']);
         $password = $password ?: str_random(20);
     }
     $user = User::register($username, $email, $password);
     // If a valid authentication token was provided, then we will assign
     // the attributes associated with it to the user's account. If this
     // includes an email address, then we will activate the user's account
     // from the get-go.
     if (isset($token)) {
         foreach ($token->payload as $k => $v) {
             $user->{$k} = $v;
         }
         if (isset($token->payload['email'])) {
             $user->activate();
         }
     }
     if ($actor->isAdmin() && array_get($data, 'attributes.isActivated')) {
         $user->activate();
     }
     $this->events->fire(new UserWillBeSaved($user, $actor, $data));
     $this->validator->assertValid(array_merge($user->getAttributes(), compact('password')));
     if ($avatarUrl = array_get($data, 'attributes.avatarUrl')) {
         $validation = $this->validatorFactory->make(compact('avatarUrl'), ['avatarUrl' => 'url']);
         if ($validation->fails()) {
             throw new ValidationException($validation);
         }
         try {
             $this->saveAvatarFromUrl($user, $avatarUrl);
         } catch (Exception $e) {
             //
         }
     }
     $user->save();
     if (isset($token)) {
         $token->delete();
     }
     $this->dispatchEventsFor($user, $actor);
     return $user;
 }
Beispiel #27
0
 /**
  * Validate attributes.
  *
  * @param array $attributes
  * @param Model $model
  *
  * @throws \Illuminate\Validation\ValidationException
  * @return $this
  */
 public function validate(array $attributes, Model $model = null)
 {
     if ($this->skipValidation) {
         return $this;
     }
     if (!$this->validator) {
         $this->validator = $this->app->make(Factory::class);
     }
     $validator = $this->validator->make($this->prepareAttributes($attributes), $this->getRules($attributes, $model));
     if ($validator->fails()) {
         throw new ValidationException($validator);
     }
     return $this;
 }
Beispiel #28
0
 /**
  * @param Request $request
  * @return RedirectResponse
  */
 public function handle(Request $request)
 {
     $input = $request->getParsedBody();
     $token = PasswordToken::findOrFail(array_get($input, 'passwordToken'));
     $password = array_get($input, 'password');
     try {
         // todo: probably shouldn't use the user validator for this,
         // passwords should be validated separately
         $this->validator->assertValid(compact('password'));
         $validator = $this->validatorFactory->make($input, ['password' => 'required|confirmed']);
         if ($validator->fails()) {
             throw new ValidationException($validator);
         }
     } catch (ValidationException $e) {
         $request->getAttribute('session')->set('error', $e->errors()->first());
         return new RedirectResponse($this->url->toRoute('resetPassword', ['token' => $token->id]));
     }
     $token->user->changePassword($password);
     $token->user->save();
     $token->delete();
     $session = $request->getAttribute('session');
     $this->authenticator->logIn($session, $token->user->id);
     return new RedirectResponse($this->url->toBase());
 }
 /**
  * @param Factory $validator
  * @param Throttle $throttle
  * @param User $user
  * @return CommandResult
  */
 public function handle(Factory $validator, Throttle $throttle, User $user)
 {
     // validate data
     $validationResult = $validator->make(array('email' => $this->email, 'password' => $this->password), array('email' => 'required|email', 'password' => 'required'));
     if ($validationResult->fails()) {
         return new CommandResult(false, $validationResult->getMessageBag()->first(), null, 400);
     }
     // we need to flag that a user that is authenticating has no throttle entry by default
     $throttleEntry = false;
     // check if the user exist and get its throttle entry
     // then we will check if the user is suspended or banned
     if ($user = $user->where('email', $this->email)->first()) {
         if (!($throttleEntry = $throttle->where('user_id', $user->id)->first())) {
             $throttleEntry = $throttle::create(array('user_id' => $user->id));
         }
         // if the user is currently suspended, lets check its suspension is already expire
         // so we can clear its login attempts and attempt it to login again,
         // if not expired yet, then we will redirect it back with the suspended notice
         if ($throttleEntry->isSuspended()) {
             $now = Carbon::now();
             $suspendedUntil = Carbon::createFromTimeStamp(strtotime($throttleEntry->suspended_at))->addMinutes($throttle->getSuspensionTime());
             if ($now > $suspendedUntil) {
                 $throttleEntry->clearLoginAttempts();
                 $throttleEntry->unSuspend();
             } else {
                 $minsRemaining = $now->diffInMinutes($suspendedUntil);
                 return new CommandResult(false, 'This account is currently suspended. You can login after ' . $minsRemaining . ' minutes.', null, 401);
             }
         } elseif ($throttleEntry->isBanned()) {
             return new CommandResult(false, "This account is currently banned.", null, 401);
         }
     }
     // attempt to login
     if (Auth::attempt(array('email' => $this->email, 'password' => $this->password), $this->remember)) {
         $throttleEntry->clearLoginAttempts();
         return new CommandResult(true, "Authentication Successful.", Auth::user(), 200);
     }
     // login attempt failed, let's increment login attempt
     if ($throttleEntry) {
         $throttleEntry->addLoginAttempt();
         return new CommandResult(false, "These credentials do not match our records. Login attempt remaining: " . $throttleEntry->getRemainingLoginAttempts(), null, 401);
     }
     return new CommandResult(false, "These credentials do not match our records.", null, 401);
 }
Beispiel #30
0
 public function handle(Repository $config, Factory $validation, Mailer $mailer)
 {
     $data = $config->get('recruitment');
     $validator = $validation->make($data, ['name' => 'required', 'email' => 'required|email', 'cv' => 'required|cv'], ['cv.cv' => 'CV must be an accessible file to attach or a valid url']);
     if ($validator->fails()) {
         foreach ($validator->getMessageBag()->all() as $field => $error) {
             $this->error($error);
         }
         return 1;
     }
     $fol = new FileOrLink($data['cv']);
     $data['cvFol'] = $fol;
     $mailer->send('digbang::mail', $data, function ($mail) use($data, $fol) {
         $mail->from($data['email'])->to(self::MAIL_TO)->subject(sprintf(self::MAIL_SUBJECT, $data['name']));
         if ($fol->isFile()) {
             $mail->attach($data['cv']);
         }
     });
     $this->info('Gracias por tu contacto. ¡Nos comunicaremos dentro de poco!');
 }