Advertisement
Guest User

Untitled

a guest
Oct 1st, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.66 KB | None | 0 0
  1. <?php
  2. require_once 'engine/init.php';
  3.  
  4. // Client 11 loginWebService
  5. // DEV: Uncomment all //error_log lines and tail error.log file to see communication from and to client.
  6. // ...: Configure webserver to don't display PHP errors/warnings so the client can parse the json response.
  7. if($_SERVER['HTTP_USER_AGENT'] == "Mozilla/5.0" && $config['ServerEngine'] === 'TFS_10' && $config['login_web_service'] == true) {
  8.  
  9. function sendError($message, $code = 3) {
  10. $response = json_encode(array('errorCode' => $code, 'errorMessage' => $message));
  11. //error_log("\nServer = " . $response . "\n-");
  12. die($response);
  13. }
  14.  
  15. function sendMessage($message) {
  16. $response = json_encode($message);
  17. //error_log("\nServer = " . $response . "\n\n-");
  18. die($response);
  19. }
  20.  
  21.  
  22. header("Content-Type: application/json");
  23. $input = file_get_contents("php://input");
  24. //error_log("\n\n\nClient = " . $input . "\n");
  25.  
  26. $client = json_decode($input);
  27.  
  28. if (!isset($client->type)) {
  29. sendError("Type missing.");
  30. }
  31.  
  32. switch($client->type) {
  33. // {"count":0,"isreturner":true,"offset":0,"showrewardnews":false,"type":"news"}
  34. case "cacheinfo":
  35. // {"type":"cacheinfo"}
  36. sendMessage(array(
  37. 'playersonline' => (int)user_count_online(),
  38. 'twitchstreams' => 0,
  39. 'twitchviewer' => 0,
  40. 'gamingyoutubestreams' => 0,
  41. 'gamingyoutubeviewer' => 0
  42. ));
  43. break;
  44.  
  45. case 'eventschedule':
  46. // {"type":"eventschedule"}
  47. sendMessage(array(
  48. 'eventlist' => array()
  49. ));
  50. /*
  51. array(
  52. array(
  53. 'description' => "Description text.\n\nTest",
  54. 'startdate' => 1590979202,
  55. 'colordark' => "#735D10", // HEX color code
  56. 'name' => "Full Moon",
  57. 'enddate' => 1590979202 + (300 * 24 * 60 * 60),
  58. 'isseasonal' => false,
  59. 'colorlight' => "#8B6D05"
  60. ),
  61. array(
  62. 'description' => "Winterberries can now be found all over Tibia!",
  63. 'startdate' => 1590979202,
  64. 'colordark' => "#7A4C1F",
  65. 'name' => "Annual Autumn Vintage",
  66. 'enddate' => 1590979202 + (7 * 24 * 60 * 60),
  67. 'isseasonal' => false,
  68. 'colorlight' => "#935416"
  69. ),
  70. array(
  71. 'description' => "This is the time of witches, ghosts and vampires.",
  72. 'startdate' => 1590979202,
  73. 'colordark' => "#235c00",
  74. 'name' => "Halloween Event",
  75. 'enddate' => 1590979202 + (30 * 24 * 60 * 60),
  76. 'isseasonal' => false,
  77. 'colorlight' => "#2d7400"
  78. )
  79. )
  80. */
  81. break;
  82.  
  83. case 'boostedcreature':
  84. // {"type":"boostedcreature"}
  85. sendMessage(array(
  86. //'boostedcreature' => false,
  87. 'raceid' => 219
  88. ));
  89. break;
  90.  
  91. case 'news':
  92. // {"count":0,"isreturner":true,"offset":0,"showrewardnews":false,"type":"news"}
  93. sendMessage(array(
  94. 'gamenews' => array(), // element structure?
  95. 'categorycounts' => array(
  96. 'support' => 1,
  97. 'game contents' => 2,
  98. 'useful info' => 3,
  99. 'major updates' => 4,
  100. 'client features' => 5
  101. ),
  102. 'maxeditdate' => 1590979202
  103. ));
  104. break;
  105.  
  106. case "login":
  107. /* {
  108. 'accountname' => 'username',
  109. "email":"my@email.com",
  110. 'password' => 'superpass',
  111. 'stayloggedin' => true,
  112. 'token' => '123123', (or not set)
  113. 'type' => 'login',
  114. } */
  115.  
  116. $email = (isset($client->email)) ? sanitize($client->email) : false;
  117. $username = (isset($client->accountname)) ? sanitize($client->accountname) : false;
  118. $password = SHA1($client->password);
  119. $token = (isset($client->token)) ? sanitize($client->token) : false;
  120.  
  121. $fields = '`id`, `premdays`';
  122. if ($config['twoFactorAuthenticator']) $fields .= ', `secret`';
  123.  
  124. $account = false;
  125.  
  126. if ($email !== false) {
  127. $fields .= ', `name`';
  128. $account = mysql_select_single("SELECT {$fields} FROM `accounts` WHERE `email`='{$email}' AND `password`='{$password}' LIMIT 1;");
  129. if ($account !== false) {
  130. $username = $account['name'];
  131. }
  132. } elseif ($username !== false) {
  133. $account = mysql_select_single("SELECT {$fields} FROM `accounts` WHERE `name`='{$username}' AND `password`='{$password}' LIMIT 1;");
  134. }
  135.  
  136. if ($account === false) {
  137. sendError('Wrong username and/or password.');
  138. }
  139.  
  140. if ($config['twoFactorAuthenticator'] === true && $account['secret'] !== null) {
  141. if ($token === false) {
  142. sendError('Submit a valid two-factor authentication token.', 6);
  143. } else {
  144. require_once("engine/function/rfc6238.php");
  145. if (TokenAuth6238::verify($account['secret'], $token) !== true) {
  146. sendError('Two-factor authentication failed, token is wrong.', 6);
  147. }
  148. }
  149. }
  150.  
  151. $players = mysql_select_multi("SELECT `name`, `sex`, `level`, `vocation`, `lookbody`, `looktype`, `lookhead`, `looklegs`, `lookfeet`, `lookaddons`, `deletion` FROM `players` WHERE `account_id`='".$account['id']."';");
  152. if ($players !== false) {
  153.  
  154. $gameserver = $config['gameserver'];
  155. // Override $config['gameserver'] if server has installed Lua script for loginWebService
  156. $sql_elements = mysql_select_multi("
  157. SELECT
  158. `key`,
  159. `value`
  160. FROM `znote_global_storage`
  161. WHERE `key` IN('SERVER_NAME', 'IP', 'GAME_PORT')
  162. ");
  163. if ($sql_elements !== false) {
  164. foreach ($sql_elements AS $element) {
  165. switch ($element['key']) {
  166. case 'SERVER_NAME':
  167. $gameserver['name'] = $element['value'];
  168. break;
  169. case 'IP':
  170. $gameserver['ip'] = $element['value'];
  171. break;
  172. case 'GAME_PORT':
  173. $gameserver['port'] = (int)$element['value'];
  174. break;
  175. }
  176. }
  177. }
  178.  
  179. $sessionKey = ($email !== false) ? $email."\n".$client->password : $username."\n".$client->password;
  180. if (isset($account['secret']) && strlen($account['secret']) > 5) $sessionKey .= "\n".$token."\n".floor(time() / 30);
  181.  
  182. $response = array(
  183. 'session' => array(
  184. 'fpstracking' => false,
  185. 'optiontracking' => false,
  186. 'isreturner' => true,
  187. 'returnernotification' => false,
  188. 'showrewardnews' => false,
  189. 'tournamentticketpurchasestate' => 0,
  190. 'emailcoderequest' => false,
  191. 'sessionkey' => $sessionKey,
  192. 'lastlogintime' => 0,
  193. 'ispremium' => ($account['premdays'] > 0) ? true : false,
  194. 'premiumuntil' => time() + ($account['premdays'] * 86400),
  195. 'status' => 'active'
  196. ),
  197. 'playdata' => array(
  198. 'worlds' => array(
  199. array(
  200. 'id' => 0,
  201. 'name' => $gameserver['name'],
  202. 'externaladdress' => $gameserver['ip'],
  203. 'externalport' => $gameserver['port'],
  204. 'previewstate' => 0,
  205. 'location' => 'ALL',
  206. 'pvptype' => 'pvp',
  207. 'externaladdressunprotected' => $gameserver['ip'],
  208. 'externaladdressprotected' => $gameserver['ip'],
  209. 'externalportunprotected' => $gameserver['port'],
  210. 'externalportprotected' => $gameserver['port'],
  211. 'istournamentworld' => false,
  212. 'restrictedstore' => false,
  213. 'currenttournamentphase' => 2,
  214. 'anticheatprotection' => false
  215. )
  216. ),
  217. 'characters' => array(
  218. //array( 'worldid' => ASD, 'name' => asd, 'ismale' => true, 'tutorial' => false ),
  219. )
  220. )
  221. );
  222.  
  223. foreach ($players as $player) {
  224. $response['playdata']['characters'][] = array(
  225. 'worldid' => 0,
  226. 'name' => $player['name'],
  227. 'ismale' => ($player['sex'] === 1) ? true : false,
  228. 'tutorial' => false,
  229. 'level' => intval($player['level']),
  230. 'vocation' => vocation_id_to_name($player['vocation']),
  231. 'outfitid' => intval($player['looktype']),
  232. 'headcolor' => intval($player['lookhead']),
  233. 'torsocolor' => intval($player['lookbody']),
  234. 'legscolor' => intval($player['looklegs']),
  235. 'detailcolor' => intval($player['lookfeet']),
  236. 'addonsflags' => intval($player['lookaddons']),
  237. 'ishidden' => intval($player['deletion']) === 1,
  238. 'istournamentparticipant' => false,
  239. 'remainingdailytournamentplaytime' => 0
  240. );
  241. }
  242.  
  243. sendMessage($response);
  244. } else {
  245. sendError("Character list is empty.");
  246. }
  247. break;
  248.  
  249. default:
  250. sendError("Unsupported type: " . sanitize($client->type));
  251. }
  252.  
  253. } // End client 11 loginWebService
  254.  
  255. logged_in_redirect();
  256. include 'layout/overall/header.php';
  257.  
  258. if (empty($_POST) === false) {
  259.  
  260. if ($config['log_ip']) {
  261. znote_visitor_insert_detailed_data(5);
  262. }
  263.  
  264. $username = $_POST['username'];
  265. $password = $_POST['password'];
  266.  
  267. if (empty($username) || empty($password)) {
  268. $errors[] = 'You need to enter a username and password.';
  269. } else if (strlen($username) > 32 || strlen($password) > 64) {
  270. $errors[] = 'Username or password is too long.';
  271. } else if (user_exist($username) === false) {
  272. $errors[] = 'Failed to authorize your account, are the details correct, have you <a href=\'register.php\'>register</a>ed?';
  273. } /*else if (user_activated($username) === false) {
  274. $errors[] = 'You havent activated your account! Please check your email. <br>Note it may appear in your junk/spam box.';
  275. } */else if ($config['use_token'] && !Token::isValid($_POST['token'])) {
  276. Token::debug($_POST['token']);
  277. $errors[] = 'Token is invalid.';
  278. } else {
  279.  
  280. // Starting loging
  281. if ($config['ServerEngine'] == 'TFS_02' || $config['ServerEngine'] == 'OTHIRE' || $config['ServerEngine'] == 'TFS_10') $login = user_login($username, $password);
  282. else if ($config['ServerEngine'] == 'TFS_03') $login = user_login_03($username, $password);
  283. else $login = false;
  284. if ($login === false) {
  285. $errors[] = 'Username and password combination is wrong.';
  286. } else {
  287. // Check if user have access to login
  288. $status = false;
  289. if ($config['mailserver']['register']) {
  290. $authenticate = mysql_select_single("SELECT `id` FROM `znote_accounts` WHERE `account_id`='$login' AND `active`='1' LIMIT 1;");
  291. if ($authenticate !== false) {
  292. $status = true;
  293. } else {
  294. $errors[] = "Your account is not activated. An email should have been sent to you when you registered. Please find it and click the activation link to activate your account.";
  295. }
  296. } else $status = true;
  297.  
  298. if ($status) {
  299. // Regular login success, now lets check authentication token code
  300. if ($config['ServerEngine'] == 'TFS_10' && $config['twoFactorAuthenticator']) {
  301. require_once("engine/function/rfc6238.php");
  302.  
  303. // Two factor authentication code / token
  304. $authcode = (isset($_POST['authcode'])) ? getValue($_POST['authcode']) : false;
  305.  
  306. // Load secret values from db
  307. $query = mysql_select_single("SELECT `a`.`secret` AS `secret`, `za`.`secret` AS `znote_secret` FROM `accounts` AS `a` INNER JOIN `znote_accounts` AS `za` ON `a`.`id` = `za`.`account_id` WHERE `a`.`id`='".(int)$login."' LIMIT 1;");
  308.  
  309. // If account table HAS a secret, we need to validate it
  310. if ($query['secret'] !== NULL) {
  311.  
  312. // Validate the secret first to make sure all is good.
  313. if (TokenAuth6238::verify($query['secret'], $authcode) !== true) {
  314. $errors[] = "Submitted Two-Factor Authentication token is wrong.";
  315. $errors[] = "Make sure to type the correct token from your mobile authenticator.";
  316. $status = false;
  317. }
  318.  
  319. } else {
  320.  
  321. // secret from accounts table is null/not set. Perhaps we can activate it:
  322. if ($query['znote_secret'] !== NULL && $authcode !== false && !empty($authcode)) {
  323.  
  324. // Validate the secret first to make sure all is good.
  325. if (TokenAuth6238::verify($query['znote_secret'], $authcode)) {
  326. // Success, enable the 2FA system
  327. mysql_update("UPDATE `accounts` SET `secret`= '".$query['znote_secret']."' WHERE `id`='$login';");
  328. } else {
  329. $errors[] = "Activating Two-Factor authentication failed.";
  330. $errors[] = "Try to login without token and configure your app properly.";
  331. $errors[] = "Submitted Two-Factor Authentication token is wrong.";
  332. $errors[] = "Make sure to type the correct token from your mobile authenticator.";
  333. $status = false;
  334. }
  335. }
  336. }
  337. } // End tfs 1.0+ with 2FA auth
  338.  
  339. if ($status) {
  340. setSession('user_id', $login);
  341.  
  342. // if IP is not set (etc acc created before Znote AAC was in use)
  343. $znote_data = user_znote_account_data($login, 'ip');
  344. if ($znote_data['ip'] == 0) {
  345. $update_data = array(
  346. 'ip' => getIPLong(),
  347. );
  348. user_update_znote_account($update_data);
  349. }
  350.  
  351. // Send them to myaccount.php
  352. header('Location: myaccount.php');
  353. exit();
  354. }
  355. }
  356. }
  357. }
  358. } else {
  359. header('Location: index.php');
  360. }
  361.  
  362. if (empty($errors) === false) {
  363. ?>
  364. <h2>We tried to log you in, but...</h2>
  365. <?php
  366. header("HTTP/1.1 401 Not Found");
  367. echo output_errors($errors);
  368. }
  369.  
  370. include 'layout/overall/footer.php'; ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement