in classes/loginflow/authcode.php [292:373]
protected function handlemigration($oidcuniqid, $authparams, $tokenparams, $idtoken, $connectiononly = false) {
global $USER, $DB, $CFG;
// Check if OIDC user is already connected to a Moodle user.
$tokenrec = $DB->get_record('auth_oidc_token', ['oidcuniqid' => $oidcuniqid]);
if (!empty($tokenrec)) {
$existinguserparams = ['username' => $tokenrec->username, 'mnethostid' => $CFG->mnet_localhost_id];
$existinguser = $DB->get_record('user', $existinguserparams);
if (empty($existinguser)) {
$DB->delete_records('auth_oidc_token', ['id' => $tokenrec->id]);
} else {
if ($USER->username === $tokenrec->username) {
// Already connected to current user.
if ($connectiononly !== true && $USER->auth !== 'oidc') {
// Update auth plugin.
$DB->update_record('user', (object)['id' => $USER->id, 'auth' => 'oidc']);
$USER = $DB->get_record('user', ['id' => $USER->id]);
$USER->auth = 'oidc';
}
$this->updatetoken($tokenrec->id, $authparams, $tokenparams);
return true;
} else {
// OIDC user connected to user that is not us. Can't continue.
throw new \moodle_exception('errorauthuserconnectedtodifferent', 'auth_oidc');
}
}
}
// Check if Moodle user is already connected to an OIDC user.
$tokenrec = $DB->get_record('auth_oidc_token', ['userid' => $USER->id]);
if (!empty($tokenrec)) {
if ($tokenrec->oidcuniqid === $oidcuniqid) {
// Already connected to current user.
if ($connectiononly !== true && $USER->auth !== 'oidc') {
// Update auth plugin.
$DB->update_record('user', (object)['id' => $USER->id, 'auth' => 'oidc']);
$USER = $DB->get_record('user', ['id' => $USER->id]);
$USER->auth = 'oidc';
}
$this->updatetoken($tokenrec->id, $authparams, $tokenparams);
return true;
} else {
throw new \moodle_exception('errorauthuseralreadyconnected', 'auth_oidc');
}
}
// Create token data.
$tokenrec = $this->createtoken($oidcuniqid, $USER->username, $authparams, $tokenparams, $idtoken, $USER->id);
$eventdata = [
'objectid' => $USER->id,
'userid' => $USER->id,
'other' => [
'username' => $USER->username,
'userid' => $USER->id,
'oidcuniqid' => $oidcuniqid,
],
];
$event = \auth_oidc\event\user_connected::create($eventdata);
$event->trigger();
// Switch auth method, if requested.
if ($connectiononly !== true) {
if ($USER->auth !== 'oidc') {
$DB->delete_records('auth_oidc_prevlogin', ['userid' => $USER->id]);
$userrec = $DB->get_record('user', ['id' => $USER->id]);
if (!empty($userrec)) {
$prevloginrec = [
'userid' => $userrec->id,
'method' => $userrec->auth,
'password' => $userrec->password,
];
$DB->insert_record('auth_oidc_prevlogin', $prevloginrec);
}
}
$DB->update_record('user', (object)['id' => $USER->id, 'auth' => 'oidc']);
$USER = $DB->get_record('user', ['id' => $USER->id]);
$USER->auth = 'oidc';
}
return true;
}