Token.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. * @return self ::$secret in clear text only when returned by this method.
  46. */
  47. public static function generate(string $type, string $user_uid): self
  48. {
  49. $secret = Str::random(32);
  50. $token = new Token([
  51. 'key' => bin2hex(random_bytes(7)),
  52. 'secret' => password_hash($secret, PASSWORD_DEFAULT),
  53. 'type' => $type,
  54. 'user_uid' => $user_uid
  55. ]);
  56. $token->insert();
  57. $token->secret = $secret;
  58. return $token;
  59. }
  60. }