api_user.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * A library for managing users of the web services API
  4. */
  5. // API key functions /////////////////////////////////////////////////////////////////////
  6. /**
  7. * Generate a new API user for a site, returning a new keypair on success.
  8. *
  9. * @param int $site_guid The GUID of the site. (default is current site)
  10. *
  11. * @return stdClass object or false
  12. */
  13. function create_api_user($site_guid) {
  14. global $CONFIG;
  15. if (!isset($site_guid)) {
  16. $site_guid = $CONFIG->site_id;
  17. }
  18. $site_guid = (int)$site_guid;
  19. $public = sha1(rand() . $site_guid . microtime());
  20. $secret = sha1(rand() . $site_guid . microtime() . $public);
  21. $insert = insert_data("INSERT into {$CONFIG->dbprefix}api_users
  22. (site_guid, api_key, secret) values
  23. ($site_guid, '$public', '$secret')");
  24. if ($insert) {
  25. return get_api_user($site_guid, $public);
  26. }
  27. return false;
  28. }
  29. /**
  30. * Find an API User's details based on the provided public api key.
  31. * These users are not users in the traditional sense.
  32. *
  33. * @param int $site_guid The GUID of the site.
  34. * @param string $api_key The API Key
  35. *
  36. * @return mixed stdClass representing the database row or false.
  37. */
  38. function get_api_user($site_guid, $api_key) {
  39. global $CONFIG;
  40. $api_key = sanitise_string($api_key);
  41. $site_guid = (int)$site_guid;
  42. $query = "SELECT * from {$CONFIG->dbprefix}api_users"
  43. . " where api_key='$api_key' and site_guid=$site_guid and active=1";
  44. return get_data_row($query);
  45. }
  46. /**
  47. * Revoke an api user key.
  48. *
  49. * @param int $site_guid The GUID of the site.
  50. * @param string $api_key The API Key (public).
  51. *
  52. * @return bool
  53. */
  54. function remove_api_user($site_guid, $api_key) {
  55. global $CONFIG;
  56. $keypair = get_api_user($site_guid, $api_key);
  57. if ($keypair) {
  58. return delete_data("DELETE from {$CONFIG->dbprefix}api_users where id={$keypair->id}");
  59. }
  60. return false;
  61. }