Ejemplo n.º 1
0
 /**
  * Run the request filter.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     if ($request->exists('g-recaptcha-response')) {
         $recaptcha = new ReCaptcha(Settings::get('secret_key'));
         /**
          * Verify the reponse, pass user's IP address
          */
         $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
         /**
          * Fail, if the response isn't OK
          */
         if (!$response->isSuccess()) {
             if ($request->ajax()) {
                 throw new AjaxException($response->getErrorCodes());
             } else {
                 foreach ($response->getErrorCodes() as $code) {
                     Flash::error($code);
                 }
                 return redirect()->back()->withInput();
             }
         }
     }
     /**
      * Handle request
      */
     return $next($request);
 }
 public function post(Request $request)
 {
     // get the data and its validation rules
     $data = ['email' => $request->input('email'), 'message' => $request->input('message')];
     $rules = ['email' => 'bail|required|email', 'message' => 'required'];
     // build the validator
     $validator = Validator::make($data, $rules);
     // verify the reCAPTCHA with Google
     $recaptcha = new ReCaptcha(env('RECAPTCHA_SECRET'));
     $recaptcha_resp = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
     // validate the request
     $recaptcha_failed = $recaptcha_resp->isSuccess() == FALSE;
     $validator_failed = $validator->fails();
     // if the reCAPTCHA failed then add a message to the validator
     if ($recaptcha_resp->isSuccess() == FALSE) {
         $validator->errors()->add('recaptcha', 'Prove you are not a robot.');
     }
     // if the validation failed then redirect back to the register page
     if ($recaptcha_failed || $validator_failed) {
         return redirect(route('contactform.get'))->withErrors($validator)->withInput();
     }
     // send the email to the webmaster
     $email = $data['email'];
     Mail::raw($data['message'], function ($m) use($email) {
         $m->from($email, $email);
         $m->to(env('CONTACT_FORM_EMAIL'), env('CONTACT_FORM_NAME'));
         $m->subject('Message revieved from user');
     });
     // flash a success message back to the contact page
     Session::flash('success', 'Your message has been sent.');
     return redirect(route('contactform.get'));
 }
