-
Notifications
You must be signed in to change notification settings - Fork 46
/
apigee_edge.module
1841 lines (1702 loc) · 70.5 KB
/
apigee_edge.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Copyright 2018 Google Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* 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.
*/
/**
* Main module file for Apigee Edge.
*/
use Apigee\Edge\Api\Management\Entity\AppCredentialInterface;
use Apigee\Edge\Api\Management\Serializer\AppCredentialSerializer;
use Apigee\Edge\Exception\ApiException;
use Apigee\Edge\Exception\ClientErrorException;
use Apigee\Edge\Structure\CredentialProduct;
use Drupal\apigee_edge\Element\StatusPropertyElement;
use Drupal\apigee_edge\Entity\ApiProduct;
use Drupal\apigee_edge\Entity\AppInterface;
use Drupal\apigee_edge\Entity\Developer;
use Drupal\apigee_edge\Exception\DeveloperUpdateFailedException;
use Drupal\apigee_edge\Exception\UserDeveloperConversionNoStorageFormatterFoundException;
use Drupal\apigee_edge\Exception\UserDeveloperConversionUserFieldDoesNotExistException;
use Drupal\apigee_edge\Form\DeveloperSettingsForm;
use Drupal\apigee_edge\JobExecutor;
use Drupal\apigee_edge\Plugin\Field\FieldType\ApigeeEdgeDeveloperIdFieldItem;
use Drupal\apigee_edge\Plugin\Validation\Constraint\DeveloperEmailUniqueValidator;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Template\Attribute;
use Drupal\Core\TempStore\TempStoreException;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
use Drupal\user\UserInterface;
use Drupal\Component\Utility\Html;
define('APIGEE_EDGE_USER_REGISTRATION_SOURCE', 'apigee_edge_user_registration_source');
/**
* Implements hook_module_implements_alter().
*/
function apigee_edge_module_implements_alter(&$implementations, $hook) {
if (in_array($hook, ['form_user_register_form_alter', 'form_user_form_alter'])) {
// Move apigee_edge_form_user_register_form_alter() and
// apigee_edge_form_user_form_alter() alter hook implementations to the
// end of the list.
$group = $implementations['apigee_edge'];
unset($implementations['apigee_edge']);
$implementations['apigee_edge'] = $group;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function apigee_edge_form_apigee_edge_authentication_form_alter(array &$form, FormStateInterface $form_state, string $form_id) {
/** @var bool $do_not_alter_key_entity_forms */
$do_not_alter_key_entity_forms = \Drupal::config('apigee_edge.dangerzone')->get('do_not_alter_key_entity_forms');
// Even if the original Key forms should not be altered, the Authentication
// form provided by this module should still work the same.
if ($do_not_alter_key_entity_forms) {
/** @var \Drupal\apigee_edge\KeyEntityFormEnhancer $key_entity_form_enhancer */
$key_entity_form_enhancer = \Drupal::service('apigee_edge.key_entity_form_enhancer');
$key_entity_form_enhancer->alterForm($form, $form_state);
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function apigee_edge_form_key_form_alter(array &$form, FormStateInterface $form_state, string $form_id) {
/** @var bool $do_not_alter_key_entity_forms */
$do_not_alter_key_entity_forms = \Drupal::config('apigee_edge.dangerzone')->get('do_not_alter_key_entity_forms');
// Even if the original Key forms should not be altered, the Authentication
// form provided by this module should still work the same.
if ($do_not_alter_key_entity_forms) {
return;
}
/** @var \Drupal\apigee_edge\KeyEntityFormEnhancer $key_entity_form_enhancer */
$key_entity_form_enhancer = \Drupal::service('apigee_edge.key_entity_form_enhancer');
// Only those Key forms gets altered that defines an Apigee Edge key type.
$key_entity_form_enhancer->alterForm($form, $form_state);
}
/**
* Implements hook_theme().
*/
function apigee_edge_theme() {
return [
'apigee_entity' => [
'render element' => 'elements',
],
'apigee_entity_list' => [
'render element' => 'elements',
],
'apigee_entity__app' => [
'render element' => 'elements',
'base hook' => 'apigee_entity',
],
'app_credential' => [
'render element' => 'elements',
],
'app_credential_product_list' => [
'render element' => 'elements',
],
'status_property' => [
'render element' => 'element',
],
'apigee_secret' => [
'render element' => 'elements',
'base hook' => 'apigee_secret',
],
];
}
/**
* Preprocess variables for the apigee_secret element template.
*/
function template_preprocess_apigee_secret(&$variables) {
$variables['value'] = [
'#markup' => $variables['elements']['#value'],
];
}
/**
* Prepares variables for Apigee entity templates.
*
* Default template: apigee-entity.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
*/
function template_preprocess_apigee_entity(array &$variables) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
/** @var \Drupal\apigee_edge\Entity\EdgeEntityInterface $entity */
$entity = $variables['entity'] = $variables['elements']['#entity'];
$variables['label'] = $entity->label();
if (!$entity->isNew() && $entity->hasLinkTemplate('canonical')) {
$variables['url'] = $entity->toUrl('canonical', ['language' => $entity->language()])->toString();
}
// Helpful $content variable for templates.
$variables += ['content' => []];
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function apigee_edge_theme_suggestions_apigee_entity(array $variables) {
$suggestions = [];
/** @var \Drupal\apigee_edge\Entity\EdgeEntityInterface $entity */
$entity = $variables['elements']['#entity'];
$sanitized_view_mode = str_replace('.', '_', $variables['elements']['#view_mode']);
if ($entity instanceof AppInterface) {
$suggestions[] = 'apigee_entity__app';
$suggestions[] = 'apigee_entity__app__' . $sanitized_view_mode;
}
$suggestions[] = 'apigee_entity__' . $entity->getEntityTypeId();
$suggestions[] = 'apigee_entity__' . $entity->getEntityTypeId() . '__' . $sanitized_view_mode;
return $suggestions;
}
/**
* Prepares variables for Apigee entity list templates.
*
* Default template: apigee-entity-list.html.twig.
*/
function template_preprocess_apigee_entity_list(array &$variables) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
$variables['entity_type_id'] = $variables['elements']['#entity_type']->id();
$variables += ['content' => []];
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function apigee_edge_theme_suggestions_apigee_entity_list(array $variables) {
$suggestions = [];
$view_mode = $variables['elements']['#view_mode'];
$entity_type_id = $variables['elements']['#entity_type']->id();
// Add a suggestion based on the entity type and on the view mode.
$suggestions[] = 'apigee_entity_list__' . $entity_type_id;
$suggestions[] = 'apigee_entity_list__' . $entity_type_id . '__' . $view_mode;
return $suggestions;
}
/**
* Prepares variables for status_property templates.
*
* Default template: status_property.html.twig.
*
* @param array $variables
* An associative array.
*/
function template_preprocess_status_property(array &$variables) {
$element = &$variables['element'];
$element['value'] = $element['#value'];
$classes = ['status-value-' . Html::getClass($element['#value'])];
if ($element['#indicator_status'] !== '') {
$classes[] = str_replace('_', '-', $element['#indicator_status']);
}
$element['attributes'] = new Attribute(['class' => $classes]);
}
/**
* Implements hook_system_breadcrumb_alter().
*/
function apigee_edge_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
// Remove breadcrumb cache from every path under "/user" to let
// CreateAppForDeveloperBreadcrumbBuilder build breadcrumb properly on the
// add developer app for developer page.
if (preg_match('/^\/user.*/', $route_match->getRouteObject()->getPath())) {
$breadcrumb->mergeCacheMaxAge(0);
}
if ($route_match->getRouteName() === 'entity.developer_app.add_form_for_developer') {
$collection_route_by_developer_name = 'entity.developer_app.collection_by_developer';
/** @var \Drupal\Core\Controller\TitleResolverInterface $title_resolver */
$title_resolver = \Drupal::service('title_resolver');
/** @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$breadcrumb->addLink(Link::createFromRoute(
$title_resolver->getTitle(\Drupal::requestStack()->getCurrentRequest(), $route_provider->getRouteByName($collection_route_by_developer_name)),
$collection_route_by_developer_name,
['user' => $route_match->getParameter('user')->id()]
));
}
}
/**
* Implements hook_entity_base_field_info().
*/
function apigee_edge_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() === 'user') {
$fields['first_name'] = BaseFieldDefinition::create('string')
->setLabel(t('First name'))
->setDescription(t('Your first name.'))
->setSetting('max_length', 64)
->setRequired(TRUE)
->setInitialValue('Firstname')
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => '-11',
'settings' => [
'display_label' => TRUE,
],
])
->setDisplayConfigurable('form', TRUE);
$fields['last_name'] = BaseFieldDefinition::create('string')
->setLabel(t('Last name'))
->setDescription(t('Your last name.'))
->setSetting('max_length', 64)
->setRequired(TRUE)
->setInitialValue('Lastname')
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => '-11',
'settings' => [
'display_label' => TRUE,
],
])
->setDisplayConfigurable('form', TRUE);
$fields['apigee_edge_developer_id'] = BaseFieldDefinition::create('string')
->setName('apigee_edge_developer_id')
->setLabel(t('Apigee Edge Developer ID'))
->setComputed(TRUE)
->setClass(ApigeeEdgeDeveloperIdFieldItem::class);
}
return $fields;
}
/**
* Implements hook_entity_base_field_info_alter().
*/
function apigee_edge_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\FieldDefinitionInterface[] $fields */
if ($entity_type->id() === 'user') {
/** @var \Drupal\Core\Field\BaseFieldDefinition $mail */
$mail = $fields['mail'];
$mail->setRequired(TRUE);
$mail->addConstraint('DeveloperMailUnique');
// Add a bundle to these fields to allow other modules to display them
// as configurable (fields added through the UI or configuration do have a
// target bundle set).
// @see https://github.com/apigee/apigee-edge-drupal/issues/396
$fields['first_name']->setTargetBundle('user');
$fields['last_name']->setTargetBundle('user');
}
}
/**
* Implements hook_entity_extra_field_info().
*/
function apigee_edge_entity_extra_field_info() {
$extra = [];
foreach (\Drupal::entityTypeManager()->getDefinitions() as $definition) {
if (in_array(AppInterface::class, class_implements($definition->getOriginalClass()))) {
// Bundles are not supported therefore both keys are the same.
$extra[$definition->id()][$definition->id()]['display']['credentials'] = [
'label' => new TranslatableMarkup('Credentials'),
'description' => new TranslatableMarkup('Displays credentials provided by a @label', ['@label' => $definition->getSingularLabel()]),
// By default it should be displayed in the end of the view.
'weight' => 100,
'visible' => TRUE,
];
$extra[$definition->id()][$definition->id()]['display']['warnings'] = [
'label' => new TranslatableMarkup('Warnings'),
'description' => new TranslatableMarkup('Displays app warnings'),
'weight' => -100,
'visible' => TRUE,
];
}
}
return $extra;
}
/**
* Implements hook_field_formatter_info_alter().
*/
function apigee_edge_field_formatter_info_alter(array &$info) {
$info['basic_string']['field_types'][] = 'app_callback_url';
}
/**
* Implements hook_entity_view().
*/
function apigee_edge_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($entity instanceof AppInterface) {
// Add some required assets to an app's full entity view mode.
$build['#attached']['library'][] = 'apigee_edge/apigee_edge.components';
$build['#attached']['library'][] = 'apigee_edge/apigee_edge.app_view';
if (\Drupal::moduleHandler()->moduleExists('apigee_edge_teams')) {
if ($team = \Drupal::routeMatch()->getParameter('team')) {
$team_app_name = $team->getName();
}
}
if ($user = \Drupal::routeMatch()->getParameter('user')) {
$build['#attached']['drupalSettings']['currentUser'] = $user->id();
}
if ($display->getComponent('credentials')) {
/** @var \Drupal\apigee_edge\Entity\AppInterface $entity */
$defaults = [
'#cache' => [
'contexts' => $entity->getCacheContexts(),
'tags' => $entity->getCacheTags(),
],
];
$build['credentials'] = [
'#type' => 'container',
];
$index = 0;
foreach ($entity->getCredentials() as $credential) {
$build['credentials'][$credential->getStatus()][] = [
'#type' => 'app_credential',
'#credential' => $credential,
'#app_name' => $entity->getName(),
'#team_app_name' => isset($team_app_name) ? $team_app_name : '',
'#app' => $entity,
'#attributes' => [
'class' => 'items--inline',
'data-app-keys-url' => $entity->toUrl('api-keys', ['absolute' => TRUE])->toString(FALSE),
'data-app-container-index' => $index,
],
] + $defaults;
$index++;
}
// Hide revoked credentials in a collapsible section.
if (!empty($build['credentials'][AppCredentialInterface::STATUS_REVOKED])) {
$revoked_credentials = $build['credentials'][AppCredentialInterface::STATUS_REVOKED];
$build['credentials'][AppCredentialInterface::STATUS_REVOKED] = [
'#type' => 'details',
'#title' => t('Revoked keys (@count)', ['@count' => count($revoked_credentials)]),
'#weight' => 100,
'credentials' => $revoked_credentials,
];
}
}
// Add link to add keys.
if($entity->access('add_api_key') && $entity->hasLinkTemplate('add-api-key-form')) {
$build['add_keys'] = Link::fromTextAndUrl(t('Add key'), $entity->toUrl('add-api-key-form', [
'attributes' => [
'data-dialog-type' => 'modal',
'data-dialog-options' => json_encode([
'width' => 500,
'height' => 250,
'draggable' => FALSE,
'autoResize' => FALSE,
]),
'class' => [
'use-ajax',
'button',
],
],
]))->toRenderable();
$build['#attached']['library'][] = 'core/drupal.dialog.ajax';
}
}
if ($display->getComponent('warnings')) {
/** @var \Drupal\apigee_edge\Entity\AppWarningsCheckerInterface $app_warnings_checker */
$app_warnings_checker = \Drupal::service('apigee_edge.entity.app_warnings_checker');
$warnings = array_filter($app_warnings_checker->getWarnings($entity));
if (count($warnings)) {
$build['warnings'] = [
'#theme' => 'status_messages',
'#message_list' => [
'warning' => $warnings,
],
];
}
}
}
/**
* Implements hook_ENTITY_TYPE_access().
*
* Supported operations: view, view label, assign.
*
* "assign" is a custom entity on API Products. It is being used on app
* create/edit forms. A developer may have view access to an API product but
* they can not assign it to an app (they can not obtain an API key for that
* API product).
*
* Rules:
* - The user gets allowed if has "Bypass API Product access control"
* permission always.
* - If operation is "view" or "view label" then the user gets access allowed
* for the API Product (entity) if the API product's access attribute value is
* either one of the selected access attribute values OR if a developer
* app is in association with the selected API product.
* - If operation is "assign" then disallow access if the role is configured
* in the "Access by visibility" settings at the route
* apigee_edge.settings.developer.api_product_access.
*/
function apigee_edge_api_product_access(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\apigee_edge\Entity\ApiProductInterface $entity */
if (!in_array($operation, ['view', 'view label', 'assign'])) {
return AccessResult::neutral(sprintf('%s is not supported by %s.', $operation, __FUNCTION__));
}
$config_name = 'apigee_edge.api_product_settings';
$result = AccessResult::allowedIfHasPermission($account, 'bypass api product access control');
if ($result->isNeutral()) {
// Attribute may not exists but in that case it means public.
// Access attribute needs to be set to lower case
// to match the portal visibilities that is set in the config apigee_edge.api_product_settings.
$product_visibility = $entity->getAttributeValue('access') ? strtolower($entity->getAttributeValue('access')) : 'public';
$visible_to_roles = \Drupal::config($config_name)->get('access')[$product_visibility] ?? [];
// A user may not have access to this API product based on the current
// access setting but we should still grant view access
// if they have a developer app in association with this API product.
if (empty(array_intersect($visible_to_roles, $account->getRoles()))) {
if ($operation === 'assign') {
// If the apigee_edge.settings.developer.api_product_access settings
// limits access to this API product, do not allow user to assign it
// to an application.
$result = AccessResult::forbidden("User {$account->getEmail()} is does not have permissions to see API Product with visibility {$product_visibility}.");
}
else {
$result = _apigee_edge_user_has_an_app_with_product($entity->id(), $account, TRUE);
}
}
else {
$result = AccessResult::allowed();
}
}
// If the API product gets updated it should not have any effect this
// access control so we did not add $entity as a dependency to the result.
return $result->cachePerUser()->addCacheTags(['config:' . $config_name]);
}
/**
* Implements hook_entity_access().
*/
function apigee_edge_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
if (!$entity->getEntityType()->entityClassImplements(AppInterface::class) || !in_array($operation, ['revoke_api_key', 'delete_api_key'])) {
return AccessResult::neutral();
}
/** @var \Drupal\apigee_edge\Entity\AppInterface $entity **/
$approved_credentials = array_filter($entity->getCredentials(), function (AppCredentialInterface $credential) {
return $credential->getStatus() === AppCredentialInterface::STATUS_APPROVED;
});
// Prevent revoking/deleting the only active key.
if (count($approved_credentials) <= 1) {
$action = $operation === "revoke_api_key" ? "revoke" : "delete";
return AccessResult::forbidden("You cannot $action the only active key.");
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function apigee_edge_form_entity_form_display_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form['#entity_type'] === 'developer_app') {
$form['#validate'][] = '_apigee_edge_developer_app_entity_form_display_edit_form_validate';
}
}
/**
* Extra validation for the entity_form_display.edit form of developer apps.
*
* This makes sure that fields marked as 'required' can't be disabled.
*
* @param array $form
* Form array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state.
*/
function _apigee_edge_developer_app_entity_form_display_edit_form_validate(array &$form, FormStateInterface $form_state) {
$required = \Drupal::config('apigee_edge.developer_app_settings')->get('required_base_fields');
foreach ($form_state->getValue('fields') as $field_name => $data) {
if (in_array($field_name, $required) && $data['region'] === 'hidden') {
$form_state->setError($form['fields'][$field_name], t('%field-name is required.', [
'%field-name' => $form['fields'][$field_name]['human_name']['#plain_text'],
]));
}
}
}
/**
* After build callback for verification email content form element.
*
* @param array $form_element
* Form element array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*
* @return array
* Form array.
*
* @see \Drupal\apigee_edge\Form\DeveloperSettingsForm::buildForm
*/
function apigee_edge_developer_settings_form_verification_email_body_after_build(array $form_element, FormStateInterface $form_state) {
if (isset($form_element['format'])) {
// Hide input format settings when textarea itself is also hidden.
$form_element['format']['#states']['visible'] = $form_element['#states']['visible'];
}
return $form_element;
}
/**
* Implements hook_mail().
*
* Based on user_mail().
*/
function apigee_edge_mail($key, &$message, $params) {
$token_service = \Drupal::token();
$language_manager = \Drupal::languageManager();
$langcode = $message['langcode'];
/** @var \Drupal\Core\Session\AccountInterface $account */
$account = $params['account'];
$variables = ['user' => $account];
$language = $language_manager->getLanguage($account->getPreferredLangcode());
$original_language = $language_manager->getConfigOverrideLanguage();
$language_manager->setConfigOverrideLanguage($language);
$config = \Drupal::config('apigee_edge.developer_settings');
$token_options = [
'langcode' => $langcode,
'callback' => '_apigee_edge_existing_developer_mail_tokens',
'clear' => TRUE,
];
$message['subject'] .= PlainTextOutput::renderFromHtml($token_service->replace($config->get('verification_email.subject'), $variables, $token_options));
$message['body'][] = $token_service->replace($config->get('verification_email.body'), $variables, $token_options);
$language_manager->setConfigOverrideLanguage($original_language);
}
/**
* Token callback to add unsafe tokens for existing developer user mails.
*
* This function is used by \Drupal\Core\Utility\Token::replace() to set up
* some additional tokens that can be used in email messages generated by
* apigee_edge_mail().
*
* @param array $replacements
* An associative array variable containing mappings from token names to
* values (for use with strtr()).
* @param array $data
* An associative array of token replacement values. If the 'user' element
* exists, it must contain a user account object with the following
* properties:
* - login: The UNIX timestamp of the user's last login.
* - pass: The hashed account login password.
* @param array $options
* A keyed array of settings and flags to control the token replacement
* process. See \Drupal\Core\Utility\Token::replace().
*/
function _apigee_edge_existing_developer_mail_tokens(array &$replacements, array $data, array $options) {
if (isset($data['user'])) {
$replacements['[user:developer-email-verification-url]'] = _apigee_edge_existing_developer_email_verification_link($data['user'], $options);
}
}
/**
* Sends a verification email to the developer email that is already taken.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The user object of the account being notified. Must contain at
* least the fields 'uid', 'name', and 'mail'.
* @param string $langcode
* (optional) Language code to use for the notification, overriding account
* language.
*
* @return array
* An array containing various information about the message.
* See \Drupal\Core\Mail\MailManagerInterface::mail() for details.
*
* @see \_apigee_edge_existing_developer_mail_tokens()
*/
function _apigee_edge_send_developer_email_verification_email(AccountInterface $account, $langcode = NULL) {
if (\Drupal::config('apigee_edge.developer_settings')->get('verification_action') === DeveloperSettingsForm::VERIFICATION_ACTION_VERIFY_EMAIL) {
$params['account'] = $account;
$langcode = $langcode ? $langcode : $account->getPreferredLangcode();
// Get the custom site notification email to use as the from email address
// if it has been set.
$site_mail = \Drupal::config('system.site')->get('mail_notification');
// If the custom site notification email has not been set, we use the site
// default for this.
if (empty($site_mail)) {
$site_mail = \Drupal::config('system.site')->get('mail');
}
if (empty($site_mail)) {
$site_mail = ini_get('sendmail_from');
}
$mail = \Drupal::service('plugin.manager.mail')->mail('apigee_edge', 'developer_email_verification', $account->getEmail(), $langcode, $params, $site_mail);
// TODO Should we notify admins about this?
}
return empty($mail) ? NULL : $mail['result'];
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function apigee_edge_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Only alter the user edit form.
if ($form_id === 'user_register_form') {
return;
}
// The email field should be always required because it is required on
// Apigee Edge.
$form['account']['mail']['#required'] = TRUE;
$user = \Drupal::currentUser();
// Make the same information available here as on user_register_form.
// @see \Drupal\user\RegisterForm::form()
$form['administer_users'] = [
'#type' => 'value',
'#value' => $user->hasPermission('administer users'),
];
// Add the API connection custom validation callback to the beginning of the
// chain apigee_edge_module_implements_alter() ensures that form_alter hook is
// called in the last time.
$validation_functions[] = 'apigee_edge_form_user_form_api_connection_validate';
// Add email custom validation callback to the chain immediately after the API
// connection validation apigee_edge_module_implements_alter() ensures that
// form_alter hook is called in the last time.
$validation_functions[] = 'apigee_edge_form_user_form_developer_email_validate';
$form['#validate'] = array_merge($validation_functions, $form['#validate']);
}
/**
* Validates whether the provided email address is already taken on Apigee Edge.
*
* @param array $form
* Form array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*/
function apigee_edge_form_user_form_developer_email_validate(array $form, FormStateInterface $form_state) {
// If email address was changed.
if ($form_state->getValue('mail') !== $form_state->getBuildInfo()['callback_object']->getEntity()->mail->value) {
$developer = NULL;
try {
$developer = Developer::load($form_state->getValue('mail'));
}
catch (\Exception $exception) {
// Nothing to do here, if there is no connection to Apigee Edge interrupt
// the registration in the
// apigee_edge_form_user_form_api_connection_validate() function.
}
if ($developer) {
// Add email address to the whitelist because we would like to
// display a custom error message instead of what this
// field validation handler returns.
DeveloperEmailUniqueValidator::whitelist($form_state->getValue('mail'));
if ($form_state->getValue('administer_users')) {
$form_state->setErrorByName('mail', t('This email address already belongs to a developer on Apigee Edge.'));
}
else {
$config = Drupal::config('apigee_edge.developer_settings');
$form_state->setErrorByName('mail', $config->get('user_edit_error_message.value'));
}
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function apigee_edge_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$validation_functions = [];
// The email field should be always required because it is required on
// Apigee Edge.
$form['account']['mail']['#required'] = TRUE;
// Add the API connection custom validation callback to the beginning of the
// chain apigee_edge_module_implements_alter() ensures that form_alter hook is
// called in the last time.
$validation_functions[] = 'apigee_edge_form_user_form_api_connection_validate';
$userInput = $form_state->getUserInput();
// Because this form alter is called earlier than the validation callback
// (and the entity validations by user module) we have to use raw
// user input here to check whether this form element should be visible
// next time when the form is displayed on the UI with validation errors.
if (!empty($userInput['mail']) && $form['account']['mail']['#default_value'] !== $userInput['mail']) {
// Only add our extra features to the form if the provided email does not
// belong to a user in Drupal yet. Otherwise let Drupal's build-in
// validation to handle this problem.
$user = user_load_by_mail($userInput['mail']);
if (!$user) {
// Add email custom validation callback to the chain immediately after the
// API connection validation apigee_edge_module_implements_alter() ensures
// that form_alter hook is called in the last time.
$validation_functions[] = 'apigee_edge_form_user_register_form_developer_email_validate';
try {
$developer = Developer::load($userInput['mail']);
$form['developer_exists'] = [
'#type' => 'value',
'#value' => (bool) $developer,
];
if ($developer) {
if ($form['administer_users']['#value']) {
$form['account']['apigee_edge_developer_exists'] = [
'#type' => 'checkbox',
'#title' => t('I understand the provided email address belongs to a developer on Apigee Edge and I confirm user creation'),
'#required' => TRUE,
'#weight' => 0,
];
}
else {
$config = Drupal::config('apigee_edge.developer_settings');
if ($config->get('verification_action') === DeveloperSettingsForm::VERIFICATION_ACTION_VERIFY_EMAIL) {
$form['account']['apigee_edge_developer_unreceived_mail'] = [
'#type' => 'checkbox',
'#title' => t('I did not get an email. Please send me a new one.'),
'#weight' => 0,
];
}
}
}
}
catch (\Exception $exception) {
// Nothing to do here, if there is no connection to Apigee Edge
// Nothing to do here, if there is no connection to Apigee Edge
// interrupt the registration in the
// apigee_edge_form_user_form_api_connection_validate() function.
}
}
}
$form['#validate'] = array_merge($validation_functions, $form['#validate']);
$form['#after_build'][] = 'apigee_edge_form_user_register_form_after_build';
}
/**
* After build function for user_registration_form.
*
* @param array $form
* Form array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*
* @return array
* Form array.
*/
function apigee_edge_form_user_register_form_after_build(array $form, FormStateInterface $form_state) {
if (isset($form['account']['apigee_edge_developer_exists']) && isset($form['account']['mail'])) {
$form['account']['apigee_edge_developer_exists']['#weight'] = $form['account']['mail']['#weight'] + 0.0001;
}
if (isset($form['account']['apigee_edge_developer_unreceived_mail']) && isset($form['account']['mail'])) {
$form['account']['apigee_edge_developer_unreceived_mail']['#weight'] = $form['account']['mail']['#weight'] + 0.0001;
}
return $form;
}
/**
* Validates whether there is connection to Apigee Edge or not.
*
* @param array $form
* Form array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*/
function apigee_edge_form_user_form_api_connection_validate(array $form, FormStateInterface $form_state) {
// If there is no connection to Apigee Edge interrupt the registration/user
// update, otherwise it could be a security leak if a developer exists in
// Apigee Edge with the same email address.
/** @var \Drupal\apigee_edge\SDKConnectorInterface $sdk_connector */
$sdk_connector = \Drupal::service('apigee_edge.sdk_connector');
try {
$sdk_connector->testConnection();
}
catch (\Exception $exception) {
$context = [
'@user_email' => $form_state->getValue('mail'),
'@message' => (string) $exception,
];
$logger = \Drupal::logger('apigee_edge');
Error::logException($logger, $exception, 'Could not create/update Drupal user: @user_email, because there was no connection to Apigee Edge. @message %function (line %line of %file). <pre>@backtrace_string</pre>', $context);
$form_state->setError($form, t('User registration is temporarily unavailable. Try again later or contact the site administrator.'));
}
}
/**
* Validates whether the provided email address is already taken on Apigee Edge.
*
* @param array $form
* Form array.
* @param Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*/
function apigee_edge_form_user_register_form_developer_email_validate(array $form, FormStateInterface $form_state) {
// Do nothing if the developer does not exists.
if (empty($form_state->getValue('developer_exists'))) {
return;
}
/** @var \Drupal\user\RegisterForm $registerForm */
$registerForm = $form_state->getFormObject();
// Pass this information to hook_user_presave() in case if we would get
// there.
$registerForm->getEntity()->{APIGEE_EDGE_USER_REGISTRATION_SOURCE} = 'user_register_form';
// Do nothing if user has administer users permission.
// (Form is probably displayed on admin/people/create.)
if ($form_state->getValue('administer_users')) {
// Add email address to the whitelist because we do not want to
// display the same error message for an admin user as a regular user.
DeveloperEmailUniqueValidator::whitelist($form_state->getValue('mail'));
// If administrator has not confirmed that they would like to create a user
// in Drupal with an existing developer id on Apigee Edge then add a custom
// error to the field.
if (empty($form_state->getValue('apigee_edge_developer_exists'))) {
$form_state->setErrorByName('mail', t('This email address already exists on Apigee Edge.'));
}
return;
}
$config = \Drupal::config('apigee_edge.developer_settings');
$request = \Drupal::request();
$token = $request->query->get($config->get('verification_token'));
$timestamp = $request->query->get('timestamp');
/** @var \Drupal\user\UserInterface $account */
// Build user object from the submitted form values.
$account = $registerForm->buildEntity($form, $form_state);
// If required parameters are available in the url.
if ($token && $timestamp) {
// If token is (still) valid then account's email to the whitelist of the
// validator. This way it is not going to throw a validation error for this
// email this time.
if (apigee_edge_existing_developer_registration_hash_validate($account, $token, $timestamp)) {
DeveloperEmailUniqueValidator::whitelist($account->getEmail());
return;
}
else {
// Let user known that the token in the url has expired.
// Drupal sends a new verification email.
$form_state->setErrorByName('mail', t('Registration token expired or invalid. We have sent you a new link.'));
}
}
// Use shared storage to keep track of sent verification emails.
// Form state's storage can not be used for this purpose because its values
// are being cleared for every new requests. Private storage is too private
// in case of anonymous user because every page request creates a new, empty
// private temp storage.
$storage = \Drupal::service('tempstore.shared');
/** @var \Drupal\Core\TempStore\PrivateTempStore $sendNotifications */
$sendNotifications = $storage->get('apigee_edge_developer_email_verification_sent');
// Do not send multiple email verifications to the same email address
// every time when form validation fails with an error.
if (!$sendNotifications->get($account->getEmail()) || $form_state->getValue('apigee_edge_developer_unreceived_mail')) {
// Send verification email to the user.
$result = _apigee_edge_send_developer_email_verification_email($account, $account->getPreferredLangcode());
try {
$sendNotifications->set($account->getEmail(), $result);
}
catch (TempStoreException $e) {
$logger = \Drupal::logger(__FUNCTION__);
Error::logException($logger, $e);
}
}
}
/**
* Generates an URL to confirm identity of a user with existing developer mail.
*
* Based on user_cancel_url().
*
* @param \Drupal\user\UserInterface $account
* User object.
* @param array $options
* (optional) A keyed array of settings. Supported options are:
* - langcode: A language code to be used when generating locale-sensitive
* URLs. If langcode is NULL the users preferred language is used.
*
* @return string
* A unique URL that may be used to confirm the cancellation of the user
* account.
*
* @see \_apigee_edge_existing_developer_mail_tokens()
* @see \Drupal\user\Controller\UserController::confirmCancel()
*/
function _apigee_edge_existing_developer_email_verification_link(UserInterface $account, array $options = []) {
$languageManager = \Drupal::languageManager();
$timestamp = \Drupal::time()->getRequestTime();
$langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode();
$url_options = ['absolute' => TRUE, 'language' => $languageManager->getLanguage($langcode)];
$url_options['query'][\Drupal::config('apigee_edge.developer_settings')->get('verification_token')] = apigee_edge_existing_developer_registration_hash($account, $timestamp);
$url_options['query']['timestamp'] = $timestamp;
// For now, use this method for generating url to the user register and
// edit forms.
$route = 'user.register';
$route_params = [];
if (!$account->isAnonymous() && $account->id()) {
$route = 'entity.user.edit_form';
$route_params['user'] = $account->id();
}
return Url::fromRoute($route, $route_params, $url_options)->toString();
}
/**
* Generates a token for an email address that is already taken on Apigee Edge.
*
* We do not want to enforce a user to use the same first name, last name,
* username when this token is generated and when they re-open the registration