소스 검색

feat():授权

geek 4 년 전
부모
커밋
803e2461d6

+ 124 - 0
application/api/BaseController.php

@@ -0,0 +1,124 @@
+<?php
+declare (strict_types = 1);
+
+namespace app\api;
+
+use app\api\exception\ApiException;
+use app\common\until\Token;
+use think\App;
+use think\exception\ValidateException;
+use think\Validate;
+
+/**
+ * 控制器基础类
+ */
+abstract class BaseController
+{
+    /**
+     * Request实例
+     * @var \think\Request
+     */
+    protected $request;
+
+    /**
+     * 应用实例
+     * @var \think\App
+     */
+    protected $app;
+
+    /**
+     * 是否批量验证
+     * @var bool
+     */
+    protected $batchValidate = false;
+
+    /**
+     * 控制器中间件
+     * @var array
+     */
+    protected $middleware = [];
+
+    public $userId = 0;
+    
+    /**
+     * 构造方法
+     * @access public
+     * @param  App  $app  应用对象
+     */
+    public function __construct(App $app)
+    {
+        $this->app     = $app;
+        $this->request = $this->app->request;
+        $this->request['Accept'] = 'application/json';
+        $route = [
+            '/api/Token/getToken',
+            '/api/index',
+            '/api/user/login',
+            '/api/admin/login',
+            '/api/setting/read',
+        ];
+        if (!in_array($this->request->baseUrl(),$route)){
+            if (empty($this->request->header('token'))) {
+//                throw new ApiException('token不为空');
+            }else{
+                $token = new Token();
+                $decodeToken = $token->decodeToken();
+                $this->userId = $decodeToken['userId'];
+            }
+//            $token = new Token();
+//            $decodeToken = $token->decodeToken();
+//            $this->userId = $decodeToken['userId'];
+        }
+        // 控制器初始化
+        $this->initialize();
+    }
+
+    // 初始化
+    protected function initialize()
+    {}
+
+    /**
+     * 验证数据
+     * @access protected
+     * @param  array        $data     数据
+     * @param  string|array $validate 验证器名或者验证规则数组
+     * @param  array        $message  提示信息
+     * @param  bool         $batch    是否批量验证
+     * @return array|string|true
+     * @throws ValidateException
+     */
+    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
+    {
+        if (is_array($validate)) {
+            $v = new Validate();
+            $v->rule($validate);
+        } else {
+            if (strpos($validate, '.')) {
+                // 支持场景
+                [$validate, $scene] = explode('.', $validate);
+            }
+            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
+            $v     = new $class();
+            if (!empty($scene)) {
+                $v->scene($scene);
+            }
+        }
+
+        $v->message($message);
+
+        // 是否批量验证
+        if ($batch || $this->batchValidate) {
+            $v->batch(true);
+        }
+
+        return $v->failException(true)->check($data);
+    }
+
+
+    protected function isAdmin() {
+        if (request()->header('flag') === 'admin'){
+            return true;
+        }
+        return false;
+    }
+}

+ 44 - 0
application/api/controller/User.php

@@ -0,0 +1,44 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/12/5 17:15
+ */
+
+namespace app\api\controller;
+
+
+use app\api\BaseController;
+use app\common\service\CommonService;
+
+class User extends BaseController {
+
+    public function login() {
+        $params = [
+            'id'     => CommonService::getChannelId(),
+            'userid' => input('unionid'),
+            'name'   => input('nickName'),
+            'avatar' => input('avatar'),
+            'key'    => md5(input('userid').CommonService::getAuthKey())
+        ];
+        session('unionid', input('unionid'));
+        header('Location:http://mudu.tv/activity.php?a=userAssign&'.http_build_query($params));
+    }
+
+    public function checkLogin() {
+        $visitorId = input('visitorId');
+        $notifyUrl = input('notify_url');
+        if (empty(session('unionid'))){
+            header("Location:".CommonService::getAuthUrl());
+            die();
+        }
+        //增加客户自己的验证逻辑,例如登录,关注,付费,填手机号等
+        $key = md5($visitorId.CommonService::getAuthKey());
+        if(strpos($notifyUrl,'?') !== false){//url参数处理,将key加到url参数中
+            $returnUrl = $notifyUrl."&key=".$key."&expire=3600";
+        }else{
+            $returnUrl = $notifyUrl."?key=".$key."&expire=3600";
+        }
+        header("Location:".$returnUrl.'&a='.session('unionid'));//跳转到直播观看页
+        //        redirect($returnUrl);
+    }
+}

