MiniAuth.php
940 Bytes
<?php
declare(strict_types=1);
namespace app\middleware;
use app\service\AuthContext;
use think\facade\Db;
/**
* 小程序端:Authorization: Bearer <mp_token>
*/
class MiniAuth
{
public function handle($request, \Closure $next)
{
$auth = $request->header('Authorization', '');
if (!is_string($auth) || !str_starts_with($auth, 'Bearer ')) {
return json(['code' => 401, 'msg' => '请先完成授权', 'data' => []]);
}
$token = trim(substr($auth, 7));
$user = Db::name('mp_user')->where('api_token', $token)->find();
if (!$user) {
return json(['code' => 401, 'msg' => '请先登录或重新进入', 'data' => []]);
}
if ((int) ($user['status'] ?? 1) !== 1) {
return json(['code' => 403, 'msg' => '账号已被禁用', 'data' => []]);
}
AuthContext::setMpUser($user);
return $next($request);
}
}