user.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. <?php
  2. /**
  3. * A framework for simple user authentication.
  4. *
  5. * Users are recorded using {username, password, token} triplets.
  6. * Whenever a user logs in successfully, his or her database
  7. * entry is assigned a new random token, which is used in
  8. * salting subsequent password checks.
  9. */
  10. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  11. define('USER_HOME', $databaseConfig['databaseLocation'] . '/users/');
  12. define('DATABASE_LOCATION', $databaseConfig['databaseLocation'] . '/');
  13. if(!empty($databaseConfig['timezone'])) : define('TIMEZONE', $databaseConfig['timezone']); else : define('TIMEZONE', 'America/Los_Angeles'); endif;
  14. if(!empty($databaseConfig['titleLogo'])) : define('TITLELOGO', $databaseConfig['titleLogo']); else : define('TITLELOGO', ''); endif;
  15. if(!empty($databaseConfig['loadingIcon'])) : define('LOADINGICON', $databaseConfig['loadingIcon']); else : define('LOADINGICON', ''); endif;
  16. define('FAIL_LOG', 'loginLog.json');
  17. class User
  18. {
  19. // =======================================================================
  20. // IMPORTANT VALUES THAT YOU *NEED* TO CHANGE FOR THIS TO BE SECURE
  21. // =======================================================================
  22. // Keeping this location on ./... means that it will be publically visible to all,
  23. // and you need to use htaccess rules or some such to ensure no one
  24. // grabs your user's data.
  25. //const USER_HOME = "../users/";
  26. // In order for users to be notified by email of certain things, set this to true.
  27. // Note that the server you run this on should have sendmail in order for
  28. // notification emails to work. Also note that password resetting doesn't work
  29. // unless mail notification is turned on.
  30. const use_mail = true;
  31. // This value should point to a directory that is not available to web users.
  32. // If your documents are in ./public_html, for instance., then put database
  33. // in something like ./database - that way, you don't have to rely on
  34. // htaccess rules or the likes, because it's simply impossible to get to the
  35. // database from a public, or private, URL.
  36. //
  37. // By default it's set to the stupidly dangerous and publically accessible same
  38. // base dir as your web page. So change it, because people are going to try
  39. // to download your database file. And succeed.
  40. //const DATABASE_LOCATION = "../";
  41. // if this is set to "true", registration failure due to known usernames is reported,
  42. // and login failures are explained as either the wrong username or the wrong password.
  43. // You really want to set this to 'false', but it's on true by default because goddamnit
  44. // I'm going to confront you with security issues right off the bat =)
  45. const unsafe_reporting = false;
  46. /**
  47. Think about security for a moment. On the one hand, you want your website
  48. to not reveal whether usernames are already taken, so when people log in
  49. you will want to say "username or password incorrect". However, you also want
  50. to be able to tell people that they can't register because the username they
  51. picked is already taken.
  52. Because these are mutually exclusive, you can't do both using this framework.
  53. You can either use unsafe reporting, where the system will will tell you that
  54. a username exists, both during registration and login, or you can use safe
  55. reporting, and then the system will reject registrations based on username
  56. similarity, not exact match. But then it also won't say which of the username
  57. or password in a login attempt was incorrect.
  58. **/
  59. // =======================================================================
  60. // You can modify the following values, but they're not security related
  61. // =======================================================================
  62. // rename this to whatever you like
  63. const DATABASE_NAME = "users";
  64. // this is the session timeout. If someone hasn't performed any page requests
  65. // in [timeout] seconds, they're considered logged out.
  66. const time_out = 604800;
  67. // You'll probably want to change this to something sensible. If your site is
  68. // www.sockmonkey.com, then you want this to be "sockmonkey.com"
  69. const DOMAIN_NAME = "Organizr";
  70. // This is going to be the "from" address
  71. const MAILER_NAME = "noreply@organizr";
  72. // if you want people to be able to reply to a real address, override
  73. // this variable to "yourmail@somedomain.ext" here.
  74. const MAILER_REPLYTO = "noreply@organizr";
  75. // =======================================================================
  76. // Don't modify any variables beyond this point =)
  77. // =======================================================================
  78. // this is the global error message. If anything goes wrong, this tells you why.
  79. var $error = "";
  80. // progress log
  81. var $info_log = array();
  82. // Information logging
  83. function info($string) { $this->info_log[] = $string; }
  84. // error log
  85. var $error_log = array();
  86. // Error logging
  87. function error($string) { $this->error_log[] = $string; }
  88. // all possible values for a hexadecimal number
  89. var $hex = "0123456789abcdef";
  90. // all possible values for an ascii password, skewed a bit so the number to letter ratio is closer to 1:1
  91. var $ascii = "0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F2G3H4I5J6K7L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z23456789";
  92. // the regular expression for email matching (see http://www.regular-expressions.info/email.html)
  93. const emailregexp = "/[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/";
  94. // the regular expression for SHA1 hash matching
  95. const sha1regexp = "/[0123456789abcdef]{40,40}/";
  96. // this will tell us whether the client that requested the page is authenticated or not.
  97. var $authenticated = false;
  98. // the guest user name
  99. const GUEST_USER = "guest user";
  100. // this will contain the user name for the user doing the page request
  101. var $username = User::GUEST_USER;
  102. // if this is a properly logged in user, this will contain the data directory location for this user
  103. var $userdir = false;
  104. // the user's email address, if logged in.
  105. var $email = "";
  106. // the user's role in the system
  107. var $role = "";
  108. // global database handle
  109. var $database = false;
  110. // class object constructor
  111. function __construct($registration_callback=false)
  112. {
  113. // session management comes first. Warnings are repressed with @ because it will warn if something else already called session_start()
  114. @session_start();
  115. if(!isset($_COOKIE['Organizr'])) {
  116. if (empty($_SESSION["username"]) || empty($_SESSION["token"])) $this->resetSession();
  117. }else{
  118. $_SESSION["username"] = $_COOKIE['OrganizrU'];
  119. }
  120. // file location for the user database
  121. $dbfile = DATABASE_LOCATION . User::DATABASE_NAME . ".db";
  122. // do we need to build a new database?
  123. $rebuild = false;
  124. if(!file_exists($dbfile)) { $rebuild = true;}
  125. // bind the database handler
  126. $this->database = new PDO("sqlite:" . $dbfile);
  127. // If we need to rebuild, the file will have been automatically made by the PDO call,
  128. // but we'll still need to define the user table before we can use the database.
  129. if($rebuild) { $this->rebuild_database($dbfile); }
  130. // finally, process the page request.
  131. $this->process($registration_callback);
  132. }
  133. // this function rebuilds the database if there is no database to work with yet
  134. function rebuild_database($dbfile)
  135. {
  136. $this->info("rebuilding database as ".$dbfile);
  137. $this->database->beginTransaction();
  138. $create = "CREATE TABLE users (username TEXT UNIQUE, password TEXT, email TEXT UNIQUE, token TEXT, role TEXT, active TEXT, last TEXT);";
  139. $this->database->exec($create);
  140. $this->database->commit();
  141. }
  142. // process a page request
  143. function process(&$registration_callback=false)
  144. {
  145. $this->database->beginTransaction();
  146. if(isset($_POST["op"]))
  147. {
  148. $operation = $_POST["op"];
  149. // logging in or out, and dropping your registration, may change authentication status
  150. if($operation == "login") { $this->authenticated = $this->login(); }
  151. // logout and unregister will unset authentication if successful
  152. elseif($operation == "logout") { $this->authenticated = !$this->logout(); }
  153. elseif($operation == "unregister") { $this->authenticated = !$this->unregister(); }
  154. // anything else won't change authentication status.
  155. elseif($operation == "register") { $this->register($registration_callback); }
  156. elseif($operation == "update") { $this->update(); }
  157. // we only allow password resetting if we can send notification mails
  158. elseif($operation == "reset" && User::use_mail) { $this->reset_password(); }
  159. }
  160. // if the previous operations didn't authorise the current user,
  161. // see if they're already marked as authorised in the database.
  162. if(!$this->authenticated) {
  163. $username = $_SESSION["username"];
  164. if($username != User::GUEST_USER) {
  165. $this->authenticated = $this->authenticate_user($username,"");
  166. if($this->authenticated) { $this->mark_user_active($username); }}}
  167. // at this point we can make some globals available.
  168. $this->username = $_SESSION["username"];
  169. $this->userdir = ($this->username !=User::GUEST_USER? USER_HOME . $this->username : false);
  170. $this->email = $this->get_user_email($this->username);
  171. $this->role = $this->get_user_role($this->username);
  172. // clear database
  173. $this->database->commit();
  174. $this->database = null;
  175. }
  176. // ---------------------
  177. // validation passthroughs
  178. // ---------------------
  179. /**
  180. * Called when the requested POST operation is "login"
  181. */
  182. function login()
  183. {
  184. // get relevant values
  185. $username = $_POST["username"];
  186. $sha1 = $_POST["sha1"];
  187. $rememberMe = $_POST["rememberMe"];
  188. // step 1: someone could have bypassed the javascript validation, so validate again.
  189. if(!$this->validate_user_name($username)) {
  190. $this->info("log in error: user name did not pass validation");
  191. return false; }
  192. if(preg_match(User::sha1regexp, $sha1)==0) {
  193. $this->info("log in error: password did not pass validation");
  194. return false; }
  195. // step 2: if validation passed, log the user in
  196. if($rememberMe == "true") {
  197. return $this->login_user($username, $sha1, true);
  198. }else{
  199. return $this->login_user($username, $sha1, false);
  200. }
  201. }
  202. /**
  203. * Called when the requested POST operation is "logout"
  204. */
  205. function logout()
  206. {
  207. // get relevant value
  208. $username = $_POST["username"];
  209. // step 1: validate the user name.
  210. if(!$this->validate_user_name($username)) {
  211. $this->info("log in error: user name did not pass validation");
  212. return false; }
  213. // step 2: if validation passed, log the user out
  214. return $this->logout_user($username);
  215. }
  216. /**
  217. * Users should always have the option to unregister
  218. */
  219. function unregister()
  220. {
  221. // get relevant value
  222. $username = $_POST["username"];
  223. // step 1: validate the user name.
  224. if(!$this->validate_user_name($username)) {
  225. $this->info("unregistration error: user name did not pass validation");
  226. return false; }
  227. // step 2: if validation passed, drop the user from the system
  228. return $this->unregister_user($username);
  229. }
  230. /**
  231. * Called when the requested POST operation is "register"
  232. */
  233. function register(&$registration_callback=false)
  234. {
  235. // get relevant values
  236. $username = $_POST["username"];
  237. $email = $_POST["email"];
  238. $sha1 = $_POST["sha1"];
  239. // step 1: someone could have bypassed the javascript validation, so validate again.
  240. if(!$this->validate_user_name($username)) {
  241. $this->info("registration error: user name did not pass validation");
  242. return false; }
  243. if(preg_match(User::emailregexp, $email)==0) {
  244. $this->info("registration error: email address did not pass validation");
  245. return false; }
  246. if(preg_match(User::sha1regexp, $sha1)==0) {
  247. $this->info("registration error: password did not pass validation");
  248. return false; }
  249. // step 2: if validation passed, register user
  250. $registered = $this->register_user($username, $email, $sha1, $registration_callback);
  251. if($registered && User::use_mail)
  252. {
  253. // send email notification
  254. $from = User::MAILER_NAME;
  255. $replyto = User::MAILER_REPLYTO;
  256. $domain_name = User::DOMAIN_NAME;
  257. $subject = User::DOMAIN_NAME . " registration";
  258. $body = <<<EOT
  259. Hi,
  260. this is an automated message to let you know that someone signed up at $domain_name with the user name "$username", using this email address as mailing address.
  261. Because of the way our user registration works, we have no idea which password was used to register this account (it gets one-way hashed by the browser before it is sent to our user registration system, so that we don't know your password either), so if you registered this account, hopefully you wrote your password down somewhere.
  262. However, if you ever forget your password, you can click the "I forgot my password" link in the log-in section for $domain_name and you will be sent an email containing a new, ridiculously long and complicated password that you can use to log in. You can change your password after logging in, but that's up to you. No one's going to guess it, or brute force it, but if other people can read your emails, it's generally a good idea to change passwords.
  263. If you were not the one to register this account, you can either contact us the normal way or —much easier— you can ask the system to reset the password for the account, after which you can simply log in with the temporary password and delete the account. That'll teach whoever pretended to be you not to mess with you!
  264. Of course, if you did register it yourself, welcome to $domain_name!
  265. - the $domain_name team
  266. EOT;
  267. $headers = "From: $from\r\n";
  268. $headers .= "Reply-To: $replyto\r\n";
  269. $headers .= "X-Mailer: PHP/" . phpversion();
  270. mail($email, $subject, $body, $headers);
  271. }
  272. return $registered;
  273. }
  274. /**
  275. * Called when the requested POST operation is "update"
  276. */
  277. function update()
  278. {
  279. // get relevant values
  280. $email = trim($_POST["email"]);
  281. $sha1 = trim($_POST["sha1"]);
  282. $role = trim($_POST["role"]);
  283. // step 1: someone could have bypassed the javascript validation, so validate again.
  284. if($email !="" && preg_match(User::emailregexp, $email)==0) {
  285. $this->info("registration error: email address did not pass validation");
  286. return false; }
  287. if($sha1 !="" && preg_match(User::sha1regexp, $sha1)==0) {
  288. $this->info("registration error: password did not pass validation");
  289. return false; }
  290. // step 2: if validation passed, update the user's information
  291. return $this->update_user($email, $sha1, $role);
  292. }
  293. /**
  294. * Reset a user's password
  295. */
  296. function reset_password()
  297. {
  298. // get the email for which we should reset
  299. $email = $_POST["email"];
  300. // step 1: someone could have bypassed the javascript validation, so validate again.
  301. if(preg_match(User::emailregexp, $email)==0) {
  302. $this->info("email address did not pass validation");
  303. return false; }
  304. // step 2: if validation passed, see if there is a matching user, and reset the password if there is
  305. $newpassword = $this->random_ascii_string(64);
  306. $sha1 = sha1($newpassword);
  307. $query = "SELECT username, token FROM users WHERE email = '$email'";
  308. $username = "";
  309. $token = "";
  310. foreach($this->database->query($query) as $data) { $username = $data["username"]; $token = $data["token"]; break; }
  311. // step 2a: if there was no user to reset a password for, stop.
  312. if($username == "" || $token == "") return false;
  313. // step 2b: if there was a user to reset a password for, reset it.
  314. $dbpassword = $this->token_hash_password($username, $sha1, $token);
  315. $update = "UPDATE users SET password = '$dbpassword' WHERE email= '$email'";
  316. $this->database->exec($update);
  317. $this->info("Email has been sent with new password");
  318. // step 3: notify the user of the new password
  319. $from = User::MAILER_NAME;
  320. $replyto = User::MAILER_REPLYTO;
  321. $domain_name = User::DOMAIN_NAME;
  322. $subject = User::DOMAIN_NAME . " password reset request";
  323. $body = <<<EOT
  324. Hi,
  325. this is an automated message to let you know that someone requested a password reset for the $domain_name user account with user name "$username", which is linked to this email address.
  326. We've reset the password to the following 64 character string, so make sure to copy/paste it without any leading or trailing spaces:
  327. $newpassword
  328. If you didn't even know this account existed, now is the time to log in and delete it. How dare people use your email address to register accounts! Of course, if you did register it yourself, but you didn't request the reset, some jerk is apparently reset-spamming. We hope he gets run over by a steam shovel driven by rabid ocelots or something.
  329. Then again, it's far more likely that you did register this account, and you simply forgot the password so you asked for the reset yourself, in which case: here's your new password, and thank you for your patronage at $domain_name!
  330. - the $domain_name team
  331. EOT;
  332. $headers = "From: $from\r\n";
  333. $headers .= "Reply-To: $replyto\r\n";
  334. $headers .= "X-Mailer: PHP/" . phpversion();
  335. mail($email, $subject, $body, $headers);
  336. }
  337. // ------------------
  338. // specific functions
  339. // ------------------
  340. // session management: set session values
  341. function setSession($username, $token)
  342. {
  343. $_SESSION["username"]=$username;
  344. $_SESSION["token"]=$token;
  345. }
  346. // session management: reset session values
  347. function resetSession()
  348. {
  349. $_SESSION["username"] = User::GUEST_USER;
  350. $_SESSION["token"] = -1;
  351. }
  352. /**
  353. * Validate a username. Empty usernames or names
  354. * that are modified by making them SQL safe are
  355. * considered not validated.
  356. */
  357. function validate_user_name($username)
  358. {
  359. $cleaned = $this->clean_SQLite_string($username);
  360. $validated = ($cleaned != "" && $cleaned==$username);
  361. if(!$validated) { $this->error = "user name did not pass validation."; $this->error("user name did not pass validation."); }
  362. return $validated;
  363. }
  364. /**
  365. * Clean strings for SQL insertion as string in SQLite (single quote enclosed).
  366. * Note that if the cleaning changes the string, this system won't insert.
  367. * The validate_user_name() function will flag this as a validation failure and
  368. * the database operation is never carried out.
  369. */
  370. function clean_SQLite_string($string)
  371. {
  372. $search = array("'", "\\", ";");
  373. $replace = array('', '', '');
  374. return trim(str_replace($search, $replace, $string));
  375. }
  376. /**
  377. * Verify that the given username is allowed
  378. * to perform the given operation.
  379. */
  380. function authenticate_user($username, $operation)
  381. {
  382. // actually logged in?
  383. if($this->is_user_active($username)===false) { return false; }
  384. // logged in, but do the tokens match?
  385. $token = $this->get_user_token($username);
  386. if(isset($_COOKIE["Organizr"])){
  387. if($_COOKIE["Organizr"] == $token){
  388. return true;
  389. }else{
  390. $this->error("cookie token mismatch for $username");
  391. unset($_COOKIE['Organizr']);
  392. setcookie('Organizr', '', time() - 3600, '/');
  393. unset($_COOKIE['OrganizrU']);
  394. setcookie('OrganizrU', '', time() - 3600, '/');
  395. return false;
  396. }
  397. }else{
  398. if($token != $_SESSION["token"]) {
  399. $this->error("token mismatch for $username");
  400. return false;
  401. }
  402. // active, using the correct token -> authenticated
  403. return true;
  404. }
  405. }
  406. /**
  407. * Unicode friendly(ish) version of strtolower
  408. * see: http://ca3.php.net/manual/en/function.strtolower.php#91805
  409. */
  410. function strtolower_utf8($string)
  411. {
  412. $convert_to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
  413. "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
  414. "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
  415. "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
  416. "ь", "э", "ю", "я" );
  417. $convert_from = array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
  418. "V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
  419. "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
  420. "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
  421. "Ь", "Э", "Ю", "Я" );
  422. return str_replace($convert_from, $convert_to, $string);
  423. }
  424. /**
  425. * This functions flattens user name strings for similarity comparison purposes
  426. */
  427. function homogenise_username($string)
  428. {
  429. // cut off trailing numbers
  430. $string = preg_replace("/\d+$/", '', $string);
  431. // and then replace non-terminal numbers with
  432. // their usual letter counterparts.
  433. $s = array("1","3","4","5","7","8","0");
  434. $r = array("i","e","a","s","t","ate","o");
  435. $string = str_replace($s, $r, $string);
  436. // finally, collapse case
  437. return $this->strtolower_utf8($string);
  438. }
  439. /**
  440. * We don't require assloads of personal information.
  441. * A username and a password are all we want. The rest
  442. * is profile information that can be set, but in no way
  443. * needs to be, in the user's profile section
  444. */
  445. function register_user($username, $email, $sha1, &$registration_callback = false)
  446. {
  447. $dbpassword = $this->token_hash_password($username, $sha1, "");
  448. if($dbpassword==$sha1) die("password hashing is not implemented.");
  449. $newRole = "admin";
  450. $queryAdmin = "SELECT username FROM users";
  451. foreach($this->database->query($queryAdmin) as $data) {
  452. $newRole = "user";
  453. }
  454. // Does user already exist? (see notes on safe reporting)
  455. if(User::unsafe_reporting) {
  456. $query = "SELECT username FROM users WHERE username LIKE '$username'";
  457. foreach($this->database->query($query) as $data) {
  458. $this->info("user account for $username not created.");
  459. $this->error = "this user name is already being used by someone else.";
  460. $this->error("this user name is already being used by someone else.");
  461. return false; }}
  462. else{ $query = "SELECT username FROM users";
  463. $usernames = array();
  464. foreach($this->database->query($query) as $data) { $usernames[] = $this->homogenise_username($data["username"]); }
  465. if(in_array($this->homogenise_username($username), $usernames)) {
  466. $this->info("user account for $username not created.");
  467. $this->error = "this user name is not allowed, because it is too similar to other user names.";
  468. $this->error("this user name is not allowed, because it is too similar to other user names.");
  469. return false; }}
  470. // Is email address already in use? (see notes on safe reporting)
  471. $query = "SELECT * FROM users WHERE email = '$email'";
  472. foreach($this->database->query($query) as $data) {
  473. $this->info("user account for $username not created.");
  474. $this->error = "this email address is already in use by someone else.";
  475. $this->error("this email address is already in use by someone else.");
  476. return false; }
  477. // This user can be registered
  478. $insert = "INSERT INTO users (username, email, password, token, role, active, last) ";
  479. $insert .= "VALUES ('$username', '$email', '$dbpassword', '', '$newRole', 'false', '') ";
  480. $this->database->exec($insert);
  481. $query = "SELECT * FROM users WHERE username = '$username'";
  482. foreach($this->database->query($query) as $data) {
  483. $this->info("created user account for $username");
  484. $this->update_user_token($username, $sha1, false);
  485. // make the user's data directory
  486. $dir = USER_HOME . $username;
  487. if(!mkdir($dir, 0760, true)) { $this->error("could not make user directory $dir"); return false; }
  488. $this->info("created user directory $dir");
  489. // if there is a callback, call it
  490. if($registration_callback !== false) { $registration_callback($username, $email, $dir); }
  491. return true; }
  492. $this->error = "unknown database error occured.";
  493. $this->error("unknown database error occured.");
  494. return false;
  495. }
  496. /**
  497. * Log a user in
  498. */
  499. function login_user($username, $sha1, $remember)
  500. {
  501. function buildLog($username, $authType){
  502. if(file_exists(FAIL_LOG)) {
  503. $getFailLog = str_replace("\r\ndate", "date", file_get_contents(FAIL_LOG));
  504. $gotFailLog = json_decode($getFailLog, true);
  505. }
  506. $failLogEntryFirst = array('logType' => 'login_log', 'auth' => array(array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType)));
  507. $failLogEntry = array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType);
  508. if(isset($gotFailLog)) {
  509. array_push($gotFailLog["auth"], $failLogEntry);
  510. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotFailLog));
  511. }else{
  512. $writeFailLog = str_replace("date", "\r\ndate", json_encode($failLogEntryFirst));
  513. }
  514. return $writeFailLog;
  515. }
  516. // transform sha1 into real password
  517. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  518. if($dbpassword==$sha1) {
  519. $this->info("password hashing is not implemented.");
  520. return false; }
  521. // perform the authentication step
  522. $query = "SELECT password FROM users WHERE username = '$username'";
  523. foreach($this->database->query($query) as $data) {
  524. if($dbpassword==$data["password"]) {
  525. // authentication passed - 1) mark active and update token
  526. $this->mark_user_active($username);
  527. $this->setSession($username, $this->update_user_token($username, $sha1, false));
  528. // authentication passed - 2) signal authenticated
  529. if($remember == "true") {
  530. setcookie("Organizr", $this->get_user_token($username), time() + (86400 * 7), "/");
  531. setcookie("OrganizrU", $username, time() + (86400 * 7), "/");
  532. }
  533. $this->info("Welcome $username");
  534. file_put_contents(FAIL_LOG, buildLog($username, "good_auth"));
  535. chmod(FAIL_LOG, 0660);
  536. return true;
  537. }
  538. // authentication failed
  539. //$this->info("password mismatch for $username");
  540. file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
  541. chmod(FAIL_LOG, 0660);
  542. if(User::unsafe_reporting) { $this->error = "incorrect password for $username."; $this->error("incorrect password for $username."); }
  543. else { $this->error = "the specified username/password combination is incorrect."; $this->error("the specified username/password combination is incorrect."); }
  544. return false; }
  545. // authentication could not take place
  546. //$this->info("there was no user $username in the database");
  547. file_put_contents(FAIL_LOG, buildLog($username, "bad_auth"));
  548. chmod(FAIL_LOG, 0660);
  549. if(User::unsafe_reporting) { $this->error = "user $username is unknown."; $this->error("user $username is unknown."); }
  550. else { $this->error = "you either did not correctly input your username, or password (... or both)."; $this->error("you either did not correctly input your username, or password (... or both)."); }
  551. return false;
  552. }
  553. /**
  554. * Update a user's information
  555. */
  556. function update_user($email, $sha1, $role)
  557. {
  558. $username = $_SESSION["username"];
  559. if($email !="") {
  560. $update = "UPDATE users SET email = '$email' WHERE username = '$username'";
  561. $this->database->exec($update); }
  562. if($role !="") {
  563. $update = "UPDATE users SET role = '$role' WHERE username = '$username'";
  564. $this->database->exec($update); }
  565. if($sha1 !="") {
  566. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  567. $update = "UPDATE users SET password = '$dbpassword' WHERE username = '$username'";
  568. $this->database->exec($update); }
  569. $this->info("update the information for $username");
  570. }
  571. /**
  572. * Log a user out.
  573. */
  574. function logout_user($username)
  575. {
  576. $update = "UPDATE users SET active = 'false' WHERE username = '$username'";
  577. $this->database->exec($update);
  578. $this->resetSession();
  579. $this->info("logged $username out");
  580. unset($_COOKIE['Organizr']);
  581. setcookie('Organizr', '', time() - 3600, '/');
  582. unset($_COOKIE['OrganizrU']);
  583. setcookie('OrganizrU', '', time() - 3600, '/');
  584. return true;
  585. }
  586. /**
  587. * Drop a user from the system
  588. */
  589. function unregister_user($username)
  590. {
  591. $delete = "DELETE FROM users WHERE username = '$username'";
  592. $this->database->exec($delete);
  593. $this->info("removed $username from the Organizr");
  594. //$this->resetSession();
  595. $dir = USER_HOME . $username;
  596. if(!rmdir($dir)) { $this->error("could not delete user directory $dir"); }
  597. $this->info("deleted user directory $dir");
  598. return true;
  599. }
  600. /**
  601. * The incoming password will already be a sha1 print (40 bytes) long,
  602. * but for the database we want it to be hased as sha256 (using 64 bytes).
  603. */
  604. function token_hash_password($username, $sha1, $token)
  605. {
  606. return hash("sha256", $username . $sha1 . $token);
  607. }
  608. /**
  609. * Get a user's email address
  610. */
  611. function get_user_email($username)
  612. {
  613. if($username && $username !="" && $username !=User::GUEST_USER) {
  614. $query = "SELECT email FROM users WHERE username = '$username'";
  615. foreach($this->database->query($query) as $data) { return $data["email"]; }}
  616. return "";
  617. }
  618. /**
  619. * Get a user's role
  620. */
  621. function get_user_role($username)
  622. {
  623. if($username && $username !="" && $username !=User::GUEST_USER) {
  624. $query = "SELECT role FROM users WHERE username = '$username'";
  625. foreach($this->database->query($query) as $data) { return $data["role"]; }}
  626. return User::GUEST_USER;
  627. }
  628. /**
  629. * Get the user token
  630. */
  631. function get_user_token($username)
  632. {
  633. $query = "SELECT token FROM users WHERE username = '$username'";
  634. foreach($this->database->query($query) as $data) { return $data["token"]; }
  635. return false;
  636. }
  637. /**
  638. * Update the user's token and password upon successful login
  639. */
  640. function update_user_token($username, $sha1, $noMsg)
  641. {
  642. // update the user's token
  643. $token = $this->random_hex_string(32);
  644. $update = "UPDATE users SET token = '$token' WHERE username = '$username'";
  645. $this->database->exec($update);
  646. // update the user's password
  647. $newpassword = $this->token_hash_password($username, $sha1, $token);
  648. $update = "UPDATE users SET password = '$newpassword' WHERE username = '$username'";
  649. $this->database->exec($update);
  650. if($noMsg == "false"){
  651. $this->info("updated token and password for $username");
  652. }
  653. return $token;
  654. }
  655. /**
  656. * Mark a user as active.
  657. */
  658. function mark_user_active($username)
  659. {
  660. $update = "UPDATE users SET active = 'true', last = '" . time() . "' WHERE username = '$username'";
  661. $this->database->exec($update);
  662. //$this->info("$username has been marked currently active.");
  663. return true;
  664. }
  665. /**
  666. * Check if user can be considered active
  667. */
  668. function is_user_active($username)
  669. {
  670. $last = 0;
  671. $active = "false";
  672. $query = "SELECT last, active FROM users WHERE username = '$username'";
  673. foreach($this->database->query($query) as $data) {
  674. $last = intval($data["last"]);
  675. $active = $data["active"];
  676. break; }
  677. if($active=="true") {
  678. $diff = time() - $last;
  679. if($diff >= User::time_out) {
  680. $this->logout_user($username);
  681. $this->error("$username was active but timed out (timeout set at " . User::time_out . " seconds, difference was $diff seconds)");
  682. return false; }
  683. //$this->info("$username is active");
  684. return true; }
  685. $this->error("$username is not active");
  686. $this->resetSession();
  687. return false;
  688. }
  689. /**
  690. * Random hex string generator
  691. */
  692. function random_hex_string($len)
  693. {
  694. $string = "";
  695. $max = strlen($this->hex)-1;
  696. while($len-->0) { $string .= $this->hex[mt_rand(0, $max)]; }
  697. return $string;
  698. }
  699. /**
  700. * Random password string generator
  701. */
  702. function random_ascii_string($len)
  703. {
  704. $string = "";
  705. $max = strlen($this->ascii)-1;
  706. while($len-->0) { $string .= $this->ascii[mt_rand(0, $max)]; }
  707. return $string;
  708. }
  709. }
  710. ?>