added login destination

This commit is contained in:
Bachir Soussi Chiadmi
2018-01-06 18:42:28 +01:00
parent 5ec2f4311c
commit 057a3a3171
22 changed files with 1840 additions and 0 deletions
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
@@ -0,0 +1,31 @@
The Login Destination module provides a way to customize the destination that a
user is redirected to after logging in, registering to the site, using a
one-time login link or logging out.
The configuration consists of specifying so called login destination rules that
are evaluated when the login or logout takes place. Those rules are evaluated
against certain conditions and the user is taken to the destination specified
by the first matching rule. If the destination is empty, no redirect is
performed aka user is taken to the default destination. You can define pages
from which a user logs in/out to be a matching criterion. You can also select
certain user roles that are matched against those of a user. Note that only one
role has to match in order for the redirect to take place. If no roles are
selected the redirect is performed regardless of user roles.
The destination you specify can be an internal page or an external URL.
Remember to precede the url with http://. You can also use the <front> tag to
redirect to the front page. In case of
login/register form the page from which the user entered the form is treated as
the current page. Note that if you provide your own login/logout links you have
to add the 'current' GET parameter to them so Login Destination knows where
your users come from.
It also possible to set some advanced parameters on the setting page. Every
time in Drupal you can specify the 'destination' GET parameter in url to
redirect the user to a custom page. If you check the option
'Preserve the destination parameter' Login Destination will give priority to
this parameter over its own module settings. However with this option enabled
the redirect from the login block will not work. In some rare cases you can
also redirect the user just after using the one-time login link, before given
the possibility to change their password. Do this by checking the
'Redirect immediately after using one-time login link' option.
@@ -0,0 +1,5 @@
{
"name": "drupal/login_destination",
"description": "The Login Destination module add possibility customize the destination that the user is redirected to after login.",
"type": "drupal-module"
}
@@ -0,0 +1,2 @@
preserve_destination: FALSE
immediate_redirect: FALSE
@@ -0,0 +1,34 @@
login_destination.destination.*:
type: config_entity
label: 'Login destination configuration entity'
mapping:
name:
type: string
label: 'Login destination rule machine name'
label:
type: string
label: 'Short description of the rule'
triggers:
type: array
label: 'Triggers'
destination_path:
type: string
label: 'Destination'
pages_type:
type: integer
label: 'Pages type'
pages:
type: string
label: 'Pages'
roles:
type: array
label: 'Roles'
weight:
type: integer
label: 'Weight'
enabled:
type: boolean
label: 'Enabled'
uuid:
type: string
label: 'UUID'
@@ -0,0 +1,10 @@
login_destination.settings:
type: config_object
label: 'Login destination settings'
mapping:
preserve_destination:
type: boolean
label: 'Preserve the destination parameter'
immediate_redirect:
type: boolean
label: 'Redirect immediately after using one-time login link'
@@ -0,0 +1,12 @@
name: Login Destination
type: module
description: Add possibility customize the destination that the user is redirected to after login.
package: User
# core: 8.x
configure: login_destination.settings
# Information added by Drupal.org packaging script on 2018-01-01
version: '8.x-1.x-dev'
core: '8.x'
project: 'login_destination'
datestamp: 1514805488
@@ -0,0 +1,5 @@
login_destination.add:
route_name: login_destination.add
title: 'Add Login Destination'
appears_on:
- login_destination.list
@@ -0,0 +1,6 @@
login_destination.list:
title: 'Login destinations'
parent: user.admin_index
description: 'Customize the destination that the user is redirected to after login.'
weight: -5
route_name: login_destination.list
@@ -0,0 +1,9 @@
login_destination.list:
title: 'Login destinations'
route_name: login_destination.list
base_route: login_destination.list
login_destination.settings:
title: 'Settings'
route_name: login_destination.settings
base_route: login_destination.list
@@ -0,0 +1,148 @@
<?php
/**
* @file
* Control where users are directed to, once they login, register or logout.
*/
use \Drupal\Core\Routing\RouteMatchInterface;
use \Drupal\Core\Url;
use \Drupal\Core\Session\AccountInterface;
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\user\UserInterface;
/**
* Implements hook_help().
*/
function login_destination_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.login_destination':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Login Destination module allows you to customize the destination that the user is redirected to after logging in, registering to the site, using a one-time login link or logging out. The destination can be an internal page or an external URL. You may specify certain conditions like pages or user roles and make the destination depend upon them.') . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating login destinations') . '</dt>';
$output .= '<dd>' . t('Users with sufficient permissions can create login destination through the !link. The page listing the login destinations provides an interface to add, edit and delete them', [
'!link' => (string) \Drupal::l('Login destination page', Url::fromRoute('login_destination.list')),
]) . '</dd>';
$output .= '<dt>' . t('Assigning destinations') . '</dt>';
$output .= '<dd>' . t('You can add login destinations and specify the page where the user will be redirected when it logs in or logs out. You can also configure specific pages where the destination can work or not and select for what user roles the login destination applies') . '</dd>';
$output .= '</dl>';
return $output;
case 'login_destination.list':
$output = '<p>' . t('Login destination rules are evaluated each time a user logs in, registers to the site, uses a one-time login link or logs out. Each rule consists of the destination, path conditions and user roles conditions. First matching rule gets executed.') . '</p>';
return $output;
}
}
/**
* Implements hook_user_login().
*/
function login_destination_user_login(AccountInterface $account) {
if (isset($account->user_is_new) && $account->user_is_new) {
// User is just registered.
login_destination_perform_redirect('registration', $account);
}
elseif (\Drupal::service('current_route_match')->getRouteName() === 'user.reset.login') {
// User is used a one-time login link.
login_destination_perform_redirect('one-time-login', $account);
}
else {
login_destination_perform_redirect('login', $account);
}
}
/**
* Implements hook_user_logout().
*/
function login_destination_user_logout(AccountInterface $account) {
login_destination_perform_redirect('logout', $account);
}
/**
* Implements hook_toolbar_alter().
*/
function login_destination_toolbar_alter(&$items) {
if (empty($items['user']['tray']['user_links'])) {
return;
}
// Disable cache for user links in toolbar, to be able set current param.
$items['user']['tray']['user_links']['#cache']['context'] = [];
$items['user']['tray']['user_links']['#cache']['max-age'] = 0;
if (\Drupal::currentUser()->isAnonymous()) {
$url_login = Url::fromRoute('user.login');
// Change route name, since route "user.page" always redirects to "user.login".
$items['user']['tray']['user_links']['#links']['login']['url'] = $url_login;
$url = &$items['user']['tray']['user_links']['#links']['login']['url'];
}
else {
$url = &$items['user']['tray']['user_links']['#links']['logout']['url'];
}
// Get current path.
$current = \Drupal::service('path.current')->getPath();
// Add current param to be able to evaluate previous page.
$url->setOptions(['query' => ['current' => $current]]);
}
/**
* Implements hook_link_alter().
*/
function login_destination_link_alter(&$variables) {
$routes = [
'user.login',
'user.logout'
];
/* @var Drupal\Core\Url $url */
$url = $variables['url'];
if ($url->isExternal()) {
return;
}
if ($url->isRouted() && !in_array($url->getRouteName(), $routes)) {
return;
}
// Get current path.
$current = \Drupal::service('path.current')->getPath();
$variables['options']['query']['current'] = $current;
}
/**
* Implements hook_entity_presave().
*/
function login_destination_entity_presave(EntityInterface $entity) {
// Verify that entity is a user entity, and this is new entity.
if (!$entity instanceof UserInterface || !$entity->isNew()) {
return;
}
// Save parameter to user entity, which will allow us understand that user
// is just created. Do not need to save parameter, when needs verification
// by administrator.
$needs_verification = \Drupal::config('user.settings')->get('verify_mail');
if ($needs_verification || !$entity->isActive()) {
return;
}
$entity->user_is_new = TRUE;
}
/**
* Evaluate rules and perform redirect.
*
* This function is intended to be used by external modules.
*
* @param string $trigger
* Action of login destination rule.
* @param \Drupal\Core\Session\AccountInterface $account
* User Account.
*/
function login_destination_perform_redirect($trigger, AccountInterface $account) {
/* @var Drupal\login_destination\LoginDestinationManager $service */
$service = \Drupal::service('login_destination.manager');
$destination = $service->findDestination($trigger, $account);
if ($destination) {
$service->prepareDestination($destination);
}
}
@@ -0,0 +1,2 @@
administer login destination settings:
title: 'Administer Login Destination settings'
@@ -0,0 +1,40 @@
login_destination.settings:
path: '/admin/config/people/login-destination/settings'
defaults:
_form: '\Drupal\login_destination\Form\LoginDestinationSettingsForm'
_title: 'Login destination Settings'
requirements:
_permission: 'administer login destination settings'
login_destination.list:
path: '/admin/config/people/login-destination'
defaults:
_content: '\Drupal\Core\Entity\Controller\EntityListController::listing'
_entity_list: 'login_destination'
_title: 'Login destinations'
requirements:
_permission: 'administer login destination settings'
login_destination.add:
path: '/admin/config/people/login-destination/add'
defaults:
_entity_form: login_destination.add
_title: 'Add login destination rule'
requirements:
_permission: 'administer login destination settings'
entity.login_destination.edit_form:
path: '/admin/config/people/login-destination/{login_destination}/edit'
defaults:
_entity_form: login_destination.edit
_title: 'Edit login destination rule'
requirements:
_permission: 'administer login destination settings'
entity.login_destination.delete_form:
path: '/admin/config/people/login-destination/{login_destination}/delete'
defaults:
_entity_form: login_destination.delete
_title: 'Delete login destination rule'
requirements:
_permission: 'administer login destination settings'
@@ -0,0 +1,4 @@
services:
login_destination.manager:
class: Drupal\login_destination\LoginDestinationManager
arguments: ['@entity_type.manager', '@path.alias_manager', '@path.matcher', '@path.current', '@config.factory', '@request_stack']
@@ -0,0 +1,92 @@
<?php
namespace Drupal\login_destination\Controller;
use Drupal\Core\Config\Entity\DraggableListBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\login_destination\Entity\LoginDestination;
/**
* Provides a listing of Login Destinations rules.
*/
class LoginDestinationListBuilder extends DraggableListBuilder {
/**
* The key to use for the form element containing the entities.
*
* @var string
*/
protected $entitiesKey = 'login_destination';
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'login_destination_overview';
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header = [
'label' => $this->t('Label'),
'destination' => $this->t('Destination'),
'triggers' => $this->t('Triggers'),
'pages' => $this->t('Pages'),
'roles' => $this->t('Roles'),
'enabled' => $this->t('Enabled'),
];
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
/** @var LoginDestination $entity */
$row['label'] = $entity->getLabel();
if ($entity->isDestinationCurrent()) {
$row['destination'] = [
'#markup' => $entity->viewDestination(),
];
}
else {
$row['destination'] = [
'#type' => 'link',
'#title' => $entity->viewDestination(),
'#url' => Url::fromUri($entity->getDestination()),
];
}
$row['triggers'] = [
'#markup' => $entity->viewTriggers(),
];
$row['pages'] = [
'#markup' => $entity->viewPages(),
];
$row['roles'] = [
'#markup' => $entity->viewRoles(),
];
$row['enabled'] = [
'#type' => 'checkbox',
'#default_value' => $entity->isEnabled(),
];
return $row + parent::buildRow($entity);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
foreach ($form_state->getValue($this->entitiesKey) as $id => $value) {
// Save entity only when its weight was changed.
$this->entities[$id]->set('enabled', $value['enabled']);
$this->entities[$id]->save();
}
}
}
@@ -0,0 +1,349 @@
<?php
namespace Drupal\login_destination\Entity;
use \Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Url;
use Drupal\login_destination\LoginDestinationInterface;
/**
* Defines a login destination configuration entity.
*
* @ConfigEntityType(
* id = "login_destination",
* label = @Translation("Login Destination"),
* handlers = {
* "form" = {
* "add" = "Drupal\login_destination\Form\LoginDestinationRuleForm",
* "edit" = "Drupal\login_destination\Form\LoginDestinationRuleForm",
* "delete" = "Drupal\login_destination\Form\LoginDestinationDeleteRuleForm",
* },
* "list_builder" = "Drupal\login_destination\Controller\LoginDestinationListBuilder",
* },
* admin_permission = "administer login destination settings",
* config_prefix = "destination",
* entity_keys = {
* "id" = "name",
* "uuid" = "uuid",
* "weight" = "weight",
* },
* links = {
* "edit-form" = "/admin/config/people/login-destination/{login_destination}/edit",
* "delete-form" = "/admin/config/people/login-destination/{login_destination}/delete",
* }
* )
*/
class LoginDestination extends ConfigEntityBase implements LoginDestinationInterface {
/**
* Redirect from all pages except listed.
*/
const REDIRECT_NOT_LISTED = 0;
/**
* Redirect from only the listed pages.
*/
const REDIRECT_LISTED = 1;
/**
* Login trigger.
*/
const TRIGGER_LOGIN = 'login';
/**
* Registration trigger.
*/
const TRIGGER_REGISTRATION = 'registration';
/**
* One-time login trigger.
*/
const TRIGGER_ONE_TIME_LOGIN = 'one-time-login';
/**
* Logout trigger.
*/
const TRIGGER_LOGOUT = 'logout';
/**
* The login destination machine name.
*
* @var string
*/
public $name;
/**
* The login destination short description.
*
* @var string
*/
public $label;
/**
* The login destination triggers.
*
* @var array
*/
public $triggers = [];
/**
* The login destination roles.
*
* @var array
*/
public $roles = [];
/**
* The login destination pages type.
*
* @var int
*/
public $pages_type = self::REDIRECT_NOT_LISTED;
/**
* The login destination pages.
*
* @var string
*/
public $pages = '';
/**
* Status.
*
* @var bool
*/
public $enabled = TRUE;
/**
* The login destination destination.
*
* @var string
*/
public $destination_path;
/**
* The login destination weight.
*
* @var int
*/
public $weight = 0;
/**
* {@inheritdoc}
*/
public function id() {
return $this->name;
}
/**
* @inheritdoc
*/
public function getLabel() {
return $this->label;
}
/**
* @inheritdoc
*/
public function getMachineName() {
return $this->name;
}
/**
* @inheritdoc
*/
public function getTriggers() {
return $this->triggers;
}
/**
* @inheritdoc
*/
public function getDestination() {
return $this->destination_path;
}
/**
* @inheritdoc
*/
public function getPagesType() {
return $this->pages_type;
}
/**
* @inheritdoc
*/
public function getPages() {
return $this->pages;
}
/**
* @inheritdoc
*/
public function getRoles() {
return $this->roles;
}
/**
* @inheritdoc
*/
public function getWeight() {
return $this->weight;
}
/**
* {@inheritdoc}
*/
public function viewTriggers() {
$items = [];
foreach ($this->triggers as $trigger) {
if (empty($trigger)) {
continue;
}
switch ($trigger) {
case LoginDestination::TRIGGER_REGISTRATION:
$items[] = t('Registration');
break;
case LoginDestination::TRIGGER_LOGIN:
$items[] = t('Login');
break;
case LoginDestination::TRIGGER_ONE_TIME_LOGIN:
$items[] = t('One-time login link');
break;
case LoginDestination::TRIGGER_LOGOUT:
$items[] = t('Logout');
break;
}
}
return $this->renderItemList($items, t('All triggers'));
}
/**
* {@inheritdoc}
*/
public function viewRoles() {
$roles = $this->getAllSystemRoles();
$items = array_values(array_intersect_key($roles, $this->roles));
return $this->renderItemList($items, t('All roles'));
}
/**
* {@inheritdoc}
*/
public function viewPages() {
$type = $this->pages_type;
$pages = trim($this->pages);
if (empty($pages)) {
if ($type == self::REDIRECT_NOT_LISTED) {
return t('All pages');
}
return t('No pages');
}
$pages = explode("\n", preg_replace('/\r/', '', $this->pages));
$items = [];
foreach ($pages as $page) {
$items[] = $type == self::REDIRECT_NOT_LISTED ? '~ ' . $page : $page;
}
return $this->renderItemList($items, t('Empty'));
}
/**
* {@inheritdoc}
*/
public function viewDestination() {
if ($this->isDestinationCurrent()) {
$scheme = 'internal';
}
else {
$url = Url::fromUri($this->destination_path);
$label = $this->destination_path;
if ($url->isExternal()) {
return Html::escape($label);
}
$scheme = parse_url($this->destination_path, PHP_URL_SCHEME);
}
if ($scheme === 'internal') {
return t('Internal destination');
}
if ($scheme === 'entity') {
$params = $url->getRouteParameters();
$entity = \Drupal::entityTypeManager()
->getStorage('node')
->load(reset($params));
return $entity->get('title')->value;
}
return Html::escape($this->destination_path);
}
/**
* Check is destination path links to a current page or not.
*
* @return bool
* TRUE or FALSE.
*/
public function isDestinationCurrent() {
return Unicode::strpos($this->destination_path, '<current>') !== FALSE;
}
/**
* Render item list.
*
* @param array $array
* List of items.
* @param string $empty_message
* Default empty message.
*
* @return string|\Drupal\Core\Render\Markup
* List of items or empty message.
*/
protected function renderItemList(array $array, $empty_message) {
$items = [];
foreach ($array as $value) {
if (!empty($value)) {
$items[] = Html::escape($value);
}
}
if (count($items) === 0) {
return $empty_message;
}
$item_list = [
'#theme' => 'item_list',
'#items' => $items,
'#list_type' => 'ul',
];
return \Drupal::service('renderer')->render($item_list);
}
/**
* Get all roles in the system.
*
* @return array
* List of system roles.
*/
public function getAllSystemRoles() {
$role_options = [];
foreach (user_roles(TRUE) as $role) {
$role_options[$role->id()] = $role->label();
}
return $role_options;
}
/**
* {@inheritdoc}
*/
public function isEnabled() {
return $this->enabled;
}
}
@@ -0,0 +1,52 @@
<?php
namespace Drupal\login_destination\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Provides a deletion confirmation form for login destination.
*/
class LoginDestinationDeleteRuleForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
/** @var $login_destination \Drupal\login_destination\Entity\LoginDestination */
$login_destination = $this->entity;
return $this->t('Are you sure you want to delete the login destination "@destination"?', [
'@destination' => $login_destination->getLabel(),
]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('login_destination.list');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var $login_destination \Drupal\login_destination\Entity\LoginDestination */
$login_destination = $this->entity;
$login_destination->delete();
drupal_set_message($this->t('The login destination %destination has been deleted.', [
'%destination' => $login_destination->getLabel(),
]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,301 @@
<?php
namespace Drupal\login_destination\Form;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\login_destination\Entity\LoginDestination;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base for controller for login destination add/edit forms.
*/
class LoginDestinationRuleForm extends EntityForm {
/**
* The login destination entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $loginDestinationStorage;
/**
* Constructs a base class for login destination add and edit forms.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $login_destination_storage
* The login destination entity storage.
*/
public function __construct(EntityStorageInterface $login_destination_storage) {
$this->loginDestinationStorage = $login_destination_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container->get('entity_type.manager')
->getStorage('login_destination'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
/** @var $login_destination LoginDestination */
$login_destination = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#default_value' => $login_destination->getLabel(),
'#description' => $this->t('A short description of this login destination rule.'),
'#required' => TRUE,
];
$form['name'] = [
'#type' => 'machine_name',
'#machine_name' => [
'exists' => [$this->loginDestinationStorage, 'load'],
],
'#disabled' => !$login_destination->isNew(),
'#default_value' => $login_destination->id(),
'#required' => TRUE,
'#description' => $this->t('A unique machine-readable name for this login destination rule.'),
];
$form['triggers'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Redirect upon triggers'),
'#options' => [
LoginDestination::TRIGGER_REGISTRATION => $this->t('Registration'),
LoginDestination::TRIGGER_LOGIN => $this->t('Login'),
LoginDestination::TRIGGER_ONE_TIME_LOGIN => $this->t('One-time login link'),
LoginDestination::TRIGGER_LOGOUT => $this->t('Logout'),
],
'#required' => TRUE,
'#default_value' => !empty($login_destination->triggers) ? $login_destination->getTriggers() : [],
'#description' => $this->t('Redirect only upon selected trigger(s).'),
];
$form['destination_path'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#placeholder' => '',
'#attributes' => [
'data-autocomplete-first-character-blacklist' => '/#?',
],
'#title' => $this->t('Redirect destination'),
'#default_value' => $this->getUriAsDisplayableString($login_destination->getDestination()),
'#element_validate' => [[$this, 'validateUriElement']],
'#maxlength' => 2048,
'#required' => TRUE,
'#process_default_value' => FALSE,
'#description' => $this->t('Start typing the title of a piece of content to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page. Enter %current to link to a current page.', [
'%front' => '<front>',
'%current' => '<current>',
'%add-node' => '/node/add',
'%url' => 'http://example.com',
]),
];
$form['pages_type'] = [
'#type' => 'radios',
'#title' => $this->t('Redirect from specific pages'),
'#default_value' => $login_destination->getPagesType(),
'#options' => [
$login_destination::REDIRECT_NOT_LISTED => $this->t('All pages except those listed'),
$login_destination::REDIRECT_LISTED => $this->t('Only the listed pages'),
],
];
$form['pages'] = [
'#type' => 'textarea',
'#default_value' => $login_destination->getPages(),
'#description' => $this->t('Specify pages by using their paths. Enter one path per line. The \'*\' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page. %login is the login form. %register is the registration form. %reset is the one-time login (e-mail validation).', [
'%blog' => 'blog',
'%blog-wildcard' => '/blog/*',
'%front' => '<front>',
'%login' => '/user',
'%register' => '/user/register',
'%reset' => '/user/*/edit',
]),
];
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Redirect users with roles'),
'#options' => $login_destination->getAllSystemRoles(),
'#default_value' => $login_destination->getRoles(),
'#description' => $this->t('Redirect only the selected role(s). If you select no roles, all users will be redirected.'),
];
$form['uuid'] = [
'#type' => 'value',
'#value' => $login_destination->get('uuid'),
];
return parent::form($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// Get selected roles.
$roles = array_filter($form_state->getValue('roles'));
// Set filtered values.
$form_state->setValue('roles', $roles);
$form_state->setValue('triggers', array_filter($form_state->getValue('triggers')));
// Get entered by user destination path.
$destination = $form_state->getValue('destination_path');
// @todo verify that selected role has access to entered path.
// @todo verify entered paths to specific pages.
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
/* @var $login_destination \Drupal\login_destination\Entity\LoginDestination */
$login_destination = $this->entity;
if ($login_destination->save()) {
drupal_set_message($this->t('Saved the %label login destination.', [
'%label' => $login_destination->getLabel(),
]));
}
else {
drupal_set_message($this->t('The %label login destination was not saved.', [
'%label' => $login_destination->getLabel(),
]));
}
$form_state->setRedirect('login_destination.list');
}
/**
* Form element validation handler for the 'uri' element.
*
* Disallows saving inaccessible or untrusted URLs.
*
* @see LinkWidget::validateUriElement()
*/
public function validateUriElement($element, FormStateInterface $form_state, $form) {
$uri = $this->getUserEnteredStringAsUri($element['#value']);
$form_state->setValueForElement($element, $uri);
// If getUserEnteredStringAsUri() mapped the entered value to a 'internal:'
// URI , ensure the raw value begins with '/', '?' or '#'.
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], [
'/',
'?',
'#',
], TRUE) && substr($element['#value'], 0, 7) !== '<front>'
&& substr($element['#value'], 0, 9) !== '<current>'
) {
$form_state->setError($element, t('Manually entered paths should start with /, ? or #.'));
return;
}
}
/**
* Gets the URI without the 'internal:' or 'entity:' scheme.
*
* The following two forms of URIs are transformed:
* - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
* - 'internal:' URIs: the scheme is stripped.
*
* This method is the inverse of ::getUserEnteredStringAsUri().
*
* @param string $uri
* The URI to get the displayable string for.
*
* @return string
*
* @see LinkWidget::getUriAsDisplayableString()
*/
protected function getUriAsDisplayableString($uri) {
$scheme = parse_url($uri, PHP_URL_SCHEME);
// By default, the displayable string is the URI.
$displayable_string = $uri;
// A different displayable string may be chosen in case of the 'internal:'
// or 'entity:' built-in schemes.
if ($scheme === 'internal') {
$uri_reference = explode(':', $uri, 2)[1];
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
$path = parse_url($uri, PHP_URL_PATH);
if ($path === '/') {
$uri_reference = '<front>' . substr($uri_reference, 1);
}
$displayable_string = $uri_reference;
}
elseif ($scheme === 'entity') {
list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2);
// Show the 'entity:' URI as the entity autocomplete would.
$entity_manager = \Drupal::entityTypeManager();
if ($entity_manager->getDefinition($entity_type, FALSE) && $entity = \Drupal::entityTypeManager()
->getStorage($entity_type)
->load($entity_id)
) {
$displayable_string = EntityAutocomplete::getEntityLabels(array($entity));
}
}
return $displayable_string;
}
/**
* Gets the user-entered string as a URI.
*
* The following two forms of input are mapped to URIs:
* - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs;
* - strings without a detectable scheme: to 'internal:' URIs.
*
* This method is the inverse of ::getUriAsDisplayableString().
*
* @param string $string
* The user-entered string.
*
* @return string
* The URI, if a non-empty $uri was passed.
*
* @see LinkWidget::getUserEnteredStringAsUri()
*/
protected function getUserEnteredStringAsUri($string) {
// By default, assume the entered string is an URI.
$uri = $string;
// Detect entity autocomplete string, map to 'entity:' URI.
$entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string);
if ($entity_id !== NULL) {
// @todo Support entity types other than 'node'. Will be fixed in
// https://www.drupal.org/node/2423093.
$uri = 'entity:node/' . $entity_id;
}
// Detect a schemeless string, map to 'internal:' URI.
elseif (!empty($string) && parse_url($string, PHP_URL_SCHEME) === NULL) {
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
// - '<front>' -> '/'
// - '<front>#foo' -> '/#foo'
if (strpos($string, '<front>') === 0) {
$string = '/' . substr($string, strlen('<front>'));
}
$uri = 'internal:' . $string;
}
return $uri;
}
}
@@ -0,0 +1,60 @@
<?php
namespace Drupal\login_destination\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides form for managing module settings.
*/
class LoginDestinationSettingsForm extends ConfigFormBase {
/**
* @inheritdoc
*/
public function getFormId() {
return 'login_destination_settings';
}
/**
* @inheritdoc
*/
protected function getEditableConfigNames() {
return ['login_destination.settings'];
}
/**
* @inheritdoc
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('login_destination.settings');
$form['settings']['preserve_destination'] = [
'#type' => 'checkbox',
'#default_value' => $config->get('preserve_destination'),
'#title' => t('Preserve the destination parameter'),
'#description' => t("The 'destination' GET parameter will have priority over the settings of this module. With this setting enabled, redirect from the user login block will not work."),
];
$form['settings']['immediate_redirect'] = [
'#type' => 'checkbox',
'#default_value' => $config->get('immediate_redirect'),
'#title' => t('Redirect immediately after using one-time login link'),
'#description' => t('User will be redirected before given the possibility to change their password.'),
];
return parent::buildForm($form, $form_state);
}
/**
* @inheritdoc
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('login_destination.settings');
$config->set('preserve_destination', $form_state->getValue('preserve_destination'));
$config->set('immediate_redirect', $form_state->getValue('immediate_redirect'));
$config->save();
parent::submitForm($form, $form_state);
}
}
@@ -0,0 +1,117 @@
<?php
namespace Drupal\login_destination;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Provides an interface providing additional methods.
*/
interface LoginDestinationInterface extends ConfigEntityInterface {
/**
* Get short description of the login destination rule.
*
* @return string
* Login destination rule description.
*/
public function getLabel();
/**
* Get machine name for destination rule.
*
* @return string
* Login destination rule machine name.
*/
public function getMachineName();
/**
* Get login destination.
*
* @return string
* Destination path.
*/
public function getDestination();
/**
* Get Login Destination Rule triggers.
*
* @return array
* List of triggers.
*/
public function getTriggers();
/**
* Get Type of pages:
* - 0: all pages except listed pages.
* - 1: only listed pages.
*
* @return int
* Type of pages.
*/
public function getPagesType();
/**
* Get pages.
*
* @return array
* List of pages.
*/
public function getPages();
/**
* Get Login destination roles.
*
* @return array
* List of roles.
*/
public function getRoles();
/**
* Get Login destination rule weight.
*
* @return int
* Weight value.
*/
public function getWeight();
/**
* Prepare list of triggers for displaying.
*
* @return string
* HTML view for list of triggers.
*/
public function viewTriggers();
/**
* Prepare list of roles for displaying.
*
* @return mixed
* HTML view for list of roles.
*/
public function viewRoles();
/**
* Prepare list of pages for displaying.
*
* @return string
* HTML view for list of paths.
*/
public function viewPages();
/**
* Prepare redirect destination for displaying.
*
* @return string
* Destination path.
*/
public function viewDestination();
/**
* Return status.
*
* @return bool
*/
public function isEnabled();
}
@@ -0,0 +1,189 @@
<?php
namespace Drupal\login_destination;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\login_destination\Entity\LoginDestination;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Defines a login destination manager service.
*/
class LoginDestinationManager implements LoginDestinationManagerInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The alias manager that caches alias lookups based on the request.
*
* @var \Drupal\Core\Path\AliasManagerInterface
*/
protected $aliasManager;
/**
* The path matcher.
*
* @var \Drupal\Core\Path\PathMatcherInterface
*/
protected $pathMatcher;
/**
* The current path.
*
* @var \Drupal\Core\Path\CurrentPathStack
*/
protected $currentPath;
/**
* The configuration factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
* The alias manager.
* @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
* The path matcher.
* @param \Drupal\Core\Path\CurrentPathStack $current_path
* The current path.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, AliasManagerInterface $alias_manager, PathMatcherInterface $path_matcher, CurrentPathStack $current_path, ConfigFactoryInterface $config_factory, RequestStack $request_stack) {
$this->entityTypeManager = $entity_type_manager;
$this->aliasManager = $alias_manager;
$this->pathMatcher = $path_matcher;
$this->currentPath = $current_path;
$this->configFactory = $config_factory;
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public function findDestination($trigger, AccountInterface $account) {
$destinations = $this->entityTypeManager->getStorage('login_destination')
->loadMultiple();
uasort($destinations, '\Drupal\login_destination\Entity\LoginDestination::sort');
$path = $this->getCurrentPath();
$path_alias = Unicode::strtolower($this->aliasManager->getAliasByPath($path));
// Get user roles.
$user_roles = $account->getRoles();
/** @var LoginDestination $destination */
foreach ($destinations as $destination) {
if (!$destination->isEnabled()) {
continue;
}
// Determine if the trigger matches that of the login destination rule.
$destination_triggers = $destination->getTriggers();
if (!in_array($trigger, $destination_triggers)) {
continue;
}
$destination_roles = $destination->getRoles();
$role_match = array_intersect($user_roles, $destination_roles);
// Ensure the user logging in has a role allowed by the login destination rule.
// Or Login Destination Rule does not have any selected roles.
if (empty($role_match) && !empty($destination_roles)) {
continue;
}
$pages = Unicode::strtolower($destination->getPages());
if (!empty($pages)) {
$type = $destination->getPagesType();
$page_match = $this->pathMatcher->matchPath($path_alias, $pages) || $this->pathMatcher->matchPath($path, $pages);
// Make sure the page matches(or does not match if the rule specifies that).
if (($page_match && $type == $destination::REDIRECT_LISTED) || (!$page_match && $type == $destination::REDIRECT_NOT_LISTED)) {
return $destination;
}
continue;
}
return $destination;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function prepareDestination(LoginDestination $destination) {
// Get config with settings.
$config = $this->configFactory->get('login_destination.settings');
if ($config->get('preserve_destination')) {
// Get current destination value.
$drupal_destination = $this->requestStack->getCurrentRequest()->query->get('destination');
if (UrlHelper::isExternal($drupal_destination)) {
$drupal_destination = NULL;
}
// Determine if a destination exist in the URL.
if (!empty($drupal_destination)) {
return;
}
}
// Prepare destination path.
$path = $destination->getDestination();
// Check if rules refers to the current page.
if ($destination->isDestinationCurrent()) {
$request = $this->requestStack->getCurrentRequest();
$query = $request->get('current');
$path_destination = !empty($query) ? $query : '';
}
else {
$path_destination = Url::fromUri($path)->toString();
}
// Set destination to current request.
$this->requestStack->getCurrentRequest()->query->set('destination', $path_destination);
}
/**
* Get current path.
*
* @return string
*/
protected function getCurrentPath() {
$current = $this->requestStack->getCurrentRequest()->get('current', '');
if (empty($current)) {
$current = $this->currentPath->getPath();
}
return $current;
}
}
@@ -0,0 +1,33 @@
<?php
namespace Drupal\login_destination;
use Drupal\Core\Session\AccountInterface;
use Drupal\login_destination\Entity\LoginDestination;
/**
* Defines a login destination manager service interface.
*/
interface LoginDestinationManagerInterface {
/**
* Find destination.
*
* @param string $trigger
* Trigger.
* @param \Drupal\Core\Session\AccountInterface $account
* User account.
*
* @return bool|\Drupal\login_destination\Entity\LoginDestination
*/
public function findDestination($trigger, AccountInterface $account);
/**
* Prepare request destination provided by login destination rule.
*
* @param \Drupal\login_destination\Entity\LoginDestination $destination
* Login destination rule.
*/
public function prepareDestination(LoginDestination $destination);
}