Beispiel #1
0
 protected function startup()
 {
     parent::startup();
     $this->position = time();
     $this->route->setLocalUrl(Strings::webalize(Strings::random()));
     $this->getRoute()->setPublished(TRUE);
 }
Beispiel #2
0
 public function startup()
 {
     parent::startup();
     $this->dir = new DirEntity();
     $this->dir->setInvisible(TRUE);
     $this->dir->setName(Strings::webalize(get_class($this)) . Strings::random());
 }
 /**
  * @param string|NULL
  */
 public function renderIn($backlink)
 {
     $httpRequest = $this->getHttpRequest();
     $referer = NULL;
     if ($httpRequest instanceof \Nette\Http\Request) {
         $referer = $httpRequest->getReferer();
     }
     if (!$backlink && $referer && $referer->getHost() == $httpRequest->getUrl()->getHost()) {
         $url = new UrlScript($referer);
         $url->setScriptPath($httpRequest->getUrl()->getScriptPath());
         $tmp = new Request($url);
         $req = $this->router->match($tmp);
         if (!$req) {
             return;
         }
         if (isset($req->parameters[static::SIGNAL_KEY])) {
             $params = $req->parameters;
             unset($params[static::SIGNAL_KEY]);
             $req->setParameters($params);
         }
         if ($req->getPresenterName() != $this->getName()) {
             $session = $this->getSession('Nette.Application/requests');
             do {
                 $key = Strings::random(5);
             } while (isset($session[$key]));
             $session[$key] = array($this->getUser()->getId(), $req);
             $session->setExpiration('+ 10 minutes', $key);
             $this->params['backlink'] = $key;
         }
     }
 }
Beispiel #4
0
 /**
  * @return string
  */
 private function generateToken($random = NULL)
 {
     if ($random === NULL) {
         $random = Nette\Utils\Strings::random(10);
     }
     return $random . base64_encode(sha1($this->getToken() . $random, TRUE));
 }
 /**
  * Computes salted password hash.
  * @param string $password
  * @param string $salt
  * @return string
  */
 public static function calculateHash($password, $salt = null)
 {
     if ($salt === null) {
         $salt = '$2a$07$' . Nette\Utils\Strings::random(32) . '$';
     }
     return crypt($password, $salt);
 }
 /**
  * @param string
  * @param string|NULL
  * @return string
  */
 private function calculateAddonsPortalPasswordHash($password, $salt = NULL)
 {
     if ($password === Strings::upper($password)) {
         // perhaps caps lock is on
         $password = Strings::lower($password);
     }
     return crypt($password, $salt ?: '$2a$07$' . Strings::random(22));
 }
 /**
  * Generuje hash hesla i se solicim retezcem
  * @return string
  */
 public function generateHash($password, $salt = NULL)
 {
     if ($password === Strings::upper($password)) {
         // v pripade zapleho capslocku
         $password = Strings::lower($password);
     }
     return crypt($password, $salt ?: $this->user_salt . Strings::random(23));
 }
 /**
  * Generuje hash hesla i se solicim retezcem
  * @return string
  */
 public function generateHash($heslo, $salt = NULL)
 {
     if ($heslo === Strings::upper($heslo)) {
         // v pripade zapleho capslocku
         $heslo = Strings::lower($heslo);
     }
     return crypt($heslo, $salt ?: '$2a$07$' . Strings::random(23));
 }
Beispiel #9
0
 public function __construct(NewsletterEntity $newsletter)
 {
     $this->newsletter = $newsletter;
     $this->dir = new DirEntity();
     $this->dir->setParent($this->newsletter->route->getDir());
     $this->dir->setInvisible(TRUE);
     $this->dir->setName(Strings::webalize(get_class($this)) . Strings::random());
 }
 /**
  * Computes password hash.
  *
  * @param string
  * @param string|NULL
  * @return string
  */
 public static function calculateHash($password, $salt = NULL)
 {
     if ($password === Strings::upper($password)) {
         // perhaps caps lock is on
         $password = Strings::lower($password);
     }
     return crypt($password, $salt ?: '$2a$07$' . Strings::random(22));
 }
Beispiel #11
0
 /**
  * @return string
  */
 public function getToken()
 {
     $session = $this->getSession()->getSection(__CLASS__);
     if (!isset($session->token)) {
         $session->token = Nette\Utils\Strings::random();
     }
     return $session->token;
 }
