token-functions.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. <?php
  2. function jwtParse($token)
  3. {
  4. try {
  5. $result = array();
  6. $result['valid'] = false;
  7. // Check Token with JWT
  8. // Set key
  9. if (!isset($GLOBALS['organizrHash'])) {
  10. return null;
  11. }
  12. $key = $GLOBALS['organizrHash'];
  13. // SHA256 Encryption
  14. $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
  15. $jwttoken = (new Lcobucci\JWT\Parser())->parse((string)$token); // Parses from a string
  16. $jwttoken->getHeaders(); // Retrieves the token header
  17. $jwttoken->getClaims(); // Retrieves the token claims
  18. // Start Validation
  19. if ($jwttoken->verify($signer, $key)) {
  20. $data = new Lcobucci\JWT\ValidationData(); // It will use the current time to validate (iat, nbf and exp)
  21. $data->setIssuer('Organizr');
  22. $data->setAudience('Organizr');
  23. if ($jwttoken->validate($data)) {
  24. $result['valid'] = true;
  25. $result['username'] = $jwttoken->getClaim('username');
  26. $result['group'] = $jwttoken->getClaim('group');
  27. $result['groupID'] = $jwttoken->getClaim('groupID');
  28. $result['userID'] = $jwttoken->getClaim('userID');
  29. $result['email'] = $jwttoken->getClaim('email');
  30. $result['image'] = $jwttoken->getClaim('image');
  31. $result['tokenExpire'] = $jwttoken->getClaim('exp');
  32. $result['tokenDate'] = $jwttoken->getClaim('iat');
  33. $result['token'] = $jwttoken->getClaim('exp');
  34. }
  35. }
  36. if ($result['valid'] == true) {
  37. return $result;
  38. } else {
  39. return false;
  40. }
  41. } catch (\RunException $e) {
  42. return false;
  43. } catch (\OutOfBoundsException $e) {
  44. return false;
  45. } catch (\RunTimeException $e) {
  46. return false;
  47. } catch (\InvalidArgumentException $e) {
  48. return false;
  49. }
  50. }
  51. function createToken($username, $email, $image, $group, $groupID, $key, $days = 1)
  52. {
  53. if (!isset($GLOBALS['dbLocation']) || !isset($GLOBALS['dbName'])) {
  54. return false;
  55. }
  56. //Quick get user ID
  57. try {
  58. $database = new Dibi\Connection([
  59. 'driver' => 'sqlite3',
  60. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  61. ]);
  62. $result = $database->fetch('SELECT * FROM users WHERE username = ? COLLATE NOCASE OR email = ? COLLATE NOCASE', $username, $email);
  63. // Create JWT
  64. // Set key
  65. // SHA256 Encryption
  66. $signer = new Lcobucci\JWT\Signer\Hmac\Sha256();
  67. // Start Builder
  68. $jwttoken = (new Lcobucci\JWT\Builder())->setIssuer('Organizr')// Configures the issuer (iss claim)
  69. ->setAudience('Organizr')// Configures the audience (aud claim)
  70. ->setId('4f1g23a12aa', true)// Configures the id (jti claim), replicating as a header item
  71. ->setIssuedAt(time())// Configures the time that the token was issue (iat claim)
  72. ->setExpiration(time() + (86400 * $days))// Configures the expiration time of the token (exp claim)
  73. ->set('username', $result['username'])// Configures a new claim, called "username"
  74. ->set('group', $result['group'])// Configures a new claim, called "group"
  75. ->set('groupID', $result['group_id'])// Configures a new claim, called "groupID"
  76. ->set('email', $result['email'])// Configures a new claim, called "email"
  77. ->set('image', $result['image'])// Configures a new claim, called "image"
  78. ->set('userID', $result['id'])// Configures a new claim, called "image"
  79. ->sign($signer, $key)// creates a signature using "testing" as key
  80. ->getToken(); // Retrieves the generated token
  81. $jwttoken->getHeaders(); // Retrieves the token headers
  82. $jwttoken->getClaims(); // Retrieves the token claims
  83. coookie('set', $GLOBALS['cookieName'], $jwttoken, $days);
  84. // Add token to DB
  85. $addToken = [
  86. 'token' => (string)$jwttoken,
  87. 'user_id' => $result['id'],
  88. 'created' => $GLOBALS['currentTime'],
  89. 'expires' => gmdate("Y-m-d\TH:i:s\Z", time() + (86400 * $days))
  90. ];
  91. $database->query('INSERT INTO [tokens]', $addToken);
  92. return $jwttoken;
  93. } catch (Dibi\Exception $e) {
  94. writeLog('error', $e, 'SYSTEM');
  95. return false;
  96. }
  97. }
  98. function validateToken($token, $global = false)
  99. {
  100. // Validate script
  101. $userInfo = jwtParse($token);
  102. $validated = $userInfo ? true : false;
  103. if ($validated == true) {
  104. if ($global == true) {
  105. try {
  106. $database = new Dibi\Connection([
  107. 'driver' => 'sqlite3',
  108. 'database' => $GLOBALS['dbLocation'] . $GLOBALS['dbName'],
  109. ]);
  110. $all = $database->fetchAll('SELECT * FROM `tokens` WHERE `user_id` = ? AND `expires` > ?', $userInfo['userID'], $GLOBALS['currentTime']);
  111. $tokenCheck = (searchArray($all, 'token', $token) !== false);
  112. if (!$tokenCheck) {
  113. // Delete cookie & reload page
  114. coookie('delete', $GLOBALS['cookieName']);
  115. $GLOBALS['organizrUser'] = false;
  116. }
  117. $result = $database->fetch('SELECT * FROM users WHERE id = ?', $userInfo['userID']);
  118. $GLOBALS['organizrUser'] = array(
  119. "token" => $token,
  120. "tokenDate" => $userInfo['tokenDate'],
  121. "tokenExpire" => $userInfo['tokenExpire'],
  122. "username" => $result['username'],
  123. "uid" => guestHash(0, 5),
  124. "group" => $result['group'],
  125. "groupID" => $result['group_id'],
  126. "email" => $result['email'],
  127. "image" => $result['image'],
  128. "userID" => $result['id'],
  129. "loggedin" => true,
  130. "locked" => $result['locked'],
  131. "tokenList" => $all,
  132. "authService" => explode('::', $result['auth_service'])[0]
  133. );
  134. } catch (Dibi\Exception $e) {
  135. $GLOBALS['organizrUser'] = false;
  136. }
  137. }
  138. } else {
  139. // Delete cookie & reload page
  140. coookie('delete', $GLOBALS['cookieName']);
  141. $GLOBALS['organizrUser'] = false;
  142. }
  143. }
  144. function getOrganizrUserToken()
  145. {
  146. if (isset($_COOKIE[$GLOBALS['cookieName']])) {
  147. // Get token form cookie and validate
  148. validateToken($_COOKIE[$GLOBALS['cookieName']], true);
  149. } else {
  150. $GLOBALS['organizrUser'] = array(
  151. "token" => null,
  152. "tokenDate" => null,
  153. "tokenExpire" => null,
  154. "username" => "Guest",
  155. "uid" => guestHash(0, 5),
  156. "group" => getGuest()['group'],
  157. "groupID" => getGuest()['group_id'],
  158. "email" => null,
  159. //"groupImage"=>getGuest()['image'],
  160. "image" => getGuest()['image'],
  161. "userID" => null,
  162. "loggedin" => false,
  163. "locked" => false,
  164. "tokenList" => null,
  165. "authService" => null
  166. );
  167. }
  168. }