Skip to content

Commit

Permalink
GH-150 Move local ident login handling to a separate unit of code
Browse files Browse the repository at this point in the history
  • Loading branch information
mdziekon committed Feb 14, 2021
1 parent d70b9ec commit 2a81568
Show file tree
Hide file tree
Showing 3 changed files with 186 additions and 102 deletions.
169 changes: 67 additions & 102 deletions login.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,42 +14,8 @@

includeLang('login');

$sessionCookieKey = getSessionCookieKey();

if($_POST)
{
if ($_POST['uniSelect'] != LOGINPAGE_UNIVERSUMCODE) {
message($_Lang['Login_BadUniversum'], $_Lang['Err_Title']);
}

if (time() < SERVER_MAINOPEN_TSTAMP) {
$serverStartMessage = sprintf(
$_Lang['Login_UniversumNotStarted'],
prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1),
date('H:i:s', SERVER_MAINOPEN_TSTAMP)
);

message($serverStartMessage, $_Lang['Page_Title']);
}

$Username = trim($_POST['username']);
if (preg_match(REGEXP_USERNAME_ABSOLUTE, $Username)) {
$Search['mode'] = 1;
$Search['where'] = "`username` = '{$Username}'";
$Search['password'] = md5($_POST['password']);
$Search['IPHash'] = md5(Users\Session\getCurrentIP());

$rateLimitVerificationResult = Session\Utils\RateLimiter\verifyLoginRateLimit([
'ipHash' => $Search['IPHash'],
]);

if ($rateLimitVerificationResult['isIpRateLimited']) {
$Search['error'] = 5;
$Search['where'] = '';
}
} else {
$Search['error'] = 1;
}
if ($_POST) {
// TODO: Remove this useless block
} else if (Session\Utils\Cookie\hasSessionCookie()) {
$loginAttemptResult = Session\Input\CookieLogin\handleCookieLogin([]);

Expand Down Expand Up @@ -77,77 +43,63 @@
}
}