Beispiel #12
0
 public function setUp()
 {
     $array = array(array('guid' => 0, 'name' => 'test', 'account' => 1, 'type' => 1), array('guid' => 0, 'name' => 'test', 'account' => 1, 'type' => 1));
     for ($i = 2; $i < 500; $i++) {
         $array[] = array('guid' => $i, 'name' => \Nette\Utils\Strings::random(10), 'account' => rand(1, 1000), 'type' => rand(0, 1));
     }
     $this->dataSource = new ArrayDataSource($array);
 }
Beispiel #13
0
 /**
  * @param ServerToken $serverToken
  * @param $expiration
  * @param null $randomSalt
  */
 function __construct(ServerToken $serverToken, $expiration, $randomSalt = null)
 {
     $this->serverToken = $serverToken;
     $this->expiration = (string) $expiration;
     if ($randomSalt === null) {
         $randomSalt = Strings::random(5);
     }
     $this->randomSalt = $randomSalt;
 }
Beispiel #14
0
 /**
  * @param Uploader $uploader
  * @param IUploadQueueFactory $uploadQueueFactory
  * @param IStorage $cacheStorage
  */
 public function __construct(Uploader $uploader, IUploadQueueFactory $uploadQueueFactory, IStorage $cacheStorage)
 {
     parent::__construct();
     $this->uploader = $uploader;
     $this->uploadQueueFactory = $uploadQueueFactory;
     $this->cacheStorage = $cacheStorage;
     $this->templateFile = __DIR__ . '/../templates/control/plupload.latte';
     $this->id = Strings::random();
 }
Beispiel #15
0
 /**
  * Process all {macros} and <tags/>.
  * @param  string
  * @return string
  */
 public function parse($s)
 {
     if (!Strings::checkEncoding($s)) {
         throw new ParseException('Template is not valid UTF-8 stream.');
     }
     $s = str_replace("\r\n", "\n", $s);
     $this->templateId = Strings::random();
     $this->input =& $s;
     $this->offset = 0;
     $this->output = '';
     $this->htmlNodes = $this->macroNodes = array();
     foreach ($this->macroHandlers as $handler) {
         $handler->initialize($this);
     }
     $len = strlen($s);
     try {
         while ($this->offset < $len) {
             $matches = $this->{"context" . $this->context[0]}();
             if (!$matches) {
                 // EOF
                 break;
             } elseif (!empty($matches['comment'])) {
                 // {* *}
             } elseif (!empty($matches['macro'])) {
                 // {macro}
                 list($macroName, $macroArgs, $macroModifiers) = $this->parseMacro($matches['macro']);
                 $isRightmost = $this->offset >= $len || $this->input[$this->offset] === "\n";
                 $this->writeMacro($macroName, $macroArgs, $macroModifiers, $isRightmost);
             } else {
                 // common behaviour
                 $this->output .= $matches[0];
             }
         }
     } catch (ParseException $e) {
         if (!$e->sourceLine) {
             $e->sourceLine = $this->getLine();
         }
         throw $e;
     }
     $this->output .= substr($this->input, $this->offset);
     foreach ($this->htmlNodes as $node) {
         if (!empty($node->attrs)) {
             throw new ParseException("Missing end tag </{$node->name}> for macro-attribute " . self::N_PREFIX . implode(' and ' . self::N_PREFIX, array_keys($node->attrs)) . ".", 0, $this->getLine());
         }
     }
     $prologs = $epilogs = '';
     foreach ($this->macroHandlers as $handler) {
         $res = $handler->finalize();
         $prologs .= isset($res[0]) ? "<?php {$res['0']}\n?>" : '';
         $epilogs .= isset($res[1]) ? "<?php {$res['1']}\n?>" : '';
     }
     $this->output = ($prologs ? $prologs . "<?php\n//\n// main template\n//\n?>\n" : '') . $this->output . $epilogs;
     if ($this->macroNodes) {
         throw new ParseException("There are unclosed macros.", 0, $this->getLine());
     }
     return $this->output;
 }
 /**
  * Computes salted password hash.
  * @param  string
  * @return string
  */
 public static function calculateHash($password, $salt = NULL)
 {
     if ($password === Strings::upper($password)) {
         // perhaps caps lock is on
         $password = Strings::lower($password);
     }
     $password = substr($password, 0, self::PASSWORD_MAX_LENGTH);
     return crypt($password, $salt ?: '$2a$07$' . Strings::random(22));
 }
