-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCASAuthenticator.php
More file actions
657 lines (579 loc) · 23.7 KB
/
CASAuthenticator.php
File metadata and controls
657 lines (579 loc) · 23.7 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
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
<?php
namespace YaleREDCap\CASAuthenticator;
/**
* @property \ExternalModules\Framework $framework
* @see Framework
*/
class CASAuthenticator extends \ExternalModules\AbstractExternalModule
{
public function redcap_every_page_top($project_id)
{
$page = defined('PAGE') ? PAGE : null;
if ( empty($page) ) {
return;
}
// If we're on the EM Manager page, add a little CSS to make the
// setting descriptives wider in the project settings
if ( $page === 'manager/project.php' ) {
echo "<style>label:has(.cas-descriptive){width:100%;}</style>";
return;
}
if ( $page !== 'surveys/index.php' ) {
return;
}
// Note: This handles the survey condition as well, since it shares the same $page
$initialized = $this->initializeCas();
if ( $initialized === false ) {
$this->casLog('CAS Authenticator: Error initializing CAS');
$this->framework->exitAfterHook();
return;
}
$dashboard_hash = filter_input(INPUT_GET, '__dashboard', FILTER_SANITIZE_STRING);
$report_hash = filter_input(INPUT_GET, '__report', FILTER_SANITIZE_STRING);
$file_hash = filter_input(INPUT_GET, '__file', FILTER_SANITIZE_STRING);
if ( isset($dashboard_hash) ) {
$this->handleDashboard($dashboard_hash);
} elseif ( isset($report_hash) ) {
$this->handleReport($report_hash);
} elseif ( isset($file_hash) ) {
$this->handleFile($file_hash);
}
}
public function redcap_survey_page_top(
$project_id,
$record,
$instrument,
$event_id,
$group_id,
$survey_hash,
$response_id,
$repeat_instance
) {
$projectSettings = $this->framework->getProjectSettings();
foreach ( $projectSettings["survey"] as $index => $surveyName ) {
if ( $projectSettings["event"][$index] !== null && $projectSettings["event"][$index] !== $event_id ) {
continue;
}
if ( $projectSettings["survey"][$index] !== $instrument ) {
continue;
}
$surveyPage = filter_input(INPUT_GET, '__page__', FILTER_SANITIZE_NUMBER_INT);
$this->framework->log('CAS Authenticator: Handling Survey', [
"instrument" => $instrument,
"event_id" => $event_id,
"survey page" => $surveyPage
]);
try {
$id = $this->authenticate();
} catch ( \CAS_GracefullTerminationException $e ) {
if ( $e->getCode() !== 0 ) {
$this->framework->log('CAS Authenticator: Error getting code', [ 'error' => $e->getMessage() ]);
}
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error', [ 'error' => $e->getMessage() ]);
} finally {
if ( $id === false || empty($id) ) {
$this->framework->exitAfterHook();
return;
}
// Successful authentication
if ( $surveyPage === 1 || empty($surveyPage) ) {
$this->casLog('CAS Authenticator: Survey Auth Succeeded', [
"CASAuthenticator_NetId" => $id,
"instrument" => $instrument,
"event_id" => $event_id,
"response_id" => $response_id
]);
} else {
$this->framework->log('CAS Authenticator: Survey Auth Succeeded', [
"CASAuthenticator_NetId" => $id,
"instrument" => $instrument,
"event_id" => $event_id,
"response_id" => $response_id,
"survey_page" => $surveyPage
]);
}
$field = $projectSettings["id-field"][$index];
if ( $field !== null ) {
?>
<script>
const ready = fn => document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn);
ready(function () {
field = $(`input[name="<?= $field ?>"]`);
id = "<?= $id ?>";
if (field.length) {
field.val(id);
field.closest('tr').addClass('@READONLY');
}
});
</script>
<?php
}
return;
}
}
}
public function redcap_module_configuration_settings($project_id, $settings)
{
if ( empty($project_id) ) {
return $settings;
}
try {
$surveys = $this->getSurveys($project_id);
$reports = $this->getReports($project_id);
$dashboards = $this->getDashboards($project_id);
$files = $this->getFiles($project_id);
$folders = $this->getFolders($project_id);
foreach ( $settings as &$settingRow ) {
$this->getChoices($settingRow, [
"surveys" => $surveys,
"reports" => $reports,
"dashboards" => $dashboards,
"files" => $files,
"folders" => $folders
]);
if ( $settingRow['type'] == 'sub_settings' ) {
foreach ( $settingRow['sub_settings'] as &$subSettingRow ) {
$this->getChoices($subSettingRow, [
"surveys" => $surveys,
"reports" => $reports,
"dashboards" => $dashboards,
"files" => $files,
"folders" => $folders
]);
}
}
}
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error getting choices', [ 'error' => $e->getMessage() ]);
} finally {
return $settings;
}
}
private function getChoices(&$row, $data)
{
if ( $row['key'] == 'survey' ) {
$row['choices'] = $data['surveys'];
} elseif ( $row['key'] == 'dashboard' ) {
$row['choices'] = $data['dashboards'];
} elseif ( $row['key'] == 'report' ) {
$row['choices'] = $data['reports'];
} elseif ($row['key'] == 'file' ) {
$row['choices'] = $data['files'];
} elseif ($row['key'] == 'folder' ) {
$row['choices'] = $data['folders'];
}
}
private function handleDashboard($dashboard_hash)
{
$projectSettings = $this->framework->getProjectSettings();
$dashboard = $this->getDashboardFromHash($dashboard_hash);
if ( $dashboard === null ) {
$this->framework->log('CAS Authenticator: Dashboard not found', [ 'dashboard_hash' => $dashboard_hash ]);
return;
}
foreach ( $projectSettings["dashboard"] as $thisDashId ) {
if ( $dashboard['dash_id'] != $thisDashId ) {
continue;
}
$this->framework->log('CAS Authenticator: Handling Dashboard', [
"dashboard_hash" => $dashboard_hash,
"dashboard_id" => $dashboard['dash_id'],
"dashboard" => $dashboard['title']
]);
try {
$id = $this->authenticate();
} catch ( \CAS_GracefullTerminationException $e ) {
if ( $e->getCode() !== 0 ) {
$this->framework->log('CAS Authenticator: Error getting code', [ 'error' => $e->getMessage() ]);
}
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error', [ 'error' => $e->getMessage() ]);
} finally {
if ( $id === false || empty($id) ) {
$this->framework->exitAfterHook();
return;
}
// Successful authentication
$this->casLog('CAS Authenticator: Dashboard Auth Succeeded', [
"CASAuthenticator_NetId" => $id,
"dashboard_hash" => $dashboard_hash,
"dashboard_id" => $dashboard['dash_id'],
"dashboard" => $dashboard['title']
]);
}
}
}
private function handleReport($report_hash)
{
$projectSettings = $this->framework->getProjectSettings();
$report = $this->getReportFromHash($report_hash);
if ( $report === null ) {
$this->framework->log('CAS Authenticator: Report not found', [ 'report_hash' => $report_hash ]);
return;
}
foreach ( $projectSettings["report"] as $thisReportId ) {
if ( $report['report_id'] != $thisReportId ) {
continue;
}
$this->framework->log('CAS Authenticator: Handling Report', [
"report_hash" => $report_hash,
"report_id" => $report['report_id'],
"report" => $report['title']
]);
try {
$id = $this->authenticate();
} catch ( \CAS_GracefullTerminationException $e ) {
if ( $e->getCode() !== 0 ) {
$this->framework->log('CAS Authenticator: Error getting code', [ 'error' => $e->getMessage() ]);
}
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error', [ 'error' => $e->getMessage() ]);
} finally {
if ( $id === false || empty($id) ) {
$this->framework->exitAfterHook();
return;
}
// Successful authentication
$this->casLog('CAS Authenticator: Report Auth Succeeded', [
"CASAuthenticator_NetId" => $id,
"report_hash" => $report_hash,
"report_id" => $report['report_id'],
"report" => $report['title']
]);
}
}
}
private function handleFile ($file_hash) {
$projectSettings = $this->framework->getProjectSettings();
$file = $this->getFileFromHash($file_hash);
if ( $file === null ) {
$this->framework->log('CAS Authenticator: File not found', [ 'file_hash' => $file_hash ]);
return;
}
// First check if this file individually should be CAS'd
$matched = false;
foreach ( $projectSettings["file"] as $thisDocsId ) {
if ($file['docs_id'] == $thisDocsId) {
$matched = true;
break;
}
}
// Check if the file is in a folder that should be CAS'd
if ($matched === false && $file['folder_id'] !== null) {
foreach ($projectSettings['folder'] as $thisFolderId) {
$allFolderIds = $this->getAllFolderIds($file['folder_id']);
if (in_array($thisFolderId, $allFolderIds)) {
$matched = true;
break;
}
}
}
if ($matched === false) {
return;
}
try {
$id = $this->authenticate();
} catch ( \CAS_GracefullTerminationException $e ) {
if ( $e->getCode() !== 0 ) {
$this->framework->log('CAS Authenticator: Error getting code', [ 'error' => $e->getMessage() ]);
}
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error', [ 'error' => $e->getMessage() ]);
} finally {
if ( $id === false || empty($id) ) {
$this->framework->exitAfterHook();
return;
}
// Successful authentication
$this->casLog('CAS Authenticator: File Auth Succeeded', [
"CASAuthenticator_NetId" => $id,
"file_hash" => $file_hash,
"docs_id" => $file['docs_id'],
"filename" => $file['docs_name']
]);
}
}
private function getFileFromHash($hash) {
$sql = "SELECT rds.docs_id, rdff.folder_id, rd.docs_name
FROM redcap_docs_share rds
LEFT JOIN redcap_docs_folders_files rdff
ON rds.docs_id = rdff.docs_id
LEFT JOIN redcap_docs rd
ON rds.docs_id = rd.docs_id
WHERE rds.hash = ?";
$result = $this->framework->query($sql, [ $hash ]);
return $this->framework->escape($result->fetch_assoc());
}
/**
* Get all parent folder IDs for a given folder ID (including self)
* @param mixed $folder_id
* @return array folder IDs
*/
private function getAllFolderIds($folder_id) {
if (empty($folder_id)) {
return [];
}
$folders = [$folder_id];
$nextFolderId = $this->getParentFolderId($folder_id);
while ($nextFolderId !== null) {
$folders[] = $nextFolderId;
$nextFolderId = $this->getParentFolderId($nextFolderId);
}
return $folders;
}
private function getParentFolderId($folder_id) {
if (empty($folder_id)) {
return null;
}
$sql = "SELECT parent_folder_id
FROM redcap_docs_folders
WHERE folder_id = ?";
$result = $this->framework->query($sql, [ $folder_id ]);
$row = $result->fetch_assoc();
if (empty($row)) {
return null;
}
return $row['parent_folder_id'];
}
private function getDashboardFromHash($dashboard_hash)
{
$project_id = $this->framework->getProjectId();
$sql = 'SELECT dash_id, title, hash FROM redcap_project_dashboards WHERE hash = ? AND project_id = ?';
$result = $this->framework->query($sql, [ $dashboard_hash, $project_id ]);
return $this->framework->escape($result->fetch_assoc());
}
private function getReportFromHash($report_hash)
{
$project_id = $this->framework->getProjectId();
$sql = 'SELECT report_id, title, hash FROM redcap_reports WHERE hash = ? AND project_id = ?';
$result = $this->query($sql, [ $report_hash, $project_id ]);
return $this->framework->escape($result->fetch_assoc());
}
private function getSurveys($pid)
{
$forms = [];
$surveys = [];
$formsSql = "SELECT DISTINCT form_name
FROM redcap_metadata
WHERE project_id = ?
ORDER BY form_name";
$formsResult = $this->framework->query($formsSql, [ $pid ]);
while ($formsRow = $formsResult->fetch_assoc()) {
$forms[] = $formsRow['form_name'];
}
$surveysSql = "SELECT form_name
FROM redcap_surveys
WHERE project_id = ?
ORDER BY form_name";
$surveysResult = self::query($surveysSql, [ $pid ]);
while ( $surveysRow = $surveysResult->fetch_assoc() ) {
if ( !in_array($surveysRow['form_name'], $forms) ) {
continue;
}
$surveysRow = static::escape($surveysRow);
$surveys[] = [ 'value' => $surveysRow['form_name'], 'name' => strip_tags(nl2br($surveysRow['form_name'])) ];
}
return $surveys;
}
private function getDashboards($pid)
{
$dashboards = [];
$sql = "SELECT dash_id, title
FROM redcap_project_dashboards
WHERE project_id = ?
AND is_public = 1
ORDER BY dash_id";
$result = self::query($sql, [ $pid ]);
while ( $row = $result->fetch_assoc() ) {
$row = static::escape($row);
$dashboards[] = [ 'value' => $row['dash_id'], 'name' => strip_tags(nl2br($row['title'])) ];
}
return $dashboards;
}
private function getReports($pid)
{
$reports = [];
$sql = "SELECT report_id,title
FROM redcap_reports
WHERE project_id = ?
AND is_public = 1
ORDER BY report_id";
$result = self::query($sql, [ $pid ]);
while ( $row = $result->fetch_assoc() ) {
$row = static::escape($row);
$reports[] = [ 'value' => $row['report_id'], 'name' => strip_tags(nl2br($row['title'])) ];
}
return $reports;
}
private function getFiles($pid) {
$files = [];
$sql = "SELECT docs_id, docs_name
FROM redcap_docs
WHERE project_id = ?";
$result = $this->framework->query($sql, [ $pid ]);
while ( $row = $result->fetch_assoc() ) {
$row = $this->framework->escape($row);
$files[] = [ 'value' => $row['docs_id'], 'name' => strip_tags(nl2br($row['docs_name'])) ];
}
return $files;
}
private function getFolders($pid) {
$folders = [];
$sql = "SELECT folder_id, name
FROM redcap_docs_folders
WHERE project_id = ?";
$result = $this->framework->query($sql, [ $pid ]);
while ( $row = $result->fetch_assoc() ) {
$row = $this->framework->escape($row);
$folders[] = [ 'value' => $row['folder_id'], 'name' => strip_tags(nl2br($row['name'])) ];
}
return $folders;
}
private function initializeCas()
{
try {
require_once __DIR__ . '/vendor/autoload.php';
$cas_host = $this->getSystemSetting("cas-host");
$cas_context = $this->getSystemSetting("cas-context");
$cas_port = (int) $this->getSystemSetting("cas-port");
$cas_server_ca_cert_id = $this->getSystemSetting("cas-server-ca-cert-pem");
$cas_server_ca_cert_path = empty($cas_server_ca_cert_id) ? $this->getSafePath('cacert.pem') : $this->getFile($cas_server_ca_cert_id);
$server_force_https = $this->getSystemSetting("server-force-https");
$service_base_url = (SSL ? "https" : "http") . "://" . SERVER_NAME;
// Enable https fix
if ( $server_force_https == 1 ) {
$_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https';
$_SERVER['HTTP_X_FORWARDED_PORT'] = 443;
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_PORT'] = 443;
}
// Initialize phpCAS
\phpCAS::client(CAS_VERSION_2_0, $cas_host, $cas_port, $cas_context, $service_base_url, false);
// Set the CA certificate that is the issuer of the cert
// on the CAS server
\phpCAS::setCasServerCACert($cas_server_ca_cert_path);
// Don't exit, let me handle instead
\CAS_GracefullTerminationException::throwInsteadOfExiting();
return true;
} catch ( \Throwable $e ) {
$this->log('CAS Authenticator: Error initializing CAS', [ 'error' => $e->getMessage() ]);
return false;
}
}
/**
* Initiate CAS authentication
*
*
* @return string|boolean username of authenticated user (false if not authenticated)
*/
private function authenticate()
{
try {
// force CAS authentication
\phpCAS::forceAuthentication();
// Return authenticated username
return \phpCAS::getUser();
} catch ( \CAS_GracefullTerminationException $e ) {
if ( $e->getCode() !== 0 ) {
$this->framework->log('CAS Authenticator: Error getting code', [ 'error' => $e->getMessage() ]);
}
return false;
} catch ( \Throwable $e ) {
$this->framework->log('CAS Authenticator: Error authenticating', [ 'error' => json_encode($e, JSON_PRETTY_PRINT) ]);
return false;
}
}
/**
* Get url to file with provided edoc ID.
*
* @param string $edocId ID of the file to find
*
* @return string path to file in edoc folder
*/
private function getFile(string $edocId)
{
$filePath = "";
if ( $edocId === null ) {
return $filePath;
}
$result = $this->query('SELECT stored_name FROM redcap_edocs_metadata WHERE doc_id = ?', $edocId);
$filename = $result->fetch_assoc()["stored_name"];
if ( defined('EDOC_PATH') ) {
$filePath = $this->framework->getSafePath(EDOC_PATH . $filename, EDOC_PATH);
}
return $filePath;
}
/**
* Make sure settings meet certain conditions.
*
* This is called when a user clicks "Save" in either system or project
* configuration.
*
* @param mixed $settings Array of settings user is trying to set
*
* @return string|null if not null, the error message to show to user
*/
public function validateSettings($settings)
{
if ( empty($this->framework->getProjectId()) ) {
return;
}
// project-level settings
if ( count($settings["survey"]) > 0 ) {
foreach ( $settings["survey"] as $i => $form ) {
if ( empty($form) ) {
continue;
}
$id_field = $settings["id-field"][$i];
$project_id = $this->getProjectId();
// form must be a survey
$surveyResult = $this->query(
'SELECT survey_id FROM redcap_surveys
WHERE project_id = ?
AND form_name = ?',
[ $project_id, $form ]
);
if ( $surveyResult->num_rows < 1 ) {
return "The selected form ($form) is not enabled as a survey.";
}
if ( !$id_field ) {
continue;
}
// id_field must be a text input on that survey
$fieldResult = $this->query(
'SELECT element_type FROM redcap_metadata
WHERE project_id = ?
AND form_name = ?
AND field_name = ?',
[ $project_id, $form, $id_field ]
);
if ( $fieldResult->num_rows < 1 ) {
return "The selected id field ($id_field) is not on the selected survey ($form).";
}
$row = $fieldResult->fetch_assoc();
if ( $row["element_type"] !== "text" ) {
return "The selected id field ($id_field) is not a text input field.";
}
}
}
}
private function casLog($message, $params = [], $record = null, $event = null)
{
$doProjectLogging = $this->getProjectSetting('logging');
if ( $doProjectLogging ) {
$changes = "";
foreach ( $params as $label => $value ) {
$changes .= $label . ": " . $value . "\n";
}
\REDCap::logEvent(
$message,
$changes,
null,
$record,
$event
);
}
$this->framework->log($message, $params);
}
}