通用接口
webman-admin在plugin/admin/api
目錄提供了一些通用接口供內(nèi)部調(diào)用(非網(wǎng)絡(luò)接口)。
Auth 權(quán)限接口
<?php
namespace plugin\admin\api;
use plugin\admin\app\model\Role;
use plugin\admin\app\model\Rule;
use support\exception\BusinessException;
use function admin;
/**
* 對(duì)外提供的鑒權(quán)接口
*/
class Auth
{
/**
* 判斷是否有權(quán)限訪問某個(gè)控制器和方法,無權(quán)限時(shí)拋出異常
* @param string $controller
* @param string $action
* @return void
* @throws \ReflectionException|BusinessException
*/
public static function access(string $controller, string $action)
{}
/**
* 判斷是否有權(quán)限訪問某個(gè)控制器和方法,有權(quán)限返回true,無權(quán)限返回false
* @param string $controller
* @param string $action
* @param int $code
* @param string $msg
* @return bool
* @throws \ReflectionException|BusinessException
*/
public static function canAccess(string $controller, string $action, int &$code = 0, string &$msg = ''): bool
{}
}
Menu 菜單接口
class Menu
{
/**
* 根據(jù)key獲取菜單
* @param $key
* @return array
*/
public static function get($key)
{}
/**
* 根據(jù)id獲得菜單
* @param $id
* @return array
*/
public static function find($id): array
{}
/**
* 添加菜單
* @param array $menu
* @return int
*/
public static function add(array $menu)
{}
/**
* 導(dǎo)入菜單
* @param array $menu_tree
* @return void
*/
public static function import(array $menu_tree)
{}
/**
* 按照key刪除菜單
* @param $key
* @return void
*/
public static function delete($key)
{}
}
提示
一般來說應(yīng)用插件無需手動(dòng)調(diào)用Menu菜單接口,開發(fā)者只需要準(zhǔn)備好menu.php菜單配置,通過webman-admin安裝插件時(shí)會(huì)自動(dòng)導(dǎo)入菜單。
Middleware 中間件
為了讓其它系統(tǒng)能夠接入webman-admin的權(quán)限體系,webman-admin提供了一個(gè)鑒權(quán)中間件,實(shí)現(xiàn)如下
<?php
namespace plugin\admin\api;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use support\exception\BusinessException;
/**
* 對(duì)外提供的鑒權(quán)中間件
*/
class Middleware implements MiddlewareInterface
{
/**
* 鑒權(quán)
* @param Request $request
* @param callable $handler
* @return Response
* @throws \ReflectionException
* @throws BusinessException
*/
public function process(Request $request, callable $handler): Response
{
$controller = $request->controller;
$action = $request->action;
$code = 0;
$msg = '';
if (!Auth::canAccess($controller, $action, $code, $msg)) {
if ($request->expectsJson()) {
$response = json(['code' => $code, 'msg' => $msg, 'type' => 'error']);
} else {
$response = \response($msg, 401);
}
} else {
$response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
}
return $response;
}
}
提示
如果此中間件無法滿足開發(fā)者需求,開發(fā)者可以在自己的項(xiàng)目中實(shí)現(xiàn)自己的鑒權(quán)中間件,不一定強(qiáng)制用此鑒權(quán)中間件
快捷函數(shù)
webman-admin提供了幾個(gè)快捷函數(shù),說明如下
<?php
/**
* 獲取當(dāng)前管理員id
* @return integer|null
*/
function admin_id(): ?int
{}
/**
* 獲取當(dāng)前管理員
* @param null|array|string $fields
* @return array|mixed|null
*/
function admin($fields = null)
{}