- Refactor

- Bugfixes
- Add possibility to determine LogLevel and logger name in environment
This commit is contained in:
Alexander Schäferdiek 2016-07-11 22:29:44 +02:00
parent 283315ab08
commit 74a2bae39f
22 changed files with 191 additions and 149 deletions

View file

@ -43,6 +43,7 @@ as dependencies.
* Point your document root to `public/`. * Point your document root to `public/`.
* Example nginx conf: * Example nginx conf:
root .../public; root .../public;
index index.php; index index.php;
@ -68,13 +69,21 @@ as dependencies.
* Change directory to project home * Change directory to project home
* `git pull` * `git pull`
* `composer update` * `composer update`
* look for changes
* `php bin/phpmig migrate` * `php bin/phpmig migrate`
* look into Changelog for major changes
## Translations ## ## Translations ##
This app uses Symfony Translator. It's bootstraped in `Util\TranslationHelper` and locales are placed under `data/locale/`. Adjust to your needs or help translating. This app uses Symfony Translator. It's bootstraped in `Util\BootstrapHelper` and locales are placed under `data/locale/`. Adjust to your needs or help translating.
## Changelog ## ## Changelog ##
- 0.1.3.2:
- Refactor
- Bugfixes
- Add possibility to determine LogLevel and logger name in environment
- 0.1.3.1:
- Bugfixes
- 0.1.3: - 0.1.3:
- add authentication after sign up - add authentication after sign up
- only logged in users can delete their account (with the help of the token) - only logged in users can delete their account (with the help of the token)
@ -87,7 +96,7 @@ This app uses Symfony Translator. It's bootstraped in `Util\TranslationHelper` a
- updated readme and `env.example` - updated readme and `env.example`
- fix some language validator inconsistencies - fix some language validator inconsistencies
- added admin notifications - added admin notifications
- added possiblity for users to delete their account - added possibility for users to delete their account
- added back index page - added back index page
- works with mod_admin_rest version [afc42d7](https://github.com/snowblindroan/mod_admin_rest/commit/afc42d70f0aceb2351a1bc786d61e3f4dbdfb948) - works with mod_admin_rest version [afc42d7](https://github.com/snowblindroan/mod_admin_rest/commit/afc42d70f0aceb2351a1bc786d61e3f4dbdfb948)
- 0.1: - 0.1:

View file

@ -7,11 +7,11 @@ require_once __DIR__ . DIRECTORY_SEPARATOR . '../vendor/autoload.php';
/* /*
* Bootstrap environment, configs and database * Bootstrap environment, configs and database
*/ */
$env = EnvironmentHelper::getAppEnvironment(); $env = BootstrapHelper::bootEnvironment();
$config = Config::$CONFIG; $config = Config::$CONFIG;
$db = DatabaseHelper::getAppDatabase(); $db = BootstrapHelper::bootDatabase();
$translator = TranslationHelper::getAppTranslator(); $translator = BootstrapHelper::bootTranslator();
$logger = LoggerHelper::getAppLogger(); $logger = BootstrapHelper::bootLogger();
// handle all users awaiting verification and notify them // handle all users awaiting verification and notify them
$users = UserAwaitingVerification::all(); $users = UserAwaitingVerification::all();

View file

@ -27,8 +27,6 @@ class Config
], ],
'logger_settings' => [ 'logger_settings' => [
'level' => Logger::DEBUG,
'name' => 'application',
'path' => __DIR__ . DIRECTORY_SEPARATOR . '..'. DIRECTORY_SEPARATOR .'log'. DIRECTORY_SEPARATOR .'application.log', 'path' => __DIR__ . DIRECTORY_SEPARATOR . '..'. DIRECTORY_SEPARATOR .'log'. DIRECTORY_SEPARATOR .'application.log',
], ],
]; ];

View file

