1
0
mirror of https://github.com/flarum/core.git synced 2025-10-12 07:24:27 +02:00

Major refactor and improvements

- Reorganised all namespaces and class names for consistency and structure. Following PSR bylaws (Abstract prefix, Interface/Trait suffix).
  - Move models into root of Core, because writing `use Flarum\Core\Discussion` is nice. Namespace the rest by type. (Namespacing by entity was too arbitrary.)
  - Moved some non-domain stuff out of Core: Database, Formatter, Settings.
  - Renamed config table and all references to "settings" for consistency.
  - Remove Core class and add url()/isInstalled()/inDebugMode() as instance methods of Foundation\Application.
  - Cleanup, docblocking, etc.

- Improvements to HTTP architecture
  - API and forum/admin Actions are now actually all the same thing (simple PSR-7 Request handlers), renamed to Controllers.
  - Upgrade to tobscure/json-api 0.2 branch.
  - Where possible, moved generic functionality to tobscure/json-api (e.g. pagination links). I'm quite happy with the backend balance now re: #262

- Improvements to other architecture
  - Use Illuminate's Auth\Access\Gate interface/implementation instead of our old Locked trait. We still use events to actually determine the permissions though. Our Policy classes are actually glorified event subscribers.
  - Extract model validation into Core\Validator classes.
  - Make post visibility permission stuff much more efficient and DRY.

- Renamed Flarum\Event classes for consistency. ref #246
  - `Configure` prefix for events dedicated to configuring an object.
  - `Get` prefix for events whose listeners should return something.
  - `Prepare` prefix when a variable is passed by reference so it can be modified.
  - `Scope` prefix when a query builder is passed.

- Miscellaneous improvements/bug-fixes. I'm easily distracted!
  - Increase default height of post composer.
  - Improve post stream redraw flickering in Safari by keying loading post placeholders with their IDs. ref #451
  - Use a PHP JavaScript minification library for minifying TextFormatter's JavaScript, instead of ClosureCompilerService (can't rely on external service!)
  - Use UrlGenerator properly in various places. closes #123
  - Make Api\Client return Response object. closes #128
  - Allow extensions to specify custom icon images.
  - Allow external API/admin URLs to be optionally specified in config.php. If the value or "url" is an array, we look for the corresponding path inside. Otherwise, we append the path to the base URL, using the corresponding value in "paths" if present. closes #244
This commit is contained in:
Toby Zerner
2015-10-08 14:28:02 +10:30
parent 8c7cdb184f
commit dd67291ce0
434 changed files with 8676 additions and 7997 deletions

View File

@@ -12,13 +12,14 @@ namespace Flarum\Api\Middleware;
use Flarum\Api\AccessToken;
use Flarum\Api\ApiKey;
use Flarum\Core\Users\User;
use Flarum\Core\Guest;
use Flarum\Core\User;
use Illuminate\Contracts\Container\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class LoginWithHeader implements MiddlewareInterface
class AuthenticateWithHeader implements MiddlewareInterface
{
/**
* @var Container
@@ -42,6 +43,17 @@ class LoginWithHeader implements MiddlewareInterface
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
$request = $this->logIn($request);
return $out ? $out($request, $response) : $response;
}
/**
* @param Request $request
* @return Request
*/
protected function logIn(Request $request)
{
$header = $request->getHeaderLine('authorization');
@@ -51,18 +63,20 @@ class LoginWithHeader implements MiddlewareInterface
$token = substr($parts[0], strlen($this->prefix));
if (($accessToken = AccessToken::find($token)) && $accessToken->isValid()) {
$this->app->instance('flarum.actor', $user = $accessToken->user);
$user = $accessToken->user;
$user->updateLastSeen()->save();
return $request->withAttribute('actor', $user);
} elseif (isset($parts[1]) && ($apiKey = ApiKey::valid($token))) {
$userParts = explode('=', trim($parts[1]));
if (isset($userParts[0]) && $userParts[0] === 'userId') {
$this->app->instance('flarum.actor', $user = User::find($userParts[1]));
return $request->withAttribute('actor', $user = User::find($userParts[1]));
}
}
}
return $out ? $out($request, $response) : $response;
return $request->withAttribute('actor', new Guest);
}
}

View File

@@ -10,18 +10,34 @@
namespace Flarum\Api\Middleware;
use Flarum\Core\Exceptions\JsonApiSerializable;
use Flarum\Api\JsonApiResponse;
use Flarum\Foundation\Application;
use Illuminate\Contracts\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Tobscure\JsonApi\Document;
use Tobscure\JsonApi\Exception\JsonApiSerializableInterface;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Stratigility\ErrorMiddlewareInterface;
use Flarum\Core;
use Exception;
class JsonApiErrors implements ErrorMiddlewareInterface
class HandleErrors implements ErrorMiddlewareInterface
{
/**
* @var Application
*/
private $app;
/**
* @param Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
}
/**
* {@inheritdoc}
*/
@@ -32,11 +48,11 @@ class JsonApiErrors implements ErrorMiddlewareInterface
public function handle(Exception $e)
{
if ($e instanceof JsonApiSerializable) {
if ($e instanceof JsonApiSerializableInterface) {
$status = $e->getStatusCode();
$errors = $e->getErrors();
} else if ($e instanceof ValidationException) {
} elseif ($e instanceof ValidationException) {
$status = 422;
$errors = $e->errors()->toArray();
@@ -46,7 +62,7 @@ class JsonApiErrors implements ErrorMiddlewareInterface
'source' => ['pointer' => '/data/attributes/' . $field],
];
}, array_keys($errors), $errors);
} else if ($e instanceof ModelNotFoundException) {
} elseif ($e instanceof ModelNotFoundException) {
$status = 404;
$errors = [];
@@ -58,19 +74,16 @@ class JsonApiErrors implements ErrorMiddlewareInterface
'title' => 'Internal Server Error'
];
if (Core::inDebugMode()) {
if ($this->app->inDebugMode()) {
$error['detail'] = (string) $e;
}
$errors = [$error];
}
// JSON API errors must be collected in an array under the
// "errors" key in the top level of the document
$data = [
'errors' => $errors,
];
$document = new Document;
$document->setErrors($errors);
return new JsonResponse($data, $status);
return new JsonApiResponse($document, $status);
}
}

View File

@@ -1,38 +0,0 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class ReadJsonParameters implements MiddlewareInterface
{
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (str_contains($request->getHeaderLine('content-type'), 'json')) {
$input = json_decode($request->getBody(), true);
if (! is_array($input)) {
$input = [];
}
foreach ($input as $name => $value) {
$request = $request->withAttribute($name, $value);
}
}
return $out ? $out($request, $response) : $response;
}
}