Made imperative bits of the session system procedural like the rest.

This commit is contained in:
flash 2018-10-03 00:34:05 +02:00
parent 787550b000
commit f01a6d5372
17 changed files with 135 additions and 156 deletions

View file

@ -282,11 +282,11 @@ MIG;
exit; exit;
} }
if (isset($_COOKIE['msz_uid'], $_COOKIE['msz_sid'])) { if (isset($_COOKIE['msz_uid'], $_COOKIE['msz_sid'])
$app->startSession((int)$_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($mszUserId);
user_bump_last_active($app->getUserId());
$getUserDisplayInfo = Database::prepare(' $getUserDisplayInfo = Database::prepare('
SELECT SELECT
@ -297,22 +297,21 @@ MIG;
ON u.`display_role` = r.`role_id` ON u.`display_role` = r.`role_id`
WHERE `user_id` = :user_id WHERE `user_id` = :user_id
'); ');
$getUserDisplayInfo->bindValue('user_id', $app->getUserId()); $getUserDisplayInfo->bindValue('user_id', $mszUserId);
$userDisplayInfo = $getUserDisplayInfo->execute() ? $getUserDisplayInfo->fetch() : []; $userDisplayInfo = $getUserDisplayInfo->execute() ? $getUserDisplayInfo->fetch() : [];
tpl_var('current_user', $userDisplayInfo); tpl_var('current_user', $userDisplayInfo);
} }
}
csrf_init($app->getCsrfSecretKey(), empty($userDisplayInfo) ? ip_remote_address() : $_COOKIE['msz_sid']); csrf_init($app->getCsrfSecretKey(), empty($userDisplayInfo) ? ip_remote_address() : $_COOKIE['msz_sid']);
$privateInfo = $app->getPrivateInfo(); $privateInfo = $app->getPrivateInfo();
if (!$misuzuBypassLockdown && $privateInfo['enabled'] && !$app->hasActiveSession()) { if (!$misuzuBypassLockdown && $privateInfo['enabled'] && !empty($userDisplayInfo)) {
if ($app->hasActiveSession()) { if (user_session_active()) {
$generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $app->getUserId()); $generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $userDisplayInfo['user_id']);
if (!perms_check($generalPerms, $privateInfo['permission'])) { if (!perms_check($generalPerms, $privateInfo['permission'])) {
$app->stopSession(); // au revoir user_session_stop(); // au revoir
} }
} else { } else {
http_response_code(401); http_response_code(401);
@ -324,7 +323,7 @@ MIG;
} }
$inManageMode = starts_with($_SERVER['REQUEST_URI'], '/manage'); $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); tpl_var('has_manage_access', $hasManageAccess);
if ($inManageMode) { if ($inManageMode) {
@ -333,6 +332,6 @@ MIG;
exit; exit;
} }
tpl_var('manage_menu', manage_get_menu($app->getUserId())); tpl_var('manage_menu', manage_get_menu($userDisplayInfo['user_id'] ?? 0));
} }
} }

View file