Beispiel #17
0
 /**
  * Computes salted password hash.
  * @param  string
  * @return string
  */
 public static function hashPassword($password, $options = NULL)
 {
     if ($password === Strings::upper($password)) {
         // perhaps caps lock is on
         $password = Strings::lower($password);
     }
     $password = substr($password, 0, self::PASSWORD_MAX_LENGTH);
     $options = $options ?: implode('$', array('algo' => PHP_VERSION_ID < 50307 ? '$2a' : '$2y', 'cost' => '07', 'salt' => Strings::random(22)));
     return crypt($password, $options);
 }
Beispiel #18
0
 /**
  * @param FileUpload $file
  * @return string
  */
 public function save(FileUpload $file)
 {
     do {
         $filename = Strings::random(5) . '-' . $file->getSanitizedName();
         $targetFile = $this->getAbsolutePath() . '/' . $filename;
     } while (file_exists($targetFile));
     $image = $file->toImage();
     $image->save($targetFile);
     return $filename;
 }
Beispiel #19
0
 /**
  * Computes salted password hash.
  *
  * @param $password
  * @param null $options
  * @return string
  */
 public static function hashPassword($password, $options = NULL)
 {
     if ($password === Nette\Utils\Strings::upper($password)) {
         // perhaps caps lock is on
         $password = Nette\Utils\Strings::lower($password);
     }
     $password = substr($password, 0, 4096);
     $options = $options ?: implode('$', ['algo' => PHP_VERSION_ID < 50307 ? '$2a' : '$2y', 'cost' => '07', 'salt' => Nette\Utils\Strings::random(22)]);
     return crypt($password, $options);
 }
Beispiel #20
0
 /**
  * @param PayPal $payPal
  * @param Session $session
  */
 public function __construct(PayPal $payPal, Session $session)
 {
     parent::__construct();
     $this->payPal = $payPal;
     $this->session = $session->getSection('PayPalExpress');
     $this->session->setExpiration('+10 minutes');
     if (empty($this->session->token)) {
         $this->session->token = $this->_ec = Strings::random(6);
     }
 }
Beispiel #21
0
 public function register(ArrayHash $data)
 {
     if ($this->findByNick($data->nick)) {
         throw new AuthenticationException("Uživatel '{$data->nick}' již existuje.");
     }
     /** @var User $user */
     $user = User::from($data);
     $user->salt = Strings::random(5, 'A-Za-z0-9');
     $user->password = PasswordHasher::hashPassword($user->nick, $user->password, $user->salt);
     $this->persist($user);
 }
