Files
grocy/services/SessionService.php
T

90 lines
2.0 KiB
PHP
Raw Normal View History

2018-04-10 20:30:11 +02:00
<?php
2018-04-11 19:49:35 +02:00
namespace Grocy\Services;
class SessionService extends BaseService
2018-04-10 20:30:11 +02:00
{
const SESSION_COOKIE_NAME = 'grocy_session';
2020-08-31 20:40:31 +02:00
/**
* @return string
*/
public function CreateSession($userId, $stayLoggedInPermanently = false)
{
$newSessionKey = $this->GenerateSessionKey();
$expires = date('Y-m-d H:i:s', intval(time() + 2592000));
2020-09-01 21:29:47 +02:00
// Default is that sessions expire in 30 days
2020-08-31 20:40:31 +02:00
if ($stayLoggedInPermanently === true)
{
$expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32); // Never
}
$sessionRow = $this->getDatabase()->sessions()->createRow([
'user_id' => $userId,
'session_key' => $newSessionKey,
'expires' => $expires
]);
$sessionRow->save();
return $newSessionKey;
}
public function GetDefaultUser()
{
return $this->getDatabase()->users(1);
}
public function GetUserBySessionKey($sessionKey)
{
$sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch();
if ($sessionRow !== null)
{
return $this->getDatabase()->users($sessionRow->user_id);
}
return null;
}
2018-04-10 20:30:11 +02:00
/**
* @return boolean
*/
2018-04-11 19:49:35 +02:00
public function IsValidSession($sessionKey)
2018-04-10 20:30:11 +02:00
{
if ($sessionKey === null || empty($sessionKey))
{
return false;
}
else
{
$sessionRow = $this->getDatabase()->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch();
if ($sessionRow !== null)
{
2020-09-01 21:29:47 +02:00
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
2020-08-31 20:40:31 +02:00
$sessionRow->update([
'last_used' => date('Y-m-d H:i:s', time())
2020-08-31 20:40:31 +02:00
]);
$this->getDatabaseService()->SetDbChangedTime($dbModTime);
return true;
}
else
{
return false;
}
2018-09-24 13:16:57 +02:00
}
2018-04-10 20:30:11 +02:00
}
2018-04-11 19:49:35 +02:00
public function RemoveSession($sessionKey)
2018-04-10 20:30:11 +02:00
{
$this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete();
2018-04-10 20:30:11 +02:00
}
private function GenerateSessionKey()
{
return RandomString(50);
}
2018-04-10 20:30:11 +02:00
}