Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
killua-eu committed Dec 25, 2019
1 parent b5c909c commit 681cc6c
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 51 deletions.
38 changes: 15 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# GLued-Skeleton
# Glued-Skeleton

A full blown modular webapp skeleton built around

Expand Down Expand Up @@ -138,36 +138,28 @@ Credit for the initial translation implementation goes to https://github.com/oda

### Validation & exceptions and error handling

Glued
Used technology

- relies on respect/validation, extends it through the core\classes\validation class to make work with forms easier.
- uses custom exceptions to display error messages on URIs
throw new HttpNotFoundException($this->request, 'User not found');
- uses flash messages
- json data validation
- `Respect\Validation` class, extended via `Core\Classes\Validation` class and `ValidationFormsMiddleware` which simplify handling validation failures of posted form data
- `Slim\Flash` to render feedback on actions
- Json data validation on API routes
- Choice between the `Whoops` and `Error` middlewares to display errors (hint: use whoops for development, error for production)

Exception and error handling is done via
Practical usage

- flash messages
- exception handlers, i.e. `throw new HttpNotFoundException($request, 'optional message');`
- api responses, i.e. via json exception renderer (see end of `core/middleware.php`)
- Distinguish between infrastructure specific exceptions (e.g. HttpNotFoundException, HttpBadRequestException) and domain specific exceptions (e.g. DomainException, UnexpectedValueException, ValidationException, etc…).
- Use domain specific exception in classes (where glued handles the data internally only), rethrow the domain specific exceptions as infrastructure specific exceptions in controllers (set the return code depending on context, emit a friendlier/more readable error message). See how `Glued\Core\Controllers\AccountsController::read()` rethrows exceptions comming from `Glued\Core\Classes\Auth\Auth::user_read()`.
- Using infrastructure specific exceptions in classes is unwanted, since throwing them requires the Request passed as a parameter (i.e. `throw new HttpNotFoundException($this->request, 'User not found');`).
- Perform validation in classes. Optionally you can also validate in controllers, if it's usefull (i.e. see `Glued\Core\Controllers\AccountsController::signup_post()` where the `$this->validator` uses the container-residing `Core\Classes\Validation` helper that re-fills the signup form and explains which data is invalid)
- Don't forget to do i18n via. the `__()` function available both in glued's php sources and in its twig templates on error messages.

**Notes on praticalities**
Notes

- Validation is in most cases done in controllers (a json controller will validate data differently from the twig controller). Class functions used by some controllers will expect validated data.
- To prevent unwanted validation rules differences, validation rules are kept in the vrules container item (single source of thruth), rather then in the controller code.
- Within classes used by controllers, throwing exceptions is limited to cases which require a total execution stop. I.e. in the `core/classes/auth/auth.php` class, exceptions are thrown only on invalid data in the `response()` function. Since the data fed to this function should be always valid (passed from the session data which the user cannot tamper with), getting invalid data here would indicate a serious problem. Other functions in this class don't throw exceptions and just return i.e. an empty result set.


### Error handling

- throw exceptions:

**NOTE:** Don't forget to do i18n!
- In classes throwing exceptions is limited to cases which require a total execution stop (i.e. security concerns). I.e. in the `core/classes/auth/auth.php` class, exceptions are thrown only on invalid data in the `response()` function. Since the data fed to this function should be always valid (passed from the session data which the user cannot tamper with), getting invalid data here would indicate a serious problem. Other functions in this class don't throw exceptions and just return i.e. an empty result set.

### Debuging

Remember that `var_dump($some_variable); die();` is your best friend.
Remember that `var_dump($some_variable); die();` is your best friend. Also use the `Whoops` error middleware (see settings.php)


### Developer tutorials
Expand Down
10 changes: 3 additions & 7 deletions glued/Core/Classes/Auth/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@
namespace Glued\Core\Classes\Auth;
use Respect\Validation\Validator as v;
use UnexpectedValueException;
use ErrorException;
use RuntimeException;

//use Psr\Http\Message\ResponseInterface as Response;
//use Psr\Http\Message\ServerRequestInterface as Request;

class Auth
{
Expand Down Expand Up @@ -44,12 +39,13 @@ public function user_create($email, $name, $password) {

public function user_read($uid) {
if (!(v::intVal()->positive()->between(0, 4294967295)->validate($uid))) {
throw new ErrorException('Bad request (wrong user id).', 550);
throw new UnexpectedValueException('Bad request (wrong user id).', 550);
}

$this->db->where("c_uid", $uid);
$result = $this->db->getOne("t_core_users");
if(!$result) {
throw new Exception('Not found (no such user).', 450);
throw new UnexpectedValueException('Not found (no such user).', 450);
}
return $result;
}
Expand Down
4 changes: 2 additions & 2 deletions glued/Core/Controllers/Accounts.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function read(Request $request, Response $response, array $args = []): Re
{
$auth = new Auth($this->db, $this->settings);
try {
$users = $auth->user_read($request, $args['uid']);
$users = $auth->user_read($args['uid']);
} catch (Throwable $e) {
if ($e->getCode() == 450) { throw new NotFound($request, 'User not found.'); }
if ($e->getCode() == 550) { throw new BadRequest($request, 'Wrong user id.'); }
Expand All @@ -38,7 +38,7 @@ public function list(Request $request, Response $response, array $args = []): Re
{
// DO RBAC HERE
$auth = new Auth($this->db, $this->settings);
$users = $auth->user_list($request);
$users = $auth->user_list();
return $this->render($response, 'Core/Views/accounts.list.twig', [
'pageTitle' => 'Accounts',
'users' => $users
Expand Down
24 changes: 5 additions & 19 deletions glued/Core/Controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@
class AuthController extends AbstractTwigController

{

public function signout_get($request, $response)
{
$this->auth->signout();
return $response->withRedirect($this->routerParser->urlFor('core.web'));
}


public function signin_get($request, $response)
{
return $this->view->render($response, 'Core/Views/signin.twig');
}


public function signin_post($request, $response)
{
$auth = $this->auth->attempt(
Expand All @@ -39,27 +42,15 @@ public function signin_post($request, $response)
return $response->withRedirect($this->routerParser->urlFor('core.dashboard.web'));
}


public function signup_get($request, $response)
{
return $this->view->render($response, 'Core/Views/signup.twig');
}
/*
public function test($request, $response) {

$this->db->join("t_core_authn a", "a.c_user_uid=u.c_uid", "LEFT");
$this->db->where("u.c_uid", 16);
$this->db->where("a.c_uid", 9);
$result = $this->db->getOne("t_core_users u", null);

echo $this->db->getLastQuery().'<br>';
print_r($result);
return $response;
}
*/
public function signup_post($request, $response)
{

$validation = $this->validator->validate($request, [
'email' =>v::noWhitespace()->notEmpty()->email()->emailAvailable($this->db),
'name' => v::notEmpty()->alnum(),
Expand All @@ -69,13 +60,8 @@ public function signup_post($request, $response)
return $response->withRedirect($this->routerParser->urlFor('core.signup.web'));
}
$this->auth->user_create($request->getParam('email'), $request->getParam('name'), $request->getParam('password'));
// signin user after account creation
$this->auth->attempt($request->getParam('email'), $request->getParam('password'));

// TODO configure session middleware according to $settings
/*
$this->flash->addMessage('info', 'You have been signed up!');
= $this->auth->attempt($user->email, $request->getParam('password')); */
$this->auth->attempt($request->getParam('email'), $request->getParam('password')); // auto sign-in after account creation
return $response->withRedirect($this->routerParser->urlFor('core.web'));
}
}

0 comments on commit 681cc6c

Please sign in to comment.