user.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. // Include functions if not already included
  11. require_once('functions.php');
  12. // Autoload frameworks
  13. require_once(__DIR__ . '/vendor/autoload.php');
  14. // Lazyload settings
  15. $databaseConfig = configLazy(__DIR__ . '/config/config.php');
  16. if(file_exists('custom.css')) : define('CUSTOMCSS', 'true'); else : define('CUSTOMCSS', 'false'); endif;
  17. $notifyExplode = explode("-", NOTIFYEFFECT);
  18. define('FAIL_LOG', DATABASE_LOCATION.'loginLog.json');
  19. @date_default_timezone_set(TIMEZONE);
  20. function guestHash($start, $end){
  21. $ip = $_SERVER['REMOTE_ADDR'];
  22. $ip = md5($ip);
  23. return substr($ip, $start, $end);
  24. }
  25. define('GUEST_HASH', "guest-".guestHash(0, 5));
  26. //JWT tokens
  27. use Lcobucci\JWT\Builder;
  28. use Lcobucci\JWT\Signer\Hmac\Sha256;
  29. use Lcobucci\JWT\ValidationData;
  30. use Lcobucci\JWT\Parser;
  31. class User
  32. {
  33. // =======================================================================
  34. // IMPORTANT VALUES THAT YOU *NEED* TO CHANGE FOR THIS TO BE SECURE
  35. // =======================================================================
  36. // Keeping this location on ./... means that it will be publically visible to all,
  37. // and you need to use htaccess rules or some such to ensure no one
  38. // grabs your user's data.
  39. //const USER_HOME = "../users/";
  40. // In order for users to be notified by email of certain things, set this to true.
  41. // Note that the server you run this on should have sendmail in order for
  42. // notification emails to work. Also note that password resetting doesn't work
  43. // unless mail notification is turned on.
  44. const use_mail = ENABLEMAIL;
  45. // This value should point to a directory that is not available to web users.
  46. // If your documents are in ./public_html, for instance., then put database
  47. // in something like ./database - that way, you don't have to rely on
  48. // htaccess rules or the likes, because it's simply impossible to get to the
  49. // database from a public, or private, URL.
  50. //
  51. // By default it's set to the stupidly dangerous and publically accessible same
  52. // base dir as your web page. So change it, because people are going to try
  53. // to download your database file. And succeed.
  54. //const DATABASE_LOCATION = "../";
  55. // if this is set to "true", registration failure due to known usernames is reported,
  56. // and login failures are explained as either the wrong username or the wrong password.
  57. // You really want to set this to 'false', but it's on true by default because goddamnit
  58. // I'm going to confront you with security issues right off the bat =)
  59. const unsafe_reporting = false;
  60. /**
  61. Think about security for a moment. On the one hand, you want your website
  62. to not reveal whether usernames are already taken, so when people log in
  63. you will want to say "username or password incorrect". However, you also want
  64. to be able to tell people that they can't register because the username they
  65. picked is already taken.
  66. Because these are mutually exclusive, you can't do both using this framework.
  67. You can either use unsafe reporting, where the system will will tell you that
  68. a username exists, both during registration and login, or you can use safe
  69. reporting, and then the system will reject registrations based on username
  70. similarity, not exact match. But then it also won't say which of the username
  71. or password in a login attempt was incorrect.
  72. **/
  73. // =======================================================================
  74. // You can modify the following values, but they're not security related
  75. // =======================================================================
  76. // rename this to whatever you like
  77. const DATABASE_NAME = "users"; // Obsolete
  78. // this is the session timeout. If someone hasn't performed any page requests
  79. // in [timeout] seconds, they're considered logged out.
  80. const time_out = 604800;
  81. // You'll probably want to change this to something sensible. If your site is
  82. // www.sockmonkey.com, then you want this to be "sockmonkey.com"
  83. const DOMAIN_NAME = "Organizr";
  84. // This is going to be the "from" address
  85. const MAILER_NAME = "noreply@organizr";
  86. // if you want people to be able to reply to a real address, override
  87. // this variable to "yourmail@somedomain.ext" here.
  88. const MAILER_REPLYTO = "noreply@organizr";
  89. // =======================================================================
  90. // Don't modify any variables beyond this point =)
  91. // =======================================================================
  92. // this is the global error message. If anything goes wrong, this tells you why.
  93. var $error = "";
  94. // progress log
  95. var $info_log = array();
  96. // Information logging
  97. function info($string) { $this->info_log[] = $string; }
  98. // error log
  99. var $error_log = array();
  100. // Error logging
  101. function error($string) { $this->error_log[] = $string; }
  102. // all possible values for a hexadecimal number
  103. var $hex = "0123456789abcdef";
  104. // all possible values for an ascii password, skewed a bit so the number to letter ratio is closer to 1:1
  105. var $ascii = "0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6A7B8C9D0E1F2G3H4I5J6K7L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z23456789";
  106. // the regular expression for email matching (see http://www.regular-expressions.info/email.html)
  107. 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])?/";
  108. // the regular expression for SHA1 hash matching
  109. const sha1regexp = "/[0123456789abcdef]{40,40}/";
  110. // this will tell us whether the client that requested the page is authenticated or not.
  111. var $authenticated = false;
  112. // the guest user name
  113. const GUEST_USER = GUEST_HASH;
  114. // this will contain the user name for the user doing the page request
  115. var $username = User::GUEST_USER;
  116. // if this is a properly logged in user, this will contain the data directory location for this user
  117. var $userdir = false;
  118. // the user's email address, if logged in.
  119. var $email = "";
  120. var $adminEmail = "";
  121. var $adminList = array();
  122. // the user's role in the system
  123. var $role = "";
  124. var $group = "";
  125. // global database handle
  126. var $database = false;
  127. //EMAIL SHIT
  128. function startEmail($email, $username, $subject, $body){
  129. $mail = new PHPMailer;
  130. $mail->isSMTP();
  131. $mail->Host = SMTPHOST;
  132. $mail->SMTPAuth = (SMTPHOSTAUTH == "true" || SMTPHOSTAUTH == true) ? true : false;
  133. $mail->Username = SMTPHOSTUSERNAME;
  134. $mail->Password = SMTPHOSTPASSWORD;
  135. $mail->SMTPSecure = SMTPHOSTTYPE;
  136. $mail->Port = SMTPHOSTPORT;
  137. $mail->setFrom(SMTPHOSTSENDEREMAIL, SMTPHOSTSENDERNAME);
  138. $mail->addReplyTo(SMTPHOSTSENDEREMAIL, SMTPHOSTSENDERNAME);
  139. $mail->isHTML(true);
  140. $mail->addAddress($email, $username);
  141. $mail->Subject = $subject;
  142. $mail->Body = $body;
  143. //$mail->send();
  144. if(!$mail->send()) {
  145. $this->error('Mailer Error: ' . $mail->ErrorInfo);
  146. $this->error = 'Mailer Error: ' . $mail->ErrorInfo;
  147. } else {
  148. $this->info('E-Mail sent!');
  149. }
  150. }
  151. function jwtParse(){
  152. $result = array();
  153. $result['valid'] = false;
  154. //Check Token with JWT
  155. if(isset($_COOKIE['Organizr_Token'])){
  156. //Set key
  157. $key = (COOKIEPASSWORD != '') ? COOKIEPASSWORD : DATABASE_LOCATION;
  158. //HSA256 Encyption
  159. $signer = new Sha256();
  160. $jwttoken = (new Parser())->parse((string) $_COOKIE['Organizr_Token']); // Parses from a string
  161. $jwttoken->getHeaders(); // Retrieves the token header
  162. $jwttoken->getClaims(); // Retrieves the token claims
  163. //Start Validation
  164. if($jwttoken->verify($signer, $key)){
  165. $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
  166. $data->setIssuer('Organizr');
  167. $data->setAudience('Organizr');
  168. //$data->setId('4f1g23a12aas');
  169. if($jwttoken->validate($data)){
  170. $result['valid'] = true;
  171. $result['username'] = $jwttoken->getClaim('username');
  172. $result['role'] = $jwttoken->getClaim('role');
  173. }
  174. }
  175. }
  176. if($result['valid'] == true){ return $result; }else{ return null; }
  177. }
  178. // class object constructor
  179. function __construct($registration_callback=false)
  180. {
  181. // session management comes first. Warnings are repressed with @ because it will warn if something else already called session_start()
  182. @session_start();
  183. if(!isset($_COOKIE['Organizr_Token'])) {
  184. if (empty($_SESSION["username"]) || empty($_SESSION["token"])) $this->resetSession();
  185. }else{
  186. if($this->jwtParse()){
  187. $_SESSION["username"] = $this->jwtParse()['username'];
  188. }else{
  189. $this->resetSession();
  190. }
  191. }
  192. // file location for the user database
  193. $dbfile = DATABASE_LOCATION.'users.db';
  194. // do we need to build a new database?
  195. $rebuild = false;
  196. if(!file_exists($dbfile)) { $rebuild = true;}
  197. // bind the database handler
  198. $this->database = new PDO("sqlite:" . $dbfile);
  199. // If we need to rebuild, the file will have been automatically made by the PDO call,
  200. // but we'll still need to define the user table before we can use the database.
  201. if($rebuild) { $this->rebuild_database($dbfile); }
  202. // finally, process the page request.
  203. $this->process($registration_callback);
  204. }
  205. // this function rebuilds the database if there is no database to work with yet
  206. function rebuild_database($dbfile)
  207. {
  208. $this->info("creating/rebuilding database as ".$dbfile);
  209. createSQLiteDB();
  210. $this->database = new PDO("sqlite:" . $dbfile);
  211. }
  212. // process a page request
  213. function process(&$registration_callback=false)
  214. {
  215. $this->database->beginTransaction();
  216. if(isset($_POST["op"]))
  217. {
  218. $operation = $_POST["op"];
  219. // logging in or out, and dropping your registration, may change authentication status
  220. if($operation == "login") { $this->authenticated = $this->login(); }
  221. // logout and unregister will unset authentication if successful
  222. elseif($operation == "logout") { $this->authenticated = !$this->logout(); }
  223. elseif($operation == "unregister") { $this->authenticated = !$this->unregister(); }
  224. // anything else won't change authentication status.
  225. elseif($operation == "register") { $this->register($registration_callback); }
  226. elseif($operation == "update") { $this->update(); }
  227. elseif($operation == "invite") { $this->invite(); }
  228. elseif($operation == "deleteinvite") { $this->deleteInvite(); }
  229. // we only allow password resetting if we can send notification mails
  230. elseif($operation == "reset" && User::use_mail) { $this->reset_password(); }
  231. }
  232. // if the previous operations didn't authorise the current user,
  233. // see if they're already marked as authorised in the database.
  234. if(!$this->authenticated) {
  235. $username = $_SESSION["username"];
  236. if($username != User::GUEST_USER) {
  237. $this->authenticated = $this->authenticate_user($username,"");
  238. if($this->authenticated) { $this->mark_user_active($username); }}}
  239. // at this point we can make some globals available.
  240. $this->username = $_SESSION["username"];
  241. $this->userdir = ($this->username !=User::GUEST_USER? USER_HOME . $this->username : false);
  242. $this->email = $this->get_user_email($this->username);
  243. $this->adminEmail = $this->get_admin_email();
  244. $this->adminList = $this->get_admin_list();
  245. $this->role = $this->get_user_role($this->username);
  246. //$this->group = $this->get_user_group($this->username);
  247. // clear database
  248. $this->database->commit();
  249. $this->database = null;
  250. }
  251. // ---------------------
  252. // validation passthroughs
  253. // ---------------------
  254. /**
  255. * Called when the requested POST operation is "login"
  256. */
  257. function login()
  258. {
  259. // get relevant values
  260. $username = $_POST["username"];
  261. $sha1 = $_POST["sha1"];
  262. $password = $_POST["password"];
  263. $rememberMe = $_POST["rememberMe"];
  264. // step 1: someone could have bypassed the javascript validation, so validate again.
  265. if(!$this->validate_user_name($username)) {
  266. $this->info("<strong>log in error:</strong> user name did not pass validation");
  267. return false; }
  268. if(preg_match(User::sha1regexp, $sha1)==0) {
  269. $this->info("<strong>log in error:</strong> password did not pass validation");
  270. return false; }
  271. // step 2: if validation passed, log the user in
  272. return $this->login_user($username, $sha1, $rememberMe == "true", $password);
  273. }
  274. /**
  275. * Called when the requested POST operation is "logout"
  276. */
  277. function logout()
  278. {
  279. // get relevant value
  280. $username = $_POST["username"];
  281. // step 1: validate the user name.
  282. if(!$this->validate_user_name($username)) {
  283. $this->info("<strong>log in error:</strong> user name did not pass validation");
  284. return false; }
  285. // step 2: if validation passed, log the user out
  286. return $this->logout_user($username);
  287. }
  288. /**
  289. * Users should always have the option to unregister
  290. */
  291. function unregister()
  292. {
  293. // get relevant value
  294. $username = $_POST["username"];
  295. // step 1: validate the user name.
  296. if(!$this->validate_user_name($username)) {
  297. $this->info("<strong>unregistration error:</strong> user name did not pass validation");
  298. return false; }
  299. // step 2: if validation passed, drop the user from the system
  300. return $this->unregister_user($username);
  301. }
  302. /**
  303. * Called when the requested POST operation is "register"
  304. */
  305. function register(&$registration_callback=false)
  306. {
  307. // get relevant values
  308. $username = $_POST["username"];
  309. $email = $_POST["email"];
  310. $sha1 = $_POST["sha1"];
  311. $settings = $_POST["settings"];
  312. $validate = (isset($_POST["validate"])) ? $_POST["validate"] : null;
  313. if(REGISTERPASSWORD != ""){
  314. if($validate == REGISTERPASSWORD){
  315. $validate = true;
  316. }
  317. }else{
  318. $validate = null;
  319. }
  320. // step 1: someone could have bypassed the javascript validation, so validate again.
  321. if(!$this->validate_user_name($username)) {
  322. $this->info("<strong>registration error:</strong> user name did not pass validation");
  323. return false; }
  324. if(preg_match(User::emailregexp, $email)==0) {
  325. $this->info("<strong>registration error:</strong> email address did not pass validation");
  326. return false; }
  327. if(preg_match(User::sha1regexp, $sha1)==0) {
  328. $this->info("<strong>registration error:</strong> password did not pass validation");
  329. return false; }
  330. // step 2: if validation passed, register user
  331. $registered = $this->register_user($username, $email, $sha1, $registration_callback, $settings, $validate);
  332. return $registered;
  333. }
  334. /**
  335. * Called when the requested POST operation is "update"
  336. */
  337. function update()
  338. {
  339. // get relevant values
  340. @$username = trim($_POST["username"]);
  341. @$email = trim($_POST["email"]);
  342. @$sha1 = trim($_POST["sha1"]);
  343. @$role = trim($_POST["role"]);
  344. // step 1: someone could have bypassed the javascript validation, so validate again.
  345. if($email !="" && preg_match(User::emailregexp, $email)==0) {
  346. $this->info("<strong>registration error:</strong> email address did not pass validation");
  347. return false; }
  348. if($sha1 !="" && preg_match(User::sha1regexp, $sha1)==0) {
  349. $this->info("<strong>registration error:</strong> password did not pass validation");
  350. return false; }
  351. // step 2: if validation passed, update the user's information
  352. return $this->update_user($username, $email, $sha1, $role);
  353. }
  354. /**
  355. * Called when the requested POST operation is "invite"
  356. */
  357. function invite()
  358. {
  359. // get relevant values
  360. @$username = trim($_POST["username"]);
  361. @$email = trim($_POST["email"]);
  362. @$server = trim($_POST["server"]);
  363. // step 1: someone could have bypassed the javascript validation, so validate again.
  364. if($email !="" && preg_match(User::emailregexp, $email)==0) {
  365. $this->info("<strong>invite error:</strong> email address did not pass validation");
  366. writeLog("error", "$email didn't pass validation");
  367. return false;
  368. }
  369. // step 2: if validation passed, send the user's information for invite
  370. return $this->invite_user($username, $email, $server);
  371. writeLog("success", "passing invite info for $email");
  372. }
  373. /**
  374. * Reset a user's password
  375. */
  376. function reset_password()
  377. {
  378. // get the email for which we should reset
  379. $email = $_POST["email"];
  380. // step 1: someone could have bypassed the javascript validation, so validate again.
  381. if(preg_match(User::emailregexp, $email)==0) {
  382. $this->info("email address did not pass validation");
  383. return false; }
  384. // step 2: if validation passed, see if there is a matching user, and reset the password if there is
  385. $newpassword = $this->random_ascii_string(20);
  386. $sha1 = sha1($newpassword);
  387. $query = "SELECT username, token FROM users WHERE email = '$email'";
  388. $username = "";
  389. $token = "";
  390. foreach($this->database->query($query) as $data) { $username = $data["username"]; $token = $data["token"]; break; }
  391. // step 2a: if there was no user to reset a password for, stop.
  392. if($username == "" || $token == "") return false;
  393. // step 2b: if there was a user to reset a password for, reset it.
  394. $dbpassword = $this->token_hash_password($username, $sha1, $token);
  395. $update = "UPDATE users SET password = '$dbpassword' WHERE email= '$email'";
  396. writeLog("success", "$username has reset their password");
  397. $this->database->exec($update);
  398. $emailTemplate = array(
  399. 'type' => 'reset',
  400. 'body' => emailTemplateResetPassword,
  401. 'subject' => emailTemplateResetPasswordSubject,
  402. 'user' => $username,
  403. 'password' => $newpassword,
  404. 'inviteCode' => null,
  405. );
  406. $emailTemplate = emailTemplate($emailTemplate);
  407. $subject = $emailTemplate['subject'];
  408. $body = buildEmail($emailTemplate);
  409. $this->startEmail($email, $username, $subject, $body);
  410. }
  411. // ------------------
  412. // specific functions
  413. // ------------------
  414. // session management: set session values
  415. function setSession($username, $token)
  416. {
  417. $_SESSION["username"]=$username;
  418. $_SESSION["token"]=$token;
  419. }
  420. // session management: reset session values
  421. function resetSession()
  422. {
  423. $_SESSION["username"] = User::GUEST_USER;
  424. $_SESSION["token"] = -1;
  425. coookie('delete','cookiePassword');
  426. coookie('delete','Auth');
  427. coookie('delete','mpt');
  428. coookie('delete','Organizr_Token');
  429. }
  430. /**
  431. * Validate a username. Empty usernames or names
  432. * that are modified by making them SQL safe are
  433. * considered not validated.
  434. */
  435. function validate_user_name($username)
  436. {
  437. $cleaned = $this->clean_SQLite_string($username);
  438. $validated = ($cleaned != "" && $cleaned==$username);
  439. if(!$validated) { $this->error = "user name did not pass validation."; $this->error("user name did not pass validation."); }
  440. return $validated;
  441. }
  442. /**
  443. * Clean strings for SQL insertion as string in SQLite (single quote enclosed).
  444. * Note that if the cleaning changes the string, this system won't insert.
  445. * The validate_user_name() function will flag this as a validation failure and
  446. * the database operation is never carried out.
  447. */
  448. function clean_SQLite_string($string)
  449. {
  450. $search = array("'", "\\", ";");
  451. $replace = array('', '', '');
  452. return trim(str_replace($search, $replace, $string));
  453. }
  454. /**
  455. * Verify that the given username is allowed
  456. * to perform the given operation.
  457. */
  458. function authenticate_user($username, $operation)
  459. {
  460. // actually logged in?
  461. if($this->is_user_active($username)===false) { return false; }
  462. // logged in, but do the tokens match?
  463. $token = $this->get_user_token($username);
  464. //Check Token with Session
  465. if(isset($_SESSION["token"])){
  466. if($token == $_SESSION["token"]) { coookie('set','cookiePassword',COOKIEPASSWORD,7); return true; }
  467. }
  468. //Check Token with JWT
  469. if(isset($_COOKIE['Organizr_Token'])){
  470. //Set key
  471. $key = (COOKIEPASSWORD != '') ? COOKIEPASSWORD : DATABASE_LOCATION;
  472. //HSA256 Encyption
  473. $signer = new Sha256();
  474. $jwttoken = (new Parser())->parse((string) $_COOKIE['Organizr_Token']); // Parses from a string
  475. $jwttoken->getHeaders(); // Retrieves the token header
  476. $jwttoken->getClaims(); // Retrieves the token claims
  477. //Start Validation
  478. if($jwttoken->verify($signer, $key)){
  479. $data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
  480. $data->setIssuer('Organizr');
  481. $data->setAudience('Organizr');
  482. //$data->setId('4f1g23a12aas');
  483. if($jwttoken->validate($data)){
  484. return true;
  485. }
  486. }
  487. }
  488. $this->error("token mismatch for $username");
  489. $this->resetSession();
  490. return false;
  491. }
  492. /**
  493. * Unicode friendly(ish) version of strtolower
  494. * see: http://ca3.php.net/manual/en/function.strtolower.php#91805
  495. */
  496. function strtolower_utf8($string)
  497. {
  498. $convert_to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
  499. "v", "w", "x", "y", "z", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï",
  500. "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ø", "ù", "ú", "û", "ü", "ý", "а", "б", "в", "г", "д", "е", "ё", "ж",
  501. "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
  502. "ь", "э", "ю", "я" );
  503. $convert_from = array( "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
  504. "V", "W", "X", "Y", "Z", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
  505. "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
  506. "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
  507. "Ь", "Э", "Ю", "Я" );
  508. return str_replace($convert_from, $convert_to, $string);
  509. }
  510. /**
  511. * This functions flattens user name strings for similarity comparison purposes
  512. */
  513. function homogenise_username($string)
  514. {
  515. // cut off trailing numbers
  516. $string = preg_replace("/\d+$/", '', $string);
  517. // and then replace non-terminal numbers with
  518. // their usual letter counterparts.
  519. $s = array("1","3","4","5","7","8","0");
  520. $r = array("i","e","a","s","t","ate","o");
  521. $string = str_replace($s, $r, $string);
  522. // finally, collapse case
  523. return $this->strtolower_utf8($string);
  524. }
  525. /**
  526. * We don't require assloads of personal information.
  527. * A username and a password are all we want. The rest
  528. * is profile information that can be set, but in no way
  529. * needs to be, in the user's profile section
  530. */
  531. function register_user($username, $email, $sha1, &$registration_callback = false, $settings, $validate, $roleOverride = 'user', $password = null) {
  532. //Admin bypass
  533. if($validate == null){
  534. $override = false;
  535. $adminList = $this->get_admin_list();
  536. if($adminList){
  537. if(in_arrayi($_SESSION["username"], $adminList)){
  538. $token = $this->get_user_token($_SESSION["username"]);
  539. if($token == $_SESSION["token"]) {
  540. $override = true;
  541. }
  542. if(isset($_COOKIE['Organizr_Token'])) {
  543. if($this->jwtParse()){
  544. $override = true;
  545. }
  546. }
  547. if($override == true) {
  548. $validate = true;
  549. writeLog("success", "Admin Override on registration for $username info");
  550. }
  551. }
  552. }
  553. }
  554. $username = strtolower($username);
  555. $dbpassword = $this->token_hash_password($username, $sha1, "");
  556. if($dbpassword==$sha1) die("password hashing is not implemented.");
  557. $newRole = "admin";
  558. $queryAdmin = "SELECT username FROM users";
  559. foreach($this->database->query($queryAdmin) as $data) {
  560. $newRole = "user";
  561. }
  562. if($roleOverride == 'admin'){ $newRole = "admin"; }
  563. if($newRole == "user" && $validate == null){
  564. writeLog("error", "$username on IP ".$_SERVER['REMOTE_ADDR']." is trying to hack your Organizr");
  565. $this->error = "Hack attempt has been made. What are you doing? Logging your IP now...";
  566. $this->error("Hack attempt has been made. What are you doing? Logging your IP now...");
  567. return false;
  568. }
  569. // Does user already exist? (see notes on safe reporting)
  570. if(User::unsafe_reporting) {
  571. $query = "SELECT username FROM users WHERE username LIKE '$username' COLLATE NOCASE";
  572. foreach($this->database->query($query) as $data) {
  573. $this->info("user account for $username not created.");
  574. $this->error = "this user name is already being used by someone else.";
  575. $this->error("this user name is already being used by someone else.");
  576. return false; }
  577. } else {
  578. $query = "SELECT username FROM users";
  579. $usernames = array();
  580. foreach($this->database->query($query) as $data) { $usernames[] = $this->homogenise_username($data["username"]); }
  581. if(in_array($this->homogenise_username($username), $usernames)) {
  582. //$this->info("user account for $username not created.");
  583. $this->error = "<strong>$username</strong> is not allowed, because it is too similar to other user names.";
  584. $this->error("<strong>$username</strong> is not allowed, because it is too similar to other user names.");
  585. return false; }
  586. }
  587. // Is email address already in use? (see notes on safe reporting)
  588. if (isset($email) && $email) {
  589. $query = "SELECT * FROM users WHERE email = '$email' COLLATE NOCASE";
  590. foreach($this->database->query($query) as $data) {
  591. $this->info("user account for $username not created.");
  592. $this->error = "this email address is already in use by someone else.";
  593. $this->error("this email address is already in use by someone else.");
  594. return false;
  595. }
  596. } else {
  597. $email = $this->random_ascii_string(32).'@placeholder.eml';
  598. }
  599. // This user can be registered
  600. $insert = "INSERT INTO users (username, email, password, token, role, active, last) ";
  601. $insert .= "VALUES ('".strtolower($username)."', '$email', '$dbpassword', '', '$newRole', 'false', '') ";
  602. $this->database->exec($insert);
  603. $query = "SELECT * FROM users WHERE username = '$username'";
  604. foreach($this->database->query($query) as $data) {
  605. $this->info("created user account for $username");
  606. writeLog("success", "$username has just registered");
  607. $this->update_user_token($username, $sha1, false);
  608. // make the user's data directory
  609. $dir = USER_HOME . $username;
  610. if(!mkdir($dir, 0760, true)) { $this->error("could not make user directory $dir"); return false; }
  611. //$this->info("created user directory $dir");
  612. // if there is a callback, call it
  613. if($registration_callback !== false) { $registration_callback($username, $email, $dir); }
  614. if($settings !== 'true' && $settings !== true) { $this->login_user($username, $sha1, true, $password, false); }
  615. //send email
  616. if($username && User::use_mail)
  617. {
  618. $emailTemplate = array(
  619. 'type' => 'registration',
  620. 'body' => emailTemplateRegisterUser,
  621. 'subject' => emailTemplateRegisterUserSubject,
  622. 'user' => $username,
  623. 'password' => null,
  624. 'inviteCode' => null,
  625. );
  626. $emailTemplate = emailTemplate($emailTemplate);
  627. $subject = $emailTemplate['subject'];
  628. $body = buildEmail($emailTemplate);
  629. $this->startEmail($email, $username, $subject, $body);
  630. }
  631. return true;
  632. }
  633. $this->error = "unknown database error occured.";
  634. $this->error("unknown database error occured.");
  635. return false;
  636. }
  637. /**
  638. * Log a user in
  639. */
  640. function login_user($username, $sha1, $remember, $password, $surface = true) {
  641. $username = strtolower($username);
  642. $buildLog = function($username, $authType) {
  643. if(file_exists(FAIL_LOG)) {
  644. $getFailLog = str_replace("\r\ndate", "date", file_get_contents(FAIL_LOG));
  645. $gotFailLog = json_decode($getFailLog, true);
  646. }
  647. $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)));
  648. $failLogEntry = array('date' => date("Y-m-d H:i:s"), 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR'], 'auth_type' => $authType);
  649. if(isset($gotFailLog)) {
  650. array_push($gotFailLog["auth"], $failLogEntry);
  651. $writeFailLog = str_replace("date", "\r\ndate", json_encode($gotFailLog));
  652. } else {
  653. $writeFailLog = str_replace("date", "\r\ndate", json_encode($failLogEntryFirst));
  654. }
  655. return $writeFailLog;
  656. };
  657. // External Authentication
  658. $authSuccess = false;
  659. $function = 'plugin_auth_'.AUTHBACKEND;
  660. switch (AUTHTYPE) {
  661. case 'external':
  662. if (function_exists($function)) {
  663. $authSuccess = $function($username, $password);
  664. }
  665. break;
  666. case 'both':
  667. if (function_exists($function)) {
  668. $authSuccess = $function($username, $password);
  669. }
  670. default: // Internal
  671. if (!$authSuccess) {
  672. // perform the internal authentication step
  673. $query = "SELECT password FROM users WHERE username = '".$username."' COLLATE NOCASE";
  674. foreach($this->database->query($query) as $data) {
  675. if (password_verify($password, $data["password"])) { // Better
  676. $authSuccess = true;
  677. } else {
  678. // Legacy - Less Secure
  679. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  680. if($dbpassword==$data["password"]) {
  681. $authSuccess = true;
  682. }
  683. }
  684. }
  685. }
  686. }
  687. if ($authSuccess) {
  688. // Make sure user exists in database
  689. $query = "SELECT username FROM users WHERE username = '".$username."' COLLATE NOCASE OR email = '".$username."' COLLATE NOCASE";
  690. $userExists = false;
  691. foreach($this->database->query($query) as $data) {
  692. $userExists = true;
  693. $username = $data['username'];
  694. break;
  695. }
  696. if ($userExists) {
  697. // authentication passed - 1) mark active and update token
  698. $this->mark_user_active($username);
  699. $this->setSession($username, $this->update_user_token($username, $sha1, false));
  700. $gotUserRole = $this->get_user_role($username);
  701. //Create JWT
  702. //Set key
  703. $key = (COOKIEPASSWORD != '') ? COOKIEPASSWORD : DATABASE_LOCATION;
  704. //HSA256 Encyption
  705. $signer = new Sha256();
  706. //Start Builder
  707. $jwttoken = (new Builder())->setIssuer('Organizr') // Configures the issuer (iss claim)
  708. ->setAudience('Organizr') // Configures the audience (aud claim)
  709. ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
  710. ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
  711. ->setExpiration(time() + (86400 * 7)) // Configures the expiration time of the token (exp claim)
  712. ->set('username', $username) // Configures a new claim, called "username"
  713. ->set('role', $gotUserRole) // Configures a new claim, called "role"
  714. ->sign($signer, $key) // creates a signature using "testing" as key
  715. ->getToken(); // Retrieves the generated token
  716. $jwttoken->getHeaders(); // Retrieves the token headers
  717. $jwttoken->getClaims(); // Retrieves the token claims
  718. $_SESSION["Organizr_Token"] = $jwttoken;
  719. // authentication passed - 2) signal authenticated
  720. if($remember == "true") {
  721. coookie('set','Organizr_Token',$jwttoken,7);
  722. }else{
  723. coookie('set','Organizr_Token',$jwttoken,1);
  724. }
  725. if(OMBIURL){
  726. $ombiToken = getOmbiToken($username, $password);
  727. if($ombiToken){
  728. coookie('set','Auth',$ombiToken,7, false);
  729. }
  730. }
  731. if(PLEXURL && isset($authSuccess['token'])){
  732. coookie('set','mpt',$authSuccess['token'],7);
  733. }
  734. $this->info("Welcome $username");
  735. file_put_contents(FAIL_LOG, $buildLog($username, "good_auth"));
  736. chmod(FAIL_LOG, 0660);
  737. coookie('set','cookiePassword',COOKIEPASSWORD,7);
  738. writeLog("success", "$username has logged in");
  739. return true;
  740. } else if (AUTHBACKENDCREATE !== 'false' && $surface) {
  741. // Create User
  742. $falseByRef = false;
  743. if(isset($authSuccess['type'])){ $roleOverride = $authSuccess['type']; }else{ $roleOverride = 'user'; }
  744. $this->register_user($username, (is_array($authSuccess) && isset($authSuccess['email']) ? $authSuccess['email'] : ''), $sha1, $falseByRef, !$remember, true, $roleOverride, $password);
  745. } else {
  746. // authentication failed
  747. //$this->info("Successful Backend Auth, No User in DB, Create Set to False");
  748. file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
  749. chmod(FAIL_LOG, 0660);
  750. if(User::unsafe_reporting) { $this->error = "Successful Backend Auth, $username not in DB, Create Set to False."; $this->error("Successful Backend Auth, $username not in DB, Create Set to False."); }
  751. else { $this->error = "Not permitted to login as this user, please contact an administrator."; $this->error("Not permitted to login as this user, please contact an administrator"); }
  752. return false;
  753. }
  754. } else if (!$authSuccess) {
  755. // authentication failed
  756. //$this->info("password mismatch for $username");
  757. writeLog("error", "$username tried to sign-in with the wrong password");
  758. file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
  759. chmod(FAIL_LOG, 0660);
  760. if(User::unsafe_reporting) { $this->error = "incorrect password for $username."; $this->error("incorrect password for $username."); }
  761. else { $this->error = "the specified username/password combination is incorrect."; $this->error("the specified username/password combination is incorrect."); }
  762. return false;
  763. } else {
  764. // authentication could not take place
  765. //$this->info("there was no user $username in the database");
  766. file_put_contents(FAIL_LOG, $buildLog($username, "bad_auth"));
  767. chmod(FAIL_LOG, 0660);
  768. if(User::unsafe_reporting) { $this->error = "user $username is unknown."; $this->error("user $username is unknown."); }
  769. 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)."); }
  770. return false;
  771. }
  772. }
  773. /**
  774. * Update a user's information
  775. */
  776. function update_user($username, $email, $sha1, $role)
  777. {
  778. //Admin bypass
  779. if(!in_arrayi($_SESSION["username"], $this->get_admin_list())){
  780. // logged in, but do the tokens match?
  781. $token = $this->get_user_token($username);
  782. if($token != $_SESSION["token"]) {
  783. writeLog("error", "$username has requested info update using token: $token");
  784. $this->error("token mismatch for $username");
  785. return false;
  786. }else{
  787. writeLog("success", "$username token has been validated");
  788. }
  789. }else{
  790. $token = $this->get_user_token($_SESSION["username"]);
  791. if($token != $_SESSION["token"]) {
  792. $override = false;
  793. }
  794. if(isset($_COOKIE['Organizr_Token'])) {
  795. if($this->jwtParse()){
  796. $override = true;
  797. }
  798. }
  799. if($override){
  800. writeLog("success", "Admin Override on update for $username info");
  801. }else{
  802. writeLog("error", $_SESSION["username"]." has requested info update using token: $token");
  803. $this->error("token mismatch for ".$_SESSION["username"]);
  804. }
  805. }
  806. if($email !="") {
  807. $update = "UPDATE users SET email = '$email' WHERE username = '$username' COLLATE NOCASE";
  808. $this->database->exec($update); }
  809. if($role !="") {
  810. $update = "UPDATE users SET role = '$role' WHERE username = '$username' COLLATE NOCASE";
  811. $this->database->exec($update); }
  812. if($sha1 !="") {
  813. $dbpassword = $this->token_hash_password($username, $sha1, $this->get_user_token($username));
  814. $update = "UPDATE users SET password = '$dbpassword' WHERE username = '$username'";
  815. $this->database->exec($update); }
  816. writeLog("success", "information for $username has been updated");
  817. $this->info("updated the information for <strong>$username</strong>");
  818. }
  819. /**
  820. * Drop a invite from the system
  821. */
  822. function deleteInvite()
  823. {
  824. @$id = trim($_POST["id"]);
  825. $delete = "DELETE FROM invites WHERE id = '$id' COLLATE NOCASE";
  826. $this->database->exec($delete);
  827. $this->info("Plex Invite: <strong>$id</strong> has been deleted out of Organizr");
  828. writeLog("success", "PLEX INVITE: $id has been deleted");
  829. return true;
  830. }
  831. /**
  832. * Invite using a user's information
  833. */
  834. function invite_user($username = "none", $email, $server)
  835. {
  836. //lang shit
  837. $language = new setLanguage;
  838. $domain = getServerPath();
  839. $topImage = $domain."images/organizr-logo-h.png";
  840. $uServer = strtoupper($server);
  841. $now = date("Y-m-d H:i:s");
  842. $inviteCode = randomCode(6);
  843. $username = (!empty($username) ? $username : strtoupper($server) . " User");
  844. $link = getServerPath()."?inviteCode=".$inviteCode;
  845. if($email !="") {
  846. $insert = "INSERT INTO invites (username, email, code, valid, date) ";
  847. $insert .= "VALUES ('".strtolower($username)."', '$email', '$inviteCode', 'Yes', '$now') ";
  848. $this->database->exec($insert);
  849. }
  850. writeLog("success", "$email has been invited to the $server server");
  851. $this->info("$email has been invited to the $server server");
  852. if($insert && User::use_mail)
  853. {
  854. $emailTemplate = array(
  855. 'type' => 'invite',
  856. 'body' => emailTemplateInviteUser,
  857. 'subject' => emailTemplateInviteUserSubject,
  858. 'user' => $username,
  859. 'password' => null,
  860. 'inviteCode' => $inviteCode,
  861. );
  862. $emailTemplate = emailTemplate($emailTemplate);
  863. $subject = $emailTemplate['subject'];
  864. $body = buildEmail($emailTemplate);
  865. $this->startEmail($email, $username, $subject, $body);
  866. }
  867. }
  868. /**
  869. * Log a user out.
  870. */
  871. function logout_user($username)
  872. {
  873. $update = "UPDATE users SET active = 'false' WHERE username = '$username' COLLATE NOCASE";
  874. $this->database->exec($update);
  875. $this->resetSession();
  876. $this->info("Buh-Bye <strong>$username</strong>!");
  877. writeLog("success", "$username has signed out");
  878. return true;
  879. }
  880. /**
  881. * Drop a user from the system
  882. */
  883. function unregister_user($username)
  884. {
  885. $delete = "DELETE FROM users WHERE username = '$username' COLLATE NOCASE";
  886. $this->database->exec($delete);
  887. $this->info("<strong>$username</strong> has been kicked out of Organizr");
  888. //$this->resetSession();
  889. $dir = USER_HOME . $username;
  890. if(!rmdir($dir)) { $this->error("could not delete user directory $dir"); }
  891. $this->info("and we deleted user directory $dir");
  892. writeLog("success", "$username has been deleted");
  893. return true;
  894. }
  895. /**
  896. * The incoming password will already be a sha1 print (40 bytes) long,
  897. * but for the database we want it to be hased as sha256 (using 64 bytes).
  898. */
  899. function token_hash_password($username, $sha1, $token)
  900. {
  901. return hash("sha256",($this->database->query('SELECT username FROM users WHERE username = \''.$username.'\' COLLATE NOCASE')->fetch()['username']).$sha1.$token);
  902. }
  903. /**
  904. * Get a user's email address
  905. */
  906. function get_user_email($username)
  907. {
  908. if($username && $username !="" && $username !=User::GUEST_USER) {
  909. $query = "SELECT email FROM users WHERE username = '$username' COLLATE NOCASE";
  910. foreach($this->database->query($query) as $data) { return $data["email"]; }}
  911. return "";
  912. }
  913. function get_admin_email()
  914. {
  915. $query = "SELECT email FROM users WHERE role = 'admin' COLLATE NOCASE LIMIT 1";
  916. foreach($this->database->query($query) as $data) { return $data["email"]; }
  917. return "";
  918. }
  919. function get_admin_list()
  920. {
  921. $query = "SELECT username FROM users WHERE role = 'admin' COLLATE NOCASE";
  922. foreach($this->database->query($query) as $data) { $list[] = $data['username']; }
  923. if(!empty($list)){ return $list; } else { return false; }
  924. }
  925. /**
  926. * Get a user's role
  927. */
  928. function get_user_role($username)
  929. {
  930. if($username && $username !="" && $username !=User::GUEST_USER) {
  931. $query = "SELECT role FROM users WHERE username = '$username' COLLATE NOCASE";
  932. foreach($this->database->query($query) as $data) { return $data["role"]; }}
  933. return "guest";
  934. }
  935. /* function get_user_group($username)
  936. {
  937. if($username && $username !="" && $username !=User::GUEST_USER) {
  938. $query = "SELECT group FROM users WHERE username = '$username' COLLATE NOCASE";
  939. foreach($this->database->query($query) as $data) { return $data["group"]; }}
  940. return User::GUEST_USER;
  941. }*/
  942. /**
  943. * Get the user token
  944. */
  945. function get_user_token($username)
  946. {
  947. $query = "SELECT token FROM users WHERE username = '$username' COLLATE NOCASE";
  948. foreach($this->database->query($query) as $data) { return $data["token"]; }
  949. return false;
  950. }
  951. /**
  952. * Update the user's token and password upon successful login
  953. */
  954. function update_user_token($username, $sha1, $noMsg)
  955. {
  956. // update the user's token
  957. $token = $this->random_hex_string(32);
  958. $update = "UPDATE users SET token = '$token' WHERE username = '$username' COLLATE NOCASE";
  959. $this->database->exec($update);
  960. // update the user's password
  961. $newpassword = $this->token_hash_password($username, $sha1, $token);
  962. $update = "UPDATE users SET password = '$newpassword' WHERE username = '$username' COLLATE NOCASE";
  963. $this->database->exec($update);
  964. if($noMsg == "false"){
  965. $this->info("token and password updated for <strong>$username</strong>");
  966. }
  967. return $token;
  968. }
  969. /**
  970. * Mark a user as active.
  971. */
  972. function mark_user_active($username)
  973. {
  974. $update = "UPDATE users SET active = 'true', last = '" . time() . "' WHERE username = '$username' COLLATE NOCASE";
  975. $this->database->exec($update);
  976. //$this->info("$username has been marked currently active.");
  977. return true;
  978. }
  979. /**
  980. * Check if user can be considered active
  981. */
  982. function is_user_active($username)
  983. {
  984. $last = 0;
  985. $active = "false";
  986. $query = "SELECT last, active FROM users WHERE username = '$username' COLLATE NOCASE";
  987. foreach($this->database->query($query) as $data) {
  988. $last = intval($data["last"]);
  989. $active = $data["active"];
  990. break; }
  991. if($active=="true") {
  992. $diff = time() - $last;
  993. if($diff >= User::time_out) {
  994. $this->logout_user($username);
  995. $this->error("$username was active but timed out (timeout set at " . User::time_out . " seconds, difference was $diff seconds)");
  996. return false; }
  997. //$this->info("$username is active");
  998. return true; }
  999. $this->error("<strong>$username</strong> is not active");
  1000. $this->resetSession();
  1001. return false;
  1002. }
  1003. /**
  1004. * Random hex string generator
  1005. */
  1006. function random_hex_string($len)
  1007. {
  1008. $string = "";
  1009. $max = strlen($this->hex)-1;
  1010. while($len-->0) { $string .= $this->hex[mt_rand(0, $max)]; }
  1011. return $string;
  1012. }
  1013. /**
  1014. * Random password string generator
  1015. */
  1016. function random_ascii_string($len)
  1017. {
  1018. $string = "";
  1019. $max = strlen($this->ascii)-1;
  1020. while($len-->0) { $string .= $this->ascii[mt_rand(0, $max)]; }
  1021. return $string;
  1022. }
  1023. }
  1024. ?>