forked from dpc-sdp/tide_authenticated_content
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tide_authenticated_content.module
239 lines (214 loc) · 7.73 KB
/
tide_authenticated_content.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
<?php
/**
* @file
* Tide Authenticated Content module functionality.
*/
use Drupal\node\NodeInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\tide_site\TideSiteHelper;
use Drupal\user\Entity\User;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_mail_alter().
*
* Using mail_alter to handle all reset links (including when status_activated
* is sent after account is activated).
*/
function tide_authenticated_content_mail_alter(&$message) {
$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('tide_site')) {
/** @var \Symfony\Component\DependencyInjection\ContainerInterface $kernel */
$container = \Drupal::getContainer();
/** @var \Drupal\Core\Entity\EntityTypeManager $em */
$em = $container->get("entity_type.manager");
/** @var \Drupal\Core\Entity\EntityRepository $er */
$er = $container->get("entity.repository");
$helper = new TideSiteHelper($em, $er);
/** @var \Drupal\taxonomy\TermInterface $site */
$site = NULL;
foreach ($message['body'] as $i => $b) {
if (preg_match(
"#http(s|)://[^/]+/user/reset/([0-9]+)/([0-9]+)/([^\s\n]+)#",
$b,
$matches
)) {
/** @var \Drupal\user\Entity\User $u */
try {
$u = $em->getStorage('user')->load($matches[2]);
}
catch (\Exception $e) {
\Drupal::logger("default")
->warning("Failed to load user: " . $e->getMessage());
return;
}
if ($u !== NULL) {
// Set in dpc-sdp/tide_authenticated_content/config/install/tide_authenticated_content.module.yml.
$config = \Drupal::config('tide_authenticated_content.module');
$backendRoles = $config->get("backend_user_roles");
$roles = $u->getRoles();
// Find users with roles in the list of configured backend roles.
if (!empty($roles) && !empty(array_intersect($backendRoles,
$roles))) {
// Current user is a backend user don't alter email.
return;
}
$user = User::load($u->id());
if ($u->hasField('field_site')) {
$siteId = $user->get("field_site")->getValue()[0]["target_id"];
}
else {
$siteId = $config->get("default_site_id");
}
if (!$siteId) {
return;
}
$site = Term::load($siteId);
}
}
}
// If user has not site we cannot find the domain so don't rewrite.
if ($site === NULL) {
return;
}
$base = $helper->getSiteProductionDomain($site);
}
if (!empty($base)) {
foreach ($message['body'] as $i => $b) {
$message['body'][$i] = preg_replace(
"#http(s|)://[^/]+/user/reset/([0-9]+)/([0-9]+)/([^\s\n]+)#",
"https://$base" . '/user/reset/$2/$3/$4',
$b
);
$message['body'][$i] = preg_replace(
"#http(s|)://[^/]+/user([\s\n]+)#",
"https://$base" . '/login$2',
$message['body'][$i]
);
}
}
}
/**
* Implements hook_ENTITY_TYPE_access().
*/
function tide_authenticated_content_user_access(
EntityInterface $user,
$operation,
AccountInterface $account
) {
$tide_config = \Drupal::config('tide_authenticated_content.module');
$protectJsonapiUserRoute = $tide_config->get("protect_jsonapi_user_route");
$currentPath = \Drupal::service('path.current')->getPath();
if ($protectJsonapiUserRoute) {
if (strpos($currentPath, '/api/v1/user/user') === 0) {
$uid = $user->id();
if ($uid !== 0 && $uid === $account->id()) {
return AccessResult::neutral();
}
return AccessResult::forbidden();
}
}
return AccessResult::neutral();
}
/**
* Implements hook_ENTITY_TYPE_access().
*/
function tide_authenticated_content_profile_access(
EntityInterface $profile,
$operation,
AccountInterface $account
) {
$tide_config = \Drupal::config('tide_authenticated_content.module');
$protectJsonapiUserRoute = $tide_config->get("protect_jsonapi_user_route");
$currentPath = \Drupal::service('path.current')->getPath();
if ($protectJsonapiUserRoute) {
if (strpos($currentPath, '/api/v1/profile') === 0) {
$uid = $profile->get('uid')->getValue()[0]['target_id'];
if ($uid !== 0 && $uid == $account->id()) {
return AccessResult::neutral();
}
return AccessResult::forbidden();
}
}
return AccessResult::neutral();
}
/**
* Implements hook_node_access_records().
*/
function tide_authenticated_content_node_access_records(NodeInterface $node) {
// Only run if the module permission by terms is enabled.
if (\Drupal::moduleHandler()->moduleExists('permissions_by_term')) {
if (!$node->isPublished()) {
// No module implements this hook for unpublished nodes, so we do.
$grants[] = [
'realm' => 'tide_authenticated_content',
'gid' => 1,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
'nid' => $node->id(),
];
return $grants;
}
}
return [];
}
/**
* Implements hook_node_grants().
*/
function tide_authenticated_content_node_grants(AccountInterface $account, $op) {
// Only run if the module permission by terms is enabled.
if (\Drupal::moduleHandler()->moduleExists('permissions_by_term')) {
if ($op === 'view') {
$view_unpublished_content_roles = array_keys(user_roles(TRUE, 'view any unpublished content'));
$account_roles = $account->getRoles();
if (!empty(array_intersect($account_roles, $view_unpublished_content_roles))) {
$grants['tide_authenticated_content'][] = 1;
return $grants;
}
}
}
return [];
}
/**
* Implements hook_node_access().
*/
function tide_authenticated_content_node_access(NodeInterface $node, $op, AccountInterface $account) {
// Only run if the module permission by terms is enabled.
if (\Drupal::moduleHandler()->moduleExists('permissions_by_term')) {
if (!$node->isPublished() && $op === 'view') {
$access_result = AccessResult::allowedIfHasPermission($account, 'view any unpublished content');
$access_result = $access_result->andIf(AccessResult::allowedIf($node->getOwnerId() == $account->id() || $node->getRevisionUserId() == $account->id()));
return $access_result->addCacheableDependency($node);
}
}
return AccessResult::neutral()->addCacheableDependency($node);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_authenticated_content_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
array_unshift($form['#validate'], '_tide_authenticated_content_user_role_validation');
}
/**
* User Roles can be blocked from logging in to Drupal.
*/
function _tide_authenticated_content_user_role_validation($form, FormStateInterface $form_state) {
// Only validating when username and password are both not empty.
if (!empty($form_state->getValue('name')) && strlen($form_state->getValue('pass')) > 0) {
// Try to search the account that associated with the 'name'.
$account_search = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['name' => $form_state->getValue('name')]);
// The authentication process begins.
if ($account = reset($account_search)) {
$tide_config = \Drupal::config('tide_authenticated_content.module');
$protectJsonapiUserRoute = $tide_config->get("protect_jsonapi_user_route");
if ($protectJsonapiUserRoute) {
if (empty(array_intersect($tide_config->get('backend_user_roles'), $account->getRoles()))) {
$form_state->setError($form, t("%username user doesn't have permission to login.", ['%username' => $form_state->getValue('name')]));
}
}
}
}
}