added remember me feature #53 (#98)

cleanup event subscriber
This commit is contained in:
Kevin Papst
2018-01-17 19:55:26 +01:00
committed by GitHub
parent 7df21f3f5a
commit 9a161b8fd9
26 changed files with 193 additions and 116 deletions

View File

@@ -0,0 +1,121 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\EventSubscriber;
use App\Event\ConfigureMainMenuEvent;
use App\Event\ConfigureAdminMenuEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Avanzu\AdminThemeBundle\Event\SidebarMenuEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* Class MenuBuilder configures the main navigation.
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class MenuBuilderSubscriber implements EventSubscriberInterface
{
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* @var AuthorizationCheckerInterface
*/
private $security;
/**
* MenuBuilderSubscriber constructor.
* @param EventDispatcherInterface $dispatcher
* @param AuthorizationCheckerInterface $security
*/
public function __construct(EventDispatcherInterface $dispatcher, AuthorizationCheckerInterface $security)
{
$this->eventDispatcher = $dispatcher;
$this->security = $security;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'theme.sidebar_setup_menu' => ['onSetupNavbar', 100],
];
}
/**
* Generate the main menu.
*
* @param SidebarMenuEvent $event
*/
public function onSetupNavbar(SidebarMenuEvent $event)
{
$request = $event->getRequest();
$isLoggedIn = $this->security->isGranted('IS_AUTHENTICATED_REMEMBERED');
$isTeamlead = $isLoggedIn && $this->security->isGranted('ROLE_TEAMLEAD');
$event->addItem(
new MenuItemModel('dashboard', 'menu.homepage', 'dashboard', [], 'fa fa-dashboard')
);
$this->eventDispatcher->dispatch(
ConfigureMainMenuEvent::CONFIGURE,
new ConfigureMainMenuEvent(
$request,
$event
)
);
if ($isTeamlead) {
$admin = new MenuItemModel('admin', 'menu.admin', '', [], 'fa fa-wrench');
$event->addItem($admin);
$this->eventDispatcher->dispatch(
ConfigureAdminMenuEvent::CONFIGURE,
new ConfigureAdminMenuEvent(
$request,
$event
)
);
}
$event->addItem(
new MenuItemModel('logout', 'menu.logout', 'security_logout', [], 'fa fa-sign-out')
);
$this->activateByRoute(
$event->getRequest()->get('_route'),
$event->getItems()
);
}
/**
* @param string $route
* @param MenuItemModel[] $items
*/
protected function activateByRoute($route, $items)
{
foreach ($items as $item) {
if ($item->hasChildren()) {
$this->activateByRoute($route, $item->getChildren());
} else {
if ($item->getRoute() == $route) {
$item->setIsActive(true);
}
}
}
}
}

View File

