summaryrefslogtreecommitdiff
path: root/it_user.class
blob: 79498619837c6e7e0dc951feac35e5934cdc63ca (plain)
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
<?php
/*
**	Copyright (C) 1995-2021 by the ITools Authors.
**	This file is part of ITools - the Internet Tools Library
**
**	ITools 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.
**
**	ITools 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/>.
**
**	it_user.class - User management and authentication
*/

/* PUBLIC and guaranteed to stay in same order (but not value) forever */
define('IT_USER_STATUS_FAILED', 1);	/* Wrong password given */
define('IT_USER_STATUS_UNKNOWN', 2);	/* Not logged in, no UID */
define('IT_USER_STATUS_ANONYMOUS', 3);	/* Not logged in, UID known */
define('IT_USER_STATUS_KNOWN', 4);	/* Not logged in, UID,username known */
define('IT_USER_STATUS_SESSION', 5);	/* Has a valid session */

/* PRIVATE */
define('_IT_USER_UID_COOKIE', 'UID');
define('_IT_USER_UID_COOKIE_LIFETIME', 0x7FFFFFFF);	/* Forever :-) */
define('_IT_USER_STATUS_INVALID', 0);	/* INTERNAL: Not yet evaluated */
define('_IT_USER_COOKIE_SAMESITE', 'Lax');

class it_user extends it_dbi
{
	/* PRIVATE */
	var $status;			# Current status (IT_USER_STATUS_...)
	var $session;			# Session object
	var $sessioninitialized = false;

	var $login_identifier_required = false;
	var $login_identifier;
	var $domain;
	var $lifetime;
	var $secret;
	var $urlauthenticationcode = 'uac';	# Name of UAC url parameter

	var $uid;
	var $username;

