Files
dafuweng-buildadmin/dafuweng-webman/app/common/controller/Frontend.php
2026-03-07 19:42:22 +08:00

61 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\controller;
use app\common\library\Auth;
use app\common\library\token\TokenExpirationException;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/**
* 前台/会员中心控制器基类
* 继承 Api增加会员鉴权
*/
class Frontend extends Api
{
protected array $noNeedLogin = [];
protected array $noNeedPermission = [];
protected ?Auth $auth = null;
/**
* 前台初始化(需在控制器方法开头调用)
* @return Response|null 若需直接返回则返回 Response否则 null
*/
public function initializeFrontend(WebmanRequest $request): ?Response
{
$response = $this->initializeApi($request);
if ($response !== null) return $response;
$this->setRequest($request);
$path = trim($request->path(), '/');
$parts = explode('/', $path);
$action = $parts[array_key_last($parts)] ?? '';
$needLogin = !action_in_arr($this->noNeedLogin, $action);
try {
$this->auth = Auth::instance();
$token = get_auth_token(['ba', 'user', 'token'], $request);
if ($token) $this->auth->init($token);
} catch (TokenExpirationException) {
if ($needLogin) return $this->error(__('Token expiration'), [], 409);
}
if ($needLogin) {
if (!$this->auth->isLogin()) {
return $this->error(__('Please login first'), ['type' => Auth::NEED_LOGIN], Auth::LOGIN_RESPONSE_CODE);
}
if (!action_in_arr($this->noNeedPermission, $action)) {
$routePath = get_controller_path($request) . '/' . $action;
if (!$this->auth->check($routePath)) {
return $this->error(__('You have no permission'), [], 401);
}
}
}
event_trigger('frontendInit', $this->auth);
return null;
}
}