+ 12 - 0
application/api/exception/ApiException.php

@@ -0,0 +1,12 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/8/26 16:18
+ */
+
+namespace app\api\exception;
+
+
+class ApiException extends \RuntimeException {
+
+}

+ 45 - 0
application/api/exception/ExceptionHandel.php

@@ -0,0 +1,45 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/12/5 17:22
+ */
+
+namespace app\api\exception;
+
+
+use app\common\until\Enum;
+use app\common\until\Until;
+use Error;
+use Exception;
+use think\exception\Handle;
+use think\exception\HttpException;
+use think\Response;
+
+class ExceptionHandel extends Handle {
+
+    /**
+     * Render an exception into an HTTP response.
+     *
+     * @access public
+     * @param  \Exception $e
+     * @return Response
+     */
+    public function render(Exception $e)
+    {
+        // 添加自定义异常处理机制
+        if ($e instanceof ApiException) {
+            Until::output([], $e->getMessage(),Enum::THROW_ERR_CODE);
+        }
+
+        if ($e instanceof TokenException) {
+            Until::output([], $e->getMessage(),Enum::REFRSEH_TOKEN);
+        }
+
+        if ($e instanceof Exception || $e instanceof Error) {
+            Until::output([], $e->getMessage().' file:' . str_replace('/mnt/www','ROOT',$e->getFile()) . ' line:' . $e->getLine() ,Enum::THROW_ERR_CODE);
+        }
+        // 其他错误交给系统处理
+        return parent::render($e);
+
+    }
+}

+ 12 - 0
application/api/exception/TokenException.php

@@ -0,0 +1,12 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/8/26 20:53
+ */
+
+namespace app\api\exception;
+
+
+class TokenException extends \RuntimeException {
+
+}

+ 33 - 0
application/common/service/CommonService.php

@@ -0,0 +1,33 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/12/5 00:49
+ */
+
+namespace app\common\service;
+
+
+class CommonService {
+
+    public static function getChannelId(): int {
+        return 492717;
+    }
+
+    public static function getAuthKey(): string {
+        return 'taT7WDgH20QP';
+    }
+
+    public static function getAuthUrl() {
+        $baseUrl = self::getBaeUrl();
+        $redirectUrl = ['redirect_uri' => self::getRedirectUrl()];
+        return $baseUrl.'?'.http_build_query($redirectUrl);
+    }
+
+    public static function getBaeUrl() {
+        return 'http://mdttest.kydev.net/api/wechat/focusarea/11/28';
+    }
+
+    public static function getRedirectUrl() {
+        return 'http://tp.llzlovesh.top/api/user/logn';
+    }
+}

+ 24 - 0
application/common/until/Enum.php

@@ -0,0 +1,24 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/8/26 20:55
+ */
+
+namespace app\common\until;
+
+
+class Enum {
+
+    //前端可以抛出的错误
+    const THROW_ERR_CODE = 0;
+    //前端不可以抛出的错误
+//    const ERR_CODE = 500;
+    //成功
+    const SUCCESS_CODE = 1;
+    //token需要刷新token
+    const REFRSEH_TOKEN = 901;
+
+    const DOMIN = 'https://llzlovesh.top/';
+
+
+}

+ 57 - 0
application/common/until/Token.php

