You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
<?php
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
use App\Helpers\ApiResponse;
|
|
|
|
|
use App\Models\User;
|
|
|
|
|
use Closure;
|
|
|
|
|
use Laravel\Sanctum\PersonalAccessToken;
|
|
|
|
|
class SupplyDemandAccess
|
|
|
|
|
{
|
|
|
|
|
use ApiResponse;
|
|
|
|
|
public static function registered($user): bool {
|
|
|
|
|
return $user && preg_match('/^1\d{10}$/', (string) $user->getRawOriginal('mobile'));
|
|
|
|
|
}
|
|
|
|
|
private function tokenUser($bearer) {
|
|
|
|
|
if (!is_string($bearer) || $bearer === '') return null;
|
|
|
|
|
$token = PersonalAccessToken::findToken($bearer);
|
|
|
|
|
if (!$token || !($token->tokenable instanceof User)) return null;
|
|
|
|
|
if ($token->expires_at && !\Illuminate\Support\Carbon::parse($token->expires_at)->isFuture()) return null;
|
|
|
|
|
// Match the existing mobile login lifecycle; token age alone does not log out a member.
|
|
|
|
|
// Revoked tokens and tokens with an explicit expiry remain invalid.
|
|
|
|
|
return $token->tokenable;
|
|
|
|
|
}
|
|
|
|
|
public function handle($request, Closure $next, $mode = 'member') {
|
|
|
|
|
$user = $this->tokenUser($request->bearerToken() ?? $request->token);
|
|
|
|
|
if ($mode === 'optional') {
|
|
|
|
|
auth()->guard('mobile')->forgetUser();
|
|
|
|
|
if ($user) auth()->guard('mobile')->setUser($user);
|
|
|
|
|
return $next($request);
|
|
|
|
|
}
|
|
|
|
|
if (!$user) return $this->fail([40001, '请重新登录']);
|
|
|
|
|
if (!self::registered($user)) return $this->fail([10003, '请先登录或注册后使用此功能']);
|
|
|
|
|
auth()->guard('mobile')->setUser($user);
|
|
|
|
|
return $next($request);
|
|
|
|
|
}
|
|
|
|
|
}
|