Prevent yourself from locking yourself out of admin group (#1195)

This commit is contained in:
David Sevilla Martín 2017-07-06 15:43:01 -04:00 committed by Franz Liedke
parent cbe49d6d07
commit a07e714f97
2 changed files with 51 additions and 0 deletions

View File

@ -104,6 +104,7 @@ class CoreServiceProvider extends AbstractServiceProvider
$events = $this->app->make('events');
$events->subscribe('Flarum\Core\Listener\SelfDemotionGuard');
$events->subscribe('Flarum\Core\Listener\DiscussionMetadataUpdater');
$events->subscribe('Flarum\Core\Listener\UserMetadataUpdater');
$events->subscribe('Flarum\Core\Listener\ExtensionValidator');

View File

@ -0,0 +1,50 @@
<?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\Core\Listener;
use Flarum\Core\Exception\PermissionDeniedException;
use Flarum\Core\Group;
use Flarum\Event\UserWillBeSaved;
use Illuminate\Contracts\Events\Dispatcher;
class SelfDemotionGuard
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(UserWillBeSaved::class, [$this, 'whenUserWillBeSaved']);
}
/**
* Prevent an admin from removing their admin permission via the API.
* @param UserWillBeSaved $event
* @throws PermissionDeniedException
*/
public function whenUserWillBeSaved(UserWillBeSaved $event)
{
$actor = $event->actor;
$user = $event->user;
$groups = array_get($event->data, 'relationships.groups.data');
if (isset($groups) && $actor->id === $user->id && $actor->isAdmin()) {
$adminGroupRemoved = empty(array_filter($groups, function ($group) {
return $group['id'] == Group::ADMINISTRATOR_ID;
}));
if ($adminGroupRemoved) {
throw new PermissionDeniedException;
}
}
}
}