@@ -0,0 +1,57 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/8/26 18:54
+ */
+
+namespace app\common\until;
+
+
+use app\api\exception\ApiException;
+use app\api\exception\TokenException;
+use Firebase\JWT\ExpiredException;
+use Firebase\JWT\JWT;
+
+class Token {
+
+    public $jwtKey = '';
+
+    public $expTime = 3600;
+
+    public function __construct() {
+        $this->jwtKey = env('app.jwt_key','Rn4zNAX9e3li5dfI6mBuWLvbacTZqUrj');
+    }
+
+
+    public function getToken(int $userId,string $visitor = '') {
+        $payload = [
+            "iat"    => time(),
+            "exp"    => time() + (3600 * 24 * 7),
+            "userId" => $userId,
+            "visitor"=> $visitor
+        ];
+        $token = JWT::encode($payload, $this->jwtKey);
+        return $token;
+    }
+
+    public function decodeToken(): array {
+        $token = request()->header('token') ?: request()->get('token');
+        if (empty($token)) {
+            throw new ApiException('token不能为空');
+        }
+
+        try {
+            $decoded = JWT::decode($token, $this->jwtKey, ['HS256']);
+        } catch (ExpiredException $e) {
+            throw new TokenException('token到期,请刷新');
+        } catch (\Exception $e) {
+            throw new ApiException('token无效' . $e->getMessage());
+        }
+        $tokenInfo = (array)$decoded;
+
+        if (time() - $tokenInfo['exp'] > 3600) {
+            $GLOBALS['refreshToken'] = $this->getToken($tokenInfo['usrId']);
+        }
+        return (array)$decoded;
+    }
+}

+ 63 - 0
application/common/until/Until.php

@@ -0,0 +1,63 @@
+<?php
+/**
+ * Author: luzheng.liu
+ * Time: 2020/8/26 16:08
+ */
+
+namespace app\common\until;
+
+
+use think\Response;
+use think\Validate;
+
+class Until {
+
+    /**
+     * @param array $data
+     * @param int $code
+     * @param string $message
+     */
+    public static function output(array $data = [],string $message = 'success',int $code = Enum::SUCCESS_CODE) {
+        $re = [
+            'code' => $code,
+            'message' => $message,
+            'data' => $data
+        ];
+        header('Content-Type: application/json; charset=utf-8');
+        echo json_encode($re);
+        die;
+    }
+
+    /**
+     * @param string $showMsg
+     * @param string $systemErrorMsg
+     * @param array $data
+     * @param int $code
+     */
+    public static function outputSystemError(string $showMsg = '',string $systemErrorMsg = '', $data = [], $code = Enum::THROW_ERR_CODE): void {
+        $output = ['code' => $code, 'msg' => $showMsg, 'systemErrorMsg' => $systemErrorMsg, 'data' => $data];
+        header('Content-Type: application/json; charset=utf-8');
+        echo json_encode($output);
+        die;
+    }
+
+    public static function modelToArray($data):array {
+        if (empty($data)) {
+            return [];
+        }
+        return json_decode(json_encode($data), true);
+    }
+
+    public static function check(array $rule, array $data): void {
+        $validate = new Validate();
+        if (!$validate->check($data, $rule)) {
+            self::output([],$validate->getError(),Enum::THROW_ERR_CODE);
+        }
+    }
+
+    public static function getInput(): array {
+        $input = file_get_contents("php://input");
+        return json_decode($input, true);
+    }
+
+}

+ 0 - 46
application/index/controller/DaKa.php

