Add Content for User page, preload user & throw 404 accordingly (#1901)

This commit is contained in:
David Sevilla Martín 2020-01-22 18:01:26 -05:00 committed by Daniël Klabbers
parent 5b3acfc0d9
commit 0c9bcba3a6
3 changed files with 89 additions and 2 deletions

View File

@ -88,8 +88,13 @@ export default class UserPage extends Page {
loadUser(username) {
const lowercaseUsername = username.toLowerCase();
// Load the preloaded user object, if any, into the global app store
// We don't use the output of the method because it returns raw JSON
// instead of the parsed models
app.preloadedApiDocument();
app.store.all('users').some(user => {
if (user.username().toLowerCase() === lowercaseUsername && user.joinTime()) {
if ((user.username().toLowerCase() === lowercaseUsername || user.id() === username) && user.joinTime()) {
this.show(user);
return true;
}

View File

@ -0,0 +1,82 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Forum\Content;
use Flarum\Api\Client;
use Flarum\Api\Controller\ShowUserController;
use Flarum\Frontend\Document;
use Flarum\Http\UrlGenerator;
use Flarum\User\User as FlarumUser;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Arr;
use Psr\Http\Message\ServerRequestInterface as Request;
class User
{
/**
* @var Client
*/
protected $api;
/**
* @var UrlGenerator
*/
protected $url;
/**
* @param Client $api
* @param UrlGenerator $url
*/
public function __construct(Client $api, UrlGenerator $url)
{
$this->api = $api;
$this->url = $url;
}
public function __invoke(Document $document, Request $request)
{
$queryParams = $request->getQueryParams();
$actor = $request->getAttribute('actor');
$userId = Arr::get($queryParams, 'username');
$params = [
'id' => $userId,
];
$apiDocument = $this->getApiDocument($actor, $params);
$user = $apiDocument->data->attributes;
$document->title = $user->displayName;
$document->canonicalUrl = $this->url->to('forum')->route('user', ['username' => $user->username]);
$document->payload['apiDocument'] = $apiDocument;
return $document;
}
/**
* Get the result of an API request to show a user.
*
* @param FlarumUser $actor
* @param array $params
* @return object
* @throws ModelNotFoundException
*/
protected function getApiDocument(FlarumUser $actor, array $params)
{
$response = $this->api->send(ShowUserController::class, $actor, $params);
$statusCode = $response->getStatusCode();
if ($statusCode === 404) {
throw new ModelNotFoundException;
}
return json_decode($response->getBody());
}
}

View File

@ -28,7 +28,7 @@ return function (RouteCollection $map, RouteHandlerFactory $route) {
$map->get(
'/u/{username}[/{filter:[^/]*}]',
'user',
$route->toForum()
$route->toForum(Content\User::class)
);
$map->get(