token-functions.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. $tokenCheck = $database->fetch('SELECT * FROM tokens WHERE user_id = ? AND token = ?', $userInfo['userID'], $token);
  111. if (!$tokenCheck) {
  112. // Delete cookie & reload page
  113. coookie('delete', $GLOBALS['cookieName']);
  114. $GLOBALS['organizrUser'] = false;
  115. }
  116. $result = $database->fetch('SELECT * FROM users WHERE id = ?', $userInfo['userID']);
  117. $GLOBALS['organizrUser'] = array(
  118. "token" => $token,
  119. "tokenDate" => $userInfo['tokenDate'],
  120. "tokenExpire" => $userInfo['tokenExpire'],
  121. "username" => $result['username'],
  122. "group" => $result['group'],
  123. "groupID" => $result['group_id'],
  124. "email" => $result['email'],
  125. "image" => $result['image'],
  126. "userID" => $result['id'],
  127. "loggedin" => true,
  128. "locked" => $result['locked']
  129. );
  130. } catch (Dibi\Exception $e) {
  131. $GLOBALS['organizrUser'] = false;
  132. }
  133. }
  134. } else {
  135. // Delete cookie & reload page
  136. coookie('delete', $GLOBALS['cookieName']);
  137. $GLOBALS['organizrUser'] = false;
  138. }
  139. }
  140. function getOrganizrUserToken()
  141. {
  142. if (isset($_COOKIE[$GLOBALS['cookieName']])) {
  143. // Get token form cookie and validate
  144. validateToken($_COOKIE[$GLOBALS['cookieName']], true);
  145. } else {
  146. $GLOBALS['organizrUser'] = array(
  147. "token" => null,
  148. "tokenDate" => null,
  149. "tokenExpire" => null,
  150. "username" => "Guest",
  151. "group" => getGuest()['group'],
  152. "groupID" => getGuest()['group_id'],
  153. "email" => null,
  154. //"groupImage"=>getGuest()['image'],
  155. "image" => getGuest()['image'],
  156. "userID" => null,
  157. "loggedin" => false,
  158. "locked" => false
  159. );
  160. }
  161. }