user.php 30 KB

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