From b41097e922d6f487468acd9ccc9543301bdeb309 Mon Sep 17 00:00:00 2001 From: Sveneld Date: Sat, 2 Mar 2024 16:40:10 +0100 Subject: [PATCH] UserComponent AuthComponent --- actions-qrcode.php | 23 +- actions-sms.php | 121 ++++----- actions-web.php | 102 ++------ admin.php | 18 +- command.php | 72 +++--- common.php | 144 +---------- index.php | 33 +-- phpcs.xml.dist | 1 + receive.php | 1 + scan.php | 21 +- src/Authentication/Auth.php | 127 ++++++++++ src/Purifier/PhonePurifier.php | 35 +++ src/Purifier/PhonePurifierInterface.php | 8 + src/User/User.php | 69 +++++ tests/Authentication/AuthTest.php | 318 ++++++++++++++++++++++++ tests/MysqliResult.php | 30 +++ tests/Purifier/PhonePurifierTest.php | 57 +++++ tests/User/UserTest.php | 97 ++++++++ 18 files changed, 906 insertions(+), 371 deletions(-) create mode 100644 src/Authentication/Auth.php create mode 100644 src/Purifier/PhonePurifier.php create mode 100644 src/Purifier/PhonePurifierInterface.php create mode 100644 src/User/User.php create mode 100644 tests/Authentication/AuthTest.php create mode 100644 tests/MysqliResult.php create mode 100644 tests/Purifier/PhonePurifierTest.php create mode 100644 tests/User/UserTest.php diff --git a/actions-qrcode.php b/actions-qrcode.php index 9d4bb4f..febadb8 100644 --- a/actions-qrcode.php +++ b/actions-qrcode.php @@ -3,17 +3,12 @@ function response($message,$error=0,$log=1) { - global $db,$systemname,$systemURL; - if ($log==1 AND $message) - { - if (isset($_COOKIE["loguserid"])) - { - $userid=$db->escape(trim($_COOKIE["loguserid"])); - } - else $userid=0; - $number=getphonenumber($userid); - logresult($number,$message); - } + global $db, $systemname, $systemURL, $user, $auth; + if ($log == 1 and $message) { + $userid = $auth->getUserId(); + $number = $user->findPhoneNumber($userid); + logresult($number, $message); + } $db->commit(); echo '',$systemname,''; echo ''; @@ -43,7 +38,7 @@ function response($message,$error=0,$log=1) function rent($userId,$bike,$force=FALSE) { - global $db,$forcestack,$watches,$credit; + global $db,$forcestack,$watches,$credit, $user; $stacktopbike=FALSE; $bikeNum = $bike; $requiredcredit=$credit["min"]+$credit["rent"]+$credit["longrental"]; @@ -90,8 +85,8 @@ function rent($userId,$bike,$force=FALSE) $result=$db->query("SELECT standName FROM stands WHERE standId='$standid'"); $row=$result->fetch_assoc(); $stand=$row["standName"]; - $user=getusername($userId); - notifyAdmins(_('Bike')." ".$bike." "._('rented out of stack by')." ".$user.". ".$stacktopbike." "._('was on the top of the stack at')." ".$stand.".",ERROR); + $userName = $user->findUserName($userId); + notifyAdmins(_('Bike')." ".$bike." "._('rented out of stack by')." ".$userName.". ".$stacktopbike." "._('was on the top of the stack at')." ".$stand.".",ERROR); } if ($forcestack AND $stacktopbike<>$bike) { diff --git a/actions-sms.php b/actions-sms.php index 6412687..86b05f9 100644 --- a/actions-sms.php +++ b/actions-sms.php @@ -8,9 +8,9 @@ function help($number) { - global $db, $smsSender; - $userid=getUser($number); - $privileges=getprivileges($userid); + global $db, $smsSender, $user; + $userid = $user->findUserIdByNumber($number); + $privileges = $user->findPrivileges($userid); if ($privileges>0) { $message="Commands:\nHELP\n"; @@ -33,20 +33,11 @@ function unknownCommand($number,$command) $smsSender->send($number,_('Error. The command')." ".$command." "._('does not exist. If you need help, send:')." HELP"); } -/** - * @deprecated, call getuserid() directly - */ -function getUser($number) -{ - return getuserid($number); -} - function validateNumber($number) { - if (getUser($number)) - return true; - else - return false; + global $user; + + return !empty($user->findUserIdByNumber($number)); } function info($number,$stand) @@ -101,8 +92,8 @@ function validateReceivedSMS($number,$receivedargumentno,$requiredargumentno,$er function credit($number) { - global $db, $smsSender; - $userid=getUser($number); + global $db, $smsSender, $user; + $userid=$user->findUserIdByNumber($number); $usercredit=getusercredit($userid).getcreditcurrency(); $smsSender->send($number,_('Your remaining credit:')." ".$usercredit); } @@ -110,9 +101,9 @@ function credit($number) function rent($number,$bike,$force=FALSE) { - global $db,$forcestack,$watches,$credit, $smsSender; + global $db,$forcestack,$watches,$credit, $smsSender, $user; $stacktopbike=FALSE; - $userId = getUser($number); + $userId = $user->findUserIdByNumber($number); $bikeNum = intval($bike); $requiredcredit=$credit["min"]+$credit["rent"]+$credit["longrental"]; @@ -178,8 +169,8 @@ function rent($number,$bike,$force=FALSE) $result=$db->query("SELECT standName FROM stands WHERE standId='$standid'"); $row=$result->fetch_assoc(); $stand=$row["standName"]; - $user=getusername($userId); - notifyAdmins(_('Bike')." ".$bike." "._('rented out of stack by')." ".$user.". ".$stacktopbike." "._('was on the top of the stack at')." ".$stand.".",ERROR); + $userName=$user->findUserName($userId); + notifyAdmins(_('Bike')." ".$bike." "._('rented out of stack by')." ".$userName.". ".$stacktopbike." "._('was on the top of the stack at')." ".$stand.".",ERROR); } if ($forcestack AND $stacktopbike<>$bikeNum) { @@ -202,12 +193,9 @@ function rent($number,$bike,$force=FALSE) $row=$result->fetch_assoc(); $note=$row["note"]; $currentUserNumber = false; - if ($currentUser) - { - $result=$db->query("SELECT number FROM users WHERE userId=$currentUser"); - $row =$result->fetch_assoc(); - $currentUserNumber =$row["number"]; - } + if ($currentUser) { + $currentUserNumber = $user->findPhoneNumber($currentUser); + } $newCode = sprintf("%04d",rand(100,9900));//do not create a code with more than one leading zero or more than two leading 9s (kind of unusual/unsafe). @@ -250,8 +238,8 @@ function rent($number,$bike,$force=FALSE) function returnBike($number,$bike,$stand,$message="",$force=FALSE) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $bikeNum = intval($bike); $stand = strtoupper($stand); @@ -313,12 +301,9 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) $result=$db->query("SELECT note FROM notes WHERE bikeNum=$bikeNum AND deleted IS NULL ORDER BY time DESC LIMIT 1"); $row=$result->fetch_assoc(); $note=$row["note"]; - if($currentUser) - { - $result=$db->query("SELECT number FROM users WHERE userId=$currentUser"); - $row =$result->fetch_assoc(); - $currentUserNumber =$row["number"]; - } + if ($currentUser) { + $currentUserNumber = $user->findPhoneNumber($currentUser); + } } if (!preg_match("/return[\s,\.]+[0-9]+[\s,\.]+[a-zA-Z0-9]+[\s,\.]+(.*)/i",$message ,$matches)) @@ -331,10 +316,8 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) if ($userNote) { $db->query("INSERT INTO notes SET bikeNum=$bikeNum,userId=$userId,note='$userNote'"); - $result=$db->query("SELECT userName,number FROM users WHERE userId='$userId'"); - $row=$result->fetch_assoc(); - $userName=$row["userName"]; - $phone=$row["number"]; + $userName = $user->findUserName($userId); + $phone = $user->findPhoneNumber($userId); $result=$db->query("SELECT stands.standName FROM bikes LEFT JOIN users ON bikes.currentUser=users.userID LEFT JOIN stands ON bikes.currentStand=stands.standId WHERE bikeNum=$bikeNum"); $row=$result->fetch_assoc(); $standName=$row["standName"]; @@ -387,8 +370,8 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) function where($number,$bike) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $bikeNum = intval($bike); $result=$db->query("SELECT number,userName,stands.standName FROM bikes LEFT JOIN users on bikes.currentUser=users.userID LEFT JOIN stands on bikes.currentStand=stands.standId where bikeNum=$bikeNum"); @@ -424,9 +407,9 @@ function where($number,$bike) function listBikes($number,$stand) { - global $db,$forcestack, $smsSender; + global $db,$forcestack, $smsSender, $user; $stacktopbike=FALSE; - $userId = getUser($number); + $userId = $user->findUserIdByNumber($number); $stand = strtoupper($stand); if (!preg_match("/^[A-Z]+[0-9]*$/",$stand)) @@ -474,8 +457,8 @@ function listBikes($number,$stand) function freeBikes($number) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $result=$db->query("SELECT count(bikeNum) as bikeCount,placeName from bikes join stands on bikes.currentStand=stands.standId where stands.serviceTag=0 group by placeName having bikeCount>0 order by placeName"); $rentedBikes=$result->num_rows; @@ -545,8 +528,8 @@ function log_sms($sms_uuid, $sender, $receive_time, $sms_text, $ip) function delnote($number,$bikeNum,$message) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $bikeNum=trim($bikeNum); if(preg_match("/^[0-9]*$/",$bikeNum)) @@ -634,8 +617,8 @@ function delnote($number,$bikeNum,$message) function untag($number,$standName,$message) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); checkUserPrivileges($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); @@ -693,8 +676,8 @@ function untag($number,$standName,$message) function delstandnote($number,$standName,$message) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); checkUserPrivileges($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); @@ -752,8 +735,8 @@ function delstandnote($number,$standName,$message) function standNote($number,$standName,$message) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); @@ -800,9 +783,8 @@ function standNote($number,$standName,$message) function tag($number,$standName,$message) { - global $db, $smsSender; - $userId = getUser($number); - + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); if ($result->num_rows!=1) @@ -846,8 +828,8 @@ function tag($number,$standName,$message) function note($number,$bikeNum,$message) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $bikeNum=trim($bikeNum); if(preg_match("/^[0-9]*$/",$bikeNum)) @@ -928,8 +910,8 @@ function note($number,$bikeNum,$message) function last($number,$bike) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $bikeNum = intval($bike); $result=$db->query("SELECT bikeNum FROM bikes where bikeNum=$bikeNum"); @@ -965,8 +947,8 @@ function last($number,$bike) function revert($number,$bikeNum) { - global $db, $smsSender; - $userId = getUser($number); + global $db, $smsSender, $user; + $userId = $user->findUserIdByNumber($number); $result=$db->query("SELECT currentUser FROM bikes WHERE bikeNum=$bikeNum AND currentUser<>'NULL'"); if (!$result->num_rows) @@ -977,7 +959,7 @@ function revert($number,$bikeNum) else { $row=$result->fetch_assoc(); - $revertusernumber=getphonenumber($row["currentUser"]); + $revertusernumber=$user->findPhoneNumber($row["currentUser"]); } $result=$db->query("SELECT parameter,standName FROM stands LEFT JOIN history ON stands.standId=parameter WHERE bikeNum=$bikeNum AND action IN ('RETURN','FORCERETURN') ORDER BY time DESC LIMIT 1"); @@ -1012,10 +994,9 @@ function revert($number,$bikeNum) function add($number,$email,$phone,$message) { - global $db, $countrycode, $smsSender; - $userId = getUser($number); - - $phone=normalizephonenumber($phone); + global $db, $countrycode, $smsSender, $user, $phonePurifier; + $userId = $user->findUserIdByNumber($number); #maybe we should check if the user exist??? + $phone = $phonePurifier->purify($phone); $result=$db->query("SELECT number,mail,userName FROM users where number=$phone OR mail='$email'"); if ($result->num_rows!=0) @@ -1049,8 +1030,8 @@ function add($number,$email,$phone,$message) function checkUserPrivileges($number) { - global $db, $sms, $smsSender; - $userId=getUser($number); + global $db, $sms, $smsSender, $user; + $userId=$user->findUserIdByNumber($number); $privileges=getPrivileges($userId); if ($privileges==0) { @@ -1059,5 +1040,3 @@ function checkUserPrivileges($number) exit; } } - -?> diff --git a/actions-web.php b/actions-web.php index fb4ae50..5943575 100644 --- a/actions-web.php +++ b/actions-web.php @@ -3,7 +3,7 @@ function response($message, $error = 0, $additional = '', $log = 1) { - global $db; + global $db, $user; $json = array('error' => $error, 'content' => $message); if (is_array($additional)) { foreach ($additional as $key => $value) { @@ -18,7 +18,7 @@ function response($message, $error = 0, $additional = '', $log = 1) $userid = 0; } - $number = getphonenumber($userid); + $number = $user->findPhoneNumber($userid); logresult($number, $message); } $db->commit(); @@ -28,7 +28,7 @@ function response($message, $error = 0, $additional = '', $log = 1) function rent($userId, $bike, $force = false) { - global $db, $forcestack, $watches, $credit; + global $db, $forcestack, $watches, $credit, $user; $stacktopbike = false; $bikeNum = $bike; $requiredcredit = $credit['min'] + $credit['rent'] + $credit['longrental']; @@ -76,8 +76,8 @@ function rent($userId, $bike, $force = false) $result = $db->query("SELECT standName FROM stands WHERE standId='$standid'"); $row = $result->fetch_assoc(); $stand = $row['standName']; - $user = getusername($userId); - notifyAdmins(_('Bike') . ' ' . $bike . ' ' . _('rented out of stack by') . ' ' . $user . '. ' . $stacktopbike . ' ' . _('was on the top of the stack at') . ' ' . $stand . '.', 1); + $userName = $user->findUserName($userId); + notifyAdmins(_('Bike') . ' ' . $bike . ' ' . _('rented out of stack by') . ' ' . $userName . '. ' . $stacktopbike . ' ' . _('was on the top of the stack at') . ' ' . $stand . '.', 1); } if ($forcestack and $stacktopbike != $bike) { response(_('Bike') . ' ' . $bike . ' ' . _('is not rentable now, you have to rent bike') . ' ' . $stacktopbike . ' ' . _('from this stand') . '.', ERROR); @@ -364,8 +364,8 @@ function last($userId, $bike = 0) function userbikes($userId) { - global $db; - if (!isloggedin()) { + global $db, $auth; + if (!$auth->isLoggedIn()) { response(''); } @@ -399,7 +399,7 @@ function userbikes($userId) function revert($userId, $bikeNum) { - global $db, $smsSender; + global $db, $smsSender, $user; $standId = 0; $result = $db->query("SELECT currentUser FROM bikes WHERE bikeNum=$bikeNum AND currentUser IS NOT NULL"); @@ -408,7 +408,7 @@ function revert($userId, $bikeNum) return; } else { $row = $result->fetch_assoc(); - $revertusernumber = getphonenumber($row['currentUser']); + $revertusernumber = $user->findPhoneNumber($row['currentUser']); } $result = $db->query("SELECT parameter,standName FROM stands LEFT JOIN history ON stands.standId=parameter WHERE bikeNum=$bikeNum AND action IN ('RETURN','FORCERETURN') ORDER BY time DESC LIMIT 1"); if ($result->num_rows == 1) { @@ -435,7 +435,7 @@ function revert($userId, $bikeNum) function register($number, $code, $checkcode, $fullname, $email, $password, $password2, $existing) { - global $db, $dbpassword, $countrycode, $systemURL; + global $db, $dbpassword, $countrycode, $systemURL, $user; $number = $db->escape(trim($number)); $code = $db->escape(trim($code)); @@ -458,9 +458,7 @@ function register($number, $code, $checkcode, $fullname, $email, $password, $pas sendConfirmationEmail($email); response(_('You have been successfully registered. Please, check your email and read the instructions to finish your registration.')); } else { // existing user, password change - $result = $db->query("SELECT userId FROM users WHERE number='$number'"); - $row = $result->fetch_assoc(); - $userId = $row['userId']; + $userId = $user->findUserIdByNumber($number); $result = $db->query("UPDATE users SET password=SHA2('$password',512) WHERE userId='$userId'"); response(_('Password successfully changed. Your username is your phone number. Continue to') . ' ' . _('login') . '.'); } @@ -476,61 +474,10 @@ function register($number, $code, $checkcode, $fullname, $email, $password, $pas } } -function login($number, $password) -{ - global $db, $systemURL, $countrycode; - - $number = $db->escape(trim($number)); - $password = $db->escape(trim($password)); - $number = str_replace(' ', '', $number); - $number = str_replace('-', '', $number); - $number = str_replace('/', '', $number); - if ($number[0] == '0') { - $number = $countrycode . substr($number, 1, strlen($number)); - } - - $result = $db->query("SELECT userId FROM users WHERE number='$number' AND password=SHA2('$password',512)"); - if ($result->num_rows == 1) { - $row = $result->fetch_assoc(); - $userId = $row['userId']; - $sessionId = hash('sha256', $userId . $number . time()); - $timeStamp = time() + 86400 * 14; // 14 days to keep user logged in - $result = $db->query("DELETE FROM sessions WHERE userId='$userId'"); - $result = $db->query("INSERT INTO sessions SET userId='$userId',sessionId='$sessionId',timeStamp='$timeStamp'"); - $db->commit(); - setcookie('loguserid', $userId, time() + 86400 * 14); - setcookie('logsession', $sessionId, time() + 86400 * 14); - header('HTTP/1.1 302 Found'); - header('Location: ' . $systemURL); - header('Connection: close'); - exit; - } else { - header('HTTP/1.1 302 Found'); - header('Location: ' . $systemURL . '?error=1'); - header('Connection: close'); - exit; - } -} - -function logout() -{ - global $db, $systemURL; - if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->escape(trim($_COOKIE['loguserid'])); - $session = $db->escape(trim($_COOKIE['logsession'])); - $result = $db->query("DELETE FROM sessions WHERE userId='$userid'"); - $db->commit(); - } - header('HTTP/1.1 302 Found'); - header('Location: ' . $systemURL); - header('Connection: close'); - exit; -} - function checkprivileges($userid) { - global $db; - $privileges = getprivileges($userid); + global $db, $user; + $privileges = $user->findPrivileges($userid); if ($privileges < 1) { response(_('Sorry, this command is only available for the privileged users.'), ERROR); exit; @@ -539,14 +486,13 @@ function checkprivileges($userid) function smscode($number) { - global $db, $gatewayId, $gatewayKey, $gatewaySenderNumber, $connectors, $smsSender; + global $db, $gatewayId, $gatewayKey, $gatewaySenderNumber, $connectors, $smsSender, $user, $phonePurifier; srand(); - $number = normalizephonenumber($number); + $number = $phonePurifier->purify($number); $number = $db->escape($number); $userexists = 0; - $result = $db->query("SELECT userId FROM users WHERE number='$number'"); - if ($result->num_rows) { + if ($user->findUserIdByNumber($number)) { $userexists = 1; } @@ -656,14 +602,14 @@ function saveuser($userid, $username, $email, $phone, $privileges, $limit) function addcredit($userid, $creditmultiplier) { - global $db, $credit; + global $db, $credit, $user; $requiredcredit = $credit['min'] + $credit['rent'] + $credit['longrental']; $addcreditamount = $requiredcredit * $creditmultiplier; $result = $db->query('UPDATE credit SET credit=credit+' . $addcreditamount . ' WHERE userId=' . $userid); $result = $db->query("INSERT INTO history SET userId=$userid,action='CREDITCHANGE',parameter='" . $addcreditamount . '|add+' . $addcreditamount . "'"); - $result = $db->query('SELECT userName FROM users WHERE users.userId=' . $userid); - $row = $result->fetch_assoc(); - response(_('Added') . ' ' . $addcreditamount . $credit['currency'] . ' ' . _('credit for') . ' ' . $row['userName'] . '.'); + $userName = $user->findUserName($userid); + + response(_('Added') . ' ' . $addcreditamount . $credit['currency'] . ' ' . _('credit for') . ' ' . $userName . '.'); } function getcouponlist() @@ -772,13 +718,13 @@ function resetpassword($number) function mapgetmarkers($userId) { - global $db, $cities; + global $db, $cities, $user; $filtercity = ''; if($cities){ if($userId!=0) { - $filtercity = ' AND city = "'.getusercity($userId).'" '; + $filtercity = ' AND city = "'.$user->findCity($userId).'" '; } else $filtercity = ""; } @@ -792,9 +738,9 @@ function mapgetmarkers($userId) function mapgetlimit($userId) { - global $db; + global $db, $auth; - if (!isloggedin()) { + if (!$auth->isLoggedIn()) { response(''); } diff --git a/admin.php b/admin.php index 8954dbc..851eacd 100644 --- a/admin.php +++ b/admin.php @@ -1,7 +1,9 @@ connect(); +$user = new User($db); +$auth = new Auth($db); -checksession(); +$auth->refreshSession(); -if (isset($_COOKIE["loguserid"])) { - $userid = $db->escape(trim($_COOKIE["loguserid"])); -} else { - $userid = 0; -} +$userid = $auth->getUserId(); -if (getprivileges($userid)<=0) exit(_('You need admin privileges to access this page.')); +if ($user->findPrivileges($userid)<=0) exit(_('You need admin privileges to access this page.')); ?> @@ -75,7 +75,7 @@ @@ -90,7 +90,7 @@ isLoggedIn()): ?>
diff --git a/command.php b/command.php index 7267633..238fa69 100644 --- a/command.php +++ b/command.php @@ -1,7 +1,11 @@ connect(); +$auth = new Auth($db); +$user = new User($db); +/** + * @var PhonePurifierInterface $phonePurifier + */ +$phonePurifier = new PhonePurifier($countrycode); -if (isset($_COOKIE["loguserid"])) { - $userid = $db->escape(trim($_COOKIE["loguserid"])); -} else { - $userid = 0; -} - -if (isset($_COOKIE["logsession"])) { - $session = $db->escape(trim($_COOKIE["logsession"])); -} else { - $session = ''; -} +$userid = $auth->getUserId(); +$session = $auth->getSessionId(); $action=""; if (isset($_GET["action"])) $action=trim($_GET["action"]); @@ -47,11 +48,12 @@ break; case "login": $number=trim($_POST["number"]); + $number = $phonePurifier->purify($number); $password=trim($_POST["password"]); - login($number,$password); + $auth->login($number,$password); break; case "logout": - logout(); + $auth->logout(); break; case "resetpassword": resetpassword($_GET["number"]); @@ -62,14 +64,14 @@ break; case "rent": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $bikeno=trim($_GET["bikeno"]); checkbikeno($bikeno); rent($userid,$bikeno); break; case "return": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $bikeno=trim($_GET["bikeno"]); $stand=trim($_GET["stand"]); $note=""; @@ -79,19 +81,19 @@ break; case "validatecoupon": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $coupon=trim($_GET["coupon"]); validatecoupon($userid,$coupon); break; case "changecity": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $city=trim($_GET["city"]); changecity($userid,$city); break; case "forcerent": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); $bikeno=trim($_GET["bikeno"]); checkbikeno($bikeno); @@ -99,7 +101,7 @@ break; case "forcereturn": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); $bikeno=trim($_GET["bikeno"]); $stand=trim($_GET["stand"]); @@ -110,21 +112,21 @@ break; case "where": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $bikeno=trim($_GET["bikeno"]); checkbikeno($bikeno); where($userid,$bikeno); break; case "removenote": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); checkbikeno($bikeno); removenote($userid,$bikeno); break; case "revert": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); $bikeno=trim($_GET["bikeno"]); checkprivileges($userid); checkbikeno($bikeno); @@ -132,7 +134,7 @@ break; case "last": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); if ($_GET["bikeno"]) { @@ -144,49 +146,49 @@ break; case "stands": #"operationId": "stand.get", logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); liststands(); break; case "userlist": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); getuserlist(); break; case "userstats": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); getuserstats(); break; case "usagestats": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); getusagestats(); break; case "edituser": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); edituser($_GET["edituserid"]); break; case "saveuser": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); saveuser($_GET["edituserid"],$_GET["username"],$_GET["email"],$_GET["phone"],$_GET["privileges"],$_GET["limit"]); break; case "addcredit": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); addcredit($_GET["edituserid"],$_GET["creditmultiplier"]); break; case "trips": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); checkprivileges($userid); if ($_GET["bikeno"]) { @@ -201,17 +203,17 @@ break; case "couponlist": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); getcouponlist(); break; case "generatecoupons": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); generatecoupons($_GET["multiplier"]); break; case "sellcoupon": logrequest($userid,$action); - checksession(); + $auth->refreshSession(); sellcoupon($_GET["coupon"]); break; case "map:markers": @@ -226,5 +228,3 @@ mapgeolocation($userid,$lat,$long); break; } - -?> \ No newline at end of file diff --git a/common.php b/common.php index 782a099..eb5065c 100644 --- a/common.php +++ b/common.php @@ -7,10 +7,13 @@ use BikeShare\Mail\PHPMailerMailSender; use BikeShare\Db\DbInterface; use BikeShare\Db\MysqliDb; +use BikeShare\Purifier\PhonePurifier; +use BikeShare\Purifier\PhonePurifierInterface; use BikeShare\Sms\SmsSender; use BikeShare\Sms\SmsSenderInterface; use BikeShare\SmsConnector\DebugConnector; use BikeShare\SmsConnector\SmsConnectorFactory; +use BikeShare\User\User; require_once 'vendor/autoload.php'; @@ -59,6 +62,12 @@ */ $codeGenerator = new CodeGenerator(); +$user = new User($db); + +/** + * @var PhonePurifierInterface $phonePurifier + */ +$phonePurifier = new PhonePurifier($countrycode); function error($message) { @@ -67,121 +76,9 @@ function error($message) exit($message); } - -function getprivileges($userid) -{ - global $db; - - $result = $db->query("SELECT privileges FROM users WHERE userId=$userid"); - if ($result->num_rows==1) - { - $row = $result->fetch_assoc(); - return $row["privileges"]; - } - return FALSE; -} - -function getusername($userid) -{ - global $db; - - $result = $db->query("SELECT userName FROM users WHERE userId=$userid"); - if ($result->num_rows==1) - { - $row = $result->fetch_assoc(); - return $row["userName"]; - } - return FALSE; -} - -function getusercity($userid) -{ - global $db; - - $result = $db->query("SELECT city FROM users WHERE userId=$userid"); - if ($result->num_rows == 1) { - $row = $result->fetch_assoc(); - return $row['city']; - } - return false; -} - -function getphonenumber($userid) -{ - global $db; - - $result = $db->query("SELECT number FROM users WHERE userId=$userid"); - if ($result->num_rows==1) - { - $row = $result->fetch_assoc(); - return $row["number"]; - } - return FALSE; -} - -function getuserid($number) -{ - global $db; - - $result = $db->query("SELECT userId FROM users WHERE number='$number'"); - if ($result->num_rows==1) - { - $row = $result->fetch_assoc(); - return $row["userId"]; - } - return FALSE; -} - -function isloggedin() -{ - global $db; - if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->escape(trim($_COOKIE['loguserid'])); - $session = $db->escape(trim($_COOKIE['logsession'])); - $result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'"); - if ($result->num_rows == 1) { - return 1; - } else { - return 0; - } - } - return 0; -} - -function checksession() -{ - global $db, $systemURL; - - $result = $db->query("DELETE FROM sessions WHERE timeStamp<='" . time() . "'"); - if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->escape(trim($_COOKIE['loguserid'])); - $session = $db->escape(trim($_COOKIE['logsession'])); - $result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'"); - if ($result->num_rows == 1) { - $timestamp = time() + 86400 * 14; - $result = $db->query("UPDATE sessions SET timeStamp='$timestamp' WHERE userId='$userid' AND sessionId='$session'"); - $db->commit(); - } else { - $result = $db->query("DELETE FROM sessions WHERE userId='$userid' OR sessionId='$session'"); - $db->commit(); - setcookie('loguserid', '', time() - 86400); - setcookie('logsession', '', time() - 86400); - header('HTTP/1.1 302 Found'); - header('Location: ' . $systemURL . '?error=2'); - header('Connection: close'); - exit; - } - } else { - header('HTTP/1.1 302 Found'); - header('Location: ' . $systemURL . '?error=2'); - header('Connection: close'); - exit; - } -} - function logrequest($userid) { - global $dbserver,$dbuser,$dbpassword,$dbname; + global $dbserver,$dbuser,$dbpassword,$dbname, $user; /** * @var DbInterface */ @@ -191,7 +88,7 @@ function logrequest($userid) #TODO does it needed??? $localdb->setAutocommit(true); - $number = getphonenumber($userid); + $number = $user->findPhoneNumber($userid); $result = $localdb->query("INSERT INTO received SET sender='$number',receive_time='" . date('Y-m-d H:i:s') . "',sms_text='" . $_SERVER['REQUEST_URI'] . "',ip='" . $_SERVER['REMOTE_ADDR'] . "'"); } @@ -552,22 +449,3 @@ function issmssystemenabled() return true; } - -function normalizephonenumber($number) -{ - global $countrycode; - $number = str_replace('+', '', $number); - $number = str_replace(' ', '', $number); - $number = str_replace('-', '', $number); - $number = str_replace('/', '', $number); - $number = str_replace('.', '', $number); - if (substr($number, 0, 1) == '0') { - $number = substr($number, 1); - } - - if (substr($number, 0, 3) != $countrycode) { - $number = $countrycode . $number; - } - - return $number; -} diff --git a/index.php b/index.php index a0cd842..d43ee5e 100644 --- a/index.php +++ b/index.php @@ -1,7 +1,9 @@ connect(); +$user = new User($db); +$auth = new Auth($db); + ?> @@ -47,25 +52,21 @@ var maplon=; var mapzoom=; escape(trim($_COOKIE["loguserid"])); -} else { - $userid = 0; -} +$userid = $auth->getUserId(); -if ($cities && isloggedin()) { - $usercity = getusercity($userid); +if ($cities && $auth->isLoggedIn()) { + $usercity = $user->findCity($userid); } -if ($citiesGPS && isloggedin()) { +if ($citiesGPS && $auth->isLoggedIn()) { echo 'maplat=',$citiesGPS[$usercity][0],";\n"; echo 'maplon=',$citiesGPS[$usercity][1],";\n"; } ?> var standselected=0; isLoggedIn()) { echo 'var loggedin=1;', "\n"; - echo 'var priv=', getprivileges($userid), ";\n"; + echo 'var priv=', $user->findPrivileges($userid), ";\n"; } else { echo 'var loggedin=0;', "\n"; echo 'var priv=0;', "\n"; @@ -91,7 +92,7 @@ isLoggedIn()) { echo '
'; } else { echo 'White bikes - Biele bicykle'; @@ -104,12 +105,12 @@
- +isLoggedIn()): ?>