Beispiel #22
0
 /**
  * @param string $token
  */
 public function render($token = NULL)
 {
     if ($token === NULL) {
         $token = \Nette\Utils\Strings::random();
     }
     $this->template->settings = $this->settings;
     $this->template->magic = $this->magic;
     $this->template->token = $token;
     $this->template->setFile(__DIR__ . '/template.latte');
     $this->template->render();
 }
 /**
  * Creates a new invoice in the database and uploads it.
  * @param  array  $form   The form submitted
  * @param  object $values The values filled
  */
 public function createInvoice($form, $values)
 {
     $file = $values->userfile;
     if (!$file->isOk()) {
         throw new Nette\InvalidArgumentException();
     }
     $original = $file->getSanitizedName();
     $filepath = $this->getUploadDir() . '/' . Strings::random(5) . '.' . $original;
     $file->move($filepath);
     $this->database->table('invoices')->insert(array('nazev' => $original, 'url' => $filepath, 'cena' => $values->cena, 'client_FK' => $values->zadavatel));
 }
             $values->avatar = $this->_uploadTitleImage($values->avatar);
             if (is_file("www/" . $this->avatar_path . $values->old_avatar)) {
                 unlink($this->www_dir . "/www/" . $this->avatar_path . $values->old_avatar);
             }
             $this->hlavne_menu->uloz(["avatar" => $values->avatar], $values->id);
         } else {
             throw new Database\DriverException('Pre titulný obrázok nebol použitý obrázok a tak nebol uložený!' . $e->getMessage());
         }
     } else {
         throw new Database\DriverException('Pri pokuse o uloženie došlo k chybe! Pravdepodobná príčina je:' . $this->presenter->upload_error[$values->avatar->error] . $e->getMessage());
     }
 } catch (Database\DriverException $e) {
Beispiel #25
0
 public function onOrderCreated(vStore\Shop\Order $order)
 {
     $customer = $order->customer;
     $entityName = vBuilder\Security::getUserClassName();
     if ($this->context->user->isLoggedIn()) {
         return;
     }
     $potentialUser = $this->context->repository->findAll($entityName)->where('[email] = %s', $customer->email)->fetch();
     if ($potentialUser) {
         // we shall not replace the existing user with another one...
         return;
     }
     $login = $this->context->config->get('user.login');
     $i = '';
     do {
         $newUsername = Strings::webalize($customer->name) . '.' . Strings::webalize($customer->surname) . $i;
         $i++;
         $usernameTaken = $this->context->repository->findAll($entityName)->where('[username] = %s', $newUsername)->fetch();
     } while ($usernameTaken);
     $user = new $entityName($this->context);
     $password = Nette\Utils\Strings::random(8);
     $user->setEmail($customer->email);
     $user->setPassword($password);
     $user->setName($customer->name);
     $user->setSurname($customer->surname);
     if ($login === 'username') {
         $user->setUsername($newUsername);
     }
     $user->setNewsletter(0);
     // No newsletter, by default
     $user->setBypassSecurityCheck(true);
     $user->save();
     // Ulozi to znovu i produkty :-(
     //$order->user = $user;
     //$order->save();
     // Docasny fix
     $orderEntity = $this->context->shop->getOrderEntityClass();
     $this->context->connection->update($orderEntity::getMetadata()->getTableName(), array('user' => $user->id))->where('[id] = %i', $order->id)->execute();
     $this->template->user = $user;
     $this->template->password = $password;
     if ($this->template->getFile() == "") {
         $this->template->setFile(__DIR__ . '/Templates/email.autoRegistration.latte');
     }
     $this->message->addTo($customer->email, $customer->displayName);
     $this->message->setSubject('Vase registrace');
     $this->message->setHtmlBody($this->template);
     $this->message->send();
 }
Beispiel #26
0
 /**
  * Stores request to session.
  * @param Request $request
  * @param mixed $expiration
  * @return string
  */
 public function storeRequest(Request $request, $expiration = '+ 10 minutes')
 {
     $request = clone $request;
     if ($this->unloader) {
         $this->unloader->filterOut($request);
     } elseif ($this->loader) {
         $this->loader->filterOut($request);
     }
     $session = $this->session->getSection(self::SESSION_SECTION);
     do {
         $key = Strings::random(5);
     } while (isset($session[$key]));
     $session[$key] = $request;
     $session->setExpiration($expiration, $key);
     return $key;
 }
Beispiel #27
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->hasOption('password') && $input->getOption('password') === NULL) {
         $output->writeln('<error>Please enable interactive mode to set password.</error>');
         return 1;
     }
     if ($input->hasOption('password') && $input->getOption('generate-password')) {
         $output->writeln('<error>Cannot set and generate password at once.</error>');
         return 1;
     }
     if (!$input->hasOption('password') && !$input->getOption('generate-password')) {
         $output->writeln('<error>Cannot create user without password.</error>');
         return 1;
     }
     $name = $input->getArgument('name');
     if ($this->model->getByNameOrEmail($name)) {
         $output->writeln('<error>User with same name already exists.</error>');
         return 1;
     }
     $email = $input->getArgument('email');
     if (!Validators::is($email, 'email')) {
         $output->writeln('<error>Invalid email</error>');
         return 1;
     }
     if ($this->model->getByNameOrEmail($email)) {
         $output->writeln('<error>User with same email already exists.</error>');
         return 1;
     }
     $printPassword = FALSE;
     if ($input->getOption('password') !== NULL) {
         $password = $input->getOption('password');
     } elseif ($this->getOption('generate-password')) {
         $password = Strings::random();
         $printPassword = TRUE;
     }
     $roles = $input->getOption('role');
     $this->factory->create($name, $email, $password, $roles);
     if ($printPassword) {
         $verbosity = $output->getVerbosity();
         $output->setVerbosity(OutputInterface::VERBOSITY_NORMAL);
         $output->write('<info>');
         $output->write($password, OutputInterface::OUTPUT_RAW);
         $output->writeln('</info>');
         $output->setVerbosity($verbosity);
     }
 }
 /**
  * @param \Nette\Security\IIdentity
  * @param string
  * @return AddonForm
  */
 public function create(IIdentity $user, $token)
 {
     $form = $this->createForm();
     $form->addHidden('token', is_null($token) ? Strings::random() : $token);
     $form->addSubmit('sub', 'Next');
     $manager = $this->manager;
     $form->onSuccess[] = function (AddonForm $form) use($manager, $user) {
         $addon = $form->getAddon();
         if ($addon->type === NULL) {
             $addon->type = Addon::TYPE_DOWNLOAD;
         }
         $values = $form->getValues(TRUE);
         $manager->fillAddonWithValues($addon, $values, $user);
         $manager->storeAddon($values['token'], $addon);
     };
     return $form;
 }
