-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.php
More file actions
681 lines (569 loc) · 20.2 KB
/
Copy pathauth.php
File metadata and controls
681 lines (569 loc) · 20.2 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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
<?php
/**
* @author Mohammed Nassar
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
* @package moodle auth
*
* Authentication Plugin: PhpCAS Authentication only
*
*
* 2013-10-10 File created.
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
require_once($CFG->libdir.'/authlib.php'); //This library defines the auth_plugin_base class that is the basis for any new authentication module for moodle.
require_once($CFG->dirroot.'/auth/plaincas/include/CAS-1.3.2/CAS.php'); // Load the CAS lib
/**
* Plugin for no authentication.
*/
class auth_plugin_plaincas extends auth_plugin_base {
var $_userInfo = array();
/**
* Constructor.
*/
function auth_plugin_plaincas() {
$this->authtype = 'plaincas';
$this->roleauth = 'auth_plaincas';
$this->errorlogtag = '[AUTH PLAINCAS] ';
$this->pluginconfig = 'auth/'.$this->authtype;
$this->config = get_config($this->pluginconfig);
}
/**
* Returns true if the username and password work or don't exist and false
* if the user exists and the password is wrong.
*
* @param string $username The username
* @param string $password The password
* @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $DB;
//$this->CAS_connect();
return phpCAS::isAuthenticated() && (trim(textlib::strtolower(phpCAS::getUser())) == $username);
}
/**
* Returns true if this authentication plugin is 'internal'.
*
* @return bool
*/
function is_internal() {
return false;
}
/**
* Indicates if password hashes should be stored in local moodle database.
* @return bool
*/
function prevent_local_passwords() {
return true;
}
/**
* Returns true if this authentication plugin can change the user's
* password.
*
* @return bool
*/
function can_change_password() {
return false;
}
/**
* Returns true if plugin allows resetting of internal password.
*
* @return bool
*/
function can_signup() {
return false;
}
/**
* Returns true if plugin allows editing the profile.
*
* @return bool
*/
function can_edit_profile() {
return false;
}
/**
* Authentication choice (CAS or other)
*/
function loginpage_hook() {
//return false;
global $CFG, $DB, $USER, $SESSION, $OUTPUT, $PAGE, $frm;
$site = get_site();
$PlainCASform = get_string('PlainCASform', 'auth_plaincas');
$username = optional_param('username', '', PARAM_RAW);
if (!empty($username)) {
if (isset($SESSION->wantsurl) && (strstr($SESSION->wantsurl, 'ticket') ||
strstr($SESSION->wantsurl, 'manual'))) {
unset($SESSION->wantsurl);
}
return;
}
// Return if CAS enabled and settings not specified yet
if (empty($this->config->hostname)) {
return;
}
$this->CAS_connect();
if (phpCAS::checkAuthentication()) {
$frm->username = phpCAS::getUser();
$frm->password = 'passwdCas';
return;
}
if (isset($_GET['loginguest']) && ($_GET['loginguest'] == true)) {
$frm->username = 'guest';
$frm->password = 'guest';
return;
}
if ($this->config->multiauth) {
$authCAS = optional_param('authParam', '', PARAM_RAW);;
if ($authCAS == 'manual') {
return;
}
if ($authCAS != 'plaincas'){
$PAGE->set_url('/login/index.php');
$PAGE->navbar->add($PlainCASform);
$PAGE->set_title("$site->fullname: $PlainCASform");
$PAGE->set_heading($site->fullname);
echo $OUTPUT->header();
include($CFG->dirroot.'/auth/plaincas/plaincas_form.html');
echo $OUTPUT->footer();
exit();
}
}
$username = '';
if (!phpCAS::isAuthenticated()) {
// force CAS authentication
phpCAS::forceAuthentication();
$key = sesskey();
if (phpCAS::isAuthenticated() || phpCAS::checkAuthentication()){
$username = phpCAS::getUser();
$user = $this->isUserExistInMoodle($username);
if ($user) {
$user_array = $this->get_userinfo($username);
$user = authenticate_user_login($username, $key);
$USER = complete_user_login($user);
$urltogo = $CFG -> wwwroot . '/';
redirect($urltogo);
} else {//Moodle should create a new user entry in its DB
$user_array = $this->get_userinfo($username);
//Creating a new user account
$user = authenticate_user_login($username, $key);
$USER = complete_user_login($user);
$urltogo = $CFG -> wwwroot . '/';
redirect($urltogo);
}
add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID, $user->id, 0, $user->id);
} else {
return false;
}
} else {
return false;
}
}
/**
* Logout from the CAS
*
*/
function prelogout_hook() {
global $CFG;
if (!empty($this->config->logoutcas)) {
$backurl = $CFG->wwwroot;
$this->CAS_connect();
phpCAS::logoutWithRedirectService($backurl);
}
}
/**
* Connect to CAS
*/
function CAS_connect() {
global $CFG, $PHPCAS_CLIENT;
if (!is_object($PHPCAS_CLIENT)) {
// Uncomment to enable debugging
phpCAS::setDebug();
// Make sure phpCAS doesn't try to start a new PHP session when connecting to the CAS server.
// Initialize phpCAS
phpCAS::client($this->config->casversion, $this->config->hostname, (int) $this->config->port, $this->config->baseuri, true);
// For quick testing you can disable SSL validation of the CAS server.
if($this->config->certificate_check && $this->config->certificate_path){
phpCAS::setCasServerCACert($this->config->certificate_path);
}else{
// Don't try to validate the server SSL credentials
phpCAS::setNoCasServerValidation();
}
return true;
} else {
return false;
}
}
/**
* Prints a form for configuring this authentication plugin.
*
* This function is called from admin/auth.php, and outputs a full page with
* a form for configuring this plugin.
*
* @param array $page An object containing all the data for this page.
*/
function config_form($config, $err, $user_fields) {
global $CFG;
include($CFG->dirroot.'/auth/plaincas/config.html');
}
/**
* A chance to validate form data, and last chance to
* do stuff before it is inserted in config_plugin
* @param object object with submitted configuration settings (without system magic quotes)
* @param array $err array of error messages
*/
function validate_form($form, &$err) {
$certificate_path = trim($form->certificate_path);
if ($form->certificate_check && empty($certificate_path)) {
$err['certificate_path'] = get_string('auth_plaincas_certificate_path_empty', 'auth_plaincas');
}
}
/**
* Processes and stores configuration data for this authentication plugin.
*/
function process_config($config) {
// CAS settings
if (!isset($config->hostname)) {
$config->hostname = '';
}
if (!isset($config->port)) {
$config->port = '';
}
if (!isset($config->casversion)) {
$config->casversion = '';
}
if (!isset($config->baseuri)) {
$config->baseuri = '';
}
if (!isset($config->logoutcas)) {
$config->logoutcas = '';
}
if (!isset($config->multiauth)) {
$config->multiauth = '';
}
if (!isset($config->certificate_check)) {
$config->certificate_check = '';
}
if (!isset($config->certificate_path)) {
$config->certificate_path = '';
}
if (!isset($config->logout_return_url)) {
$config->logout_return_url = '';
}
if (!isset($config->roles_attribute)) {
$config->roles_attribute = '';
}
// CAS Roles settings
$roles = get_all_roles();
if($roles){
foreach($roles as $role){
$fieldName = "cas_role_".$role->id;
if (!isset($config->$fieldName)) {
$config->$fieldName = '';
}
}
}
// save CAS settings
set_config('hostname', trim($config->hostname), $this->pluginconfig);
set_config('port', trim($config->port), $this->pluginconfig);
set_config('casversion', $config->casversion, $this->pluginconfig);
set_config('baseuri', trim($config->baseuri), $this->pluginconfig);
set_config('logoutcas', $config->logoutcas, $this->pluginconfig);
set_config('multiauth', $config->multiauth, $this->pluginconfig);
set_config('certificate_check', $config->certificate_check, $this->pluginconfig);
set_config('certificate_path', $config->certificate_path, $this->pluginconfig);
set_config('logout_return_url', $config->logout_return_url, $this->pluginconfig);
set_config('roles_attribute', $config->roles_attribute, $this->pluginconfig);
if($roles){
foreach($roles as $role){
$fieldName = "cas_role_".$role->id;
set_config($fieldName, trim($config->$fieldName), $this->pluginconfig);
}
}
return true;
}
/**
* Reads user information from CAS and returns it in array()
*
* Function should return all information available. If you are saving
* this information to moodle user-table you should honor syncronization flags
*
* @param string $username username
*
* @return mixed array with no magic quotes or false on error
*/
function get_userinfo($username) {
if (empty($this->config->hostname)) {
return array();
}
$userinfo = array();
$user_att = phpCAS::getAttributes();
// Check whether we have got all the essential attributes (first name, last name, email)
/*if ( empty() || empty() || empty() ) {
print_error();
}*/
$attrmap = $this->get_attributes();
foreach ($attrmap as $key=>$value) {
// Check if attribute is present
if (!isset($user_att[$value])){
$userinfo[$key] = '';
continue;
}
// Make usename lowercase
if ($key == 'username'){
$userinfo[$key] = strtolower($this->get_first_string($user_att[$value]));
} else {
$userinfo[$key] = $this->get_first_string($user_att[$value]);
}
}
return $userinfo;
}
/**
* Checks if user exists on Moodle
*
* @param string $username
*/
function isUserExistInMoodle($username) {
global $CFG, $DB;
$user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
return $user;
}
/**
* Returns array containg attribute mappings between Moodle and CAS.
*
* @return array
*/
function get_attributes() {
$configarray = (array) $this->config;
$moodleattributes = array();
foreach ($this->userfields as $field) {
if (isset($configarray["field_map_$field"])) {
$moodleattributes[$field] = $configarray["field_map_$field"];
}
}
$moodleattributes['username'] = $configarray["user_attribute"];
return $moodleattributes;
}
/**
* Cleans and returns first of potential many values (multi-valued attributes)
*
* @param string $string Possibly multi-valued attribute from CAS
*/
function get_first_string($string) {
$list = explode( ';', $string);
$clean_string = rtrim($list[0]);
return $clean_string;
}
/**
* Reads user information from CAS and returns it in an object
*
* @param string $username username (with system magic quotes)
* @return mixed object or false on error
*/
function getUserInfoAsObj($user_array) {
if ($user_array == false) {
return false; //error or not found
}
$user = new stdClass();
$user->username = $user_array['username'];
$user->email = $user_array['mail'];
$user->auth = $this->authtype;
$user->firstname = $user_array['first'];
$user->lastname = $user_array['last'];
// Prep a few params
//$user->modified = time();
$user->confirmed = 1;
$user->mnethostid = $CFG->mnet_localhost_id;
return $user;
}
/**
* Syncronizes user from CAS to moodle user table
*
* Sync is now using username attribute.
*
* @param bool $do_updates will do pull in data updates from CAS if relevant
*/
function sync_users($do_updates=true) {
global $DB;
//$id = $DB->insert_record('user', $this->_userInfo);
}
function update_user_record($username) {
global $DB;
/*$user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id));
$userid = $user->id;
$DB->set_field('user', 'email', 'myemail@mydomain.net', array('id'=>$userid));
return $DB->get_record('user', array('id'=>$userid, 'deleted'=>0));*/
}
/**
* Sync roles for this user
*
* @param $user object user object
*/
function sync_roles($user) {
global $USER;
$systemcontext = context_system::instance();
$existUserRoles = array($this->getUserRoles($USER->id));//Get the user's role in Moodle
$this->_setCASGroups ();
$CAS_roles_IDs = $this->getRolesIDs($this->_userInfo['tmp_roles']);
//Get just the ids for user's moodle roles
$moodleTempRoles = array();
foreach ($existUserRoles as $value) {
array_push($moodleTempRoles, $value->roleid);
}
$inMoodleNotInCAS = array_diff($moodleTempRoles, $CAS_roles_IDs);
$inCASNotInMoodle = array_diff($CAS_roles_IDs, $moodleTempRoles);
foreach ($inMoodleNotInCAS as $key => $value) {
// role_unassign((int)$value, $user->id, $systemcontext->id, $this->roleauth);//@TODO: still do not unassign the roles
//@TODO: Check for the context
}
foreach ($inCASNotInMoodle as $key => $value) {
role_assign((int)$value, $user->id, $systemcontext->id, $this->roleauth, $itemid = 0, $timemodified = '');
}
}
function getRolesIDs($rolesNames) {
$rolesIDs = array();
foreach ($this->_userInfo['tmp_roles'] as $key => $value) {
$role_id = substr($value, 9, 1);
array_push($rolesIDs, $role_id);
}
return $rolesIDs;
}
/**
*
*
* @author Fabian Bircher
*/
function _setCASGroups () {
if( phpCAS::checkAuthentication() ) {
//$attributes = $this->get_role_attributes(phpCAS::getAttributes());
$attributes = $this->assembledRoles();
if (!is_array($attributes)) {
$attributes = array($attributes);
}
$patterns = $this->get_role_patterns();
if (!empty($patterns)) {
foreach ($patterns as $role => $pattern) {
foreach ($attributes as $attribute) {
// An invalid pattern will generate a php warning and will not be considered.
if (preg_match($pattern, $attribute)) {
$this->_addUserRole($role);
}
}
}
}
else {
foreach ($attributes as $attribute) {
// Add all attributes as groups
$this->_addUserRole($attribute);
}
}
}
}
/**
*
*
* @author Fabian Bircher
*/
/*function get_role_attributes( $attributes ){
if (is_array($attributes['roles'])) {
return $attributes['roles'];
} else {
return array($attributes['roles']);
}
}*/
function get_role_patterns() {
$rolePatterns = array();
foreach ($this->config as $key => $value) {
if(preg_match('/^cas_role_[0-9]*$/', $key)) {
$rolePatterns[$key] = $value;
}
}
return $rolePatterns;
}
/**
*
*
* @author Fabian Bircher
*/
function _addUserRole ($roleName) {
if (! isset($this->_userInfo['tmp_roles'])) {
$this->_userInfo['tmp_roles'] = array();
}
if( !in_array(trim($roleName), $this->_userInfo['tmp_roles'])) {
$this->_userInfo['tmp_roles'][] = trim($roleName);
}
}
/**
* return user role
*/
function getUserRoles($userid) {
$context = get_context_instance (CONTEXT_SYSTEM);
$roles = get_user_roles($context, $userid, true);
return $roles;
}
/**
* Scan and Return attributes for the roles in an array
*/
function scanRolesAttributes () {
$att_roles = $this->config->roles_attribute;
if(isset($att_roles)){
preg_match_all("/\[(.*)\]/U", $att_roles, $attArray);
return $attArray;
}
}
/*
* Return the required attributes for the roles from CAS
*/
function getRolesRequiredAttrs() {
$requiredRolesAttr = array();
$scanRolesAttr = $this->scanRolesAttributes();
foreach($scanRolesAttr[1] as $key => $value){//"sc"
$tmp = phpCAS::getAttributes();
foreach ($scanRolesAttr[0] as $sytakyKey => $sytakyValue) {//"[sc]"
if($key == $sytakyKey) {
if (isset($tmp[$value])) {
$tmp = $tmp[$value];
}
$requiredRolesAttr[$sytakyValue] = $tmp;
}
}
}
return $requiredRolesAttr;
}
/*
* Assemble the roles and return the assembled roles
*/
function assembledRoles() {
$roleAttrArr = array($this->config->roles_attribute);
$requiredRolesAttr = $this->getRolesRequiredAttrs();
foreach ($requiredRolesAttr as $sytakyKey => $AttrValue) {
foreach ($roleAttrArr as $key => $roleAttrValue) {
$new_role = array();
if (!is_array($AttrValue)) {
$new_role[] = str_replace($sytakyKey, $AttrValue, $roleAttrValue);
} else {
foreach ($AttrValue as $AttrValue) {
$new_role[] = str_replace($sytakyKey, $AttrValue, $roleAttrValue);
}
}
unset($roleAttrArr[$key]);
$roleAttrArr = array_merge($roleAttrArr, $new_role);
}
}
return $roleAttrArr;
}
/**
* Hook for logout page
*/
function logoutpage_hook() {
global $USER, $redirect;
// Only do this if the user is actually logged in via CAS
if ($USER->auth === $this->authtype) {
// Check if there is an alternative logout return url defined
if (isset($this->config->logout_return_url) && !empty($this->config->logout_return_url)) {
// Set redirect to alternative return url
$redirect = $this->config->logout_return_url;
}
}
}
}