Commit c49f8dd6 authored by Mpro's avatar Mpro

nette sandbox

parents
log/*
temp/*
vendor/*
!vendor/others
.DS_Store
!.gitignore
!.htaccess
!web.config
app/config/config.local.neon
Order Allow,Deny
Deny from all
<?php
require __DIR__ . '/../vendor/autoload.php';
$configurator = new Nette\Configurator;
//$configurator->setDebugMode(TRUE); // debug mode MUST NOT be enabled on production server
$configurator->enableDebugger(__DIR__ . '/../log');
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()
->addDirectory(__DIR__)
->addDirectory(__DIR__ . '/../vendor/others')
->register();
$configurator->addConfig(__DIR__ . '/config/config.neon');
$configurator->addConfig(__DIR__ . '/config/config.local.neon');
$container = $configurator->createContainer();
return $container;
#
# SECURITY WARNING: it is CRITICAL that this file & directory are NOT accessible directly via a web browser!
#
# If you don't protect this directory from direct web access, anybody will be able to see your passwords.
# http://nette.org/security-warning
#
parameters:
php:
date.timezone: Europe/Prague
nette:
application:
errorPresenter: Error
mapping:
*: App\*Module\Presenters\*Presenter
session:
expiration: 14 days
services:
- App\Model\UserManager
- App\RouterFactory
router: @App\RouterFactory::createRouter
<?php
namespace App\Model;
use Nette,
Nette\Utils\Strings,
Nette\Security\Passwords;
/**
* Users management.
*/
class UserManager extends Nette\Object implements Nette\Security\IAuthenticator
{
const
TABLE_NAME = 'users',
COLUMN_ID = 'id',
COLUMN_NAME = 'username',
COLUMN_PASSWORD_HASH = 'password',
COLUMN_ROLE = 'role';
/** @var Nette\Database\Context */
private $database;
public function __construct(Nette\Database\Context $database)
{
$this->database = $database;
}
/**
* Performs an authentication.
* @return Nette\Security\Identity
* @throws Nette\Security\AuthenticationException
*/
public function authenticate(array $credentials)
{
list($username, $password) = $credentials;
$row = $this->database->table(self::TABLE_NAME)->where(self::COLUMN_NAME, $username)->fetch();
if (!$row) {
throw new Nette\Security\AuthenticationException('The username is incorrect.', self::IDENTITY_NOT_FOUND);
} elseif (!Passwords::verify($password, $row[self::COLUMN_PASSWORD_HASH])) {
throw new Nette\Security\AuthenticationException('The password is incorrect.', self::INVALID_CREDENTIAL);
} elseif (Passwords::needsRehash($row[self::COLUMN_PASSWORD_HASH])) {
$row->update(array(
self::COLUMN_PASSWORD_HASH => Passwords::hash($password),
));
}
$arr = $row->toArray();
unset($arr[self::COLUMN_PASSWORD_HASH]);
return new Nette\Security\Identity($row[self::COLUMN_ID], $row[self::COLUMN_ROLE], $arr);
}
/**
* Adds new user.
* @param string
* @param string
* @return void
*/
public function add($username, $password)
{
$this->database->table(self::TABLE_NAME)->insert(array(
self::COLUMN_NAME => $username,
self::COLUMN_PASSWORD_HASH => Passwords::hash($password),
));
}
}
<?php
namespace App\Presenters;
use Nette,
App\Model;
/**
* Base presenter for all application presenters.
*/
abstract class BasePresenter extends Nette\Application\UI\Presenter
{
}
<?php
namespace App\Presenters;
use Nette,
App\Model,
Nette\Diagnostics\Debugger;
/**
* Error presenter.
*/
class ErrorPresenter extends BasePresenter
{
/**
* @param Exception
* @return void
*/
public function renderDefault($exception)
{
if ($exception instanceof Nette\Application\BadRequestException) {
$code = $exception->getCode();
// load template 403.latte or 404.latte or ... 4xx.latte
$this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
// log to access.log
Debugger::log("HTTP code $code: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
} else {
$this->setView('500'); // load template 500.latte
Debugger::log($exception, Debugger::ERROR); // and log exception
}
if ($this->isAjax()) { // AJAX request? Note this error in payload.
$this->payload->error = TRUE;
$this->terminate();
}
}
}
<?php
namespace App\Presenters;
use Nette,
App\Model;
/**
* Homepage presenter.
*/
class HomepagePresenter extends BasePresenter
{
public function renderDefault()
{
$this->template->anyVariable = 'any value';
}
}
<?php
namespace App\Presenters;
use Nette,
App\Model;
/**
* Sign in/out presenters.
*/
class SignPresenter extends BasePresenter
{
/**
* Sign-in form factory.
* @return Nette\Application\UI\Form
*/
protected function createComponentSignInForm()
{
$form = new Nette\Application\UI\Form;
$form->addText('username', 'Username:')
->setRequired('Please enter your username.');
$form->addPassword('password', 'Password:')
->setRequired('Please enter your password.');
$form->addCheckbox('remember', 'Keep me signed in');
$form->addSubmit('send', 'Sign in');
// call method signInFormSucceeded() on success
$form->onSuccess[] = $this->signInFormSucceeded;
return $form;
}
public function signInFormSucceeded($form, $values)
{
if ($values->remember) {
$this->getUser()->setExpiration('14 days', FALSE);
} else {
$this->getUser()->setExpiration('20 minutes', TRUE);
}
try {
$this->getUser()->login($values->username, $values->password);
$this->redirect('Homepage:');
} catch (Nette\Security\AuthenticationException $e) {
$form->addError($e->getMessage());
}
}
public function actionOut()
{
$this->getUser()->logout();
$this->flashMessage('You have been signed out.');
$this->redirect('in');
}
}
<?php
namespace App;
use Nette,
Nette\Application\Routers\RouteList,
Nette\Application\Routers\Route,
Nette\Application\Routers\SimpleRouter;
/**
* Router factory.
*/
class RouterFactory
{
/**
* @return \Nette\Application\IRouter
*/
public function createRouter()
{
$router = new RouteList();
$router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default');
return $router;
}
}
{**
* @param string $basePath web base path
* @param array $flashes flash messages
*}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{ifset #title}{include title|striptags} | {/ifset}Nette Sandbox</title>
<link rel="stylesheet" media="screen,projection,tv" href="{$basePath}/css/screen.css">
<link rel="stylesheet" media="print" href="{$basePath}/css/print.css">
<link rel="shortcut icon" href="{$basePath}/favicon.ico">
{block head}{/block}
</head>
<body>
<script> document.documentElement.className+=' js' </script>
<div n:foreach="$flashes as $flash" class="flash {$flash->type}">{$flash->message}</div>
{include content}
{block scripts}
<script src="{$basePath}/js/jquery.js"></script>
<script src="{$basePath}/js/netteForms.js"></script>
<script src="{$basePath}/js/main.js"></script>
{/block}
</body>
</html>
{block content}
<h1 n:block=title>Access Denied</h1>
<p>You do not have permission to view this page. Please try contact the web
site administrator if you believe you should be able to view this page.</p>
<p><small>error 403</small></p>
{block content}
<h1 n:block=title>Page Not Found</h1>
<p>The page you requested could not be found. It is possible that the address is
incorrect, or that the page no longer exists. Please use a search engine to find
what you are looking for.</p>
<p><small>error 404</small></p>
{block content}
<h1 n:block=title>Method Not Allowed</h1>
<p>The requested method is not allowed for the URL.</p>
<p><small>error 405</small></p>
{block content}
<h1 n:block=title>Page Not Found</h1>
<p>The page you requested has been taken off the site. We apologize for the inconvenience.</p>
<p><small>error 410</small></p>
{block content}
<h1 n:block=title>Oops...</h1>
<p>Your browser sent a request that this server could not understand or process.</p>
{layout none}
<!DOCTYPE html><!-- "' --></script></style></noscript></xmp>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<title>Server Error</title>
<div id="error-body">
<style>
body { color: #333; background: white; width: 500px; margin: 100px auto }
h1 { font: bold 47px/1.5 sans-serif; margin: .6em 0 }
p { font: 21px/1.5 Georgia,serif; margin: 1.5em 0 }
small { font-size: 70%; color: gray }
</style>
<h1>Server Error</h1>
<p>We're sorry! The server encountered an internal error and
was unable to complete your request. Please try again later.</p>
<p><small>error 500</small></p>
<script>
document.documentElement.innerHTML = '<title>Server Error<\/title>' +
document.getElementById('error-body').innerHTML;
</script>
This diff is collapsed.
{block content}
<h1 n:block=title>Sign in</h1>
{control signInForm}
{* or use {include '../components/form.latte', form => signInForm} *}
{form $form}
<ul class=error n:if="$form->ownErrors">
<li n:foreach="$form->ownErrors as $error">{$error}</li>
</ul>
<table>
<tr n:foreach="$form->controls as $input" n:class="$input->required ? required">
<th>{label $input /}</th>
<td>{input $input} <span class=error n:ifcontent>{$input->error}</span></td>
</tr>
</table>
{/form}
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Deny Rule 1" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{URL}" pattern="*" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
\ No newline at end of file
<?php
if (!isset($_SERVER['argv'][2])) {
echo '
Add new user to database.
Usage: create-user.php <name> <password>
';
exit(1);
}
list(, $user, $password) = $_SERVER['argv'];
$container = require __DIR__ . '/../app/bootstrap.php';
$container->getByType('App\Model\UserManager')->add($user, $password);
echo "User $user was added.\n";
{
"name": "nette/sandbox",
"description": "The sandbox is a pre-packaged Nette Framework project, basic configured structure for your application.",
"homepage": "http://nette.org",
"type": "project",
"license": ["BSD-3-Clause", "GPL-2.0", "GPL-3.0"],
"authors": [
{
"name": "David Grudl",
"homepage": "http://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "http://nette.org/contributors"
}
],
"require": {
"php": ">= 5.3.7",
"nette/nette": "~2.2.0",
"dg/adminer-custom": "~1.0"
},
"require-dev": {
"nette/tester": "~1.0"
},
"minimum-stability": "stable"
}
This diff is collapsed.
Licenses
========
Good news! You may use this sandbox under the terms of either
the New BSD License or the GNU General Public License (GPL) version 2 or 3.
New BSD License
---------------
Copyright (c) 2004, 2013 David Grudl (http://davidgrudl.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of "Nette Framework" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright owner or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
GNU General Public License
--------------------------
GPL licenses are very very long, so instead of including them here we offer
you URLs with full text:
- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html)
- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)
Order Allow,Deny
Deny from all
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Deny Rule 1" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{URL}" pattern="*" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
\ No newline at end of file
Nette Framework Sandbox
=======================
The basic skeleton of application.
What is [Nette Framework](http://nette.org)?
--------------------------------------------
Nette Framework is a popular tool for PHP web development. It is designed to be
the most usable and friendliest as possible. It focuses on security and
performance and is definitely one of the safest PHP frameworks.
Nette Framework speaks your language and helps you to easily build better websites.
Installing
----------
The best way to install Nette Framework is to download latest package
from http://nette.org/download or create new project using Composer:
1. Install Composer: (see http://getcomposer.org/download)
curl -s http://getcomposer.org/installer | php
2. Create new project via Composer:
php composer.phar create-project nette/sandbox myApplication
cd myApplication
Make directories `temp` and `log` writable. Navigate your browser
to the `www` directory and you will see a welcome page. PHP 5.4 allows
you run `php -S localhost:8888 -t www` to start the web server and
then visit `http://localhost:8888` in your browser.
It is CRITICAL that file `app/config/config.neon` & whole `app`, `log`
and `temp` directory are NOT accessible directly via a web browser! If you
don't protect this directory from direct web access, anybody will be able to see
your sensitive data. See [security warning](http://nette.org/security-warning).
Order Allow,Deny
Deny from all
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Deny Rule 1" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{URL}" pattern="*" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
\ No newline at end of file
<?php
namespace Test;
use Nette,
Tester,
Tester\Assert;
$container = require __DIR__ . '/bootstrap.php';
class ExampleTest extends Tester\TestCase
{
private $container;
function __construct(Nette\DI\Container $container)
{
$this->container = $container;
}
function setUp()
{
}
function testSomething()
{
Assert::true( true );
}
}
$test = new ExampleTest($container);
$test->run();
<?php
require __DIR__ . '/../vendor/autoload.php';
if (!class_exists('Tester\Assert')) {
echo "Install Nette Tester using `composer update --dev`\n";
exit(1);
}
Tester\Environment::setup();
$configurator = new Nette\Configurator;
$configurator->setDebugMode(FALSE);
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()
->addDirectory(__DIR__ . '/../app')
->register();
$configurator->addConfig(__DIR__ . '/../app/config/config.neon');
$configurator->addConfig(__DIR__ . '/../app/config/config.local.neon');
return $configurator->createContainer();
Order Allow,Deny
Deny from all
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Deny Rule 1" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{URL}" pattern="*" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden: Access is denied." statusDescription="You do not have permission to view this directory or page using the credentials that you supplied." />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
\ No newline at end of file
# Apache configuration file (see httpd.apache.org/docs/current/mod/quickreference.html)
# disable directory listing
<IfModule mod_autoindex.c>
Options -Indexes
</IfModule>
# enable cool URL
<IfModule mod_rewrite.c>
RewriteEngine On
# RewriteBase /
# prevents files starting with dot to be viewed by browser
RewriteRule /\.|^\. - [F]
# front controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !\.(pdf|js|ico|gif|jpg|png|css|rar|zip|tar\.gz)$ index.php [L]
</IfModule>
# enable gzip compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/x-javascript text/javascript application/javascript application/json
</IfModule>
<?php
header('HTTP/1.1 503 Service Unavailable');
header('Retry-After: 300'); // 5 minutes in seconds
?>
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<meta name="generator" content="Nette Framework">
<style>
body { color: #333; background: white; width: 500px; margin: 100px auto }
h1 { font: bold 47px/1.5 sans-serif; margin: .6em 0 }
p { font: 21px/1.5 Georgia,serif; margin: 1.5em 0 }
</style>
<title>Site is temporarily down for maintenance</title>
<h1>We're Sorry</h1>
<p>The site is temporarily down for maintenance. Please try again in a few minutes.</p>
<?php
exit;
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule (adminer.css|static/.+) index.php?file=$1 [L,QSA]
</IfModule>
<?php
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !isset($_SERVER['REMOTE_ADDR']) ||
!in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
{
header('HTTP/1.1 403 Forbidden');
echo 'Adminer is available only from localhost';
for ($i = 2e3; $i; $i--) echo substr(" \t\r\n", rand(0, 3), 1);
exit;
}
$root = __DIR__ . '/../../vendor/dg/adminer-custom';
if (!is_file($root . '/index.php')) {
echo "Install Adminer using `composer update`\n";
exit(1);
}
if (isset($_GET['file']) && preg_match('#^(?:static/)?[\w.-]+\.(\w+)$#', $_GET['file'], $m)
&& is_file("$root/$_GET[file]"))
{
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header('HTTP/1.1 304 Not Modified');
exit;
}
header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('1 month')) . ' GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
if ($m[1] === 'css') {
header('Content-Type: text/css; charset=utf-8');
} elseif ($m[1] === 'js') {
header('Content-Type: text/javascript; charset=utf-8');
} elseif ($m[1] === 'gif' || $m[1] === 'png' ||$m[1] === 'jpg') {
header("Content-Type: image/$m[1]");
}
readfile("$root/$_GET[file]");
exit;
}
require $root . '/index.php';
body {
font: 12pt/1.4 "Trebuchet MS", "Geneva CE", lucida, sans-serif;
color: black;
background: none;
width: 100%;
}
a img { border: none; }
#ajax-spinner {
display: none;
}
body {
font-size: 15px;
line-height: 1.6;
color: #333;
background: white;
}
h1 {
color: #3484D2;
}
#ajax-spinner {
margin: 15px 0 0 15px;
padding: 13px;
background: white url('../images/spinner.gif') no-repeat 50% 50%;
font-size: 0;
z-index: 123456;
display: none;
}
div.flash {
color: black;
background: #FFF9D7;
border: 1px solid #E2C822;
padding: 1em;
margin: 1em 0;
}
a[href^="#error:"] {
background: red;
color: white;
}
form th, form td {
vertical-align: top;
font-weight: normal;
}
form th {
text-align: right;
}
form .required label {
font-weight: bold;
}
form .error {
color: #D00;
font-weight: bold;
}
html.js .jshidden {
display: none;
}
<?php
// Uncomment this line if you must temporarily take down your site for maintenance.
// require '.maintenance.php';
$container = require __DIR__ . '/../app/bootstrap.php';
$container->getService('application')->run();
This diff is collapsed.
$(function(){
});
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<!-- IIS configuration file -->
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite Rule 1" stopProcessing="true">
<match url="\.(pdf|js|ico|gif|jpg|png|css|rar|zip|tar\.gz)$" ignoreCase="false" negate="true" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment