Ver código fonte

7-17利用authbase处理登录拦截

Home 4 anos atrás
pai
commit
cffcae264a

+ 34 - 0
app/api/controller/ApiBase.php

@@ -0,0 +1,34 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 20:06
+ */
+
+namespace app\api\controller;
+
+
+use app\BaseController;
+use think\exception\HttpResponseException;
+
+/**
+ * API模块下的公共控制器
+ * 如果不需要登录的场景继承ApiBase这个控制器
+ * 如果需要登录的场景继承AuthBase这个控制器
+ * Class ApiBase
+ * @package app\api\controller
+ */
+class ApiBase extends BaseController
+{
+    public function initialize()
+    {
+        parent::initialize(); // TODO: Change the autogenerated stub
+    }
+
+    public function show(...$args)
+    {
+        throw new HttpResponseException(show(...$args));
+    }
+}

+ 51 - 0
app/api/controller/AuthBase.php

@@ -0,0 +1,51 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 23:10
+ */
+
+namespace app\api\controller;
+
+/**
+ * API模块下的公共控制器
+ * 如果不需要登录的场景继承ApiBase这个控制器
+ * 如果需要登录的场景继承AuthBase这个控制器
+ * Class ApiBase
+ * @package app\api\controller
+ */
+class AuthBase extends ApiBase
+{
+    public $userId = 0;
+    public $username = '';
+    public $accessToken = '';
+
+    public function initialize()
+    {
+        parent::initialize(); // TODO: Change the autogenerated stub
+        $this->accessToken = $this->request->header('access-token');
+        if (!$this->accessToken || !$this->isLogin()) {
+            return $this->show(config('status.not_login'), '没有登录');
+        }
+    }
+
+    /**
+     * 判断用户是否登录
+     * @return bool
+     */
+    public function isLogin(): bool
+    {
+        $userInfo = cache(config('redis.token_pre') . $this->accessToken);
+        if (!$userInfo) {
+            return false;
+        }
+        if (!empty($userInfo['id']) && !empty($userInfo['username'])) {
+            $this->userId = $userInfo['id'];
+            $this->username = $userInfo['username'];
+            return true;
+        }
+        return false;
+    }
+}

+ 19 - 0
app/api/controller/User.php

@@ -0,0 +1,19 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/2/8 23:12
+ */
+
+namespace app\api\controller;
+
+
+class User extends AuthBase
+{
+    public function index()
+    {
+
+    }
+}

+ 3 - 0
app/api/exception/Http.php

@@ -33,6 +33,9 @@ class Http extends Handle
         if ($e instanceof \think\Exception) {
             return show($e->getCode(), $e->getMessage());
         }
+        if ($e instanceof \think\exception\HttpResponseException) {
+            return parent::render($request, $e);
+        }
         if (method_exists($e, "getStatusCode")) {
             $httpStatus = $e->getStatusCode();
         } else {