TestPhoneLogin.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\miniapi\service;
  4. use app\miniapi\auth\TestPhoneIdentityProvider;
  5. use app\miniapi\exception\ApiException;
  6. use app\miniapi\http\Fields;
  7. use app\miniapi\model\MiniUser;
  8. final class TestPhoneLogin
  9. {
  10. public function assertSourceAllowed(string $remoteIp): void
  11. {
  12. if (!in_array($remoteIp, config('mini_api.test_phone_allowed_ips', []), true)) {
  13. throw new ApiException(40301, '测试手机号登录仅允许指定来源', 403);
  14. }
  15. }
  16. public function login(array $input): array
  17. {
  18. if (!TestPhoneIdentityProvider::enabled()) {
  19. throw new ApiException(50301, '测试手机号登录未开启', 503);
  20. }
  21. Fields::only($input, ['phone', 'code']);
  22. $phone = Fields::text($input, 'phone', 11);
  23. $code = Fields::text($input, 'code', 5);
  24. if (!in_array($phone, TestPhoneIdentityProvider::PHONES, true)) {
  25. throw new ApiException(40102, '测试手机号或验证码错误', 401);
  26. }
  27. $identity = (new TestPhoneIdentityProvider($phone))->exchange($code);
  28. if (!MiniUser::query()->where($identity)->exists()) {
  29. throw new ApiException(50301, '测试账号尚未初始化', 503);
  30. }
  31. return (new AuthService())->issue($identity);
  32. }
  33. }