@ -9,13 +9,13 @@ site_navbar_logout_displayname="Logout"
site_navbar_backlink_enabled="false" # enables a link in the navbar to go back to e.g. main server site site_navbar_backlink_enabled="false" # enables a link in the navbar to go back to e.g. main server site
site_navbar_backlink_uri="" site_navbar_backlink_uri=""
site_navbar_backlink_displayname="" site_navbar_backlink_displayname=""
site_xmpp_server_displayname="jabber.server.org" site_xmpp_server_displayname="jabber.server.org" # displayed after the @
# verification_timeout and non-verified users will be deleted # verification_timeout and non-verified users will be deleted
verification_cleanup_time="7 day" verification_cleanup_time="7 day"
# xmpp Settings # xmpp Settings
xmpp_host="hoth.one" # hostname to connect xmpp_host="" # hostname to connect
xmpp_port="5222" # port to connect, defaults to 5222 xmpp_port="5222" # port to connect, defaults to 5222
xmpp_connection_type="tcp" # defaults to tcp xmpp_connection_type="tcp" # defaults to tcp
@ -25,7 +25,6 @@ xmpp_curl_auth_admin_username="" # configured in prosody lua file
xmpp_curl_auth_admin_password="" # configured in prosody lua file xmpp_curl_auth_admin_password="" # configured in prosody lua file
# Mail Settings # Mail Settings
# main
mail_host="" mail_host=""
mail_port="587" mail_port="587"
mail_secure="tls" mail_secure="tls"
@ -33,7 +32,13 @@ mail_auth=true
mail_username="" mail_username=""
mail_password="" mail_password=""
mail_from="webmaster@jabber.server.org" mail_from="webmaster@jabber.server.org"
mail_from_name="jabber.server.org" mail_from_name="Server Name"
# log
log_name="application"
# possible log levels from low to high, lower values produce more details:
# DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY
log_level="INFO"
# notification # notification
mail_notify="true" # sends an email to mail_notify_to if a new user successfully verified their account mail_notify="true" # sends an email to mail_notify_to if a new user successfully verified their account

View file

@ -3,8 +3,8 @@
use \Phpmig\Adapter; use \Phpmig\Adapter;
$container = new ArrayObject(); $container = new ArrayObject();
$container['env'] = EnvironmentHelper::getAppEnvironment(); $container['env'] = BootstrapHelper::bootEnvironment();
$container['db'] = DatabaseHelper::getAppDatabase(); $container['db'] = BootstrapHelper::bootDatabase();
$container['phpmig.adapter'] = new Phpmig\Adapter\PDO\Sql($container['db']->getConnection()->getPdo(), 'migrations'); $container['phpmig.adapter'] = new Phpmig\Adapter\PDO\Sql($container['db']->getConnection()->getPdo(), 'migrations');

View file

@ -26,7 +26,7 @@ verification.mail.body: |
In order to complete your registration, verify your email within 7 days by clicking on %verificationLink%. In order to complete your registration, verify your email within 7 days by clicking on %verificationLink%.
verification.code.invalid: Verification code %verificationCode% is not valid. verification.code.invalid: Verification code %verificationCode% is not valid.
verification.flash.already_in_use_username: %username% is already in use. verification.flash.already_in_use_username: %username% is already in use.
verification.flash.success: Verification successful. You can now sign in to your newly created jabber account %username%@hoth.one. verification.flash.success: Verification successful. You can now sign in to your newly created jabber account %username%@%server%.
verification.flash.unknown_error: Could not process sign up of %username%. Please contact administrator. verification.flash.unknown_error: Could not process sign up of %username%. Please contact administrator.
verification.mail.success.subject: %server%: jabber account information verification.mail.success.subject: %server%: jabber account information
verification.mail.success.body: | verification.mail.success.body: |

View file

@ -22,7 +22,7 @@ $app = new Slim\App(['settings' => Config::$CONFIG['slim_settings']]);
$container = $app->getContainer(); $container = $app->getContainer();
// Environment // Environment
$env = EnvironmentHelper::getAppEnvironment(); $env = BootstrapHelper::bootEnvironment();
$container['env'] = function() use ($env) { $container['env'] = function() use ($env) {
return $env; return $env;
}; };
@ -33,20 +33,20 @@ $container['config'] = function() {
}; };
// Database // Database
$capsule = DatabaseHelper::getAppDatabase(); $capsule = BootstrapHelper::bootDatabase();
$container['db'] = function () use ($capsule) { $container['db'] = function () use ($capsule) {
return $capsule; return $capsule;
}; };
// Translation // Translation
$translator = TranslationHelper::getAppTranslator(); $translator = BootstrapHelper::bootTranslator();
$container['translator'] = function () use ($translator) { $container['translator'] = function () use ($translator) {
return $translator; return $translator;
}; };
// Logger // Logger
$container['logger'] = function () { $container['logger'] = function () {
$logger = LoggerHelper::getAppLogger(); $logger = BootstrapHelper::bootLogger();
return $logger; return $logger;
}; };

