<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: sai <1430792918@qq.com>
// +----------------------------------------------------------------------
namespace plugin\saiadmin\app\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use Tinywan\Jwt\JwtToken;
use plugin\saiadmin\app\cache\ReflectionCache;
use plugin\saiadmin\exception\ApiException;

/**
 * 登录检查中间件
 */
class CheckLogin implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        // 通过反射获取控制器哪些方法不需要登录
        $noNeedLogin = ReflectionCache::getNoNeedLogin($request->controller);
        // 访问的方法需要登录
        if (!in_array($request->action, $noNeedLogin)) {
            try {
                $token = JwtToken::getExtend();
            } catch (\Throwable $e) {
                throw new ApiException('Your login credential is invalid or expired, please login again', 401);
            }
            if ($token['plat'] !== 'saiadmin') {
                throw new ApiException('Login credential verification failed');
            }
            // 一次合并设置，避免 setHeader 覆盖导致只保留最后一个
            $request->setHeader(array_merge($request->header() ?: [], [
                'check_login' => true,
                'check_admin' => $token,
            ]));
        }
        return $handler($request);
    }
}