if(!empty($Search['where']))
{
$Query_User_Fields = "`id`, `username`, `password`, `isAI`";
$Query_User_GetData = "SELECT {$Query_User_Fields} FROM {{table}} WHERE {$Search['where']} LIMIT 1;";
$UserData = doquery($Query_User_GetData, 'users', true);
if($UserData['id'] > 0)
{
include_once($_EnginePath.'/includes/functions/IPandUA_Logger.php');

$PasswordOK = false;
if($Search['mode'] == 1 AND $UserData['password'] == $Search['password'])
{
$PasswordOK = true;
}
if($PasswordOK === true)
{
// User is ready to Login
if($Search['mode'] == 1)
{
if($_POST['rememberme'] == 'on')
{
$Cookie_Expire = time() + TIME_YEAR;
$Cookie_Remember = 1;
}
else
{
$Cookie_Expire = 0;
$Cookie_Remember = 0;
}

$Cookie_Set = Session\Utils\Cookie\packSessionCookie([
'userId' => $UserData['id'],
'username' => $UserData['username'],
'obscuredPasswordHash' => Session\Utils\Cookie\createCookiePasswordHash([
'passwordHash' => $UserData['password'],
]),
'isRememberMeActive' => $Cookie_Remember,
]);

setcookie($sessionCookieKey, $Cookie_Set, $Cookie_Expire, '/', '', false, true);
}

IPandUA_Logger($UserData);
header("Location: ./overview.php");
die();
}
else
{
$Search['error'] = 4;
}
if ($_POST) {
include_once($_EnginePath . '/includes/functions/IPandUA_Logger.php');

$ipHash = md5(Users\Session\getCurrentIP());

$loginAttemptResult = Session\Input\LocalIdentityLogin\handleLocalIdentityLogin([
'input' => &$_POST,
'ipHash' => $ipHash,
'currentTimestamp' => time(),
]);

if ($loginAttemptResult['isSuccess']) {
$userEntity = $loginAttemptResult['payload']['userEntity'];

IPandUA_Logger($userEntity, false);

Session\Utils\Redirects\redirectToOverview();

die();
}
else
{
$Search['error'] = 3;

$Search['mode'] = 1;

Session\Utils\RateLimiter\updateLoginRateLimiterEntry([
'ipHash' => $ipHash,
]);

if (isset($loginAttemptResult['error']['userEntity'])) {
$userEntity = $loginAttemptResult['error']['userEntity'];

IPandUA_Logger($userEntity, true);
}

switch ($loginAttemptResult['error']['code']) {
case 'INVALID_UNIVERSUM_CODE':
$Search['error'] = 6;
break;
case 'UNIVERSUM_NOT_OPEN_YET':
$Search['error'] = 7;
break;
case 'INVALID_USERNAME':
$Search['error'] = 1;
break;
case 'LOGIN_ATTEMPTS_RATE_LIMITED':
$Search['error'] = 5;
break;
case 'USER_NOT_FOUND':
$Search['error'] = 3;
break;
case 'INVALID_PASSWORD':
$Search['error'] = 4;
break;
}
}

if(!empty($Search['error']))
{
if (
$Search['mode'] == 1 &&
!empty($Search['IPHash'])
) {
Session\Utils\RateLimiter\updateLoginRateLimiterEntry([
'ipHash' => $Search['IPHash'],
]);
}

if($UserData['id'] > 0)
{
IPandUA_Logger($UserData, true);
}
if($Search['error'] == 1)
{
message($_Lang['Login_BadSignsUser'], $_Lang['Err_Title']);
Expand Down Expand Up @@ -176,6 +128,19 @@
{
message($_Lang['Login_FailLoginProtection'], $_Lang['Err_Title']);
}
elseif($Search['error'] == 6) {
message($_Lang['Login_BadUniversum'], $_Lang['Err_Title']);
}
elseif($Search['error'] == 7)
{
$errorMessage = $serverStartMessage = sprintf(
$_Lang['Login_UniversumNotStarted'],
prettyDate('d m Y', SERVER_MAINOPEN_TSTAMP, 1),
date('H:i:s', SERVER_MAINOPEN_TSTAMP)
);

message($errorMessage, $_Lang['Err_Title']);
}
else
{
message($_Lang['Login_UnknownError'], $_Lang['Err_Title']);
Expand Down
1 change: 1 addition & 0 deletions modules/session/_includes.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
$includePath = $_EnginePath . 'modules/session/';

include($includePath . './input/cookieLogin.inputHandler.php');
include($includePath . './input/localIdentityLogin.inputHandler.php');

include($includePath . './screens/LoginView/LoginView.component.php');
include($includePath . './screens/LoginView/components/LoginForm/LoginForm.component.php');
Expand Down
118 changes: 118 additions & 0 deletions modules/session/input/localIdentityLogin.inputHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

namespace UniEngine\Engine\Modules\Session\Input\LocalIdentityLogin;

use UniEngine\Engine\Includes\Helpers\Users;
use UniEngine\Engine\Modules\Session;

// Arguments:
// - $params
//
function handleLocalIdentityLogin($params) {
$createSuccess = function ($payload) {
return [
'isSuccess' => true,
'payload' => $payload,
];
};
$createFailure = function ($error) {
return [
'isSuccess' => false,
'error' => $error,
];
};

$input = &$params['input'];
$ipHash = $params['ipHash'];
$currentTimestamp = $params['currentTimestamp'];

if ($input['uniSelect'] != LOGINPAGE_UNIVERSUMCODE) {
return $createFailure([
'code' => 'INVALID_UNIVERSUM_CODE',
]);
}

$serverOpeningTimestamp = SERVER_MAINOPEN_TSTAMP;

if ($currentTimestamp < $serverOpeningTimestamp) {
return $createFailure([
'code' => 'UNIVERSUM_NOT_OPEN_YET',
'openingTimestamp' => $serverOpeningTimestamp,
]);
}

$inputUsername = trim($input['username']);

if (!preg_match(REGEXP_USERNAME_ABSOLUTE, $inputUsername)) {
return $createFailure([
'code' => 'INVALID_USERNAME',
]);
}

$rateLimitVerificationResult = Session\Utils\RateLimiter\verifyLoginRateLimit([
'ipHash' => $ipHash,
]);

if ($rateLimitVerificationResult['isIpRateLimited']) {
return $createFailure([
'code' => 'LOGIN_ATTEMPTS_RATE_LIMITED',
]);
}

$Query_User_Fields = "`id`, `username`, `password`, `isAI`";
$Query_User_GetData = "SELECT {$Query_User_Fields} FROM {{table}} WHERE `username` = '{$inputUsername}' LIMIT 1;";
$userEntity = doquery($Query_User_GetData, 'users', true);

if (
!$userEntity ||
$userEntity['id'] <= 0
) {
return $createFailure([
'code' => 'USER_NOT_FOUND',
]);
}

$inputPassword = $input['password'];
$inputPasswordHash = md5($inputPassword);
$dbPasswordHash = $userEntity['password'];

if ($inputPasswordHash !== $dbPasswordHash) {
return $createFailure([
'code' => 'INVALID_PASSWORD',
'userEntity' => $userEntity,
]);
}

$isRememberMeEnabled = ($input['rememberme'] == 'on');

$sessionCookieKey = getSessionCookieKey();
$sessionCookieValue = Session\Utils\Cookie\packSessionCookie([
'userId' => $userEntity['id'],
'username' => $userEntity['username'],
'obscuredPasswordHash' => Session\Utils\Cookie\createCookiePasswordHash([
'passwordHash' => $dbPasswordHash,
]),
'isRememberMeActive' => ($isRememberMeEnabled ? 1 : 0),
]);
$sessionCookieExpirationTimestamp = (
$isRememberMeEnabled ?
($currentTimestamp + TIME_YEAR) :
0
);

setcookie(
$sessionCookieKey,
$sessionCookieValue,
$sessionCookieExpirationTimestamp,
'/',
'',
false,
true
);

return $createSuccess([
'userEntity' => $userEntity,
]);
}

?>

0 comments on commit 2a81568

Please sign in to comment.