-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathEvents.php
More file actions
471 lines (408 loc) · 13.4 KB
/
Events.php
File metadata and controls
471 lines (408 loc) · 13.4 KB
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
<?php
/**
* Keycloak Sign-In
* @link https://github.com/cuzy-app/auth-keycloak
* @license https://github.com/cuzy-app/auth-keycloak/blob/master/docs/LICENCE.md
* @author [Marc FARRE](https://marc.fun) for [CUZY.APP](https://www.cuzy.app)
*/
namespace humhub\modules\authKeycloak;
use humhub\commands\CronController;
use humhub\compat\HForm;
use humhub\helpers\ControllerHelper;
use humhub\modules\admin\models\forms\UserEditForm;
use humhub\modules\authKeycloak\authclient\Keycloak;
use humhub\modules\authKeycloak\components\KeycloakApi;
use humhub\modules\authKeycloak\jobs\GroupsFullSync;
use humhub\modules\authKeycloak\jobs\GroupsUserSync;
use humhub\modules\authKeycloak\jobs\UpdateUserEmail;
use humhub\modules\authKeycloak\jobs\UpdateUserUsername;
use humhub\modules\authKeycloak\models\ConfigureForm;
use humhub\modules\ui\menu\MenuLink;
use humhub\modules\user\authclient\Collection;
use humhub\modules\user\events\UserEvent;
use humhub\modules\user\models\Auth;
use humhub\modules\user\models\forms\Registration;
use humhub\modules\user\models\Group;
use humhub\modules\user\models\GroupUser;
use humhub\modules\user\models\User;
use humhub\modules\user\widgets\AccountProfileMenu;
use Throwable;
use Yii;
use yii\base\Event;
use yii\db\AfterSaveEvent;
use yii\helpers\Console;
class Events
{
/**
* @param Event $event
* @return void
*/
public static function onAuthClientCollectionInit($event)
{
/** @var Collection $authClientCollection */
$authClientCollection = $event->sender;
$config = new ConfigureForm();
if ($config->enabled) {
$authClientCollection->setClient(Keycloak::DEFAULT_NAME, [
'class' => Keycloak::class,
'clientId' => $config->clientId,
'clientSecret' => $config->clientSecret,
]);
}
}
/**
* Sync user attributes with Keycloak
* @param $event UserEvent
*/
public static function onAfterLogin($event)
{
if (empty($event->user)) {
return;
}
$user = $event->user;
$config = new ConfigureForm();
if (!$config->enabled || !$config->hasApiParams()) {
return;
}
// Recover Auth record for newly registered Keycloak users.
// On a user's very first login, Keycloak::syncUserAttributes() runs
// before the user has been persisted in the database, so the Auth
// record cannot be written at that point. EVENT_AFTER_LOGIN fires
// after the user has been persisted, so we can catch up here.
// Without this, user_auth.source_id stays empty until the user
// logs in a second time, which in turn prevents the group sync
// (both GroupsUserSync and GroupsFullSync rely on this record).
if ($user->auth_mode === Keycloak::DEFAULT_NAME) {
$existingAuth = Auth::findOne([
'user_id' => $user->id,
'source' => Keycloak::DEFAULT_NAME,
]);
if ($existingAuth === null) {
$authClient = Yii::$app->authClientCollection->getClient(Keycloak::DEFAULT_NAME);
if ($authClient instanceof Keycloak) {
$authClient->createOrUpdateAuthRecord($user);
}
}
}
if ($config->updatedBrokerUsernameFromHumhubUsername) {
Yii::$app->queue->push(new UpdateUserUsername(['userId' => $user->id]));
}
if ($config->updatedBrokerEmailFromHumhubEmail) {
Yii::$app->queue->push(new UpdateUserEmail(['userId' => $user->id]));
}
if ($config->syncKeycloakGroupsToHumhub()) {
Yii::$app->queue->push(new GroupsUserSync(['userId' => $user->id]));
}
}
/**
* Registration form: hide username field
* Admin User edit form: hide password changing
* @param Event $event
*/
public static function onHFormBeforeRender($event)
{
if (
Yii::$app->request->isConsoleRequest
|| !Yii::$app->authClientCollection->hasClient(Keycloak::DEFAULT_NAME)
) {
return;
}
// Registration form: hide username field
if (
$event->sender instanceof Registration
&& Yii::$app->controller->module->id !== 'admin'
&& !Yii::$app->request->get('token') // If invited
) {
$config = new ConfigureForm();
/** @var Registration $hform */
$hform = $event->sender;
$errors = $hform->getErrors();
if (
$config->enabled
&& $config->hideRegistrationUsernameField
&& !isset($errors['username'])
) {
unset($hform->definition['elements']['User']['title']);
$hform->definition['elements']['User']['elements']['username']['type'] = 'hidden';
}
return;
}
// Admin User edit form: hide password changing
if (
Yii::$app->controller->module->id === 'admin'
&& Yii::$app->controller->id === 'user'
&& Yii::$app->controller->action->id === 'edit'
&& !empty($event->sender->models['User'])
&& $event->sender->models['User'] instanceof UserEditForm
) {
$config = new ConfigureForm();
if (
$config->enabled
&& $config->hideAdminUserEditPassword
) {
/** @var HForm $hform */
$hform = $event->sender;
unset($hform->definition['elements']['Password']);
}
}
}
/**
* If user email or username has changed in HumHub, update it on the broker (IdP)
* @param AfterSaveEvent $event
*/
public static function onModelUserAfterUpdate($event)
{
if (!isset($event->sender, $event->changedAttributes)) {
return;
}
/** @var User $user */
$user = $event->sender;
// Get changed attributes
$changedAttributes = $event->changedAttributes;
$config = new ConfigureForm();
if (!$config->enabled || !$config->hasApiParams()) {
return;
}
if (
array_key_exists('username', $changedAttributes)
&& $config->updatedBrokerUsernameFromHumhubUsername
) {
Yii::$app->queue->push(new UpdateUserUsername(['userId' => $user->id]));
}
if (
array_key_exists('email', $changedAttributes)
&& $config->updatedBrokerEmailFromHumhubEmail
) {
Yii::$app->queue->push(new UpdateUserEmail(['userId' => $user->id]));
}
}
/**
* Remove session on Keycloak after logout
* @param $event
*/
public static function onComponentUserAfterLogout($event)
{
/** @var User $user */
$user = $event->identity;
$config = new ConfigureForm();
if (
$config->enabled
&& $config->removeKeycloakSessionsAfterLogout
) {
(new KeycloakApi())->revokeUserSession($user->id);
}
}
/**
* @param $event
* @return void
*/
public static function onModelGroupAfterInsert($event)
{
if (
empty($event->sender)
|| !(new ConfigureForm())->syncHumhubGroupsToKeycloak()
) {
return;
}
/** @var Group $group */
$group = $event->sender;
(new KeycloakApi())->linkSameGroupNameOrCreateGroup($group->id);
}
/**
* @param $event
* @return void
*/
public static function onModelGroupAfterDelete($event)
{
if (
empty($event->sender)
|| !(new ConfigureForm())->syncHumhubGroupsToKeycloak(true)
) {
return;
}
/** @var Group $group */
$group = $event->sender;
(new KeycloakApi())->removeGroup($group->keycloak_id);
}
/**
* @param $event
* @return void
*/
public static function onModelGroupAfterUpdate($event)
{
if (
empty($event->sender)
|| !isset($event->changedAttributes)
|| !(new ConfigureForm())->syncHumhubGroupsToKeycloak()
) {
return;
}
/** @var Group $group */
$group = $event->sender;
// Get changed attributes
$changedAttributes = $event->changedAttributes;
// If name has changed
if (array_key_exists('name', $changedAttributes)) {
(new KeycloakApi())->renameGroup($group->id);
}
}
/**
* @param $event
* @return void
*/
public static function onModelGroupUserAfterInsert($event)
{
if (
empty($event->sender)
|| !(new ConfigureForm())->syncHumhubGroupsToKeycloak()
) {
return;
}
/** @var GroupUser $groupUser */
$groupUser = $event->sender;
$group = $groupUser->group;
$user = $groupUser->user;
if ($group === null || $user === null) {
return;
}
(new KeycloakApi())->addUserToGroup($user->id, $group->id);
}
/**
* @param $event
* @return void
*/
public static function onModelGroupUserAfterDelete($event)
{
if (
empty($event->sender)
|| !(new ConfigureForm())->syncHumhubGroupsToKeycloak(true)
) {
return;
}
/** @var GroupUser $groupUser */
$groupUser = $event->sender;
$group = $groupUser->group;
$user = $groupUser->user;
if ($group === null || $user === null) {
return;
}
(new KeycloakApi())->deleteUserFromGroup($user->id, $group->id);
}
/**
* @param $event
* @return void
* @throws Throwable
*/
public static function onCronDailyRun($event)
{
/** @var Module $module */
$module = Yii::$app->getModule('auth-keycloak');
if (!$module?->isEnabled) {
return;
}
/** @var CronController $controller */
$controller = $event->sender;
$controller->stdout("Auth Keycloak module: adding to jobs Keycloak groups synchronization with the API...");
$config = new ConfigureForm();
if (
!$config->enabled
|| $config->groupsSyncMode === ConfigureForm::GROUP_SYNC_MODE_NONE
|| !$config->hasApiParams()
) {
return;
}
Yii::$app->queue->push(new GroupsFullSync());
$controller->stdout('done.' . PHP_EOL, Console::FG_GREEN);
}
/**
* @param $event
* @return void
*/
public static function onAuthAfterInsert($event)
{
if (
empty($event->sender)
|| !(new ConfigureForm())->syncKeycloakGroupsToHumhub()
) {
return;
}
/** @var Auth $auth */
$auth = $event->sender;
if ($auth->source === Keycloak::DEFAULT_NAME) {
$config = new ConfigureForm();
if (
$config->enabled
&& $config->hasApiParams()
&& $config->syncKeycloakGroupsToHumhub()
) {
Yii::$app->queue->push(new GroupsUserSync(['userId' => $auth->user_id]));
}
}
}
/**
* @param $event
* @return void
*/
public static function onAuthAfterUpdate($event)
{
if (
empty($event->sender)
|| !isset($event->changedAttributes)
|| !(new ConfigureForm())->syncKeycloakGroupsToHumhub()
) {
return;
}
/** @var Auth $auth */
$auth = $event->sender;
// Get changed attributes
$changedAttributes = $event->changedAttributes;
if (
$auth->source === Keycloak::DEFAULT_NAME
&& array_key_exists('source', $changedAttributes)
) {
$config = new ConfigureForm();
if (
$config->enabled
&& $config->hasApiParams()
&& $config->syncKeycloakGroupsToHumhub()
) {
Yii::$app->queue->push(new GroupsUserSync(['userId' => $auth->user_id]));
}
}
}
/**
* @param Event $event
* @return void
*/
public static function onAccountProfileMenuInit(Event $event)
{
/** @var Module $module */
$module = Yii::$app->getModule('auth-keycloak');
if (!$module?->isEnabled) {
return;
}
$settings = $module->settings;
if (
Yii::$app->user->isGuest
|| !$settings->get('addChangePasswordFormToAccount')
) {
return;
}
$keycloakApi = new KeycloakApi();
if (
!$keycloakApi->isConnected()
|| $keycloakApi->getUserAuth(Yii::$app->user->id) === null
) {
return;
}
/** @var AccountProfileMenu $menu */
$menu = $event->sender;
$menu->addEntry(new MenuLink([
'label' => Yii::t('AuthKeycloakModule.base', 'Change password on {keycloakRealmDisplayName}', ['keycloakRealmDisplayName' => $keycloakApi->realm['displayName'] ?? '']),
'url' => ['/auth-keycloak/user/change-password'],
'sortOrder' => 410,
'isActive' => ControllerHelper::isActivePath('auth-keycloak', 'user', 'change-password'),
'isVisible' => true,
]));
}
}