@ -39,7 +39,7 @@ switch ($authMode) {
break; break;
case 'logout': case 'logout':
if (!$app->hasActiveSession()) { if (!user_session_active()) {
header('Location: /'); header('Location: /');
return; return;
} }
@ -47,7 +47,7 @@ switch ($authMode) {
if (csrf_verify('logout', $_GET['s'] ?? '')) { if (csrf_verify('logout', $_GET['s'] ?? '')) {
set_cookie_m('uid', '', -3600); set_cookie_m('uid', '', -3600);
set_cookie_m('sid', '', -3600); set_cookie_m('sid', '', -3600);
user_session_delete($app->getSessionId()); user_session_stop(true);
header('Location: /'); header('Location: /');
return; return;
} }
@ -56,7 +56,7 @@ switch ($authMode) {
break; break;
case 'reset': case 'reset':
if ($app->hasActiveSession()) { if (user_session_active()) {
header('Location: /settings.php'); header('Location: /settings.php');
break; break;
} }
@ -153,7 +153,7 @@ switch ($authMode) {
break; break;
case 'forgot': case 'forgot':
if ($app->hasActiveSession() || $preventPasswordReset) { if (user_session_active() || $preventPasswordReset) {
header('Location: /'); header('Location: /');
break; break;
} }
@ -239,7 +239,7 @@ MSG;
break; break;
case 'login': case 'login':
if ($app->hasActiveSession()) { if (user_session_active()) {
header('Location: /'); header('Location: /');
break; break;
} }
@ -314,7 +314,7 @@ MSG;
break; break;
} }
$app->startSession($userId, $sessionKey); user_session_start($userId, $sessionKey);
$cookieLife = Carbon::now()->addMonth()->timestamp; $cookieLife = Carbon::now()->addMonth()->timestamp;
set_cookie_m('uid', $userId, $cookieLife); set_cookie_m('uid', $userId, $cookieLife);
set_cookie_m('sid', $sessionKey, $cookieLife); set_cookie_m('sid', $sessionKey, $cookieLife);
@ -333,7 +333,7 @@ MSG;
break; break;
case 'register': case 'register':
if ($app->hasActiveSession()) { if (user_session_active()) {
header('Location: /'); header('Location: /');
} }

View file

@ -11,7 +11,7 @@ $changelogDate = $_GET['d'] ?? '';
$changelogUser = (int)($_GET['u'] ?? 0); $changelogUser = (int)($_GET['u'] ?? 0);
$changelogTags = $_GET['t'] ?? ''; $changelogTags = $_GET['t'] ?? '';
$commentPerms = comments_get_perms($app->getUserId()); $commentPerms = comments_get_perms(user_session_current('user_id', 0));
tpl_vars([ tpl_vars([
'changelog_offset' => $changelogOffset, 'changelog_offset' => $changelogOffset,
@ -62,7 +62,7 @@ if ($changelogChange > 0) {
"changelog-date-{$change['change_date']}", "changelog-date-{$change['change_date']}",
true true
), ),
'comments' => comments_category_get($commentsCategory['category_id'], $app->getUserId()), 'comments' => comments_category_get($commentsCategory['category_id'], user_session_current('user_id', 0)),
]); ]);
return; return;
} }
@ -88,7 +88,7 @@ if (!$changes) {
if (!empty($changelogDate) && count($changes) > 0) { if (!empty($changelogDate) && count($changes) > 0) {
tpl_vars([ tpl_vars([
'comments_category' => $commentsCategory = comments_category_info("changelog-date-{$changelogDate}", true), '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)),
]); ]);
} }

View file

@ -20,12 +20,12 @@ if (!csrf_verify('comments', $_REQUEST['csrf'] ?? '')) {
return; return;
} }
if ($app->getUserId() < 1) { if (!user_session_active()) {
echo render_info_or_json($isXHR, 'You must be logged in to manage comments.', 401); echo render_info_or_json($isXHR, 'You must be logged in to manage comments.', 401);
return; return;
} }
$commentPerms = comments_get_perms($app->getUserId()); $commentPerms = comments_get_perms(user_session_current('user_id', 0));
switch ($_GET['m'] ?? null) { switch ($_GET['m'] ?? null) {
case 'vote': case 'vote':
@ -46,7 +46,7 @@ switch ($_GET['m'] ?? null) {
$vote = MSZ_COMMENTS_VOTE_TYPES[(int)($_GET['v'] ?? 0)]; $vote = MSZ_COMMENTS_VOTE_TYPES[(int)($_GET['v'] ?? 0)];
$voteResult = comments_vote_add( $voteResult = comments_vote_add(
$comment, $comment,
$app->getUserId(), user_session_current('user_id', 0),
$vote $vote
); );
@ -72,7 +72,7 @@ switch ($_GET['m'] ?? null) {
} }
if (!$commentPerms['can_delete_any'] 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); echo render_info_or_json($isXHR, "You're not allowed to delete comments made by others.", 403);
break; break;
} }
@ -147,7 +147,7 @@ switch ($_GET['m'] ?? null) {
} }
$commentId = comments_post_create( $commentId = comments_post_create(
$app->getUserId(), user_session_current('user_id', 0),
$categoryId, $categoryId,
$commentText, $commentText,
$commentPin, $commentPin,

View file

@ -17,7 +17,7 @@ if (empty($forum) || ($forum['forum_type'] == MSZ_FORUM_TYPE_LINK && empty($foru
return; 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)) { if (!perms_check($perms, MSZ_FORUM_PERM_VIEW_FORUM)) {
echo render_error(403); echo render_error(403);
@ -33,14 +33,14 @@ if ($forum['forum_type'] == MSZ_FORUM_TYPE_LINK) {
} }
$topics = forum_may_have_topics($forum['forum_type']) $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) { foreach ($forum['forum_subforums'] as $skey => $subforum) {
$forum['forum_subforums'][$skey]['forum_subforums'] $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', [ echo tpl_render('forum.forum', [

View file

@ -1,11 +1,11 @@
<?php <?php
require_once __DIR__ . '/../../misuzu.php'; require_once __DIR__ . '/../../misuzu.php';
$categories = forum_get_root_categories($app->getUserId()); $categories = forum_get_root_categories(user_session_current('user_id', 0));
$blankForum = count($categories) <= 1 && $categories[0]['forum_children'] < 1; $blankForum = count($categories) <= 1 && $categories[0]['forum_children'] < 1;
foreach ($categories as $key => $category) { 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) { foreach ($categories[$key]['forum_subforums'] as $skey => $sub) {
if (!forum_may_have_children($sub['forum_type'])) { if (!forum_may_have_children($sub['forum_type'])) {
@ -13,7 +13,7 @@ foreach ($categories as $key => $category) {
} }
$categories[$key]['forum_subforums'][$skey]['forum_subforums'] $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);
} }
} }

View file

@ -3,7 +3,7 @@ use Misuzu\Database;
require_once __DIR__ . '/../../misuzu.php'; require_once __DIR__ . '/../../misuzu.php';
if (!$app->hasActiveSession()) { if (!user_session_active()) {
echo render_error(403); echo render_error(403);
return; return;
} }
@ -67,7 +67,7 @@ if (empty($forum)) {
return; 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'] if ($forum['forum_archived']
|| !empty($topic['topic_locked']) || !empty($topic['topic_locked'])
@ -83,7 +83,7 @@ if (!forum_may_have_topics($forum['forum_type'])) {
} }
if ($postRequest) { if ($postRequest) {
if (!csrf_verify('settings', $_POST['csrf'] ?? '')) { if (!csrf_verify('forum_post', $_POST['csrf'] ?? '')) {
echo 'Could not verify request.'; echo 'Could not verify request.';
return; return;
} }
@ -116,18 +116,18 @@ if ($postRequest) {
return; 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( $postId = forum_post_create(
$topicId, $topicId,
$forum['forum_id'], $forum['forum_id'],
$app->getUserId(), user_session_current('user_id', 0),
ip_remote_address(), ip_remote_address(),
$postText, $postText,
MSZ_PARSER_BBCODE 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}"); header("Location: /forum/topic.php?p={$postId}#p{$postId}");
return; return;

View file

@ -22,7 +22,7 @@ if (!$topic) {
return; 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)) { if (!perms_check($perms, MSZ_FORUM_PERM_VIEW_FORUM)) {
echo render_error(403); echo render_error(403);
@ -36,7 +36,7 @@ if (!$posts) {
return; 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', [ echo tpl_render('forum.topic', [
'topic_breadcrumbs' => forum_get_breadcrumbs($topic['forum_id']), 'topic_breadcrumbs' => forum_get_breadcrumbs($topic['forum_id']),

View file

@ -3,7 +3,7 @@ use Misuzu\Database;
require_once __DIR__ . '/../../misuzu.php'; 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); $queryOffset = (int)($_GET['o'] ?? 0);
switch ($_GET['v'] ?? null) { switch ($_GET['v'] ?? null) {
@ -113,11 +113,11 @@ switch ($_GET['v'] ?? null) {
if ($changeId < 1) { if ($changeId < 1) {
$changeId = Database::lastInsertId(); $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); header('Location: ?v=change&c=' . $changeId);
return; return;
} else { } 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']); $addTag->bindValue('tag_id', $_POST['add_tag']);
if ($addTag->execute()) { if ($addTag->execute()) {
audit_log('CHANGELOG_TAG_ADD', $app->getUserId(), [ audit_log('CHANGELOG_TAG_ADD', user_session_current('user_id', 0), [
$changeId, $changeId,
$_POST['add_tag'] $_POST['add_tag']
]); ]);
@ -144,7 +144,7 @@ switch ($_GET['v'] ?? null) {
$removeTag->bindValue('tag_id', $_POST['remove_tag']); $removeTag->bindValue('tag_id', $_POST['remove_tag']);
if ($removeTag->execute()) { if ($removeTag->execute()) {
audit_log('CHANGELOG_TAG_REMOVE', $app->getUserId(), [ audit_log('CHANGELOG_TAG_REMOVE', user_session_current('user_id', 0), [
$changeId, $changeId,
$_POST['remove_tag'] $_POST['remove_tag']
]); ]);
@ -288,11 +288,11 @@ switch ($_GET['v'] ?? null) {
if ($tagId < 1) { if ($tagId < 1) {
$tagId = Database::lastInsertId(); $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); header('Location: ?v=tag&t=' . $tagId);
return; return;
} else { } 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) { if ($actionId < 1) {
$actionId = Database::lastInsertId(); $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); header('Location: ?v=action&a=' . $actionId);
return; return;
} else { } else {
audit_log('CHANGELOG_ACTION_EDIT', $app->getUserId(), [$actionId]); audit_log('CHANGELOG_ACTION_EDIT', user_session_current('user_id', 0), [$actionId]);
} }
} }
} }

View file

@ -1,7 +1,7 @@
<?php <?php
require_once __DIR__ . '/../../misuzu.php'; require_once __DIR__ . '/../../misuzu.php';
$generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $app->getUserId()); $generalPerms = perms_get_user(MSZ_PERMS_GENERAL, user_session_current('user_id', 0));
switch ($_GET['v'] ?? null) { switch ($_GET['v'] ?? null) {
default: default:

View file

@ -3,7 +3,7 @@ use Misuzu\Database;
require_once __DIR__ . '/../../misuzu.php'; 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'; $isPostRequest = $_SERVER['REQUEST_METHOD'] === 'POST';
$queryQffset = (int)($_GET['o'] ?? 0); $queryQffset = (int)($_GET['o'] ?? 0);

View file

@ -57,9 +57,9 @@ if ($postId !== null) {
echo tpl_render('news.post', [ echo tpl_render('news.post', [
'post' => $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_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; return;
} }

View file

@ -99,7 +99,7 @@ switch ($mode) {
} }
$isEditing = false; $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 = [ $perms = [
'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE), 'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE),
'edit_avatar' => perms_check($userPerms, MSZ_PERM_USER_CHANGE_AVATAR), '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), 'edit_about' => perms_check($userPerms, MSZ_PERM_USER_EDIT_ABOUT),
]; ];
if ($app->hasActiveSession()) { if (user_session_active()) {
$canEdit = $app->getUserId() === $profile['user_id'] $canEdit = user_session_current('user_id', 0) === $profile['user_id']
|| perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS); || perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS);
$isEditing = $canEdit && $mode === 'edit'; $isEditing = $canEdit && $mode === 'edit';
@ -134,7 +134,7 @@ switch ($mode) {
OR (`user_id` = `profile` AND `subject_id` = `visitor`) OR (`user_id` = `profile` AND `subject_id` = `visitor`)
) as `relation_created` ) as `relation_created`
'); ');
$getFriendInfo->bindValue('visitor', $app->getUserId()); $getFriendInfo->bindValue('visitor', user_session_current('user_id', 0));
$getFriendInfo->bindValue('profile', $profile['user_id']); $getFriendInfo->bindValue('profile', $profile['user_id']);
$friendInfo = $getFriendInfo->execute() ? $getFriendInfo->fetch(PDO::FETCH_ASSOC) : []; $friendInfo = $getFriendInfo->execute() ? $getFriendInfo->fetch(PDO::FETCH_ASSOC) : [];
@ -161,7 +161,7 @@ switch ($mode) {
'can_edit' => $canEdit ?? false, 'can_edit' => $canEdit ?? false,
'is_editing' => $isEditing, 'is_editing' => $isEditing,
'perms' => $perms, '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")), 'has_background' => is_file(build_path($app->getStoragePath(), 'backgrounds/original', "{$profile['user_id']}.msz")),
]); ]);
echo tpl_render('user.profile'); echo tpl_render('user.profile');

View file

@ -8,7 +8,7 @@ if (empty($_SERVER['HTTP_REFERER']) || !is_local_url($_SERVER['HTTP_REFERER']))
return; return;
} }
if (!$app->hasActiveSession()) { if (!user_session_active()) {
echo render_error(403); echo render_error(403);
return; return;
} }
@ -24,14 +24,14 @@ switch ($_GET['m'] ?? null) {
break; 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); echo render_error(500);
return; return;
} }
break; break;
case 'remove': case 'remove':
if (!user_relation_remove($app->getUserId(), $subjectId)) { if (!user_relation_remove(user_session_current('user_id', 0), $subjectId)) {
echo render_error(500); echo render_error(500);
return; return;
} }

View file

@ -6,7 +6,7 @@ require_once __DIR__ . '/../misuzu.php';
$queryOffset = (int)($_GET['o'] ?? 0); $queryOffset = (int)($_GET['o'] ?? 0);
$queryTake = 15; $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 = [ $perms = [
'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE), 'edit_profile' => perms_check($userPerms, MSZ_PERM_USER_EDIT_PROFILE),
'edit_avatar' => perms_check($userPerms, MSZ_PERM_USER_CHANGE_AVATAR), '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), 'edit_about' => perms_check($userPerms, MSZ_PERM_USER_EDIT_ABOUT),
]; ];
if (!$app->hasActiveSession()) { if (!user_session_active()) {
echo render_error(403); echo render_error(403);
return; return;
} }
$settingsUserId = !empty($_REQUEST['user']) && perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS) $settingsUserId = !empty($_REQUEST['user']) && perms_check($userPerms, MSZ_PERM_USER_MANAGE_USERS)
? (int)$_REQUEST['user'] ? (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); echo render_error(400);
return; return;
} }
@ -235,7 +235,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$settingsErrors[] = 'Invalid session.'; $settingsErrors[] = 'Invalid session.';
} elseif ((int)$session['user_id'] !== $settingsUserId) { } elseif ((int)$session['user_id'] !== $settingsUserId) {
$settingsErrors[] = 'You may only end your own sessions.'; $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')); header('Location: /auth.php?m=logout&s=' . csrf_token('logout'));
return; return;
} else { } else {
@ -404,7 +404,7 @@ switch ($settingsMode) {
$sessions = $getSessions->execute() ? $getSessions->fetchAll() : []; $sessions = $getSessions->execute() ? $getSessions->fetchAll() : [];
tpl_vars([ tpl_vars([
'active_session_id' => $app->getSessionId(), 'active_session_id' => user_session_current('session_id'),
'user_sessions' => $sessions, 'user_sessions' => $sessions,
'sessions_offset' => $queryOffset, 'sessions_offset' => $queryOffset,
'sessions_take' => $queryTake, 'sessions_take' => $queryTake,

View file

@ -31,18 +31,6 @@ final class Application
'sendmail' => Swift_SendmailTransport::class, 'sendmail' => Swift_SendmailTransport::class,
]; ];
/**
* Active Session ID.
* @var int
*/
private $currentSessionId = 0;
/**
* Active User ID.
* @var int
*/
private $currentUserId = 0;
private $config = []; private $config = [];
private $mailerInstance = null; private $mailerInstance = null;
@ -105,63 +93,6 @@ final class Application
return is_readable($path) && is_writable($path); 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. * Sets up the database module.
*/ */

View file

@ -1,6 +1,7 @@
<?php <?php
use Misuzu\Database; use Misuzu\Database;
define('MSZ_SESSION_DATA_STORE', '_msz_user_session_data');
define('MSZ_SESSION_KEY_SIZE', 64); define('MSZ_SESSION_KEY_SIZE', 64);
function user_session_create( function user_session_create(
@ -31,32 +32,32 @@ function user_session_create(
return $createSession->execute() ? $sessionKey : ''; return $createSession->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 []; return [];
} }
$findSession = Database::prepare(' $findSession = Database::prepare(sprintf('
SELECT SELECT
`session_id`, `user_id`, INET6_NTOA(`session_ip`) as `session_ip`, `session_id`, `user_id`, INET6_NTOA(`session_ip`) as `session_ip`,
`session_country`, `user_agent`, `session_key`, `created_at`, `expires_on` `session_country`, `user_agent`, `session_key`, `created_at`, `expires_on`
FROM `msz_sessions` FROM `msz_sessions`
WHERE `session_id` = :session_id WHERE `%s` = :session_id
'); ', $byKey ? 'session_key' : 'session_id'));
$findSession->bindValue('session_id', $sessionId); $findSession->bindValue('session_id', $sessionId);
$session = $findSession->execute() ? $findSession->fetch(PDO::FETCH_ASSOC) : false; $session = $findSession->execute() ? $findSession->fetch(PDO::FETCH_ASSOC) : false;
return $session ? $session : []; return $session ? $session : [];
} }
function user_session_delete(int $sessionId): bool function user_session_delete(int $sessionId): void
{ {
$deleteSession = Database::prepare(' $deleteSession = Database::prepare('
DELETE FROM `msz_sessions` DELETE FROM `msz_sessions`
WHERE `session_id` = :session_id WHERE `session_id` = :session_id
'); ');
$deleteSession->bindValue('session_id', $sessionId); $deleteSession->bindValue('session_id', $sessionId);
return $deleteSession->execute(); $deleteSession->execute();
} }
function user_session_generate_key(): string function user_session_generate_key(): string
@ -73,3 +74,51 @@ function user_session_purge_all(int $userId): void
'user_id' => $userId, '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']);
}