Ejemplo n.º 3
0
 public function feedbackSave(Request $request)
 {
     $rules = ['name' => 'required', 'email' => 'required_if:phone,""', 'phone' => 'required_if:email,""', 'message' => 'required'];
     $messages = ['name.required' => 'Введите Ваше имя. Мы же должны как-то к Вам обращаться :)', 'email.required_if' => 'А где же ваш email для обратной связи?', 'phone.required_if' => 'Укажите пожалуйста Ваш телефончик для обратной связи', 'message.required' => 'А где собственно сообщение?'];
     $validator = Validator::make($request->all(), $rules, $messages);
     $validator->after(function ($validator) use($request) {
         if (app()->environment() == 'production') {
             $recaptcha = new ReCaptcha(env('GOOGLE_RECAPTCHA_SECRET'));
             $resp = $recaptcha->verify($request->get('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
             if (!$resp->isSuccess()) {
                 $validator->errors()->add('google_recaptcha_error', 'Ошибка reCAPTCHA: ' . implode(', ', $resp->getErrorCodes()));
             }
         }
     });
     if ($validator->fails()) {
         $this->throwValidationException($request, $validator);
     }
     $data = $request->all();
     $settings = Settings::find(1);
     Mail::queue(['text' => 'emails.feedback'], ['data' => $data], function ($message) use($data, $settings) {
         $message->from(env('MAIL_ADDRESS'), env('MAIL_NAME'));
         $message->to(isset($settings->email) ? $settings->email : env('MAIL_ADDRESS'));
         $message->subject('Обратная связь');
     });
     if ($request->ajax()) {
         return response()->json(['status' => 'success', 'message' => 'Сообщение отправлено']);
     }
     Flash::success("Сообщение отправлено");
     return redirect('/');
 }
Ejemplo n.º 4
0
 /**
  * Validate Captcha
  * @param $request
  * @return bool
  */
 private function validateCaptcha(Request $request)
 {
     // validate google captcha
     $recaptcha = new ReCaptcha(env('RECAPTCHA_PRIVATE_KEY'));
     $response = $recaptcha->verify(input('g-recaptcha-response'), $request->getClientIp());
     return $response;
 }
 public function attachCaptchaRule(ModelValidator $validator)
 {
     // ensure that when we get a validator instance, the model that we are validating is indeed the user that is
     // registering
     if (false == ($validator->model === $this->registeringUser)) {
         return;
     }
     $validator->validator->addExtension('recaptcha', function ($attribute, $value, $parameters) {
         $recaptcha = new ReCaptcha(app('Flarum\\Core\\Settings\\SettingsRepository')->get('recaptcha.secret_key'));
         $resp = $recaptcha->verify($this->captchaResponse);
         if ($resp->isSuccess()) {
             // verified!
             return true;
         } else {
             $errors = $resp->getErrorCodes();
         }
         return $errors;
     });
     $rules = $validator->validator->getRules();
     $data = $validator->validator->getData();
     $data['recaptcha_response'] = $this->captchaResponse;
     $rules['recaptcha_response'] = 'required|recaptcha';
     $validator->validator->setData($data);
     $validator->validator->setRules($rules);
     // clear user reference for good measures
     // will cause above check to fail later, therefore causing no validation in subsequent calls
     $this->registeringUser = null;
 }
Ejemplo n.º 6
0
 public function createGuestPost(Requests\Bins\CreateGuestBin $request)
 {
     $recaptcha = new ReCaptcha(env('RECAPTCHA_SECRET'));
     $response = $recaptcha->verify($request->input('grc-response'), $_SERVER['REMOTE_ADDR']);
     if (!$response->isSuccess()) {
         session()->flash('error', 'You must prove you are human by completing the catpcha!');
         return redirect()->route('bins.create');
     }
     $description = $request->has('description') && trim($request->input('description')) != '' ? $request->input('description') : null;
     $bin = Bin::create(['title' => $request->input('title'), 'description' => $description, 'visibility' => $request->input('visibility')]);
     $bin->versions()->sync($request->input('versions'));
     $files = [];
     foreach ($request->input('name') as $key => $value) {
         $files[$key]['name'] = $value;
     }
     foreach ($request->input('language') as $key => $value) {
         $files[$key]['language'] = $value;
     }
     foreach ($request->input('code') as $key => $value) {
         $files[$key]['code'] = $value;
     }
     foreach ($files as $item) {
         $type = Type::where('css_class', $item['language'])->first();
         $bin->snippets()->create(['type_id' => $type->id, 'name' => $item['name'], 'code' => $item['code']]);
     }
     session()->flash('success', 'Bin created successfully!');
     return redirect()->route('bin.code', $bin->getRouteKey());
 }
Ejemplo n.º 7
0
 /**
  * @param $response
  * @param $ip
  * @return bool
  */
 public function verify($response, $ip)
 {
     $resp = $this->recaptcha->verify($response, $ip);
     if ($resp->isSuccess()) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof Recaptcha) {
         throw new UnexpectedTypeException($constraint, Recaptcha::class);
     }
     $check = $this->validator->verify($value, $this->siteUrl);
     if (!$check->isSuccess()) {
         $this->context->buildViolation($constraint->message)->addViolation();
     }
 }
Ejemplo n.º 9
0
 /**
  * Function to verify captcha request
  *
  * @param   \Illuminate\Http\Request        $request
  * @return  \Illuminate\Http\JsonResponse
  */
 public function verify(Request $request)
 {
     $recaptcha = new ReCaptcha(config('googleApi.googleRecaptchaSecretKey'));
     $resp = $recaptcha->verify($request->input('g-recaptcha-response'), $request->getClientIp());
     if ($resp->isSuccess()) {
         $response = ['success' => true];
         return response()->json($response);
     } else {
         $response = ['success' => false, 'error-codes' => $resp->getErrorCodes()];
         return response()->json($response);
     }
 }
 /**
  * Validates a value.
  * @param mixed $value the data value to be validated.
  */
 protected function validateValue($value)
 {
     $remoteIp = \Yii::$app->getRequest()->getUserIP();
     $recaptcha = new GoogleReCaptcha($this->secretKey);
     $response = $recaptcha->verify($value, $remoteIp);
     if ($response->isSuccess()) {
         return null;
     }
     $debug = json_encode(['remoteIp' => $remoteIp, 'errorCodes' => $response->getErrorCodes()]);
     \Yii::error(__METHOD__ . ': ' . $debug, __CLASS__);
     return [$this->message, []];
 }
Ejemplo n.º 11
0
 public function submit()
 {
     $url = trim(Request::input('uri'));
     $reason = trim(Request::input('reason'));
     $info = trim(Request::input('info'));
     $captcha = trim(Request::input('g-recaptcha-response'));
     $verify = new ReCaptcha(env('RECAPTCHA_PRIVATE'));
     $resp = $verify->verify($captcha, Request::ip());
     if (!$resp->isSuccess()) {
         return redirect()->back()->withInput()->with('error', 'You entered the captcha incorrectly.');
     }
     if (!$url || !$reason || !$info) {
         return redirect()->back()->withInput()->with('error', 'Please fill in all of the required fields.');
     }
     $urlRegex = "/\\/?([a-z]+)\\/?(thread|res)\\/?([0-9]+)/";
     $matches = array();
     // Does this url match our pattern?
     if (!preg_match($urlRegex, $url, $matches)) {
         return redirect()->back()->withInput()->with('error', 'The URL you entered is not valid.');
     }
     // Assign values
     $board = $matches[1];
     $thread_id = $matches[3];
     // Does this thread exist?
     $thread = Thread::withTrashed()->where('board', '=', $board)->where('thread_id', '=', $thread_id)->firstOrFail();
     if ($thread->deleted_at != null) {
         return redirect()->back()->withInput()->with('error', 'This thread has already been taken down.');
     }
     // Was this thread denied less than 3 days ago?
     $lastTakedown = TakedownRequest::where('thread_id', '=', $thread->id)->orderBy('id', 'desc')->first();
     if ($lastTakedown) {
         // Was this request denied?
         if ($lastTakedown->processed == 1 && $lastTakedown->approved == 0 && strtotime($lastTakedown->deleted_at) > time() - 259200) {
             // 3 days
             return redirect()->back()->withInput()->with('error', 'This thread was recently reversed due to a previous takedown request. Please wait before resubmitting.');
         } else {
             if ($lastTakedown->processed == 0) {
                 return redirect()->back()->withInput()->with('error', 'Someone has already requested this thread be taken down.');
             }
         }
     }
     $request = new TakedownRequest();
     $request->thread_id = $thread->id;
     $request->reason = $reason;
     $request->info_provided = $info;
     $request->user_ip = Request::ip();
     $request->save();
     // Soft delete
     $thread->takedown_reason = "This thread has been automatically taken down - '" . $reason . "'";
     $thread->save();
     $thread->delete();
     return redirect()->back()->with('success', 'Your takedown request has been sent. The thread has been automatically taken down. Please keep in mind that the takedown could be revsered in the future by an Admin.');
 }
Ejemplo n.º 12
0
 /**
  * @Route("/auth-cookie", requirements={}, defaults={}, name="api_v1_auth_cookie")
  * @Method({"POST"})
  * @param Request $request
  * @return Response
  */
 public function authCookieAction(Request $request)
 {
     $r = array('error' => 'Unknown', 'data' => array());
     $response = new JsonResponse();
     do {
         $reCaptchaResponse = $request->request->get('recaptcha_response');
         if (empty($reCaptchaResponse)) {
             $r['error'] = 'Captcha response required';
             break;
         }
         $reCaptcha = new ReCaptcha($this->getParameter('improv.recaptcha.sercret'));
         $resp = $reCaptcha->verify($reCaptchaResponse, $request->getClientIp());
         if ($resp->isSuccess()) {
             $r['error'] = null;
             $username = sha1(time() . ':::' . uniqid());
             $password = md5('pass:::' . $username);
             $salt = md5('salt:::' . $username);
             $user = new RedisUser($username, $password, $salt, array('ROLE_USER'));
             $expire = 24 * 60 * 60;
             $redisKey = 'user:'******'improv.predis');
             $predis->connection()->set($redisKey, time());
             $predis->connection()->expire($redisKey, $expire);
             $securityParameters = Yaml::parse(file_get_contents(sprintf('%s/config/security.yml', $this->container->getParameter('kernel.root_dir'))));
             if (!isset($securityParameters['security']['firewalls']['main'])) {
                 throw new \LogicException('Firewall not found');
             }
             $providerKey = $securityParameters['security']['firewalls']['main']['provider'];
             $securityKey = $this->container->getParameter(trim($securityParameters['security']['firewalls']['main']['remember_me']['secret'], '%'));
             $rememberMeParams = $securityParameters['security']['firewalls']['main']['remember_me'];
             unset($rememberMeParams['secret']);
             $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
             $this->get('security.token_storage')->setToken($token);
             // now the user is logged in
             $userProvider = new RedisUserProvider();
             $rememberMeService = new TokenBasedRememberMeServices(array($userProvider), $securityKey, $providerKey, array_merge(array('path' => '/', 'name' => 'i', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 24 * 60 * 60, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'), $rememberMeParams));
             $rememberMeService->loginSuccess($request, $response, $token);
             /**
              * Fire the login event
              * Logging the user in above the way we do it doesn't do this automatically
              */
             $this->get('event_dispatcher')->dispatch('security.interactive_login', new InteractiveLoginEvent($request, $token));
         } else {
             $r['error'] = "Invalid captcha\n\n" . json_encode($resp->getErrorCodes());
         }
     } while (false);
     $response->setData($r);
     return $response;
 }
Ejemplo n.º 13
0
 public function checkCaptcha()
 {
     $response = Input::get('g-recaptcha-response');
     $remoteip = $_SERVER['REMOTE_ADDR'];
     $secret = config('services.recaptcha.secret');
     $recaptcha = new ReCaptcha($secret);
     $resp = $recaptcha->verify($response, $remoteip);
     if ($resp->isSuccess()) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 14
0
 public function captchaCheck()
 {
     $response = Input::get('g-recaptcha-response');
     $remoteip = $_SERVER['REMOTE_ADDR'];
     $secret = env('RE_CAP_SECRET');
     $recaptcha = new ReCaptcha($secret);
     $resp = $recaptcha->verify($response, $remoteip);
     if ($resp->isSuccess()) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 15
0
 public function captchaCheck()
 {
     $response = Input::get('g-recaptcha-response');
     $remoteip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_STRING);
     //$_SERVER['REMOTE_ADDR'];
     $secret = config('jlourenco.support.RE_CAP_SECRET');
     $recaptcha = new ReCaptcha($secret);
     $resp = $recaptcha->verify($response, $remoteip);
     if ($resp->isSuccess()) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 16
0
 public function checkCaptcha()
 {
     $request = Request::capture();
     $response = $request->get('g-recaptcha-response');
     $remoteIP = $request->ip();
     $secret = env('RECAPTCHA_SECRET_KEY');
     $reCaptcha = new ReCaptcha($secret);
     $result = $reCaptcha->verify($response, $remoteIP);
     if ($result->isSuccess()) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 17
0
 public function validate($input)
 {
     /* @var $control ReCaptchaTag */
     $control = $this->control;
     $request = $this->getRequest();
     $reCaptcha = new ReCaptcha($control->getPrivateKey());
     $response = $reCaptcha->verify($request->getParameter(ReCaptchaTag::RE_CAPTCHA_RESPONSE_IDENTIFIER), $request->getRemoteAddress());
     if ($response->isSuccess()) {
         return true;
     } else {
         // inject error message key to be able to display a user hint
         $control->setErrorMessageKeys($response->getErrorCodes());
         return false;
     }
 }
Ejemplo n.º 18
0
 /**
  * Functie om cpatcha te testen
  * @param $request
  * @return bool
  */
 private function checkCaptcha($request)
 {
     if (env("RECAPTCHA_BYPASS", false)) {
         return true;
     }
     $response = $request->input("g-recaptcha-response");
     $remoteip = $_SERVER['REMOTE_ADDR'];
     $secret = env('RE_CAP_SECRET');
     $recaptcha = new ReCaptcha($secret);
     $resp = $recaptcha->verify($response, $remoteip);
     if ($resp->isSuccess()) {
         return true;
     }
     return false;
 }
Ejemplo n.º 19
0
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (!Middleware::hasAttribute($request, ClientIp::KEY)) {
         throw new RuntimeException('Recaptcha middleware needs ClientIp executed before');
     }
     if (Utils\Helpers::isPost($request)) {
         $recaptcha = new GoogleRecaptcha($this->secret);
         $data = $request->getParsedBody();
         $res = $recaptcha->verify(isset($data['g-recaptcha-response']) ? $data['g-recaptcha-response'] : '', ClientIp::getIp($request));
         if (!$res->isSuccess()) {
             return $response->withStatus(403);
         }
     }
     return $next($request, $response);
 }
 /**
  * Verify reCaptcha response.
  *
  * @param string $recaptchaValue
  *
  * @throws RecaptchaException
  */
 public function verify($recaptchaValue)
 {
     // We don't override the value provided by the form
     // If empty, we use the default input drawed by google JS we need to get
     // the value with hardcoded variable
     if ((null === $recaptchaValue || empty($recaptchaValue)) && $this->request->request->has(self::GOOGLE_DEFAULT_INPUT)) {
         $recaptchaValue = $this->request->request->get(self::GOOGLE_DEFAULT_INPUT);
     }
     if ($this->enabled) {
         /* @var \ReCaptcha\Response $response */
         $response = $this->reCaptcha->verify($recaptchaValue, $this->request->getClientIp());
         if (!$response->isSuccess()) {
             throw new RecaptchaException($response);
         }
     }
 }
Ejemplo n.º 21
0
 /**
  * Verify captcha
  *
  * @return bool
  */
 public function verify()
 {
     if ($this->response === null) {
         $this->response = $this->captcha->verify($this->request->get($this->input), $this->request->ip());
     }
     return $this->response->isSuccess();
 }
Ejemplo n.º 22
0
 /**
  * Perform the necessary actions to send a password reset mail
  *
  * @param $user_name_or_email string Username or user's email
  *
  * @return bool success status
  */
 public static function requestPasswordReset($user_name_or_email, $captcha)
 {
     \Slim\Slim::getInstance()->log->debug("This is registrationInputValidation()");
     $captcha_enabled = \Slim\Slim::getInstance()->config('captcha.enabled');
     if ($captcha_enabled) {
         // perform all necessary checks
         $secret = \Slim\Slim::getInstance()->config('captcha.secret');
         $recaptcha = new ReCaptcha($secret);
         $resp = $recaptcha->verify($captcha, $_SERVER['REMOTE_ADDR']);
         if ($resp->isSuccess()) {
             \Slim\Slim::getInstance()->log->debug("captcha ok");
         } else {
             $errors = $resp->getErrorCodes();
             \Slim\Slim::getInstance()->log->debug("wrong captcha", $errors);
             Session::add(Session::SESSION_FEEDBACK_NEGATIVE, Text::get('FEEDBACK_CAPTCHA_WRONG'));
             return false;
         }
     }
     if (empty($user_name_or_email)) {
         Session::add(Session::SESSION_FEEDBACK_NEGATIVE, Text::get('FEEDBACK_USERNAME_EMAIL_FIELD_EMPTY'));
         return false;
     }
     // check if that username exists
     $user = UserModel::getUserDataByUserNameOrEmail($user_name_or_email);
     if (!$user) {
         Session::add(Session::SESSION_FEEDBACK_NEGATIVE, Text::get('FEEDBACK_USER_DOES_NOT_EXIST'));
         return false;
     }
     // generate integer-timestamp (to see when exactly the user (or an attacker) requested the password reset mail)
     // generate random hash for email password reset verification (40 char string)
     $temporary_timestamp = time();
     $user_password_reset_hash = sha1(uniqid(mt_rand(), true));
     // set token (= a random hash string and a timestamp) into database ...
     $token_set = self::setPasswordResetDatabaseToken($user->getUsername(), $user_password_reset_hash, $temporary_timestamp);
     if (!$token_set) {
         return false;
     }
     // ... and send a mail to the user, containing a link with username and token hash string
     $mail_sent = self::sendPasswordResetMail($user->getUsername(), $user_password_reset_hash, $user->getEmail());
     if ($mail_sent) {
         return true;
     }
     // default return
     return false;
 }
Ejemplo n.º 23
0
 protected function validateAttribute($object, $attribute)
 {
     if ($this->skipOnError && $object->hasErrors()) {
         return;
     }
     if (null == $this->recaptchaComponent) {
         throw new \CException(Yii::t('yii', 'Property YiiRecaptcha2\\Widget.recaptchaComponent can be define.'));
     }
     $this->_recaptchaComponent = \Yii::app()->{$this->recaptchaComponent};
     $value = $object->{$attribute};
     $recaptcha = new \ReCaptcha\ReCaptcha($this->_recaptchaComponent->privateKey);
     $resp = $recaptcha->verify($value, \Yii::app()->request->getUserHostAddress());
     if (!$resp->isSuccess()) {
         foreach ($resp->getErrorCodes() as $code) {
             $this->addError($object, $attribute, $code);
         }
     }
 }
Ejemplo n.º 24
0
 /**
  * @param GetResponseEvent $event
  */
 public function verify(GetResponseEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $request = $event->getRequest();
     // Only verify against specific routes
     if (!in_array($request->get('_route'), $this->routes)) {
         return;
     }
     $recaptchaResponse = $this->recaptcha->verify($request->get('g-recaptcha-response'), $request->getClientIp());
     if ($recaptchaResponse->isSuccess()) {
         $this->eventDispatcher->dispatch(CaptchaSolvedSuccessfully::NAME, new CaptchaSolvedSuccessfully($request));
         return;
     }
     $response = new JsonResponse(['message' => 'Recaptcha invalid'], Response::HTTP_FORBIDDEN);
     $event->setResponse($response);
 }
 public function validate(Validation $validator, $attributes)
 {
     // Konfiguration und Request-Objekt beziehen
     $di = FactoryDefault::getDefault();
     $config = $di->getConfig();
     $request = $di->getRequest();
     // Googles ReCaptcha-Klasse instanzieren
     $recaptcha = new ReCaptcha($config->ReCaptcha->secret);
     // Antwort von ReCaptcha-API beziehen
     $response = $recaptcha->verify($request->getPost('g-recaptcha-response'), $request->getClientAddress());
     // Antwort überprüfen
     if (!$response->isSuccess()) {
         // Nachricht dem Validator hinzufügen
         $validator->appendMessage(new Message($this->getOption('message') ?: 'Bitte ReCaptcha ausfüllen', $attributes, 'ReCaptcha'));
         // Prüfung fehlgeschlagen
         return FALSE;
     }
     // Erfolgreich
     return TRUE;
 }
Ejemplo n.º 26
0
 /**
  * @param TokenInterface        $token
  * @param UserProviderInterface $userProvider
  * @param string                $providerKey
  *
  * @return UsernamePasswordToken
  */
 public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
 {
     if (empty($this->secretKey) == false) {
         $captcha = $this->request->get('g-recaptcha-response');
         $reCaptcha = new ReCaptcha($this->secretKey);
         $response = $reCaptcha->verify($captcha, $this->request->getClientIp());
         if ($response->isSuccess() == false) {
             throw new AuthenticationException('Captcha not passed');
         }
     }
     try {
         $user = $userProvider->loadUserByUsername($token->getUsername());
     } catch (UsernameNotFoundException $e) {
         throw new AuthenticationException('Invalid username or password');
     }
     $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials());
     if ($passwordValid) {
         return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles());
     }
     throw new AuthenticationException('Invalid username or password');
 }
Ejemplo n.º 27
0
 public static function save_place()
 {
     $flash = new Flash();
     $post_data = Flight::request()->data;
     // recaptcha
     $secret = getenv('RECAPTCHA_SECRET');
     $gRecaptchaResponse = $post_data['g-recaptcha-response'];
     $recaptcha = new ReCaptcha($secret);
     $resp = $recaptcha->verify($gRecaptchaResponse, $_SERVER['REMOTE_ADDR']);
     if ($resp->isSuccess()) {
         // verified!
         $address = "{$post_data['calle']} {$post_data['altura']}, {$post_data['ciudad']}, {$post_data['provincia']}, Argentina";
         // save new place
         Place::create(array('name' => $post_data['name'], 'address' => $address, 'start_hour' => $post_data['start_hour'], 'end_hour' => $post_data['end_hour'], 'days' => $post_data['days'], 'comments' => $post_data['comments']));
         $flash->message('success');
     } else {
         $errors = $resp->getErrorCodes();
         $flash->message('error');
     }
     Flight::redirect('/', 302);
 }
Ejemplo n.º 28
0
 public function feedback(Request $request)
 {
     $rules = ['name' => 'required', 'email' => 'required_if:phone,""', 'phone' => 'required_if:email,""', 'message' => 'required'];
     $messages = ['name.required' => 'Введите Ваше имя. Мы же должны как-то к Вам обращаться :)', 'email.required_if' => 'А где же ваш email для обратной связи?', 'phone.required_if' => 'Укажите пожалуйста Ваш телефончик для обратной связи', 'message.required' => 'А где собственно сообщение?'];
     $validator = Validator::make($request->all(), $rules, $messages);
     $validator->after(function ($validator) use($request) {
         $recaptcha = new ReCaptcha(env('GOOGLE_RECAPTCHA_SECRET'));
         $resp = $recaptcha->verify($request->get('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
         if (!$resp->isSuccess()) {
             $validator->errors()->add('google_recaptcha_error', 'Ошибка reCAPTCHA: ' . implode(', ', $resp->getErrorCodes()));
         }
     });
     if ($validator->fails()) {
         $this->throwValidationException($request, $validator);
     }
     Mail::queue('emails.feedback', ['input' => $request->all()], function ($message) {
         $message->from(env('MAIL_ADDRESS'), env('MAIL_NAME'));
         $message->to(env('MAIL_ADDRESS'));
         $message->subject('Обратная связь');
     });
     return;
 }
 /**
  * Validate Google's ReCaptcha response.
  *
  * @param  string            $input    The "g-captcha-response" field from the form submission.
  * @param  array|Traversable $feedback If $feedback is provided, then it is filled with any validation messages.
  * @return boolean Returns TRUE if the ReCaptcha was successful, otherwise an array of messages.
  * @todo   Implement {@see Charcoal\Validator\ValidatorResult}.
  */
 public function validateCaptcha($input = null, &$feedback = [])
 {
     if (is_string($input) && strlen($input)) {
         $input = filter_var($input, FILTER_UNSAFE_RAW);
     } else {
         $field = isset($this->captchaFieldName) ? $this->captchaFieldName : CaptchaConfig::DEFAULT_FIELD_NAME;
         $input = filter_input(INPUT_POST, $field, FILTER_UNSAFE_RAW);
     }
     $remoteIp = isset($this->captchaRemoteIp) ? $this->captchaRemoteIp : getenv('REMOTE_ADDR');
     $response = $this->captcha->verify($input, $remoteIp);
     $this->lastCaptchaResponse = $response;
     $this->parseCaptchaResponseCodes($response, $feedback);
     return $response->isSuccess();
 }
Ejemplo n.º 30
0
 /**
  * Process the submitted captcha and validate.
  *
  * @param array $response
  * @param string $ip
  * @return bool
  */
 public function processCaptcha($response, $ip)
 {
     if (isset($response[self::RECAPTCHA_POSTKEY])) {
         $post_response = $response[self::RECAPTCHA_POSTKEY];
     } else {
         $post_response = '';
     }
     $verify_response = $this->recaptcha->verify($post_response, $ip);
     if (!$verify_response->isSuccess()) {
         $this->_handleErrors($verify_response->getErrorCodes());
         return false;
     }
     return true;
 }