lib.php 10.8 KB
Newer Older
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
<?php
/**
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2012 Catalyst IT
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    mahara
 * @subpackage auth-browserid
 * @author     Francois Marier <francois@catalyst.net.nz>
 */

defined('INTERNAL') || die();
require_once(get_config('docroot') . 'auth/lib.php');
require_once(get_config('docroot') . 'lib/institution.php');

class AuthBrowserid extends Auth {
    public function __construct($id = null) {
        $this->has_instance_config = true;
        $this->type = 'browserid';

        $this->config['weautocreateusers'] = 1;
        if (!empty($id)) {
            return $this->init($id);
        }
        return true;
    }

    public function init($id) {
        $this->ready = parent::init($id);
        return $this->ready;
    }

    public function authenticate_user_account($user, $password) {
        // Authentication is done elsewhere in Javascript
        return false;
    }

    public function can_auto_create_users() {
        // The normal user auto creation process doesn't work for this backend
        return false;
    }

    public function create_new_user($email) {
        if (!$this->config['weautocreateusers']) {
            return null;
        }

        if (record_exists('artefact_internal_profile_email', 'email', $email)) {
61
            throw new AccountAutoCreationException(get_string('emailalreadyclaimed', 'auth.browserid', $email));
62
63
64
        }

        if (record_exists('usr', 'username', $email)) {
65
            throw new AccountAutoCreationException(get_string('emailclaimedasusername', 'auth.browserid', $email));
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
        }

        // Personal details are currently not provided by the BrowserID API.
        $user->username = $email;
        $user->firstname = '';
        $user->lastname = '';
        $user->email = $email;

        // no need for a password on BrowserID accounts
        $user->password = '';
        $user->passwordchange = 0;
        $user->authinstance = $this->instanceid;

        $user->id = create_user($user, array(), $this->institution);

        if (get_config('usersuniquebyusername')) {
            $user->join_institution($this->institution);
        }

        return $user;
    }
}

class PluginAuthBrowserid extends PluginAuth {

    private static $default_config = array(
        'weautocreateusers' => 1,
    );

    public static function has_config() {
        return false;
    }

    public static function get_config_options() {
        return array();
    }

    public static function has_instance_config() {
        return true;
    }

    public static function is_usable() {
        return extension_loaded('curl');
    }

    public static function get_instance_config_options($institution, $instance = 0) {

        if ($instance > 0) {
            $current_config = get_records_menu('auth_instance_config', 'instance', $instance, '', 'field, value');

            if ($current_config == false) {
                $current_config = array();
            }

            foreach (self::$default_config as $key => $value) {
                if (array_key_exists($key, $current_config)) {
                    self::$default_config[$key] = $current_config[$key];
                }
            }
        }

        $elements = array(
            'instance' => array(
                'type'  => 'hidden',
                'value' => $instance,
            ),
            'institution' => array(
                'type'  => 'hidden',
                'value' => $institution,
            ),
            'authname' => array(
                'type'  => 'hidden',
                'value' => 'browserid',
            ),
            'instancename' => array(
                'type'  => 'hidden',
                'value' => 'BrowserID',
            ),
            'authname' => array(
                'type'  => 'hidden',
                'value' => 'browserid',
            ),
            'weautocreateusers' => array(
                'type'         => 'checkbox',
                'title'        => get_string('weautocreateusers', 'auth'),
                'defaultvalue' => self::$default_config['weautocreateusers'],
                'help'         => true
            ),
        );

        return array(
            'elements' => $elements,
            'renderer' => 'table'
        );
    }

    public static function save_config_options($values, $form) {

        $authinstance = new stdClass();

        if ($values['instance'] > 0) {
            $values['create'] = false;
            $current = get_records_assoc('auth_instance_config', 'instance', $values['instance'], '', 'field, value');
            $authinstance->id = $values['instance'];
        }
        else {
            $values['create'] = true;
            $lastinstance = get_records_array('auth_instance', 'institution', $values['institution'], 'priority DESC', '*', '0', '1');

            if ($lastinstance == false) {
                $authinstance->priority = 0;
            }
            else {
                $authinstance->priority = $lastinstance[0]->priority + 1;
            }
        }

        $authinstance->institution  = $values['institution'];
        $authinstance->authname     = $values['authname'];
        $authinstance->instancename = $values['instancename'];

        if ($values['create']) {
            $values['instance'] = insert_record('auth_instance', $authinstance, 'id', true);
        }
        else {
            update_record('auth_instance', $authinstance, array('id' => $values['instance']));
        }

        if (empty($current)) {
            $current = array();
        }

        self::$default_config = array('weautocreateusers' => $values['weautocreateusers']);

        foreach(self::$default_config as $field => $value) {
            $record = new stdClass();
            $record->instance = $values['instance'];
            $record->field = $field;
            $record->value = $value;

            if ($values['create'] || !array_key_exists($field, $current)) {
                insert_record('auth_instance_config', $record);
            }
            else {
                update_record('auth_instance_config', $record, array('instance' => $values['instance'], 'field' => $field));
            }
        }

        return $values;
    }