@@ -1,46 +0,0 @@
-<?php
-/**
- * Author: luzheng.liu
- * Time: 2019-09-22 16:17
- */
-
-namespace app\index\controller;
-
-
-use app\index\service\DaKaService;
-use app\index\service\RiBaoService;
-use think\Controller;
-
-class DaKa extends Controller {
-
-    public function daKa() {
-        $service = new DaKaService();
-        $service->run();
-    }
-
-    public function ribao() {
-
-        $data = [
-            'msgtype' => 'text',
-            'text'    => [
-                'content' => '汇报日报了各位大佬(已写的请忽略)'
-            ]
-        ];
-        $date = date('Y-m-d');
-        var_dump($date);
-        $hm = date('H:i');
-        $w = date('w', strtotime($date));
-        if($w==6 || $w == 0){
-            var_dump($date . '周末,跳过');
-            die();
-        }
-        if ($hm !== '22:30') {
-            var_dump('不是期望时间不提示');
-            die();
-        }
-        $riBao = new RiBaoService();
-        $riBao->sendMsg($data);
-
-    }
-
-}

+ 0 - 80
application/index/controller/Index.php

@@ -1,80 +0,0 @@
-<?php
-namespace app\index\controller;
-
-use app\index\service\DaKaService;
-use app\index\service\RiBaoService;
-use think\Db;
-use think\Validate;
-
-class Index
-{
-    public function index()
-    {
-
-        return 'index';
-    }
-
-
-    public function chatInfo() {
-
-    }
-
-
-    public function sendChatMsg() {
-        $params = input();
-        $rules = [
-            'userId' => 'require',
-            'otherUserId' => 'require',
-            'content' => 'require'
-        ];
-
-        new Validate($params);
-    }
-
-    public function chatList() {
-
-    }
-
-    public function hello($name = 'ThinkPHP5')
-    {
-        return 'hello,' . $name;
-    }
-
-
-    public function daka() {
-        $service = new DaKaService();
-        $service->run();
-
-    }
-    public function ribao() {
-
-        $data = [
-            'msgtype' => 'text',
-            'text'    => [
-                'content' => '@所有人 汇报日报了各位大佬(已写的请忽略)'
-            ]
-        ];
-        $date = date('Y-m-d');
-        $hm = date('H:i');
-        var_dump($date.' '.$hm);
-        $w = date('w', strtotime($date));
-        if($w==6 || $w == 0){
-            var_dump($date . '周末,跳过');
-            die();
-        }
-        $wishTime = '22:00';
-        if ($hm !== $wishTime) {
-            var_dump('不是期望时间不提示'.$wishTime);
-            die();
-        }
-
-        if(strtotime('now') < strtotime('2020-01-31')){
-            var_dump('不是期望时间不提示'.$wishTime);
-            die();
-        }
-
-        $riBao = new RiBaoService();
-        $riBao->sendMsg($data);
-
-    }
-}

+ 0 - 17
application/index/model/DakaHoliday.php

@@ -1,17 +0,0 @@
-<?php
-/**
- * Author: luzheng.liu
- * Time: 2019-09-22 16:40
- */
-
-namespace app\index\model;
-
-
-use think\Model;
-
-class DakaHoliday extends Model {
-
-    protected $table = 'daka_holiday';
-
-
-}

+ 0 - 224
application/index/service/DaKaService.php

