Skip to content

Commit

Permalink
SPR: alterações auth db
Browse files Browse the repository at this point in the history
  • Loading branch information
danielneis committed Sep 18, 2023
1 parent d1bc949 commit 40d62c1
Show file tree
Hide file tree
Showing 6 changed files with 230 additions and 14 deletions.
83 changes: 70 additions & 13 deletions auth/db/auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,13 @@ function user_login($username, $password) {
}
}

$authdb = $this->db_init();
$authdb = $this->localdb_init();

$rs = $authdb->Execute("SELECT *
FROM {$this->config->table}
FROM usuarios
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
var_dump("SELECT *
FROM usuarios
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
if (!$rs) {
$authdb->Close();
Expand All @@ -109,10 +112,10 @@ function user_login($username, $password) {
} else {
// Normal case: use external db for both usernames and passwords.

$authdb = $this->db_init();
$authdb = $this->localdb_init();

$rs = $authdb->Execute("SELECT {$this->config->fieldpass}
FROM {$this->config->table}
FROM usuarios
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
if (!$rs) {
$authdb->Close();
Expand Down Expand Up @@ -171,6 +174,29 @@ function db_init() {
return $authdb;
}

/**
* Connect to local database.
*
* @return ADOConnection
* @throws moodle_exception
*/
function localdb_init() {
if ($this->is_configured() === false) {
throw new moodle_exception('auth_dbcantconnect', 'auth_db');
}

// Connect to the external database (forcing new connection).
$localdb = ADONewConnection('mysqli');
if (!empty($this->config->debugauthdb)) {
$localdb->debug = true;
ob_start(); //Start output buffer to allow later use of the page headers.
}
$localdb->Connect('localhost', 'mdlexterno', 'senhadobancoexterno', 'banco_externo', true);
$localdb->SetFetchMode(ADODB_FETCH_ASSOC);

return $localdb;
}

/**
* Returns user attribute mappings between moodle and the external database.
*
Expand Down Expand Up @@ -207,7 +233,7 @@ function get_userinfo($username) {

$extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);

$authdb = $this->db_init();
$authdb = $this->localdb_init();

// Array to map local fieldnames we want, to external fieldnames.
$selectfields = $this->db_attributes();
Expand All @@ -225,7 +251,7 @@ function get_userinfo($username) {
}
$select = implode(', ', $select);
$sql = "SELECT $select
FROM {$this->config->table}
FROM usuarios
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'";

if ($rs = $authdb->Execute($sql)) {
Expand Down Expand Up @@ -294,7 +320,11 @@ function sync_users(progress_trace $trace, $do_updates=false) {
require_once($CFG->dirroot . '/user/lib.php');

// List external users.
$userlist = $this->get_userlist();
try {
$userlist = $this->get_userlist();
} catch (\Exception $e) {
var_dump($e);die();
}

// Delete obsolete internal users.
if (!empty($this->config->removeuser)) {
Expand Down Expand Up @@ -495,10 +525,10 @@ function user_exists($username) {

$extusername = core_text::convert($username, 'utf-8', $this->config->extencoding);

$authdb = $this->db_init();
$authdb = $this->localdb_init();

$rs = $authdb->Execute("SELECT *
FROM {$this->config->table}
FROM usuarios
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");

if (!$rs) {
Expand All @@ -518,11 +548,11 @@ function get_userlist() {
// Init result value.
$result = array();

$authdb = $this->db_init();
$authdb = $this->localdb_init();

// Fetch userlist.
$rs = $authdb->Execute("SELECT {$this->config->fielduser}
FROM {$this->config->table} ");
FROM usuarios ");

if (!$rs) {
throw new \moodle_exception('auth_dbcantconnect', 'auth_db');
Expand Down Expand Up @@ -580,7 +610,7 @@ function user_update($olduser, $newuser) {

$extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding);

$authdb = $this->db_init();
$authdb = $this->localdb_init();

$update = array();
foreach($curruser as $key=>$value) {
Expand All @@ -603,7 +633,7 @@ function user_update($olduser, $newuser) {
}
}
if (!empty($update)) {
$sql = "UPDATE {$this->config->table}
$sql = "UPDATE usuarios
SET ".implode(',', $update)."
WHERE {$this->config->fielduser} = ?";
if (!$authdb->Execute($sql, array($this->ext_addslashes($extusername)))) {
Expand Down Expand Up @@ -787,4 +817,31 @@ public function clean_data($user) {
DEBUG_DEVELOPER);
return core_user::clean_data($user);
}

function sync_spr(progress_trace $trace, $do_updates=false) {

$authdb = $this->db_init();
// Fetch userlist.
$trace->output('Conectado. ' . time());
$rs = $authdb->Execute("SELECT nome, sobrenome, cpf, email
FROM {$this->config->table}");
$trace->output('Select realizado no banco externo. ' . time());

if (!$rs) {
throw new \moodle_exception('auth_dbcantconnect', 'auth_db');
} else {
$localdb = $this->localdb_init();

$localdb->Execute('DELETE FROM usuarios');
while ($rec = $rs->FetchRow()) {
$rec = array_change_key_case((array)$rec, CASE_LOWER);
$localdb->Execute('INSERT INTO banco_externo.usuarios
(nome, sobrenome, cpf, email)
VALUES (?, ?, ?, ?)', array_values($rec));
}
$trace->output('Inserts feitos no banco local. ' . time());
$localdb->Close();
$authdb->Close();
}
}
}
52 changes: 52 additions & 0 deletions auth/db/classes/task/sync_spr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.

namespace auth_db\task;

defined('MOODLE_INTERNAL') || die();

/**
* Sync SPR task class
* @package auth_db
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class sync_spr extends \core\task\scheduled_task {

/**
* Name for this task.
*
* @return string
*/
public function get_name() {
return get_string('auth_dbsyncsprtask', 'auth_db');
}

/**
* Run task for synchronising users.
*/
public function execute() {
if (!is_enabled_auth('db')) {
mtrace('auth_db plugin is disabled, synchronisation stopped', 2);
return;
}

$dbauth = get_auth_plugin('db');
$config = get_config('auth_db');
$trace = new \text_progress_trace();
$update = !empty($config->updateusers);
$dbauth->sync_spr($trace, $update);
}
}
96 changes: 96 additions & 0 deletions auth/db/cli/sync_spr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Extdb user sync script.
*
* This script is meant to be called from a system cronjob to
* sync moodle user accounts with external database.
* It is required when using internal passwords (== passwords not defined in external database).
*
* Sample cron entry:
* # 5 minutes past 4am
* 5 4 * * * sudo -u www-data /usr/bin/php /var/www/moodle/auth/db/cli/sync_spr.php
*
* Notes:
* - it is required to use the web server account when executing PHP CLI scripts
* - you need to change the "www-data" to match the apache user account
* - use "su" if "sudo" not available
* - If you have a large number of users, you may want to raise the memory limits
* by passing -d memory_limit=256M
* - For debugging & better logging, you are encouraged to use in the command line:
* -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
*
* Performance notes:
* + The code is simpler, but not as optimized as its LDAP counterpart.
*
* @package auth_db
* @copyright 2006 Martin Langhoff
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

define('CLI_SCRIPT', true);

require(__DIR__.'/../../../config.php');
require_once("$CFG->libdir/clilib.php");

// Now get cli options.
list($options, $unrecognized) = cli_get_params(array('noupdate'=>false, 'verbose'=>false, 'help'=>false), array('n'=>'noupdate', 'v'=>'verbose', 'h'=>'help'));

if ($unrecognized) {
$unrecognized = implode("\n ", $unrecognized);
cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
}

if ($options['help']) {
$help =
"Execute user account sync with external database.
The auth_db plugin must be enabled and properly configured.
Options:
-n, --noupdate Skip update of existing users
-v, --verbose Print verbose progress information
-h, --help Print out this help
Example:
\$ sudo -u www-data /usr/bin/php auth/db/cli/sync_spr.php
Sample cron entry:
# 5 minutes past 4am
5 4 * * * sudo -u www-data /usr/bin/php /var/www/moodle/auth/db/cli/sync_spr.php
";

echo $help;
die;
}

if (!is_enabled_auth('db')) {
cli_error('auth_db plugin is disabled, synchronisation stopped', 2);
}

//if (empty($options['verbose'])) {
// $trace = new null_progress_trace();
//} else {
$trace = new text_progress_trace();
//}

$update = empty($options['noupdate']);

/** @var auth_plugin_db $dbauth */
$dbauth = get_auth_plugin('db');
$result = $dbauth->sync_spr($trace, $update);

exit($result);
10 changes: 10 additions & 0 deletions auth/db/db/tasks.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,15 @@
'month' => '*',
'dayofweek' => '*',
'disabled' => 1
),
array(
'classname' => '\auth_db\task\sync_spr',
'blocking' => 0,
'minute' => 'R',
'hour' => 'R',
'day' => '*',
'month' => '*',
'dayofweek' => '*',
'disabled' => 1
)
);
1 change: 1 addition & 0 deletions auth/db/lang/en/auth_db.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
$string['auth_dbsuspendusererror'] = 'Error suspending user {$a}';
$string['auth_dbsybasequoting'] = 'Use sybase quotes';
$string['auth_dbsybasequotinghelp'] = 'Sybase style single quote escaping - needed for Oracle, MS SQL and some other databases. Do not use for MySQL!';
$string['auth_dbsyncsprtask'] = 'Synchronise SPR users task';
$string['auth_dbsyncuserstask'] = 'Synchronise users task';
$string['auth_dbtable'] = 'Name of the table in the database';
$string['auth_dbtable_key'] = 'Table';
Expand Down
2 changes: 1 addition & 1 deletion auth/db/version.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@

defined('MOODLE_INTERNAL') || die();

$plugin->version = 2022112800; // The current plugin version (Date: YYYYMMDDXX).
$plugin->version = 2022112802; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2022111800; // Requires this Moodle version.
$plugin->component = 'auth_db'; // Full name of the plugin (used for diagnostics)

0 comments on commit 40d62c1

Please sign in to comment.