    /**
     * Add a BrowserID link/button.
     */
    public static function login_form_elements() {
        return array(
            'loginbrowserid' => array(
                'value' => '<div class="login-externallink"><a href="javascript:window.browserid_login()">' . get_string('login', 'auth.browserid') . '</a></div>'
            )
        );
    }

    /**
     * Load all of the Javascript needed to retrieve BrowserIDs from
     * the browser.
     */
    public static function login_form_js() {
        $wwwroot = get_config('wwwroot');
        return <<< EOF
<script src="https://browserid.org/include.js" type="text/javascript"></script>

<form id="browserid-form" action="{$wwwroot}auth/browserid/login.php" method="post">
<input id="browserid-assertion" type="hidden" name="assertion" value="">
<input style="display: none" type="submit">
</form>

<script type="text/javascript">
function browserid_login() {
244
    navigator.id.get(function(assertion) {
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
        if (assertion) {
            document.getElementById('browserid-assertion').setAttribute('value', assertion);
            document.getElementById('browserid-form').submit();
        }
   });
}
</script>
EOF;
    }

    public static function need_basic_login_form() {
        return false;
    }
}

class BrowserIDUser extends LiveUser {
    public function login($email) {
        $sql = "SELECT
                    a.id, i.name AS institutionname
                FROM
                    {auth_instance} a
                JOIN
                    {institution} i ON a.institution = i.name
                WHERE
                    a.authname = 'browserid' AND
                    i.suspended = 0";
        $authinstances = get_records_sql_array($sql, null);
        if (!$authinstances) {
273
            throw new ConfigException(get_string('browseridnotenabled', 'auth.browserid'));
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
        }

        foreach ($authinstances as $authinstance) {
            $auth = AuthFactory::create($authinstance->id);

            $institutionjoin = '';
            $institutionwhere = '';
            $sqlvalues = array($email);
            if ($authinstance->institutionname != 'mahara') {
                // Make sure that user is in the right institution
                $institutionjoin = 'JOIN {usr_institution} ui ON ui.usr = u.id';
                $institutionwhere = 'AND ui.institution = ?';
                $sqlvalues[] = $authinstance->institutionname;
            }

            $sql = "SELECT
                        u.*,
                        " . db_format_tsfield('u.expiry', 'expiry') . ",
                        " . db_format_tsfield('u.lastlogin', 'lastlogin') . ",
                        " . db_format_tsfield('u.lastlastlogin', 'lastlastlogin') . ",
                        " . db_format_tsfield('u.lastaccess', 'lastaccess') . ",
                        " . db_format_tsfield('u.suspendedctime', 'suspendedctime') . ",
                        " . db_format_tsfield('u.ctime', 'ctime') . "
                    FROM
                        {usr} u
                    JOIN
                        {artefact_internal_profile_email} a ON a.owner = u.id
                    $institutionjoin
                    WHERE
                        a.verified = 1 AND
                        a.email = ?
                    $institutionwhere";
            $user = get_record_sql($sql, $sqlvalues);
            if (!$user) {
                continue; // skip to the next auth_instance
            }

            if (is_site_closed($user->admin)) {
                return false;
            }
            ensure_user_account_is_active($user);

            $this->authenticate($user, $auth->instanceid);
            return true;
        }

        // TODO: pick the right authinstance for creating a new user (make sure !$institution->isFull(), default to "No institution")
        if ($user = $auth->create_new_user($email)) {
            $this->authenticate($user, $auth->instanceid);
        }
        else {
325
            throw new AuthUnknownUserException(get_string('emailnotfound', 'auth.browserid', $email));
326
327
328
        }
    }
}