-
-
Save edk24/96b9f877d9c601bccf5994dd9830f35f to your computer and use it in GitHub Desktop.
thinkphp 鉴权基类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace app\api\controller; | |
use app\api\library\Auth; | |
use app\common\enums\ApiCodeEnum; | |
use app\Controller; | |
use Exception; | |
use think\exception\HttpResponseException; | |
/** | |
* 基础控制器 | |
*/ | |
class BaseController extends Controller | |
{ | |
/** 不需要登录的方法 */ | |
protected array $noNeedLogin = []; | |
/** 鉴权 */ | |
protected Auth $auth; | |
/** 初始化 */ | |
protected function initialize() | |
{ | |
$actionName = $this->request->action(true); | |
// 登录验证 | |
$this->auth = Auth::getInstance(); | |
$needLogin = !$this->noNeedLogin($actionName); | |
if ($needLogin) { // 需要登录 | |
try { | |
$uid = session('uid'); | |
// $uid = 1; // 本地测试模拟用户登录情况 | |
if ($uid) { | |
$this->auth->directLogin($uid); | |
} | |
} catch (Exception $e) { | |
throw new HttpResponseException(resp_fail($e->getMessage(), ApiCodeEnum::NEED_LOGIN)); | |
} | |
if ($this->auth->isLogin() == false) { // 并且没有登录 | |
throw new HttpResponseException(resp_fail('请先登录', ApiCodeEnum::NEED_LOGIN)); | |
} | |
} | |
} | |
/** | |
* 是否不需要登录 | |
* | |
* @param string $actionName | |
* @return bool | |
*/ | |
private function noNeedLogin(string $actionName) | |
{ | |
$whiteList = array_map(function (string $func) { // 遍历数组, 方法名转换小写 | |
return strtolower($func); | |
}, $this->noNeedLogin); | |
return in_array($actionName, $whiteList); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
所有控制器都继承这个基类, 不需要登录的方法 定义类成员
noNeedLogin = ['getArticle']
即可
这个类是基于php8写的, 兼容低版本php 删除其中的强类型定义 应该就行