Beispiel #29
0
 /**
  * Computes salted password hash.
  * @param  string
  * @param  array with cost (4-31), salt (22 chars)
  * @return string  60 chars long
  */
 public static function hash($password, array $options = NULL)
 {
     $cost = isset($options['cost']) ? (int) $options['cost'] : self::BCRYPT_COST;
     $salt = isset($options['salt']) ? (string) $options['salt'] : Nette\Utils\Strings::random(22, '0-9A-Za-z./');
     if (PHP_VERSION_ID < 50307) {
         throw new Nette\NotSupportedException(__METHOD__ . ' requires PHP >= 5.3.7.');
     } elseif (($len = strlen($salt)) < 22) {
         throw new Nette\InvalidArgumentException("Salt must be 22 characters long, {$len} given.");
     } elseif ($cost < 4 || $cost > 31) {
         throw new Nette\InvalidArgumentException("Cost must be in range 4-31, {$cost} given.");
     }
     $hash = crypt($password, '$2y$' . ($cost < 10 ? 0 : '') . $cost . '$' . $salt);
     if (strlen($hash) < 60) {
         throw new Nette\InvalidStateException('Hash returned by crypt is invalid.');
     }
     return $hash;
 }
Beispiel #30
0
 /**
  * @param array $credentials
  * @return Identity
  * @throws AuthenticationException
  */
 public function authenticate(array $credentials)
 {
     list($code) = $credentials;
     try {
         $this->googleClient->authenticate($code);
         $this->googleClient->setAccessToken($this->googleClient->getAccessToken());
         $oauth2 = new \Google_Oauth2Service($this->googleClient);
         $googleUser = $oauth2->userinfo->get();
         if (isset($googleUser['email'])) {
             $email = filter_var($googleUser['email'], FILTER_SANITIZE_EMAIL);
             $user = $this->users->getUser($email);
             if ($user === NULL && $this->autoRegister === FALSE || $user instanceof UserEntity && $user->getActive() == 0) {
                 throw new AuthenticationException("User '{$email}' not found.", self::IDENTITY_NOT_FOUND);
             } else {
                 if ($user === NULL && $this->autoRegister === TRUE) {
                     $result = $this->users->register(array("login" => $email, "password" => Strings::random(), "name" => isset($googleUser['name']) ? $googleUser['name'] : NULL, "firstname" => isset($googleUser['given_name']) ? $googleUser['given_name'] : NULL, "lastname" => isset($googleUser['family_name']) ? $googleUser['family_name'] : NULL, "lastLogged" => new DateTime(), "ip" => $_SERVER['REMOTE_ADDR']));
                     if ($result instanceof ContactEntity) {
                         return new Identity($result->userID, $result->getUser()->role->name, $result->getUser()->toArray());
                     } else {
                         throw new AuthenticationException("User '{$email}' cannot be registered.", self::IDENTITY_NOT_FOUND);
                     }
                 } else {
                     if ($user instanceof UserEntity) {
                         $user->setLastLogged(new DateTime());
                         $user->setIp($_SERVER['REMOTE_ADDR']);
                         $this->users->updateUser($user);
                         $data = $user->toArray();
                         unset($data['password']);
                         return new Identity($user->userID, $user->role->name, $data);
                     } else {
                         throw new AuthenticationException("User '{$email}' cannot be connected.", self::IDENTITY_NOT_FOUND);
                     }
                 }
             }
         } else {
             throw new AuthenticationException("Uživatel nenalezen.");
         }
     } catch (\Google_AuthException $e) {
         throw new AuthenticationException($e->getMessage());
     } catch (\Google_ServiceException $e) {
         throw new AuthenticationException($e->getMessage());
     }
 }