View file

@ -30,7 +30,7 @@ final class DeleteAction
if ($request->isPost()) { if ($request->isPost()) {
// Form validation // Form validation
$validator = new Validator(); $validator = new ValidationHelper();
$validator->filter_rules([ $validator->filter_rules([
'username' => 'trim|sanitize_string', 'username' => 'trim|sanitize_string',
'delete_code' => 'trim|sanitize_string', 'delete_code' => 'trim|sanitize_string',

View file

@ -32,7 +32,7 @@ final class LoginAction
if ($request->isPost()) { if ($request->isPost()) {
// Form validation // Form validation
$validator = new Validator(); $validator = new ValidationHelper();
$validator->filter_rules([ $validator->filter_rules([
'username' => 'trim|sanitize_string', 'username' => 'trim|sanitize_string',
]); ]);

View file

@ -33,7 +33,7 @@ final class PasswordAction
if ($request->isPost()) { if ($request->isPost()) {
// Form validation // Form validation
$validator = new Validator(); $validator = new ValidationHelper();
$validator->validation_rules([ $validator->validation_rules([
'password' => 'required|max_len,255|min_len,8', 'password' => 'required|max_len,255|min_len,8',
'password_confirmation' => 'required|max_len,255|min_len,8', 'password_confirmation' => 'required|max_len,255|min_len,8',

View file

@ -33,7 +33,7 @@ final class SignUpAction
if ($request->isPost()) { if ($request->isPost()) {
// Form validation // Form validation
$validator = new Validator(); $validator = new ValidationHelper();
$validator->filter_rules([ $validator->filter_rules([
'username' => 'trim|sanitize_string', 'username' => 'trim|sanitize_string',
'email' => 'trim|sanitize_email', 'email' => 'trim|sanitize_email',

View file

@ -49,7 +49,7 @@ final class VerificationAction
$userAwaiting->delete(); $userAwaiting->delete();
return $response->withRedirect('signup'); return $response->withRedirect('signup');
} else if ($curl->http_status_code == 201) { } else if ($curl->http_status_code == 201) {
$this->flash->addMessage('success', $this->translator->trans('verification.flash.success', ['%username%' => $userAwaiting->username])); $this->flash->addMessage('success', $this->translator->trans('verification.flash.success', ['%username%' => $userAwaiting->username, '%server%' => getenv('site_xmpp_server_displayname')]));
$this->logger->info($this->translator->trans('log.verification.sucess', ['%username%' => $userAwaiting->username])); $this->logger->info($this->translator->trans('log.verification.sucess', ['%username%' => $userAwaiting->username]));
if (getenv('mail_notify') == true) { if (getenv('mail_notify') == true) {

View file

@ -7,7 +7,6 @@ use Fabiang\Xmpp\Client;
use Fabiang\Xmpp\Exception\Stream\AuthenticationErrorException; use Fabiang\Xmpp\Exception\Stream\AuthenticationErrorException;
use Fabiang\Xmpp\Options; use Fabiang\Xmpp\Options;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use UserRegistered;
use Zend\Authentication\Adapter\AbstractAdapter; use Zend\Authentication\Adapter\AbstractAdapter;
use Zend\Authentication\Result; use Zend\Authentication\Result;
@ -64,12 +63,6 @@ class XmppAdapter extends AbstractAdapter
$client = new Client($options); $client = new Client($options);
try { try {
/*$userRegistered = UserRegistered::with([])->find($this->getIdentity());
if (empty($userRegistered)) {
throw new AuthenticationErrorException;
}*/
$client->connect(); $client->connect();
} catch (AuthenticationErrorException $e) { } catch (AuthenticationErrorException $e) {

View file

@ -0,0 +1,128 @@
<?php
use Dotenv\Dotenv;
use Illuminate\Database\Capsule\Manager;
use Monolog\Logger;
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Translator;
class BootstrapHelper
{
/**
* Bootstraps eloquent database
*
* @return \Illuminate\Database\Capsule\Manager
*/
public static function bootDatabase()
{
$config = Config::$CONFIG['db_settings'];
$path = $config['database'];
// create database file of non-existent
if (!file_exists($path)) {
fopen($path, 'w') or die('Unable to write database file.');
}
$capsule = new Manager();
$capsule->addConnection([
'driver' => $config['driver'],
'database' => $path,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
return $capsule;
}
/**
* Bootstrap env variables
*
* @return array
* @throws Exception
*/
public static function bootEnvironment()
{
$envPath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config';
$envFile = 'env';
$exists = is_file($envPath . DIRECTORY_SEPARATOR . $envFile);
if (!$exists) {
die('Configure your environment in ' . $envPath . '.');
} else {
$env = new Dotenv($envPath, $envFile);
$res = $env->load();
return $res;
}
}
/**
* Bootstrap translator
*
* @return Translator
*/
public static function bootTranslator()
{
$translator = new Translator('en_EN', new MessageSelector());
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addResource('yaml', __DIR__ . DIRECTORY_SEPARATOR . '../../data/locale/messages.en.yml', 'en_EN');
$translator->setFallbackLocales(['en']);
return $translator;
}
/**
* Bootstrap logger
*
* @return \Monolog\Logger
*/
public static function bootLogger()
{
$logName = getenv('log_name');
$logLevel = getenv('log_level');
switch ($logLevel) {
case 'DEBUG':
$logLevelTranslated = Logger::DEBUG;
break;
case 'INFO':
$logLevelTranslated = Logger::INFO;
break;
case 'NOTICE':
$logLevelTranslated = Logger::NOTICE;
break;
case 'WARNING':
$logLevelTranslated = Logger::WARNING;
break;
case 'ERROR';
$logLevelTranslated = Logger::ERROR;
break;
case 'CRITICAL':
$logLevelTranslated = Logger::CRITICAL;
break;
case 'ALERT':
$logLevelTranslated = Logger::ALERT;
break;
case 'EMERGENCY':
$logLevelTranslated = Logger::EMERGENCY;
break;
default:
$logLevelTranslated = Logger::DEBUG;
}
$logPath = Config::$CONFIG['logger_settings']['path'];
$logger = new Monolog\Logger($logName);
$logger->pushProcessor(new \Monolog\Processor\UidProcessor());
$logger->pushHandler(new \Monolog\Handler\StreamHandler($logPath, $logLevelTranslated));
$logger->pushHandler(new \Monolog\Handler\ErrorLogHandler(NULL, $logLevelTranslated));
return $logger;
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Capsule\Manager;
class DatabaseHelper
{
public static function getAppDatabase()
{
$config = Config::$CONFIG['db_settings'];
$path = $config['database'];
// create database file of non-existent
if (!file_exists($path)) {
fopen($path, 'w') or die('Unable to write database file.');
}
$capsule = new Manager();
$capsule->addConnection([
'driver' => $config['driver'],
'database' => $path,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
return $capsule;
}
}

View file

@ -6,6 +6,7 @@ class DateHelper
{ {
/** /**
* Returns param if already carbon, else formats with Y-m-d H:i:s * Returns param if already carbon, else formats with Y-m-d H:i:s
*
* @param $date * @param $date
* @return Carbon|false * @return Carbon|false
*/ */

View file

@ -1,25 +0,0 @@
<?php
use Dotenv\Dotenv;
class EnvironmentHelper
{
/**
* @return array
* @throws Exception
*/
public static function getAppEnvironment()
{
$envPath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config';
$envFile = 'env';
$exists = is_file($envPath . DIRECTORY_SEPARATOR . $envFile);
if (!$exists) {
die('Configure your environment in ' . $envPath . '.');
} else {
$env = new Dotenv($envPath, $envFile);
$res = $env->load();
return $res;
}
}
}

View file

@ -1,14 +0,0 @@
<?php
class LoggerHelper
{
public static function getAppLogger()
{
$config = Config::$CONFIG['logger_settings'];
$logger = new Monolog\Logger($config['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($config['path'], Config::$CONFIG['logger_settings']['level']));
$logger->pushHandler(new \Monolog\Handler\ErrorLogHandler(NULL, Config::$CONFIG['logger_settings']['level']));
return $logger;
}
}

View file

@ -1,21 +0,0 @@
<?php
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Translator;
class TranslationHelper
{
/**
* @return Translator
*/
public static function getAppTranslator()
{
$translator = new Translator('en_EN', new MessageSelector());
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addResource('yaml', __DIR__ . DIRECTORY_SEPARATOR . '../../data/locale/messages.en.yml', 'en_EN');
$translator->setFallbackLocales(['en']);
return $translator;
}
}

View file

@ -4,13 +4,13 @@
* Class Validator * Class Validator
* @see Gump for use * @see Gump for use
*/ */
class Validator extends GUMP class ValidationHelper extends GUMP
{ {
private $translator; private $translator;
public function __construct() public function __construct()
{ {
$this->translator = TranslationHelper::getAppTranslator(); $this->translator = BootstrapHelper::bootTranslator();
} }
/** Validates if $field content is equal to $param /** Validates if $field content is equal to $param

View file

@ -7,9 +7,9 @@
<label for="username">{% trans %}delete.form.username{% endtrans %}</label><br/> <label for="username">{% trans %}delete.form.username{% endtrans %}</label><br/>
<input type="text" id="username" name="username" class="" placeholder="{% trans %}delete.form.username.placeholder{% endtrans %}" value="" autofocus required> @{{ getenv('site_xmpp_server_displayname') }} <input type="text" id="username" name="username" class="" placeholder="{% trans %}delete.form.username.placeholder{% endtrans %}" value="" autofocus required> @{{ getenv('site_xmpp_server_displayname') }}
<br/><br/> <br/><br/>
<label for="deletion_code">{% trans %}delete.form.delete_code{% endtrans %}</label><br/> <label for="delete_code">{% trans %}delete.form.delete_code{% endtrans %}</label><br/>
<input type="text" id="delete_code" name="delete_code" class="" placeholder="{% trans %}delete.form.delete_code.placeholder{% endtrans %}" value="" autofocus required> <input type="text" id="delete_code" name="delete_code" class="" placeholder="{% trans %}delete.form.delete_code.placeholder{% endtrans %}" value="" autofocus required>
<br/><br/> <br/><br/>
<input class="" type="submit" name="delete" value="{% trans %}delete.form.button{% endtrans %}"/> <input class="" type="submit" name="delete_button" value="{% trans %}delete.form.button{% endtrans %}"/>
</form> </form>
{% endblock %} {% endblock %}

View file

@ -1,7 +1,7 @@
{% extends 'base.twig' %} {% extends 'base.twig' %}
{% block content %} {% block content %}
<form class="" role="form" name="register" id="register" method="post"> <form class="" role="form" name="signup" id="signup" method="post">
<h1>{{ title }}</h1> <h1>{{ title }}</h1>
<label for="username">{% trans %}sign.up.form.username{% endtrans %}</label><br/> <label for="username">{% trans %}sign.up.form.username{% endtrans %}</label><br/>
@ -13,6 +13,6 @@
<label for="password">{% trans %}sign.up.form.password{% endtrans %}</label><br/> <label for="password">{% trans %}sign.up.form.password{% endtrans %}</label><br/>
<input type="password" id="password" name="password" class="form-control" placeholder="{% trans %}sign.up.form.password.placeholder{% endtrans %}" required> <input type="password" id="password" name="password" class="form-control" placeholder="{% trans %}sign.up.form.password.placeholder{% endtrans %}" required>
<br/><br/> <br/><br/>
<input class="" type="submit" name="signup" value="{% trans %}sign.up.form.button{% endtrans %}"/> <input class="" type="submit" name="signup_button" value="{% trans %}sign.up.form.button{% endtrans %}"/>
</form> </form>
{% endblock %} {% endblock %}