Token.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. // Copyright 2019 Hackware SpA <human@hackware.cl>
  3. // "Hackware Web Services Core" is released under the MIT License terms.
  4. namespace Hawese\Core;
  5. use Illuminate\Support\Str;
  6. use Exception;
  7. /**
  8. * Token class.
  9. *
  10. * Currently supports 2 token types:
  11. * - HUMAN tokens can be used only once, but last a long time. Are used as an
  12. * alternative authentication mechanism instead of passwords. Currently used
  13. * for logins with "remember me" set and for users without a password (sent
  14. * via email).
  15. * - SYSTEM tokens are used to authenticate a computer that interacts with
  16. * the API.
  17. *
  18. * This should eventually be implemented using a more lightweight database.
  19. */
  20. class Token extends TableModel
  21. {
  22. public const HUMAN = 'human';
  23. public const SYSTEM = 'system';
  24. public static $table = 'tokens';
  25. public static $attributes = [
  26. 'key' => ['required', 'string', 'min:10', 'max:255'],
  27. 'secret' => ['required', 'string', 'min:10', 'max:255'],
  28. 'type' => ['required', 'in:human,system'],
  29. 'user_uid' => [
  30. 'required', 'string', 'min:3', 'max:100'
  31. ],
  32. 'created_at' => ['nullable', 'date'],
  33. ];
  34. public static $primary_key = 'key';
  35. protected static $incrementing = false;
  36. public static $foreign_keys = [
  37. 'user_uid' => User::class,
  38. ];
  39. public function __toString()
  40. {
  41. return $this->key;
  42. }
  43. /**
  44. * Inserts a new token in database
  45. */
  46. public static function generate(string $type, string $user_uid): self
  47. {
  48. $secret = Str::random(64);
  49. $token = new Token([
  50. 'key' => bin2hex(random_bytes(7)),
  51. 'secret' => password_hash($secret, PASSWORD_DEFAULT),
  52. 'type' => $type,
  53. 'user_uid' => $user_uid
  54. ]);
  55. $token->insert();
  56. $token->secret = $secret; // return the secret in clear text just once
  57. return $token;
  58. }
  59. }