@@ -150,7 +151,7 @@
- +isLoggedIn()): ?>

Log in

The coding standard for Open Source Bike Sharing. + src tests diff --git a/receive.php b/receive.php index f2ecf93..cbd9be5 100644 --- a/receive.php +++ b/receive.php @@ -24,6 +24,7 @@ if(!validateNumber($sms->getNumber())) { + trigger_error("Invalid number: ".$sms->getNumber(), E_USER_WARNING); #### #$smsSender->send($sms->getNumber(),_('Your number is not registered.')); } diff --git a/scan.php b/scan.php index 30f4573..c3fcf1a 100644 --- a/scan.php +++ b/scan.php @@ -1,7 +1,9 @@ connect(); +$user = new User($db); +$auth = new Auth($db); -if (isset($_COOKIE["loguserid"])) { - $userid = $db->escape(trim($_COOKIE["loguserid"])); -} else { - $userid = 0; -} +$auth->refreshSession(); +$userid = $auth->getUserId(); +$session = $auth->getSessionId(); -if (isset($_COOKIE["logsession"])) { - $session = $db->escape(trim($_COOKIE["logsession"])); -} else { - $session = ''; -} $request=substr($_SERVER["REQUEST_URI"],strpos($_SERVER["REQUEST_URI"],".php")+5); $request=explode("/",$request); $action=$request[0]; @@ -34,14 +31,12 @@ { case "rent": logrequest($userid,$action); - checksession(); $bikeno=$parameter; checkbikeno($bikeno); rent($userid,$bikeno); break; case "return": logrequest($userid,$action); - checksession(); $stand=$parameter; checkstandname($stand); returnbike($userid,$stand); @@ -49,5 +44,3 @@ default: unrecognizedqrcode($userid); } - -?> \ No newline at end of file diff --git a/src/Authentication/Auth.php b/src/Authentication/Auth.php new file mode 100644 index 0000000..858c863 --- /dev/null +++ b/src/Authentication/Auth.php @@ -0,0 +1,127 @@ +db = $db; + } + + public function getUserId() + { + if (isset($_COOKIE["loguserid"])) { + return (int)$this->db->escape(trim($_COOKIE["loguserid"])); + } else { + return 0; + } + } + + public function getSessionId() + { + if (isset($_COOKIE["logsession"])) { + return $this->db->escape(trim($_COOKIE["logsession"])); + } else { + return ''; + } + } + + public function login($number, $password) + { + $number = $this->db->escape(trim($number)); + $password = $this->db->escape(trim($password)); + + $result = $this->db->query( + "SELECT userId FROM users WHERE number='$number' AND password=SHA2('$password',512)" + ); + if ($result && $result->num_rows == 1) { + $row = $result->fetch_assoc(); + $userId = $row['userId']; + $sessionId = hash('sha256', $userId . $number . time()); + $timeStamp = time() + self::SESSION_EXPIRATION; + $this->db->query("DELETE FROM sessions WHERE userId='$userId'"); + $this->db->query( + "INSERT INTO sessions SET userId='$userId',sessionId='$sessionId',timeStamp='$timeStamp'" + ); + $this->db->commit(); + setcookie('loguserid', $userId, $timeStamp); + setcookie('logsession', $sessionId, $timeStamp); + header('HTTP/1.1 302 Found'); + header('Location: /'); + header('Connection: close'); + } else { + header('HTTP/1.1 302 Found'); + header('Location: /?error=1'); + header('Connection: close'); + } + } + + public function logout() + { + if ($this->isLoggedIn()) { + $userid = $this->getUserId(); + $sessionId = $this->getSessionId(); + $this->db->query("DELETE FROM sessions WHERE userId='$userid' OR sessionId='$sessionId'"); + $this->db->commit(); + } + setcookie("loguserid", "0", time() - 3600, "/"); + setcookie("logsession", "", time() - 3600, "/"); + header('HTTP/1.1 302 Found'); + header('Location: /'); + header('Connection: close'); + } + + public function refreshSession() + { + if (!$this->isLoggedIn()) { + return; + } + + $this->db->query("DELETE FROM sessions WHERE timeStamp<='" . time() . "'"); + $userid = $this->getUserId(); + $sessionId = $this->getSessionId(); + $result = $this->db->query( + "SELECT sessionId FROM sessions WHERE userId='$userid' + AND sessionId='$sessionId' AND timeStamp>'" . time() . "'" + ); + if ($result->num_rows == 1) { + $timestamp = time() + self::SESSION_EXPIRATION; + $this->db->query( + "UPDATE sessions SET timeStamp='$timestamp' WHERE userId='$userid' AND sessionId='$sessionId'" + ); + $this->db->commit(); + } else { + $this->logout(); + } + } + + public function isLoggedIn() + { + $session = $this->getSessionId(); + + if (!empty($session)) { + $userid = $this->getUserId(); + $result = $this->db->query("SELECT sessionId FROM sessions WHERE + userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'"); + if ($result && $result->num_rows == 1) { + return true; + } + } + + return false; + } +} diff --git a/src/Purifier/PhonePurifier.php b/src/Purifier/PhonePurifier.php new file mode 100644 index 0000000..0c7ec37 --- /dev/null +++ b/src/Purifier/PhonePurifier.php @@ -0,0 +1,35 @@ +countryCode = $countryCode; + } + + public function purify($phoneNumber) + { + $phoneNumber = str_replace('+', '', $phoneNumber); + $phoneNumber = str_replace(' ', '', $phoneNumber); + $phoneNumber = str_replace('-', '', $phoneNumber); + $phoneNumber = str_replace('/', '', $phoneNumber); + $phoneNumber = str_replace('.', '', $phoneNumber); + if (substr($phoneNumber, 0, 1) == '0') { + $phoneNumber = substr($phoneNumber, 1); + } + + if (substr($phoneNumber, 0, 3) != $this->countryCode) { + $phoneNumber = $this->countryCode . $phoneNumber; + } + + return $phoneNumber; + } +} diff --git a/src/Purifier/PhonePurifierInterface.php b/src/Purifier/PhonePurifierInterface.php new file mode 100644 index 0000000..dd5693a --- /dev/null +++ b/src/Purifier/PhonePurifierInterface.php @@ -0,0 +1,8 @@ +db = $db; + } + + public function findUserIdByNumber($number) + { + $result = $this->db->query("SELECT userId FROM users WHERE userNumber='$number'"); + if ($result->num_rows == 1) { + return $result->fetch_assoc()["userId"]; + } + + return null; + } + + public function findPhoneNumber($userId) + { + $result = $this->db->query("SELECT number FROM users WHERE userId='$userId'"); + if ($result->num_rows == 1) { + return $result->fetch_assoc()["number"]; + } + + return null; + } + + public function findCity($userId) + { + $result = $this->db->query("SELECT city FROM users WHERE userId='$userId'"); + if ($result->num_rows == 1) { + return $result->fetch_assoc()["city"]; + } + + return null; + } + + public function findUserName($userId) + { + $result = $this->db->query("SELECT userName FROM users WHERE userId='$userId'"); + if ($result->num_rows == 1) { + return $result->fetch_assoc()["userName"]; + } + + return null; + } + + public function findPrivileges($userId) + { + $result = $this->db->query("SELECT privileges FROM users WHERE userId='$userId'"); + if ($result->num_rows == 1) { + return $result->fetch_assoc()["privileges"]; + } + + return null; + } +} diff --git a/tests/Authentication/AuthTest.php b/tests/Authentication/AuthTest.php new file mode 100644 index 0000000..65e1450 --- /dev/null +++ b/tests/Authentication/AuthTest.php @@ -0,0 +1,318 @@ +db = $this->createMock(DbInterface::class); + $this->auth = new Auth( + $this->db + ); + } + + protected function tearDown() + { + unset( + $this->db, + $this->auth + ); + } + + + /** + * @dataProvider testGetUserIdDataProvider + */ + public function testGetUserId( + $cookieValue = null, + $expectedUserId = 0 + ) { + if (!is_null($cookieValue)) { + $_COOKIE["loguserid"] = $cookieValue; + $this->db->expects($this->once()) + ->method('escape') + ->with($cookieValue) + ->willReturn($cookieValue); + } + $this->assertEquals($expectedUserId, $this->auth->getUserId()); + } + + public function testGetUserIdDataProvider() + { + + yield 'no cookie' => [ + 'cookieValue' => null, + 'expectedUserId' => 0, + ]; + yield 'empty cookie' => [ + 'cookieValue' => '', + 'expectedUserId' => 0, + ]; + yield 'not a number' => [ + 'cookieValue' => 'not a number', + 'expectedUserId' => 0, + ]; + yield 'number' => [ + 'cookieValue' => '123', + 'expectedUserId' => 123, + ]; + yield 'sql injection' => [ + 'cookieValue' => '123; DROP TABLE users', + 'expectedUserId' => 123, + ]; + } + + /** + * @dataProvider testGetSessionIdDataProvider + */ + public function testGetSessionId( + $cookieValue = null, + $expectedSessionId = 0 + ) { + if (!is_null($cookieValue)) { + $_COOKIE["logsession"] = $cookieValue; + $this->db->expects($this->once()) + ->method('escape') + ->with($cookieValue) + ->willReturn(str_replace(';', '\;', $cookieValue));# just an example for test + } + $this->assertEquals($expectedSessionId, $this->auth->getSessionId()); + } + + public function testGetSessionIdDataProvider() + { + + yield 'no cookie' => [ + 'cookieValue' => null, + 'expectedSessionId' => '', + ]; + yield 'empty cookie' => [ + 'cookieValue' => '', + 'expectedSessionId' => '', + ]; + yield 'not a number' => [ + 'cookieValue' => 'not a number', + 'expectedSessionId' => 'not a number', + ]; + yield 'number' => [ + 'cookieValue' => '123', + 'expectedSessionId' => '123', + ]; + yield 'sql injection' => [ + 'cookieValue' => '123; DROP TABLE users', + 'expectedSessionId' => '123\; DROP TABLE users', + ]; + } + + + public function testLogin() + { + $number = 'number'; + $password = 'password'; + $userId = '123'; + $this->db->expects($this->exactly(2)) + ->method('escape') + ->withConsecutive( + [$number], + [$password] + )->willReturnOnConsecutiveCalls($number, $password); + + $sessionId = hash('sha256', $userId . $number . '9999'); + + $this->db->expects($this->exactly(3)) + ->method('query') + ->withConsecutive( + ["SELECT userId FROM users WHERE number='$number' AND password=SHA2('$password',512)"], + ["DELETE FROM sessions WHERE userId='{$userId}'"], + ["INSERT INTO sessions SET userId='{$userId}',sessionId='{$sessionId}',timeStamp='1219599'"] + ) + ->willReturnOnConsecutiveCalls( + new \Test\BikeShare\MysqliResult(1, [['userId' => '123']]), + null, + null + ); + + + $this->auth->login($number, $password); + } + + /** + * @dataProvider testisLoggedInDataProvider + */ + public function testisLoggedIn( + $userId = 0, + $sessionId = '', + $escapeCallParams = [], + $escapeCallResults = [], + $expectedResult = false + ) { + if ($userId) { + $_COOKIE["loguserid"] = $userId; + } + if ($sessionId) { + $_COOKIE["logsession"] = $sessionId; + } + $this->db->expects($this->exactly(count($escapeCallParams))) + ->method('escape') + ->withConsecutive(...$escapeCallParams) + ->willReturnOnConsecutiveCalls(...$escapeCallResults); + + $this->db->expects(count($escapeCallParams) > 0 ? $this->exactly(1) : $this->never()) + ->method('query') + ->withConsecutive( + ["SELECT sessionId FROM sessions WHERE + userId='$userId' AND sessionId='$sessionId' AND timeStamp>'9999'"] + ) + ->willReturnOnConsecutiveCalls( + new \Test\BikeShare\MysqliResult(1, [['sessionId' => '123']]) + ); + + $this->assertEquals($expectedResult, $this->auth->isLoggedIn()); + } + + public function testisLoggedInDataProvider() + { + yield 'no user id' => [ + 'userId' => 0, + 'sessionId' => '', + 'escapeCallParams' => [], + 'escapeCallResults' => [], + 'expectedResult' => false, + ]; + yield 'no session id' => [ + 'userId' => 1, + 'sessionId' => '', + 'escapeCallParams' => [], + 'escapeCallResults' => [], + 'expectedResult' => false, + ]; + yield 'user id and session id' => [ + 'userId' => 1, + 'sessionId' => '123', + 'escapeCallParams' => [ + ['123'], + [1], + ], + 'escapeCallResults' => [ + '123', + 1, + ], + 'expectedResult' => true, + ]; + } + + public function testLogout() + { + $userId = 1; + $sessionId = '123'; + $_COOKIE["loguserid"] = $userId; + $_COOKIE["logsession"] = $sessionId; + $this->db->expects($this->exactly(4)) + ->method('escape') + ->withConsecutive( + [$sessionId], + [$userId], + [$userId], + [$sessionId] + ) + ->willReturnOnConsecutiveCalls( + $sessionId, + $userId, + $userId, + $sessionId + ); + + $this->db->expects($this->exactly(2)) + ->method('query') + ->withConsecutive( + ["SELECT sessionId FROM sessions WHERE + userId='1' AND sessionId='123' AND timeStamp>'9999'"], + ["DELETE FROM sessions WHERE userId='$userId' OR sessionId='$sessionId'"] + ) + ->willReturnOnConsecutiveCalls( + new \Test\BikeShare\MysqliResult(1, [['sessionId' => '123']]), + null + ); + + $this->auth->logout(); + } + + public function testRefreshSession() + { + $userId = 1; + $sessionId = '123'; + $_COOKIE["loguserid"] = $userId; + $_COOKIE["logsession"] = $sessionId; + $this->db->expects($this->exactly(4)) + ->method('escape') + ->withConsecutive( + [$sessionId], + [$userId], + [$userId], + [$sessionId] + ) + ->willReturnOnConsecutiveCalls( + $sessionId, + $userId, + $userId, + $sessionId + ); + + $this->db->expects($this->exactly(4)) + ->method('query') + ->withConsecutive( + ["SELECT sessionId FROM sessions WHERE + userId='1' AND sessionId='123' AND timeStamp>'9999'"], + ["DELETE FROM sessions WHERE timeStamp<='9999'"], + ["SELECT sessionId FROM sessions WHERE userId='1' + AND sessionId='123' AND timeStamp>'9999'"], + ["UPDATE sessions SET timeStamp='1219599' WHERE userId='1' AND sessionId='123'"] + ) + ->willReturnOnConsecutiveCalls( + new \Test\BikeShare\MysqliResult(1, [['sessionId' => '123']]), + null, + new \Test\BikeShare\MysqliResult(1, [['sessionId' => '123']]), + null + ); + + $this->auth->refreshSession(); + } +} + +/** + * @phpcs:disable PSR1.Files.SideEffects + */ +namespace BikeShare\Authentication; +{ +function header($header, $replace = true, $response_code = 0) +{ +} + +function setcookie($name, $value = '', $options = 0) +{ + return true; +} + +function time() +{ + return 9999; +} +} diff --git a/tests/MysqliResult.php b/tests/MysqliResult.php new file mode 100644 index 0000000..0d60974 --- /dev/null +++ b/tests/MysqliResult.php @@ -0,0 +1,30 @@ +num_rows = $numRows; + $this->fetchResult = $fetchResult; + } + + public function fetch_assoc() + { + return array_shift($this->fetchResult); + } +} diff --git a/tests/Purifier/PhonePurifierTest.php b/tests/Purifier/PhonePurifierTest.php new file mode 100644 index 0000000..778a4c1 --- /dev/null +++ b/tests/Purifier/PhonePurifierTest.php @@ -0,0 +1,57 @@ +assertEquals($expectedPhoneNumber, $purifier->purify($phoneNumber)); + } + + public function purifyDataProvider() + { + yield 'default' => [ + 'phoneNumber' => '+1234567890', + 'countryCode' => '123', + 'expectedPhoneNumber' => '1234567890' + ]; + yield 'restricted symbols remove' => [ + 'phoneNumber' => '+421 123-456-78/90.', + 'countryCode' => '421', + 'expectedPhoneNumber' => '4211234567890' + ]; + #is it correct??? maybe we should left only numbers??? + yield 'letters symbols do not remove' => [ + 'phoneNumber' => '+421 123-456-78/90abcdefghijklmnopqrstuvwxyz', + 'countryCode' => '421', + 'expectedPhoneNumber' => '4211234567890abcdefghijklmnopqrstuvwxyz' + ]; + yield 'without code' => [ + 'phoneNumber' => '0123-456-78/90', + 'countryCode' => '421', + 'expectedPhoneNumber' => '4211234567890' + ]; + yield 'with 3 symbol code and with 0' => [ + 'phoneNumber' => '0421123-456-78/90', + 'countryCode' => '421', + 'expectedPhoneNumber' => '4211234567890' + ]; + #is it correct??? maybe code can be less or more than 3 symbols??? + yield 'with 2 symbol code and with 0' => [ + 'phoneNumber' => '0123-456-78/90', + 'countryCode' => '12', + 'expectedPhoneNumber' => '121234567890' + ]; + } +} diff --git a/tests/User/UserTest.php b/tests/User/UserTest.php new file mode 100644 index 0000000..2707617 --- /dev/null +++ b/tests/User/UserTest.php @@ -0,0 +1,97 @@ +createMock(DbInterface::class); + $dbMock->expects($this->exactly(2)) + ->method('query') + ->with("SELECT userId FROM users WHERE userNumber='{$userNumber}'") + ->willReturnOnConsecutiveCalls( + new MysqliResult(1, [['userId' => $expectedUserId]]), + new MysqliResult(0, []) + ); + $user = new User($dbMock); + $this->assertEquals($expectedUserId, $user->findUserIdByNumber($userNumber)); + $this->assertNull($user->findUserIdByNumber($userNumber)); + } + + public function testFindPhoneNumberReturnsPhoneNumber() + { + $userId = 1; + $expectedPhoneNumber = '123-456-7890'; + $dbMock = $this->createMock(DbInterface::class); + $dbMock->expects($this->exactly(2)) + ->method('query') + ->with("SELECT number FROM users WHERE userId='{$userId}'") + ->willReturnOnConsecutiveCalls( + new MysqliResult(1, [['number' => $expectedPhoneNumber]]), + new MysqliResult(0, []) + ); + $user = new User($dbMock); + $this->assertEquals($expectedPhoneNumber, $user->findPhoneNumber($userId)); + $this->assertNull($user->findPhoneNumber($userId)); + } + + public function testFindCityReturnsCity() + { + $userId = 1; + $expectedCity = 'Springfield'; + $dbMock = $this->createMock(DbInterface::class); + $dbMock->expects($this->exactly(2)) + ->method('query') + ->with("SELECT city FROM users WHERE userId='{$userId}'") + ->willReturnOnConsecutiveCalls( + new MysqliResult(1, [['city' => $expectedCity]]), + new MysqliResult(0, []) + ); + $user = new User($dbMock); + $this->assertEquals($expectedCity, $user->findCity($userId)); + $this->assertNull($user->findCity($userId)); + } + + public function testFindUserNameReturnsUserName() + { + $userId = 1; + $expectedUserName = 'JohnDoe'; + $dbMock = $this->createMock(DbInterface::class); + $dbMock->expects($this->exactly(2)) + ->method('query') + ->with("SELECT userName FROM users WHERE userId='{$userId}'") + ->willReturnOnConsecutiveCalls( + new MysqliResult(1, [['userName' => $expectedUserName]]), + new MysqliResult(0, []) + ); + $user = new User($dbMock); + $this->assertEquals($expectedUserName, $user->findUserName($userId)); + $this->assertNull($user->findUserName($userId)); + } + + public function testFindPrivilegesReturnsPrivileges() + { + $userId = 1; + $expectedPrivileges = '7'; + $dbMock = $this->createMock(DbInterface::class); + $dbMock->expects($this->exactly(2)) + ->method('query') + ->with("SELECT privileges FROM users WHERE userId='{$userId}'") + ->willReturnOnConsecutiveCalls( + new MysqliResult(1, [['privileges' => $expectedPrivileges]]), + new MysqliResult(0, []) + ); + + $user = new User($dbMock); + $this->assertEquals($expectedPrivileges, $user->findPrivileges($userId)); + $this->assertNull($user->findPrivileges($userId)); + } +}