@@ -0,0 +1,107 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\EventSubscriber;
use App\Event\ConfigureMainMenuEvent;
use App\Event\ConfigureAdminMenuEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Avanzu\AdminThemeBundle\Model\MenuItemModel;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* Menu event subscriber for timesheet, customer, projects, activities.
* This is a sample implementation for developer who want to add new navigation entries in their bundles.
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class MenuSubscriber implements EventSubscriberInterface
{
/**
* @var AuthorizationCheckerInterface
*/
private $security;
/**
* MenuSubscriber constructor.
* @param AuthorizationCheckerInterface $security
*/
public function __construct(AuthorizationCheckerInterface $security)
{
$this->security = $security;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
ConfigureMainMenuEvent::CONFIGURE => ['onMainMenuConfigure', 100],
ConfigureAdminMenuEvent::CONFIGURE => ['onAdminMenuConfigure', 100],
];
}
/**
* @param \App\Event\ConfigureMainMenuEvent $event
*/
public function onMainMenuConfigure(ConfigureMainMenuEvent $event)
{
$auth = $this->security;
$isLoggedIn = $auth->isGranted('IS_AUTHENTICATED_REMEMBERED');
$isUser = $isLoggedIn && $auth->isGranted('ROLE_USER');
if (!$isLoggedIn || !$isUser) {
return;
}
$menu = $event->getMenu();
$menu->addItem(
new MenuItemModel('timesheet', 'menu.timesheet', 'timesheet', [], 'fa fa-clock-o')
);
}
/**
* @param \App\Event\ConfigureAdminMenuEvent $event
*/
public function onAdminMenuConfigure(ConfigureAdminMenuEvent $event)
{
$menu = $event->getAdminMenu();
$auth = $this->security;
if (!$auth->isGranted('IS_AUTHENTICATED_REMEMBERED') || !$auth->isGranted('ROLE_TEAMLEAD')) {
return;
}
$menu->addChild(
new MenuItemModel('timesheet_admin', 'menu.admin_timesheet', 'admin_timesheet', [], 'fa fa-clock-o')
);
if (!$auth->isGranted('ROLE_ADMIN')) {
return;
}
if ($auth->isGranted('ROLE_SUPER_ADMIN')) {
$menu->addChild(
new MenuItemModel('user_admin', 'menu.admin_user', 'admin_user', [], 'fa fa-user')
);
}
$menu->addChild(
new MenuItemModel('customer_admin', 'menu.admin_customer', 'admin_customer', [], 'fa fa-users')
)->addChild(
new MenuItemModel('project_admin', 'menu.admin_project', 'admin_project', [], 'fa fa-book')
)->addChild(
new MenuItemModel('activity_admin', 'menu.admin_activity', 'admin_activity', [], 'fa fa-tasks')
);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*
* This file is part of the Kimai package.
*
* (c) Kevin Papst <kevin@kevinpapst.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\EventSubscriber;
use App\Entity\User;
use Avanzu\AdminThemeBundle\Event\ShowUserEvent;
use Avanzu\AdminThemeBundle\Model\UserModel;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Class NavbarShowUserSubscriber
*
* @author Kevin Papst <kevin@kevinpapst.de>
*/
class NavbarShowUserSubscriber implements EventSubscriberInterface
{
/**
* @var TokenStorageInterface
*/
protected $storage;
/**
* NavbarShowUserListener constructor.
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->storage = $tokenStorage;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
'theme.navbar_user' => ['onShowUser', 100],
'theme.sidebar_user' => ['onShowUser', 100],
];
}
/**
* @param ShowUserEvent $event
*/
public function onShowUser(ShowUserEvent $event)
{
/* @var $myUser User */
$myUser = $this->storage->getToken()->getUser();
$user = new UserModel();
$user->setName($myUser->getAlias() ?: $myUser->getUsername())
->setUsername($myUser->getUsername())
->setIsOnline(true)
->setTitle($myUser->getTitle())
->setAvatar($myUser->getAvatar())
->setMemberSince(new \DateTime());
$event->setUser($user);
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\EventSubscriber;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* When visiting the homepage, this listener redirects the user to the most
* appropriate localized version according to the browser settings.
*
* See http://symfony.com/doc/current/components/http_kernel/introduction.html#the-kernel-request-event
*
* @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
*/
class RedirectToLocaleSubscriber
{
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* List of supported locales.
*
* @var string[]
*/
private $locales = [];
/**
* @var string
*/
private $defaultLocale = '';
/**
* Constructor.
*
* @param UrlGeneratorInterface $urlGenerator
* @param string $locales Supported locales separated by '|'
* @param string|null $defaultLocale
*/
public function __construct(UrlGeneratorInterface $urlGenerator, $locales, $defaultLocale = null)
{
$this->urlGenerator = $urlGenerator;
$this->locales = explode('|', trim($locales));
if (empty($this->locales)) {
throw new \UnexpectedValueException('The list of supported locales must not be empty.');
}
$this->defaultLocale = $defaultLocale ?: $this->locales[0];
if (!in_array($this->defaultLocale, $this->locales)) {
throw new \UnexpectedValueException(
sprintf('The default locale ("%s") must be one of "%s".', $this->defaultLocale, $locales)
);
}
// Add the default locale at the first position of the array,
// because Symfony\HttpFoundation\Request::getPreferredLanguage
// returns the first element when no an appropriate language is found
array_unshift($this->locales, $this->defaultLocale);
$this->locales = array_unique($this->locales);
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// Ignore sub-requests and all URLs but the homepage
if ('/' !== $request->getPathInfo()) {
return;
}
// Ignore requests from referrers with the same HTTP host in order to prevent
// changing language for users who possibly already selected it for this application.
if (0 === stripos($request->headers->get('referer'), $request->getSchemeAndHttpHost())) {
return;
}
$preferredLanguage = $request->getPreferredLanguage($this->locales);
$response = new RedirectResponse($this->urlGenerator->generate('homepage', ['_locale' => $preferredLanguage]));
$event->setResponse($response);
}
}