2013-12-23 02:55:53 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Model\User;
|
|
|
|
|
|
|
|
use SimpleValidator\Validator;
|
|
|
|
use SimpleValidator\Validators;
|
2014-02-08 20:13:14 +01:00
|
|
|
use PicoDb\Database;
|
2014-05-27 02:47:40 +02:00
|
|
|
use Model\Config;
|
|
|
|
use Model\RememberMe;
|
|
|
|
use Model\Database as DatabaseModel;
|
2013-12-23 02:55:53 +01:00
|
|
|
|
2014-11-19 01:00:53 +01:00
|
|
|
// Check if the user is logged
|
2015-01-17 19:35:59 +01:00
|
|
|
function is_loggedin()
|
2014-11-19 01:00:53 +01:00
|
|
|
{
|
|
|
|
return ! empty($_SESSION['user']);
|
|
|
|
}
|
|
|
|
|
2015-01-17 19:35:59 +01:00
|
|
|
function logout()
|
2014-11-19 01:00:53 +01:00
|
|
|
{
|
2015-01-17 19:35:59 +01:00
|
|
|
\Model\RememberMe\destroy();
|
|
|
|
\PicoFarad\Session\close();
|
2014-11-19 01:00:53 +01:00
|
|
|
}
|
|
|
|
|
2013-12-23 02:55:53 +01:00
|
|
|
// Get a user by username
|
|
|
|
function get($username)
|
|
|
|
{
|
2014-02-08 20:13:14 +01:00
|
|
|
return Database::get('db')
|
2013-12-23 02:55:53 +01:00
|
|
|
->table('config')
|
|
|
|
->columns('username', 'password', 'language')
|
|
|
|
->eq('username', $username)
|
|
|
|
->findOne();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate authentication
|
|
|
|
function validate_login(array $values)
|
|
|
|
{
|
|
|
|
$v = new Validator($values, array(
|
|
|
|
new Validators\Required('username', t('The user name is required')),
|
|
|
|
new Validators\MaxLength('username', t('The maximum length is 50 characters'), 50),
|
|
|
|
new Validators\Required('password', t('The password is required'))
|
|
|
|
));
|
|
|
|
|
|
|
|
$result = $v->execute();
|
|
|
|
$errors = $v->getErrors();
|
|
|
|
|
|
|
|
if ($result) {
|
|
|
|
|
|
|
|
$user = get($values['username']);
|
|
|
|
|
|
|
|
if ($user && \password_verify($values['password'], $user['password'])) {
|
|
|
|
|
|
|
|
unset($user['password']);
|
|
|
|
|
|
|
|
$_SESSION['user'] = $user;
|
2014-05-27 02:47:40 +02:00
|
|
|
$_SESSION['config'] = Config\get_all();
|
|
|
|
|
|
|
|
// Setup the remember me feature
|
|
|
|
if (! empty($values['remember_me'])) {
|
|
|
|
$credentials = RememberMe\create(DatabaseModel\select(), $values['username'], Config\get_ip_address(), Config\get_user_agent());
|
|
|
|
RememberMe\write_cookie($credentials['token'], $credentials['sequence'], $credentials['expiration']);
|
|
|
|
}
|
2013-12-23 02:55:53 +01:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
|
|
|
|
$result = false;
|
|
|
|
$errors['login'] = t('Bad username or password');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return array(
|
|
|
|
$result,
|
|
|
|
$errors
|
|
|
|
);
|
|
|
|
}
|