@@ -1,224 +0,0 @@
-<?php
-/**
- * Author: luzheng.liu
- * Time: 2019-09-22 16:18
- */
-
-namespace app\index\service;
-
-
-use app\index\model\DakaHoliday;
-
-class DaKaService {
-
-
-    public $data = [
-        'ValidYN'      => 'Y',
-        'AppToken'     => 66778899,
-        'CardTime'     => '2019-09-17+09:04',
-        'Address'      => '总部真北路办公考勤点',
-        'AppID'        => 'A|MI 8 SE-9|2.2.4|11584|862860041542790|',
-        'StaffID'      => '796996',
-        'UserID'       => '11584',
-        'Dimension'    => '31.258829',
-        'Longitude'    => '121.398896',
-        'MobileID'     => '862860041542790',
-        'CardRemarkSZ' => ''
-    ];
-//
-//    public $dakaInfo = [
-//        "OrderBy"   => "",
-//        "AppToken"  => "66778899",
-//        'StaffID'   => '796996',
-//        'pageSize'  => '31',
-//        'CardFrom'  => '',
-//        'DeptID'    => '',
-//        'EndDate'   => '2019-09-11',
-//        'pageNum'   => '1',
-//        "CompanyId" => 10,
-//        'AppID'     => 'A|MI+8+SE-9|2.2.4|11584|862860041542790|192.168.31.25',
-//        'BeginDate' => '2019-09-11',
-//        'UserID'    => '11584',
-//        'LangID'    => '1',
-//    ];
-
-
-    public function init() {
-
-
-        $date = date('Y-m-d');
-        $hour = date('H');
-        $w = date('w', strtotime($date));
-        if($w==6 || $w == 0){
-            var_dump($date . '周末,跳过');
-            die();
-        }
-
-        if($date < '2020-01-31' && $date > '2020-01-23'){
-            var_dump($date . '放假时间');
-            die();
-        }
-
-        list($year, $month, $day) = explode('-', $date);
-        if ($hour >= 6 && $hour <= 12) {
-            $min = $day + 2;
-            $min >= 10 ?: $min = '0'.$min;
-            $this->data['CardTime'] = $date . '+09:' . $min;
-            $makeTime = "$date 09:$min";
-
-        } else {
-            $min = $day ;
-            $this->data['CardTime'] = $date . '+19:' . $min;
-            $makeTime = "$date 19:$min";
-        }
-        $cronTime = date('Y-m-d H:i');
-        $makeTime = date('Y-m-d H:i', strtotime($makeTime));
-        if ($cronTime != $makeTime) {
-            var_dump($cronTime, $makeTime);
-            var_dump("预想时间不一致,停止打卡");
-            die();
-        }
-        var_dump("打卡时间" . date('Y-m-d H:i:s'));
-    }
-
-    public function run() {
-        $this->init();
-        list($hour, $min, $sec) = explode(':', date('H:i:s'));
-        $date = date('Y-m-d');
-        list($year, $month, $day) = explode('-', $date);
-//        try {
-//            $isHoliday = $this->getHoliday($year, (int)$month);
-//            if ($isHoliday) {
-//                var_dump($date . "这天是假期不打卡,退出");
-//                die();
-//            }
-//        } catch (\Exception $e) {
-//            var_dump('假期接口出错');
-//            var_dump($e->getMessage());
-//        }
-
-        if ($hour >= 6 && $hour <= 12) {
-            var_dump($date . "上班,打卡");
-        } else {
-            var_dump($date . "下班,打卡");
-        }
-        $this->data['AppID'] .=  '192.168.1.'.random_int(1, 200);
-        $this->curlDaka($this->data);
-
-
-    }
-
-    //获取当月假期
-    public function getHoliday($year, $month) {
-        $holidayModel = new DakaHoliday();
-        $holidayListByDb = $holidayModel::where(['request_date' => date('Y-m')])->column('holiday');
-        var_dump($holidayListByDb);
-        if (!empty($holidayListByDb)) {
-            if (in_array(date('Y-m-d'), $holidayListByDb)) {
-
-                return true;
-            }
-            return false;
-        }
-        $holidayFlag = false;
-        $returnInfo = file_get_contents("http://v.juhe.cn/calendar/month?year-month={$year}-{$month}&key=3384938f081a4a6338dcc11fdb66252f");
-        $data = json_decode($returnInfo, true);
-        if ($data['error_code'] !== 0) {
-            var_dump("请求假期接口失败--{$returnInfo}");
-            die();
-        }
-        $insertData = [];
-        $holidayList = array_column($data['result']['data']['holiday_array'], 'list');
-        $holidayList = array_merge(...$holidayList);
-        foreach ($holidayList as $k => $v) {
-            if ($v['status'] != 1) {
-                continue;
-            }
-            $date = date('Y-m-d', strtotime($v['date']));
-            if ($date === date('Y-m-d')) {
-                $holidayFlag = true;
-            }
-            $insertData[] = [
-                'holiday'      => date('Y-m-d', strtotime($v['date'])),
-                'request_date' => date('Y-m')
-            ];
-        }
-        $holidayModel->insertAll($insertData, true);
-
-        return $holidayFlag;
-    }
-
-    function curlDaka($data) {
-        $data = http_build_query($data);
-
-        $curl = curl_init();
-
-        curl_setopt_array($curl, [
-            CURLOPT_PORT           => "1001",
-            CURLOPT_URL            => "http://hr.baodao.com.cn:1001/AppWebService/GhrApp.asmx/InsertStaffCardRecord",
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_ENCODING       => "",
-            CURLOPT_MAXREDIRS      => 10,
-            CURLOPT_TIMEOUT        => 30,
-            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
-            CURLOPT_CUSTOMREQUEST  => "POST",
-            CURLOPT_POSTFIELDS     => $data,
-            CURLOPT_HTTPHEADER     => [
-                "Content-Type: application/x-www-form-urlencoded",
-                "cache-control: no-cache"
-            ],
-        ]);
-
-        $response = curl_exec($curl);
-        $err = curl_error($curl);
-
-        curl_close($curl);
-
-        if ($err) {
-            echo "cURL Error #:" . $err."\n";
-            die();
-        }
-        echo $response."\n";
-
-    }
-
-    public function curlDakaInfo($data) {
-
-        $data = http_build_query($data);
-
-        $curl = curl_init();
-
-        curl_setopt_array($curl, [
-            CURLOPT_PORT           => "1001",
-            CURLOPT_URL            => "http://hr.baodao.com.cn:1001/AppWebService/GhrApp.asmx/GetStaffCardRecordPeyDay",
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_ENCODING       => "",
-            CURLOPT_MAXREDIRS      => 10,
-            CURLOPT_TIMEOUT        => 30,
-            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
-            CURLOPT_CUSTOMREQUEST  => "POST",
-            CURLOPT_POSTFIELDS     => $data,
-            CURLOPT_HTTPHEADER     => [
-                "Accept: */*",
-                "Accept-Encoding: gzip, deflate",
-                "Cache-Control: no-cache",
-                "Connection: keep-alive",
-                "Content-Type: application/x-www-form-urlencoded",
-                "Host: hr.baodao.com.cn:1001",
-                "cache-control: no-cache"
-            ],
-        ]);
-
-        $response = curl_exec($curl);
-        $err = curl_error($curl);
-
-        curl_close($curl);
-
-        if ($err) {
-            echo "cURL Error #:" . $err . "\n";
-            die();
-        }
-        return $response;
-
-    }
-}

+ 0 - 40
application/index/service/RiBaoService.php

@@ -1,40 +0,0 @@
-<?php
-/**
- * Author: luzheng.liu
- * Time: 2019-12-18 23:13
- */
-
-namespace app\index\service;
-
-
-class RiBaoService {
-
-    public function sendMsg($data) {
-        $curl = curl_init();
-
-        curl_setopt_array($curl, [
-            CURLOPT_URL            => "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abbe9a66-2d91-4430-ac3c-6f5630404042",
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_ENCODING       => "",
-            CURLOPT_MAXREDIRS      => 10,
-            CURLOPT_TIMEOUT        => 30,
-            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
-            CURLOPT_CUSTOMREQUEST  => "POST",
-            CURLOPT_POSTFIELDS     => json_encode($data),
-            CURLOPT_HTTPHEADER     => [
-                "Content-Type: application/json",
-            ],
-        ]);
-
-        $response = curl_exec($curl);
-        $err = curl_error($curl);
-
-        curl_close($curl);
-
-        if ($err) {
-            echo "cURL Error #:" . $err;
-        } else {
-            echo $response;
-        }
-    }
-}