From f01a6d5372baf90508977ce798116e5bf650a22f Mon Sep 17 00:00:00 2001 From: flashwave Date: Wed, 3 Oct 2018 00:34:05 +0200 Subject: [PATCH] Made imperative bits of the session system procedural like the rest. --- misuzu.php | 45 ++++++++++++------------ public/auth.php | 14 ++++---- public/changelog.php | 6 ++-- public/comments.php | 10 +++--- public/forum/forum.php | 8 ++--- public/forum/index.php | 6 ++-- public/forum/posting.php | 12 +++---- public/forum/topic.php | 4 +-- public/manage/changelog.php | 18 +++++----- public/manage/index.php | 2 +- public/manage/users.php | 2 +- public/news.php | 4 +-- public/profile.php | 10 +++--- public/relations.php | 6 ++-- public/settings.php | 12 +++---- src/Application.php | 69 ------------------------------------- src/Users/session.php | 63 +++++++++++++++++++++++++++++---- 17 files changed, 135 insertions(+), 156 deletions(-) diff --git a/misuzu.php b/misuzu.php index 35375f2a..e3632759 100644 --- a/misuzu.php +++ b/misuzu.php @@ -282,37 +282,36 @@ MIG; exit; } - if (isset($_COOKIE['msz_uid'], $_COOKIE['msz_sid'])) { - $app->startSession((int)$_COOKIE['msz_uid'], $_COOKIE['msz_sid']); + if (isset($_COOKIE['msz_uid'], $_COOKIE['msz_sid']) + && user_session_start((int)$_COOKIE['msz_uid'], $_COOKIE['msz_sid'])) { + $mszUserId = (int)$_COOKIE['msz_uid']; - if ($app->hasActiveSession()) { - user_bump_last_active($app->getUserId()); + user_bump_last_active($mszUserId); - $getUserDisplayInfo = Database::prepare(' - SELECT - u.`user_id`, u.`username`, u.`user_background_settings`, - COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour` - FROM `msz_users` as u - LEFT JOIN `msz_roles` as r - ON u.`display_role` = r.`role_id` - WHERE `user_id` = :user_id - '); - $getUserDisplayInfo->bindValue('user_id', $app->getUserId()); - $userDisplayInfo = $getUserDisplayInfo->execute() ? $getUserDisplayInfo->fetch() : []; - tpl_var('current_user', $userDisplayInfo); - } + $getUserDisplayInfo = Database::prepare(' + SELECT + u.`user_id`, u.`username`, u.`user_background_settings`, + COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour` + FROM `msz_users` as u + LEFT JOIN `msz_roles` as r + ON u.`display_role` = r.`role_id` + WHERE `user_id` = :user_id + '); + $getUserDisplayInfo->bindValue('user_id', $mszUserId); + $userDisplayInfo = $getUserDisplayInfo->execute() ? $getUserDisplayInfo->fetch() : []; + tpl_var('current_user', $userDisplayInfo); } csrf_init($app->getCsrfSecretKey(), empty($userDisplayInfo) ? ip_remote_address() : $_COOKIE['msz_sid']); $privateInfo = $app->getPrivateInfo(); - if (!$misuzuBypassLockdown && $privateInfo['enabled'] && !$app->hasActiveSession()) { - if ($app->hasActiveSession()) { - $generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $app->getUserId()); + if (!$misuzuBypassLockdown && $privateInfo['enabled'] && !empty($userDisplayInfo)) { + if (user_session_active()) { + $generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $userDisplayInfo['user_id']); if (!perms_check($generalPerms, $privateInfo['permission'])) { - $app->stopSession(); // au revoir + user_session_stop(); // au revoir } } else { http_response_code(401); @@ -324,7 +323,7 @@ MIG; } $inManageMode = starts_with($_SERVER['REQUEST_URI'], '/manage'); - $hasManageAccess = perms_check(perms_get_user(MSZ_PERMS_GENERAL, $app->getUserId()), MSZ_PERM_GENERAL_CAN_MANAGE); + $hasManageAccess = perms_check(perms_get_user(MSZ_PERMS_GENERAL, $userDisplayInfo['user_id'] ?? 0), MSZ_PERM_GENERAL_CAN_MANAGE); tpl_var('has_manage_access', $hasManageAccess); if ($inManageMode) { @@ -333,6 +332,6 @@ MIG; exit; } - tpl_var('manage_menu', manage_get_menu($app->getUserId())); + tpl_var('manage_menu', manage_get_menu($userDisplayInfo['user_id'] ?? 0)); } } diff --git a/public/auth.php b/public/auth.php index 214d7036..7598c93c 100644 --- a/public/auth.php +++ b/public/auth.php @@ -39,7 +39,7 @@ switch ($authMode) { break; case 'logout': - if (!$app->hasActiveSession()) { + if (!user_session_active()) { header('Location: /'); return; } @@ -47,7 +47,7 @@ switch ($authMode) { if (csrf_verify('logout', $_GET['s'] ?? '')) { set_cookie_m('uid', '', -3600); set_cookie_m('sid', '', -3600); - user_session_delete($app->getSessionId()); + user_session_stop(true); header('Location: /'); return; } @@ -56,7 +56,7 @@ switch ($authMode) { break; case 'reset': - if ($app->hasActiveSession()) { + if (user_session_active()) { header('Location: /settings.php'); break; } @@ -153,7 +153,7 @@ switch ($authMode) { break; case 'forgot': - if ($app->hasActiveSession() || $preventPasswordReset) { + if (user_session_active() || $preventPasswordReset) { header('Location: /'); break; } @@ -239,7 +239,7 @@ MSG; break; case 'login': - if ($app->hasActiveSession()) { + if (user_session_active()) { header('Location: /'); break; } @@ -314,7 +314,7 @@ MSG; break; } - $app->startSession($userId, $sessionKey); + user_session_start($userId, $sessionKey); $cookieLife = Carbon::now()->addMonth()->timestamp; set_cookie_m('uid', $userId, $cookieLife); set_cookie_m('sid', $sessionKey, $cookieLife); @@ -333,7 +333,7 @@ MSG; break; case 'register': - if ($app->hasActiveSession()) { + if (user_session_active()) { header('Location: /'); } diff --git a/public/changelog.php b/public/changelog.php index 2345c46d..eb0e39c5 100644 --- a/public/changelog.php +++ b/public/changelog.php @@ -11,7 +11,7 @@ $changelogDate = $_GET['d'] ?? ''; $changelogUser = (int)($_GET['u'] ?? 0); $changelogTags = $_GET['t'] ?? ''; -$commentPerms = comments_get_perms($app->getUserId()); +$commentPerms = comments_get_perms(user_session_current('user_id', 0)); tpl_vars([ 'changelog_offset' => $changelogOffset, @@ -62,7 +62,7 @@ if ($changelogChange > 0) { "changelog-date-{$change['change_date']}", true ), - 'comments' => comments_category_get($commentsCategory['category_id'], $app->getUserId()), + 'comments' => comments_category_get($commentsCategory['category_id'], user_session_current('user_id', 0)), ]); return; } @@ -88,7 +88,7 @@ if (!$changes) { if (!empty($changelogDate) && count($changes) > 0) { tpl_vars([ 'comments_category' => $commentsCategory = comments_category_info("changelog-date-{$changelogDate}", true), - 'comments' => comments_category_get($commentsCategory['category_id'], $app->getUserId()), + 'comments' => comments_category_get($commentsCategory['category_id'], user_session_current('user_id', 0)), ]); } diff --git a/public/comments.php b/public/comments.php index ee032998..59fbe7e4 100644 --- a/public/comments.php +++ b/public/comments.php @@ -20,12 +20,12 @@ if (!csrf_verify('comments', $_REQUEST['csrf'] ?? '')) { return; } -if ($app->getUserId() < 1) { +if (!user_session_active()) { echo render_info_or_json($isXHR, 'You must be logged in to manage comments.', 401); return; } -$commentPerms = comments_get_perms($app->getUserId()); +$commentPerms = comments_get_perms(user_session_current('user_id', 0)); switch ($_GET['m'] ?? null) { case 'vote': @@ -46,7 +46,7 @@ switch ($_GET['m'] ?? null) { $vote = MSZ_COMMENTS_VOTE_TYPES[(int)($_GET['v'] ?? 0)]; $voteResult = comments_vote_add( $comment, - $app->getUserId(), + user_session_current('user_id', 0), $vote ); @@ -72,7 +72,7 @@ switch ($_GET['m'] ?? null) { } if (!$commentPerms['can_delete_any'] - && !comments_post_check_ownership($comment, $app->getUserId())) { + && !comments_post_check_ownership($comment, user_session_current('user_id', 0))) { echo render_info_or_json($isXHR, "You're not allowed to delete comments made by others.", 403); break; } @@ -147,7 +147,7 @@ switch ($_GET['m'] ?? null) { } $commentId = comments_post_create( - $app->getUserId(), + user_session_current('user_id', 0), $categoryId, $commentText, $commentPin, diff --git a/public/forum/forum.php b/public/forum/forum.php index 0e9ae89d..cc7dc5c8 100644 --- a/public/forum/forum.php +++ b/public/forum/forum.php @@ -17,7 +17,7 @@ if (empty($forum) || ($forum['forum_type'] == MSZ_FORUM_TYPE_LINK && empty($foru return; } -$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $forum['forum_id'], $app->getUserId()); +$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $forum['forum_id'], user_session_current('user_id', 0)); if (!perms_check($perms, MSZ_FORUM_PERM_VIEW_FORUM)) { echo render_error(403); @@ -33,14 +33,14 @@ if ($forum['forum_type'] == MSZ_FORUM_TYPE_LINK) { } $topics = forum_may_have_topics($forum['forum_type']) - ? forum_topic_listing($forum['forum_id'], $app->getUserId(), $topicsOffset, $topicsRange) + ? forum_topic_listing($forum['forum_id'], user_session_current('user_id', 0), $topicsOffset, $topicsRange) : []; -$forum['forum_subforums'] = forum_get_children($forum['forum_id'], $app->getUserId()); +$forum['forum_subforums'] = forum_get_children($forum['forum_id'], user_session_current('user_id', 0)); foreach ($forum['forum_subforums'] as $skey => $subforum) { $forum['forum_subforums'][$skey]['forum_subforums'] - = forum_get_children($subforum['forum_id'], $app->getUserId(), true); + = forum_get_children($subforum['forum_id'], user_session_current('user_id', 0), true); } echo tpl_render('forum.forum', [ diff --git a/public/forum/index.php b/public/forum/index.php index 6569f798..ea78a157 100644 --- a/public/forum/index.php +++ b/public/forum/index.php @@ -1,11 +1,11 @@ getUserId()); +$categories = forum_get_root_categories(user_session_current('user_id', 0)); $blankForum = count($categories) <= 1 && $categories[0]['forum_children'] < 1; foreach ($categories as $key => $category) { - $categories[$key]['forum_subforums'] = forum_get_children($category['forum_id'], $app->getUserId()); + $categories[$key]['forum_subforums'] = forum_get_children($category['forum_id'], user_session_current('user_id', 0)); foreach ($categories[$key]['forum_subforums'] as $skey => $sub) { if (!forum_may_have_children($sub['forum_type'])) { @@ -13,7 +13,7 @@ foreach ($categories as $key => $category) { } $categories[$key]['forum_subforums'][$skey]['forum_subforums'] - = forum_get_children($sub['forum_id'], $app->getUserId(), true); + = forum_get_children($sub['forum_id'], user_session_current('user_id', 0), true); } } diff --git a/public/forum/posting.php b/public/forum/posting.php index f8328483..d11c6d1b 100644 --- a/public/forum/posting.php +++ b/public/forum/posting.php @@ -3,7 +3,7 @@ use Misuzu\Database; require_once __DIR__ . '/../../misuzu.php'; -if (!$app->hasActiveSession()) { +if (!user_session_active()) { echo render_error(403); return; } @@ -67,7 +67,7 @@ if (empty($forum)) { return; } -$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $forum['forum_id'], $app->getUserId()); +$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $forum['forum_id'], user_session_current('user_id', 0)); if ($forum['forum_archived'] || !empty($topic['topic_locked']) @@ -83,7 +83,7 @@ if (!forum_may_have_topics($forum['forum_type'])) { } if ($postRequest) { - if (!csrf_verify('settings', $_POST['csrf'] ?? '')) { + if (!csrf_verify('forum_post', $_POST['csrf'] ?? '')) { echo 'Could not verify request.'; return; } @@ -116,18 +116,18 @@ if ($postRequest) { return; } - $topicId = forum_topic_create($forum['forum_id'], $app->getUserId(), $topicTitle); + $topicId = forum_topic_create($forum['forum_id'], user_session_current('user_id', 0), $topicTitle); } $postId = forum_post_create( $topicId, $forum['forum_id'], - $app->getUserId(), + user_session_current('user_id', 0), ip_remote_address(), $postText, MSZ_PARSER_BBCODE ); - forum_topic_mark_read($app->getUserId(), $topicId, $forum['forum_id']); + forum_topic_mark_read(user_session_current('user_id', 0), $topicId, $forum['forum_id']); header("Location: /forum/topic.php?p={$postId}#p{$postId}"); return; diff --git a/public/forum/topic.php b/public/forum/topic.php index 85d8d3fe..97b95474 100644 --- a/public/forum/topic.php +++ b/public/forum/topic.php @@ -22,7 +22,7 @@ if (!$topic) { return; } -$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $topic['forum_id'], $app->getUserId()); +$perms = forum_perms_get_user(MSZ_FORUM_PERMS_GENERAL, $topic['forum_id'], user_session_current('user_id', 0)); if (!perms_check($perms, MSZ_FORUM_PERM_VIEW_FORUM)) { echo render_error(403); @@ -36,7 +36,7 @@ if (!$posts) { return; } -forum_topic_mark_read($app->getUserId(), $topic['topic_id'], $topic['forum_id']); +forum_topic_mark_read(user_session_current('user_id', 0), $topic['topic_id'], $topic['forum_id']); echo tpl_render('forum.topic', [ 'topic_breadcrumbs' => forum_get_breadcrumbs($topic['forum_id']), diff --git a/public/manage/changelog.php b/public/manage/changelog.php index cfebc0c9..4240ee64 100644 --- a/public/manage/changelog.php +++ b/public/manage/changelog.php @@ -3,7 +3,7 @@ use Misuzu\Database; require_once __DIR__ . '/../../misuzu.php'; -$changelogPerms = perms_get_user(MSZ_PERMS_CHANGELOG, $app->getUserId()); +$changelogPerms = perms_get_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id', 0)); $queryOffset = (int)($_GET['o'] ?? 0); switch ($_GET['v'] ?? null) { @@ -113,11 +113,11 @@ switch ($_GET['v'] ?? null) { if ($changeId < 1) { $changeId = Database::lastInsertId(); - audit_log('CHANGELOG_ENTRY_CREATE', $app->getUserId(), [$changeId]); + audit_log('CHANGELOG_ENTRY_CREATE', user_session_current('user_id', 0), [$changeId]); header('Location: ?v=change&c=' . $changeId); return; } else { - audit_log('CHANGELOG_ENTRY_EDIT', $app->getUserId(), [$changeId]); + audit_log('CHANGELOG_ENTRY_EDIT', user_session_current('user_id', 0), [$changeId]); } } @@ -127,7 +127,7 @@ switch ($_GET['v'] ?? null) { $addTag->bindValue('tag_id', $_POST['add_tag']); if ($addTag->execute()) { - audit_log('CHANGELOG_TAG_ADD', $app->getUserId(), [ + audit_log('CHANGELOG_TAG_ADD', user_session_current('user_id', 0), [ $changeId, $_POST['add_tag'] ]); @@ -144,7 +144,7 @@ switch ($_GET['v'] ?? null) { $removeTag->bindValue('tag_id', $_POST['remove_tag']); if ($removeTag->execute()) { - audit_log('CHANGELOG_TAG_REMOVE', $app->getUserId(), [ + audit_log('CHANGELOG_TAG_REMOVE', user_session_current('user_id', 0), [ $changeId, $_POST['remove_tag'] ]); @@ -288,11 +288,11 @@ switch ($_GET['v'] ?? null) { if ($tagId < 1) { $tagId = Database::lastInsertId(); - audit_log('CHANGELOG_TAG_EDIT', $app->getUserId(), [$tagId]); + audit_log('CHANGELOG_TAG_EDIT', user_session_current('user_id', 0), [$tagId]); header('Location: ?v=tag&t=' . $tagId); return; } else { - audit_log('CHANGELOG_TAG_CREATE', $app->getUserId(), [$tagId]); + audit_log('CHANGELOG_TAG_CREATE', user_session_current('user_id', 0), [$tagId]); } } } @@ -362,11 +362,11 @@ switch ($_GET['v'] ?? null) { if ($actionId < 1) { $actionId = Database::lastInsertId(); - audit_log('CHANGELOG_ACTION_CREATE', $app->getUserId(), [$actionId]); + audit_log('CHANGELOG_ACTION_CREATE', user_session_current('user_id', 0), [$actionId]); header('Location: ?v=action&a=' . $actionId); return; } else { - audit_log('CHANGELOG_ACTION_EDIT', $app->getUserId(), [$actionId]); + audit_log('CHANGELOG_ACTION_EDIT', user_session_current('user_id', 0), [$actionId]); } } } diff --git a/public/manage/index.php b/public/manage/index.php index 69fc759c..a656bfc1 100644 --- a/public/manage/index.php +++ b/public/manage/index.php @@ -1,7 +1,7 @@ getUserId()); +$generalPerms = perms_get_user(MSZ_PERMS_GENERAL, user_session_current('user_id', 0)); switch ($_GET['v'] ?? null) { default: diff --git a/public/manage/users.php b/public/manage/users.php index 629e1e2e..c8cb7724 100644 --- a/public/manage/users.php +++ b/public/manage/users.php @@ -3,7 +3,7 @@ use Misuzu\Database; require_once __DIR__ . '/../../misuzu.php'; -$userPerms = perms_get_user(MSZ_PERMS_USER, $app->getUserId()); +$userPerms = perms_get_user(MSZ_PERMS_USER, user_session_current('user_id', 0)); $isPostRequest = $_SERVER['REQUEST_METHOD'] === 'POST'; $queryQffset = (int)($_GET['o'] ?? 0); diff --git a/public/news.php b/public/news.php index 01feb2b0..9482eb22 100644 --- a/public/news.php +++ b/public/news.php @@ -57,9 +57,9 @@ if ($postId !== null) { echo tpl_render('news.post', [ 'post' => $post, - 'comments_perms' => comments_get_perms($app->getUserId()), + 'comments_perms' => comments_get_perms(user_session_current('user_id', 0)), 'comments_category' => $commentsInfo, - 'comments' => comments_category_get($commentsInfo['category_id'], $app->getUserId()), + 'comments' => comments_category_get($commentsInfo['category_id'], user_session_current('user_id', 0)), ]); return; } diff --git a/public/profile.php b/public/profile.php index 543cb0df..23c8f1f5 100644 --- a/public/profile.php +++ b/public/profile.php @@ -99,7 +99,7 @@ switch ($mode) { } $isEditing = false; - $userPerms = perms_get_user(MSZ_PERMS_USER, $app->getUserId()); + $userPerms = perms_get_user(MSZ_PERMS_USER, user_session_current('user_id', 0)); $perms = [ 'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE), 'edit_avatar' => perms_check($userPerms, MSZ_PERM_USER_CHANGE_AVATAR), @@ -107,8 +107,8 @@ switch ($mode) { 'edit_about' => perms_check($userPerms, MSZ_PERM_USER_EDIT_ABOUT), ]; - if ($app->hasActiveSession()) { - $canEdit = $app->getUserId() === $profile['user_id'] + if (user_session_active()) { + $canEdit = user_session_current('user_id', 0) === $profile['user_id'] || perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS); $isEditing = $canEdit && $mode === 'edit'; @@ -134,7 +134,7 @@ switch ($mode) { OR (`user_id` = `profile` AND `subject_id` = `visitor`) ) as `relation_created` '); - $getFriendInfo->bindValue('visitor', $app->getUserId()); + $getFriendInfo->bindValue('visitor', user_session_current('user_id', 0)); $getFriendInfo->bindValue('profile', $profile['user_id']); $friendInfo = $getFriendInfo->execute() ? $getFriendInfo->fetch(PDO::FETCH_ASSOC) : []; @@ -161,7 +161,7 @@ switch ($mode) { 'can_edit' => $canEdit ?? false, 'is_editing' => $isEditing, 'perms' => $perms, - 'profile_fields' => $app->hasActiveSession() ? user_profile_fields_display($profile, !$isEditing) : [], + 'profile_fields' => user_session_active() ? user_profile_fields_display($profile, !$isEditing) : [], 'has_background' => is_file(build_path($app->getStoragePath(), 'backgrounds/original', "{$profile['user_id']}.msz")), ]); echo tpl_render('user.profile'); diff --git a/public/relations.php b/public/relations.php index 1e7165cf..509b22ab 100644 --- a/public/relations.php +++ b/public/relations.php @@ -8,7 +8,7 @@ if (empty($_SERVER['HTTP_REFERER']) || !is_local_url($_SERVER['HTTP_REFERER'])) return; } -if (!$app->hasActiveSession()) { +if (!user_session_active()) { echo render_error(403); return; } @@ -24,14 +24,14 @@ switch ($_GET['m'] ?? null) { break; } - if (user_relation_add($app->getUserId(), $subjectId, $type) !== MSZ_USER_RELATION_E_OK) { + if (user_relation_add(user_session_current('user_id', 0), $subjectId, $type) !== MSZ_USER_RELATION_E_OK) { echo render_error(500); return; } break; case 'remove': - if (!user_relation_remove($app->getUserId(), $subjectId)) { + if (!user_relation_remove(user_session_current('user_id', 0), $subjectId)) { echo render_error(500); return; } diff --git a/public/settings.php b/public/settings.php index 982520e8..b141c447 100644 --- a/public/settings.php +++ b/public/settings.php @@ -6,7 +6,7 @@ require_once __DIR__ . '/../misuzu.php'; $queryOffset = (int)($_GET['o'] ?? 0); $queryTake = 15; -$userPerms = perms_get_user(MSZ_PERMS_USER, $app->getUserId()); +$userPerms = perms_get_user(MSZ_PERMS_USER, user_session_current('user_id', 0)); $perms = [ 'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE), 'edit_avatar' => perms_check($userPerms, MSZ_PERM_USER_CHANGE_AVATAR), @@ -14,16 +14,16 @@ $perms = [ 'edit_about' => perms_check($userPerms, MSZ_PERM_USER_EDIT_ABOUT), ]; -if (!$app->hasActiveSession()) { +if (!user_session_active()) { echo render_error(403); return; } $settingsUserId = !empty($_REQUEST['user']) && perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS) ? (int)$_REQUEST['user'] - : $app->getUserId(); + : user_session_current('user_id', 0); -if ($settingsUserId !== $app->getUserId() && !user_exists($settingsUserId)) { +if ($settingsUserId !== user_session_current('user_id', 0) && !user_exists($settingsUserId)) { echo render_error(400); return; } @@ -235,7 +235,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $settingsErrors[] = 'Invalid session.'; } elseif ((int)$session['user_id'] !== $settingsUserId) { $settingsErrors[] = 'You may only end your own sessions.'; - } elseif ((int)$session['session_id'] === $app->getSessionId()) { + } elseif ((int)$session['session_id'] === user_session_current('session_id')) { header('Location: /auth.php?m=logout&s=' . csrf_token('logout')); return; } else { @@ -404,7 +404,7 @@ switch ($settingsMode) { $sessions = $getSessions->execute() ? $getSessions->fetchAll() : []; tpl_vars([ - 'active_session_id' => $app->getSessionId(), + 'active_session_id' => user_session_current('session_id'), 'user_sessions' => $sessions, 'sessions_offset' => $queryOffset, 'sessions_take' => $queryTake, diff --git a/src/Application.php b/src/Application.php index e964d3bc..39b1c48d 100644 --- a/src/Application.php +++ b/src/Application.php @@ -31,18 +31,6 @@ final class Application 'sendmail' => Swift_SendmailTransport::class, ]; - /** - * Active Session ID. - * @var int - */ - private $currentSessionId = 0; - - /** - * Active User ID. - * @var int - */ - private $currentUserId = 0; - private $config = []; private $mailerInstance = null; @@ -105,63 +93,6 @@ final class Application return is_readable($path) && is_writable($path); } - /** - * Starts a user session. - * @param int $userId - * @param string $sessionKey - */ - public function startSession(int $userId, string $sessionKey): void - { - $dbc = Database::connection(); - - $findSession = $dbc->prepare(' - SELECT `session_id`, `expires_on` - FROM `msz_sessions` - WHERE `user_id` = :user_id - AND `session_key` = :session_key - '); - $findSession->bindValue('user_id', $userId); - $findSession->bindValue('session_key', $sessionKey); - $sessionData = $findSession->execute() ? $findSession->fetch() : false; - - if ($sessionData) { - $expiresOn = new Carbon($sessionData['expires_on']); - - if ($expiresOn->isPast()) { - $deleteSession = $dbc->prepare(' - DELETE FROM `msz_sessions` - WHERE `session_id` = :session_id - '); - $deleteSession->bindValue('session_id', $sessionData['session_id']); - $deleteSession->execute(); - } else { - $this->currentSessionId = (int)$sessionData['session_id']; - $this->currentUserId = $userId; - } - } - } - - public function stopSession(): void - { - $this->currentSessionId = 0; - $this->currentUserId = 0; - } - - public function hasActiveSession(): bool - { - return $this->getSessionId() > 0; - } - - public function getSessionId(): int - { - return $this->currentSessionId; - } - - public function getUserId(): int - { - return $this->currentUserId; - } - /** * Sets up the database module. */ diff --git a/src/Users/session.php b/src/Users/session.php index 31395689..9c7a4f33 100644 --- a/src/Users/session.php +++ b/src/Users/session.php @@ -1,6 +1,7 @@ execute() ? $sessionKey : ''; } -function user_session_find(int $sessionId): array +function user_session_find($sessionId, bool $byKey = false): array { - if ($sessionId < 1) { + if (!$byKey && $sessionId < 1) { return []; } - $findSession = Database::prepare(' + $findSession = Database::prepare(sprintf(' SELECT `session_id`, `user_id`, INET6_NTOA(`session_ip`) as `session_ip`, `session_country`, `user_agent`, `session_key`, `created_at`, `expires_on` FROM `msz_sessions` - WHERE `session_id` = :session_id - '); + WHERE `%s` = :session_id + ', $byKey ? 'session_key' : 'session_id')); $findSession->bindValue('session_id', $sessionId); $session = $findSession->execute() ? $findSession->fetch(PDO::FETCH_ASSOC) : false; return $session ? $session : []; } -function user_session_delete(int $sessionId): bool +function user_session_delete(int $sessionId): void { $deleteSession = Database::prepare(' DELETE FROM `msz_sessions` WHERE `session_id` = :session_id '); $deleteSession->bindValue('session_id', $sessionId); - return $deleteSession->execute(); + $deleteSession->execute(); } function user_session_generate_key(): string @@ -73,3 +74,51 @@ function user_session_purge_all(int $userId): void 'user_id' => $userId, ]); } + +// the functions below this line are imperative + +function user_session_start(int $userId, string $sessionKey): bool +{ + $session = user_session_find($sessionKey, true); + + if (!$session + || $session['user_id'] !== $userId) { + return false; + } + + if (time() >= strtotime($session['expires_on'])) { + user_session_delete($session['session_id']); + return false; + } + + $GLOBALS[MSZ_SESSION_DATA_STORE] = $session; + return true; +} + +function user_session_stop(bool $delete = false): void +{ + if (empty($GLOBALS[MSZ_SESSION_DATA_STORE])) { + return; + } + + if ($delete) { + user_session_delete($GLOBALS[MSZ_SESSION_DATA_STORE]['session_id']); + } + + $GLOBALS[MSZ_SESSION_DATA_STORE] = []; +} + +function user_session_current(?string $variable = null, $default = null) +{ + if (empty($variable)) { + return $GLOBALS[MSZ_SESSION_DATA_STORE] ?? []; + } + + return $GLOBALS[MSZ_SESSION_DATA_STORE][$variable] ?? $default; +} + +function user_session_active(): bool +{ + return !empty($GLOBALS[MSZ_SESSION_DATA_STORE]) + && time() < strtotime($GLOBALS[MSZ_SESSION_DATA_STORE]['expires_on']); +}