HasApiTokens.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Laravel\Sanctum;
  3. use Illuminate\Support\Str;
  4. trait HasApiTokens
  5. {
  6. /**
  7. * The access token the user is using for the current request.
  8. *
  9. * @var \Laravel\Sanctum\Contracts\HasAbilities
  10. */
  11. protected $accessToken;
  12. /**
  13. * Get the access tokens that belong to model.
  14. *
  15. * @return \Illuminate\Database\Eloquent\Relations\MorphMany
  16. */
  17. public function tokens()
  18. {
  19. return $this->morphMany(Sanctum::$personalAccessTokenModel, 'tokenable');
  20. }
  21. /**
  22. * Determine if the current API token has a given scope.
  23. *
  24. * @param string $ability
  25. * @return bool
  26. */
  27. public function tokenCan(string $ability)
  28. {
  29. return $this->accessToken && $this->accessToken->can($ability);
  30. }
  31. /**
  32. * Create a new personal access token for the user.
  33. *
  34. * @param string $name
  35. * @param array $abilities
  36. * @return \Laravel\Sanctum\NewAccessToken
  37. */
  38. public function createToken(string $name, array $abilities = ['*'])
  39. {
  40. $token = $this->tokens()->create([
  41. 'name' => $name,
  42. 'token' => hash('sha256', $plainTextToken = Str::random(40)),
  43. 'abilities' => $abilities,
  44. ]);
  45. return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
  46. }
  47. /**
  48. * Get the access token currently associated with the user.
  49. *
  50. * @return \Laravel\Sanctum\Contracts\HasAbilities
  51. */
  52. public function currentAccessToken()
  53. {
  54. return $this->accessToken;
  55. }
  56. /**
  57. * Set the current access token for the user.
  58. *
  59. * @param \Laravel\Sanctum\Contracts\HasAbilities $accessToken
  60. * @return $this
  61. */
  62. public function withAccessToken($accessToken)
  63. {
  64. $this->accessToken = $accessToken;
  65. return $this;
  66. }
  67. }