PersonalAccessToken.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Models\Sanctum;
  3. use MongoDB\Laravel\Eloquent\Model as MongoModel;
  4. use Laravel\Sanctum\Contracts\HasAbilities;
  5. class PersonalAccessToken extends MongoModel implements HasAbilities
  6. {
  7. protected $connection = 'mongodb';
  8. /**
  9. * The attributes that should be cast to native types.
  10. *
  11. * @var array
  12. */
  13. protected $casts = [
  14. 'abilities' => 'json',
  15. 'last_used_at' => 'datetime',
  16. ];
  17. /**
  18. * The attributes that are mass assignable.
  19. *
  20. * @var array
  21. */
  22. protected $fillable = [
  23. 'name',
  24. 'token',
  25. 'abilities',
  26. ];
  27. /**
  28. * The attributes that should be hidden for serialization.
  29. *
  30. * @var array
  31. */
  32. protected $hidden = [
  33. 'token',
  34. ];
  35. /**
  36. * Get the tokenable model that the access token belongs to.
  37. *
  38. * @return \Illuminate\Database\Eloquent\Relations\MorphTo
  39. */
  40. public function tokenable()
  41. {
  42. return $this->morphTo('tokenable');
  43. }
  44. /**
  45. * Find the token instance matching the given token.
  46. *
  47. * @param string $token
  48. * @return static|null
  49. */
  50. public static function findToken($token)
  51. {
  52. if (strpos($token, '|') === false) {
  53. return static::where('token', hash('sha256', $token))->first();
  54. }
  55. [$id, $token] = explode('|', $token, 2);
  56. if ($instance = static::find($id)) {
  57. return hash_equals($instance->token, hash('sha256', $token)) ? $instance : null;
  58. }
  59. }
  60. /**
  61. * Determine if the token has a given ability.
  62. *
  63. * @param string $ability
  64. * @return bool
  65. */
  66. public function can($ability)
  67. {
  68. return in_array('*', $this->abilities) ||
  69. array_key_exists($ability, array_flip($this->abilities));
  70. }
  71. /**
  72. * Determine if the token is missing a given ability.
  73. *
  74. * @param string $ability
  75. * @return bool
  76. */
  77. public function cant($ability)
  78. {
  79. return !$this->can($ability);
  80. }
  81. }