	/*
	 * Used by login(), contains unvalidated user data to give overloading
	 * functions a way of accessing it.
	 */
	var $workrecord;


/**
 * Constructor
 * @param $p array(key => value) of configuration data
 */
function __construct($p = array())
{
	$this->p = $p + array(
		'uid_field'         => 'ID',
		'table'             => 'T_Users',
		'username_field'    => 'Username',
		'password_field'    => 'Password',
		'uidcookiename'     => _IT_USER_UID_COOKIE,
		'sessioncookiename' => null
	);

	# Default to uid being primary key, may change later
	parent::__construct(array('table' => $this->p['table'], 'keyfield' => $this->p['uid_field']));

	$this->session = new it_session;
	$this->status = _IT_USER_STATUS_INVALID;
}

/**
 * Minimalistic post processing to fill uid and username fields after calling read() on it_user
 */
function read($id = null)
{
	$result = parent::read($id);

	# If read succeeded, get UID. This is necessary because it's only set if a cookie is present (i.e. in web-context)
	if (isset($this->{$this->p['uid_field']}))
		$this->uid = $this->{$this->p['uid_field']};

	# Get username from database field (shortcut)
	$this->username = $this->{$this->p['username_field']};

	return $result;
}


function set_session_cookie_name($sessioncookiename)
{
	$this->p['sessioncookiename'] = $sessioncookiename;
}


function set_uid_cookie_name($uidcookiename)
{
	$this->p['uidcookiename'] = $uidcookiename;
}


function set_domain($domain)
{
	$this->domain = $domain;
}


function set_session_lifetime($lifetime)
{
	$this->lifetime = $lifetime;
}


function set_login_identifier($login_identifier)
{
	$this->login_identifier_required = true;
	$this->login_identifier = $login_identifier;
}


function _init_session()
{
	if (!$this->sessioninitialized)
	{
		# Using non-standard values for session?
		if ($this->p['sessioncookiename'])
			$this->session->set_cookiename($this->p['sessioncookiename']);

		if (isset($this->domain))
			$this->session->set_domain($this->domain);

		if (isset($this->lifetime))
			$this->session->set_lifetime($this->lifetime);

		if (isset($this->secret))
			$this->session->set_secret($this->secret);

		$this->session->init();
		$this->sessioninitialized = true;
	}
}


function get_status()
{
	if ($this->status == _IT_USER_STATUS_INVALID)
	{
		$this->_init_session();

		if ($this->session->is_valid())
		{
			$this->status = IT_USER_STATUS_SESSION;
			$this->_set_uid($this->session->get_uid());
			$this->read($this->uid);
		}
		else if (isset($_COOKIE[$this->p['uidcookiename']]) && ($this->uid = substr($_COOKIE[$this->p['uidcookiename']], 0, 32)))
		{
			@$this->read($this->uid);
			$this->status = $this->username ? IT_USER_STATUS_KNOWN : IT_USER_STATUS_ANONYMOUS;
		}
		else
		{
			$this->status = IT_USER_STATUS_UNKNOWN;
			$this->username = '';

			if ($this->p['uid_field'])
				$this->_set_uid($this->create_uid());
		}
	}

	return $this->status;
}


function get_username()
{
	return $this->username;
}


function get_uid()
{
	return $this->uid;
}


function _set_uid($uid)
{
	$this->uid = $uid;

	if (!isset($_COOKIE[$this->p['uidcookiename']]) || ($_COOKIE[$this->p['uidcookiename']] != $uid))
	{
		it::setcookie($this->p['uidcookiename'], $uid, [ 'expires' => _IT_USER_UID_COOKIE_LIFETIME, 'path' => "/", 'domain' => $this->domain, 'secure' => false, 'httponly' => true, 'samesite' => _IT_USER_COOKIE_SAMESITE ]);
		$_COOKIE[$this->p['uidcookiename']] = $uid;
	}
}


/* Return session status of this user: Is she logged in? */
function is_logged_in()
{
	return $this->status == IT_USER_STATUS_SESSION;
}


/**
 * Try to log in user. Use get_status() to check result.
 * NOTE: Must not be called AFTER get_status() has been used.
 * @param $username User ID to login
 * @param $password Password to authenticate login
 * @param $ignorepassword True if you want to login anyway (e.g. 'su')
 * @return non-false if successful, false on error
 */
function login($username, $password, $ignorepassword = false, $withsession = true)
{
	$result = false;

	$this->_init_session();
	$this->workrecord = new it_dbi(array('server' => $this->_p['server'], 'table' => $this->p['table'], 'keyfield' => $this->p['username_field']));

	if ($this->workrecord->read($username))
	{
		if ($ignorepassword || $this->check_password($password, $this->workrecord->{$this->p['password_field']}))
		{
			$this->session->set_uid($this->workrecord->{$this->p['uid_field']});
			if ($withsession)
				$result = $this->session->set_valid(true, $this->login_identifier_required, $this->login_identifier);
			else
				$result = $this->_set_uid($this->session->get_uid());
		}
	}

	if ($result && ($this->session->get_uid() == $this->workrecord->{$this->p['uid_field']}))
		$this->username = $this->workrecord->{$this->p['username_field']};

	$this->status = $result ? _IT_USER_STATUS_INVALID : IT_USER_STATUS_FAILED;

	return $result;
}


/*
 * Logout user.
 * NOTE: Must not be called AFTER get_status() has been used.
 */
function logout()
{
	$this->_init_session();
	$this->session->set_valid(false);
}


/*
 * Throw away all user information and restart from scratch...
 */
function purge()
{
	$this->status = _IT_USER_STATUS_INVALID;
	$this->_set_uid($this->create_uid());
	$this->username = "";
	$this->session->purge();
}


/**
 * Create user database record.
 * @param $tags Fields to set (uid and username are optional)
 * @see it_dbi::insert()
 */
function create($tags)
{
	# Make sure UID is always set in database records
	if ($this->p['uid_field'])
	{
		if (!$this->uid)
			$this->_set_uid($this->create_uid());

		$tags[$this->p['uid_field']] = $this->uid;
	}

	# Create dummy but unique username if none given
	if (!$tags[$this->p['username_field']] && !$this->{$this->p['username_field']})
		$tags[$this->p['username_field']] = $this->uid;

	if ($result = $this->insert($tags))
		$this->_set_uid($this->{$this->p['uid_field']});

	return $result;
}


/*
 * Create unique identifier used for anonymously users, Override if you want
 * different type of UIDs.
 * Returns newly created uid
 */
function create_uid()
{
	return bin2hex(random_bytes(16));	/* random garbage */
}


/*
 * Create a login identifier and set session to login identifier 'secret' value
 * Returns a value to be put into the login <form> which has to be passed to 
 * login() to create a valid session
 */
function create_login_identifier()
{
	return $this->session->create_login_identifier();
}


/*
 * Create a random password with given length.
 */
function create_password($length = 12, $charset = 'abcdefghjkpqrstuvwxyz23456789ABCDEFGHJKPRSTUVWXYZ')
{
	$result = "";

	if (!function_exists($rand = 'random_int'))
		$rand = 'mt_rand';

	for ($i = 0; $i < $length; $i++)
		$result .= substr($charset, $rand(0, strlen($charset) - 1), 1);

	return $result;
}


/*
 * Crypt the password, same function is used in check_login_status
 * You can use unencrypted passwords if you extend the user class and
 * override this function.
 */
function crypt_password($password)
{
	$result = $this->query("SELECT PASSWORD(" . $this->escape_string($password) . ")");
	list($pw) = mysqli_fetch_array($result);

	return $pw;
}


/*
 * Crypt the password and compare it to cryptedpassword.
 */
function check_password($password, $cryptedpassword)
{
	return $this->crypt_password($password) == $cryptedpassword;
}


/*
 * Check if cookies are enabled.
 * NOTE: Only works if you used create_login_identifier() on previous page
 */
function has_cookies()
{
	return $this->session->has_cookies();
}


/*
 * Check if $name would be an acceptable username
 */
function is_valid_username($name)
{
	if ((strlen($name) >= 2) && (strlen($name) <= 32))
	{
		if (!preg_match('/["\'\\\\&$+]/', $name))
			return true;
	}
	return false;
}


/*
 * Check if $word would be an acceptable password
 */
function is_valid_password($word)
{
	if ((strlen($word) >= 2) && (strlen($word) <= 32))
	{
		if (!preg_match('/["\'\\\\&$+]/', $word))
			return true;
	}
	return false;
}


/*
 * Sign string with current user id or session
 * @param $text Text to be signed
 * @param $withsession Sign with session if true, with uid if false
 * @return Signature for $text
 */
function create_signature($text, $withsession = true)
{
	if ($withsession)
	{
		switch ($this->get_status())
		{
		case IT_USER_STATUS_SESSION:
			$result = $this->session->create_signature($text);
			break;

		default:
			$result = md5("$this->secret,$text,$this->secret");
			break;
		}
	}
	else
	{
		/* Sign with UID only */
		$result = md5("$this->secret,$this->uid,$text,$this->secret");
	}

	return $result;
}

/*
 * Check signature for string with current user id or session
 * @param $text Text which was signed
 * @param $signature Signature to be checked
 * @param $withsession Signed with session if true, with uid if false
 * @return True if signature ok, false otherwise
 */
function check_signature($text, $signature, $withsession = true)
{
	if ($withsession)
	{
		switch ($this->get_status())
		{
		case IT_USER_STATUS_SESSION:
			$result = $this->session->check_signature($text, $signature);
			break;

		default:
			$result = (md5("$this->secret,$text,$this->secret") == $signature);
			break;
		}
	}
	else
	{
		/* Sign with UID only */
		$result = ($this->create_signature($text, false) == $signature);
	}

	return $result;
}

/*
 * Sign an url with parameters
 * @param $url URL to sign
 * @param $withsession Signed with session if true, with uid if false
 * @return Signed url
 */
function sign_url($url, $withsession = false)
{
	if (strstr($url, '?'))
		$url .= "&amp;$this->urlauthenticationcode=" . $this->create_signature(str_replace('&amp;', '&', $url), $withsession);

	return $url;
}

/*
 * Check if url GET parameters are properly signed and not modified
 * @param $withsession Signed with session if true, with uid if false
 * @return False if url was modified
 */
function check_url($withsession = false)
{
	$result = true;	/* Default to true for url without parameters */

	if (!empty($_SERVER['QUERY_STRING']))
	{
		$url = preg_replace("/&?$this->urlauthenticationcode=[a-zA-Z0-9]*/", '', $_SERVER['REQUEST_URI']);

		$result = $this->check_signature($url, $GLOBALS[$this->urlauthenticationcode], $withsession);
	}

	return $result;
}

} /* End class it_user */