ApiAccessToken.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace app\common\models;
  3. use app\common\exceptions\TokenHasExpiredException;
  4. use app\common\exceptions\TokenHasRevokedException;
  5. use app\common\exceptions\TokenNotFoundException;
  6. use Carbon\Carbon;
  7. /**
  8. * Class ErpApiAccessToken
  9. * @package Yunshop\ErpApi\common\models
  10. * @property bool revoked
  11. * @property Carbon expires_at
  12. * @property string access_token
  13. * @property int uniacid
  14. * @property int id
  15. */
  16. class ApiAccessToken extends BaseModel
  17. {
  18. public $table = 'yz_api_access_token';
  19. public $timestamps = true;
  20. protected $guarded = [''];
  21. /**
  22. * @return bool
  23. * @throws TokenHasExpiredException
  24. * @throws TokenHasRevokedException
  25. */
  26. public function valid()
  27. {
  28. if ($this->expires_at <= time()) {
  29. throw new TokenHasExpiredException();
  30. }
  31. if ($this->revoked) {
  32. throw new TokenHasRevokedException();
  33. }
  34. return true;
  35. }
  36. /**
  37. * @param $uniacid
  38. * @param $token
  39. * @return bool
  40. * @throws TokenHasExpiredException
  41. * @throws TokenHasRevokedException
  42. * @throws TokenNotFoundException
  43. */
  44. static public function verify($uniacid, $token)
  45. {
  46. $accessToken = self::where([
  47. 'uniacid' => $uniacid,
  48. 'access_token' => $token,
  49. ])->first();
  50. if (!$accessToken) {
  51. throw new TokenNotFoundException();
  52. }
  53. return $accessToken->valid();
  54. }
  55. }