2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Class for loading/storing issuers from the DB.
20 * @package auth_oauth2
21 * @copyright 2017 Damyon Wiese
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 namespace auth_oauth2;
26 defined('MOODLE_INTERNAL') || die();
31 * Class for loading/storing issuer from the DB
33 * @copyright 2017 Damyon Wiese
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class linked_login extends persistent {
38 const TABLE = 'auth_oauth2_linked_login';
41 * Return the definition of the properties of this model.
45 protected static function define_properties() {
59 'confirmtoken' => array(
62 'confirmtokenexpires' => array(
69 * Check whether there are any valid linked accounts for this issuer
70 * and username combination.
72 * @param \core\oauth2\issuer $issuer The issuer
73 * @param string $username The username to check
75 public static function has_existing_issuer_match(\core\oauth2\issuer $issuer, $username) {
78 $where = "issuerid = :issuerid
79 AND username = :username
80 AND (confirmtokenexpires = 0 OR confirmtokenexpires > :maxexpiry)";
82 $count = $DB->count_records_select(static::TABLE, $where, [
83 'issuerid' => $issuer->get('id'),
84 'username' => $username,
85 'maxexpiry' => (new \DateTime('NOW'))->getTimestamp(),
92 * Remove all linked logins that are using issuers that have been deleted.
94 * @param int $issuerid The issuer id of the issuer to check, or false to check all (defaults to all)
97 public static function delete_orphaned($issuerid = false) {
99 // Delete any linked_login entries with a issuerid
100 // which does not exist in the issuer table.
101 // In the left join, the issuer id will be null
102 // where a match linked_login.issuerid is not found.
103 $sql = "DELETE FROM {" . self::TABLE . "}
104 WHERE issuerid NOT IN (SELECT id FROM {" . \core\oauth2\issuer::TABLE . "})";
106 if (!empty($issuerid)) {
107 $sql .= ' AND issuerid = ?';
108 $params['issuerid'] = $issuerid;
110 return $DB->execute($sql, $params);