Kaynağa Gözat

procurement表添加time字段,更新JWT验证方式

haozi 5 yıl önce
ebeveyn
işleme
ecdd742b01

+ 12 - 0
app/Http/Controllers/TestController.php

@@ -1674,5 +1674,17 @@ where (commodities.owner_id,commodity_barcodes.code) in (select commodities.owne
         }
     }
 
+    public function testUser()
+    {
+        $procurementQuotations=ProcurementQuotation::query()
+            ->with('procurement.ownerMaterial.material')
+            ->where('status',0)
+            ->whereNull('offer')
+            //->where('created_at','>=',Carbon::parse($now)->subHours(4))
+            //->where('created_at','<=',$now)
+            ->get();
+        dd($procurementQuotations->toJson());
+
 
+    }
 }

+ 40 - 80
app/Http/Controllers/api/procurement/wechat/AuthController.php

@@ -2,105 +2,65 @@
 
 namespace App\Http\Controllers\api\procurement\wechat;
 
-use App\UserDetail;
-use http\Client\Curl\User;
-use Illuminate\Support\Facades\Auth;
+use App\User;
+use Firebase\JWT\JWT;
 use App\Http\Controllers\Controller;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Facades\Hash;
 
 class AuthController extends Controller
 {
-    /**
-     * Create a new AuthController instance.
-     * 要求附带email和password(数据来源users表)
-     *
-     * @return void
-     */
-    public function __construct()
-    {
-        // 这里额外注意了:官方文档样例中只除外了『login』
-        // 这样的结果是,token 只能在有效期以内进行刷新,过期无法刷新
-        // 如果把 refresh 也放进去,token 即使过期但仍在刷新期以内也可刷新
-        // 不过刷新一次作废
-        $this->middleware('auth:api', ['except' => ['login']]);
-        // 另外关于上面的中间件,官方文档写的是『auth:api』
-        // 但是我推荐用 『jwt.auth』,效果是一样的,但是有更加丰富的报错信息返回
-    }
 
-    /**
-     * Get a JWT via given credentials.
-     *
-     * @return \Illuminate\Http\JsonResponse
-     */
     public function login()
     {
         $phone=request('phone');
-        $user_id=UserDetail::query()->where('mobile_phone',$phone)->value('user_id');
-        if (!$user_id) return response()->json(['status'=>0,'error' => '当前用户不存在!'], 401);
-        $supplierUser=\App\User::query()->whereHas('roles',function($query){
-            $query->where('name','供应商');
-        })->find($user_id);
-        $receiveUser=\App\User::query()->whereHas('roles',function($query){
-            $query->where('name','供应商');
-        })->find($user_id);
-        if (!$supplierUser && !$receiveUser) return response()->json(['status'=>0,'message' => '当前用户没有指定角色,暂不可登录!'], 401);
+        $password = request("password");
+        $user=User::query()->with('roles')
+            ->whereHas('userDetail',function ($query)use($phone){
+            /** @var Builder $query */
+            $query->where('mobile_phone',$phone);
+        })->whereHas('roles',function ($builder){
+                /** @var Builder $builder */
+            $builder->whereIn('name',['供应商','收货员']);
+            })
+            ->first();
+        if (!$user)return response()->json(['status'=>0,'message' => '当前用户不存在!'], 401);
+        if (!Hash::check($password,$user->password)) return response()->json(['status'=>0,'message' => '很抱歉,您的手机号和密码不匹配'], 401);
+
         $credentials = [
-            'id'=>$user_id,
-            'password'=>request('password')
+            'id'=>$user->id,
+            'name'=>$user->name,
         ];
-
-        if (! $token = auth('api')->attempt($credentials)) {
-            return response()->json(['status'=>0,'message' => '很抱歉,您的手机号和密码不匹配'], 401);
+        $token = $this->getJWTToken($credentials);
+        $userType=0;
+        foreach ($user->roles as $role){
+            if ($role->name=='供应商')$userType=1;
+            if ($role->name=='收货员')$userType=2;
         }
-
-        return response()->json(['status'=>1,'message' => $supplierUser?'1':'2','data'=>$token], 200);
+        return response()->json(['status'=>1,'message' => $userType,'data'=>$token], 200);
     }
 
-    /**
-     * Get the authenticated User.
-     *
-     * @return \Illuminate\Http\JsonResponse
-     */
     public function me()
     {
         return response()->json(auth('api')->user());
     }
 
-    /**
-     * Log the user out (Invalidate the token).
-     *
-     * @return \Illuminate\Http\JsonResponse
-     */
-    public function logout()
-    {
-        auth('api')->logout();
-
-        return response()->json(['message' => 'Successfully logged out']);
-    }
-
-    /**
-     * Refresh a token.
-     * 刷新token,如果开启黑名单,以前的token便会失效。
-     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新,两次获得的Token是并行的,即两个都可用。
-     * @return \Illuminate\Http\JsonResponse
-     */
-    public function refresh()
+    public function getJWTToken($value)
     {
-        return $this->respondWithToken(auth('api')->refresh());
+        $time = time();
+        $payload = [
+            'iat' => $time,
+            'nbf' => $time,
+            'exp' => $time+7200,
+            'data' => [
+                'id' => $value['id'],
+                'name' => $value['name']
+            ]
+        ];
+        $key =  env('JWT_SECRET');
+        $alg = 'HS256';
+        $token = JWT::encode($payload,$key,$alg);
+        return $token;
     }
 
-    /**
-     * Get the token array structure.
-     *
-     * @param  string $token
-     *
-     * @return \Illuminate\Http\JsonResponse
-     */
-    protected function respondWithToken($token)
-    {
-        return response()->json([
-            'access_token' => $token,
-            'token_type' => 'bearer',
-            'expires_in' => auth('api')->factory()->getTTL() * 60
-        ]);
-    }
 }

+ 2 - 5
app/Http/Controllers/api/procurement/wechat/ProcurementController.php

@@ -15,12 +15,9 @@ class ProcurementController extends Controller
             ->with('procurement.ownerMaterial.material')
             ->where('status',0)
             ->whereNull('offer')
-            ->where('created_at','>=',Carbon::parse($now)->subHours(4))
-            ->where('created_at','<=',$now)
+            //->where('created_at','>=',Carbon::parse($now)->subHours(4))
+            //->where('created_at','<=',$now)
             ->get();
-        foreach ($procurementQuotations as $procurementQuotation){
-            $procurementQuotation->append('time',4);
-        }
         if (!empty($procurementQuotations))return response()->json(['status'=>1,'data'=>$procurementQuotations->toJson()], 200);
     }
 }

+ 17 - 42
app/Http/Middleware/ProcurementApiAuth.php

@@ -3,54 +3,29 @@
 namespace App\Http\Middleware;
 
 use Closure;
-use Tymon\JWTAuth\Exceptions\JWTException;
-use Tymon\JWTAuth\Exceptions\TokenExpiredException;
-use Tymon\JWTAuth\Exceptions\TokenInvalidException;
-use Tymon\JWTAuth\Facades\JWTAuth;
+use Firebase\JWT\JWT;
 
 
 class ProcurementApiAuth
 {
-    /**
-     * Handle an incoming request.
-     *
-     * @param  \Illuminate\Http\Request  $request
-     * @param  \Closure  $next
-     * @return mixed
-     */
+
     public function handle($request, Closure $next)
     {
-        try {
-            if (! $user = JWTAuth::parseToken()->authenticate()) {
-                return response()->json([
-                    'code' => 1004,
-                    'msg' => '用户不存在'
-
-                ], 404);
-            }
-            return $next($request);
-
-        } catch (TokenExpiredException $e) {
-
-            return response()->json([
-                'code' => 1003,
-                'msg' => 'token 过期' ,
-            ]);
-
-        } catch (TokenInvalidException $e) {
-
-            return response()->json([
-                'code' => 1002,
-                'msg' => 'token 无效',
-            ]);
-
-        }catch (JWTException $e) {
-
-            return response()->json([
-                'code' => 1001,
-                'msg' => '缺少token' ,
-            ]);
-
+        $alg =
+            [
+                "typ" => "JWT", //声明类型为jwt
+                "alg" => "HS256" //声明签名算法为SHA256
+            ];
+        $jwt = $request->header('token');
+
+        $key = env('JWT_SECRET');
+        try{
+            JWT::decode($jwt,$key,$alg);
+        }
+        catch (\Exception $e)
+        {
+            return response()->json('token无效:'.$e);
         }
+        return $next($request);
     }
 }

+ 3 - 12
app/User.php

@@ -9,7 +9,6 @@ use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\Gate;
 use App\Traits\ModelTimeFormat;
-use Tymon\JWTAuth\Contracts\JWTSubject;
 
 class User extends Authenticatable
 {
@@ -81,6 +80,9 @@ class User extends Authenticatable
     function roles(){
         return $this->belongsToMany('App\Role','user_role','id_user','id_role');
     }
+    function userDetail(){
+        return $this->hasOne('App\UserDetail','user_id','id');
+    }
 
     function logistics(){
         return $this->belongsToMany('App\Logistic','logistic_user','user_id','logistic_id');
@@ -132,15 +134,4 @@ class User extends Authenticatable
         }
         return $workgroupIds;
     }
-
-    //jwt
-//    public function getJWTIdentifier()
-//    {
-//        return $this->getKey();
-//    }
-//
-//    public function getJWTCustomClaims()
-//    {
-//        return [];
-//    }
 }

+ 35 - 35
bootstrap/cache/packages.php

@@ -1,125 +1,125 @@
 <?php return array (
-  'barryvdh/laravel-debugbar' =>
+  'barryvdh/laravel-debugbar' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Barryvdh\\Debugbar\\ServiceProvider',
     ),
-    'aliases' =>
+    'aliases' => 
     array (
       'Debugbar' => 'Barryvdh\\Debugbar\\Facade',
     ),
   ),
-  'beyondcode/laravel-dump-server' =>
+  'beyondcode/laravel-dump-server' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'BeyondCode\\DumpServer\\DumpServerServiceProvider',
     ),
   ),
-  'facade/ignition' =>
+  'facade/ignition' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Facade\\Ignition\\IgnitionServiceProvider',
     ),
-    'aliases' =>
+    'aliases' => 
     array (
       'Flare' => 'Facade\\Ignition\\Facades\\Flare',
     ),
   ),
-  'fideloper/proxy' =>
+  'fideloper/proxy' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Fideloper\\Proxy\\TrustedProxyServiceProvider',
     ),
   ),
-  'intervention/image' =>
+  'intervention/image' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Intervention\\Image\\ImageServiceProvider',
     ),
-    'aliases' =>
+    'aliases' => 
     array (
       'Image' => 'Intervention\\Image\\Facades\\Image',
     ),
   ),
-  'laravel/tinker' =>
+  'laravel/tinker' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Laravel\\Tinker\\TinkerServiceProvider',
     ),
   ),
-  'laravel/ui' =>
+  'laravel/ui' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Laravel\\Ui\\UiServiceProvider',
     ),
   ),
-  'maatwebsite/excel' =>
+  'maatwebsite/excel' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Maatwebsite\\Excel\\ExcelServiceProvider',
     ),
-    'aliases' =>
+    'aliases' => 
     array (
       'Excel' => 'Maatwebsite\\Excel\\Facades\\Excel',
     ),
   ),
-  'nesbot/carbon' =>
+  'nesbot/carbon' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Carbon\\Laravel\\ServiceProvider',
     ),
   ),
-  'nunomaduro/collision' =>
+  'nunomaduro/collision' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider',
     ),
   ),
-  'overtrue/laravel-pinyin' =>
+  'overtrue/laravel-pinyin' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Overtrue\\LaravelPinyin\\ServiceProvider',
     ),
-    'aliases' =>
+    'aliases' => 
     array (
       'Pinyin' => 'Overtrue\\LaravelPinyin\\Facades\\Pinyin',
     ),
   ),
-  'te7a-houdini/laravel-trix' =>
+  'te7a-houdini/laravel-trix' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Te7aHoudini\\LaravelTrix\\LaravelTrixServiceProvider',
     ),
   ),
-  'tymon/jwt-auth' =>
+  'tymon/jwt-auth' => 
   array (
-    'aliases' =>
+    'aliases' => 
     array (
       'JWTAuth' => 'Tymon\\JWTAuth\\Facades\\JWTAuth',
       'JWTFactory' => 'Tymon\\JWTAuth\\Facades\\JWTFactory',
     ),
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Tymon\\JWTAuth\\Providers\\LaravelServiceProvider',
     ),
   ),
-  'yajra/laravel-oci8' =>
+  'yajra/laravel-oci8' => 
   array (
-    'providers' =>
+    'providers' => 
     array (
       0 => 'Yajra\\Oci8\\Oci8ServiceProvider',
     ),
   ),
-);
+);

+ 4 - 3
composer.json

@@ -8,7 +8,8 @@
     ],
     "license": "MIT",
     "require": {
-        "php": "^7.2.34",
+        "php": "^7.2.14",
+        "ext-bcmath": "*",
         "ext-json": "*",
         "ext-mbstring": "*",
         "ext-openssl": "*",
@@ -17,6 +18,7 @@
         "endroid/qr-code": "^3.7",
         "facade/ignition": "^2.0",
         "fideloper/proxy": "^4.0",
+        "firebase/php-jwt": "^5.2",
         "intervention/image": "^2.5",
         "kitetail/zttp": "^0.6.0",
         "laravel/framework": "7.*",
@@ -29,8 +31,7 @@
         "pusher/pusher-php-server": "^4.1",
         "te7a-houdini/laravel-trix": "^2.0",
         "tymon/jwt-auth": "1.*@rc",
-        "yajra/laravel-oci8": "7.0",
-        "ext-bcmath": "*"
+        "yajra/laravel-oci8": "7.0"
     },
     "require-dev": {
         "barryvdh/laravel-debugbar": "^3.2",

+ 82 - 21
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "ebab4445c56757c74fdec2acdf07b0bf",
+    "content-hash": "ef2aa5c4f16558f9e3486aaabe3f801f",
     "packages": [
         {
             "name": "bacon/bacon-qr-code",
@@ -1375,6 +1375,66 @@
             ],
             "time": "2021-01-24T12:00:00+00:00"
         },
+        {
+            "name": "firebase/php-jwt",
+            "version": "v5.2.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/firebase/php-jwt.git",
+                "reference": "f42c9110abe98dd6cfe9053c49bc86acc70b2d23"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/firebase/php-jwt/zipball/f42c9110abe98dd6cfe9053c49bc86acc70b2d23",
+                "reference": "f42c9110abe98dd6cfe9053c49bc86acc70b2d23",
+                "shasum": "",
+                "mirrors": [
+                    {
+                        "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
+                        "preferred": true
+                    }
+                ]
+            },
+            "require": {
+                "php": ">=5.3.0"
+            },
+            "require-dev": {
+                "phpunit/phpunit": ">=4.8 <=9"
+            },
+            "type": "library",
+            "autoload": {
+                "psr-4": {
+                    "Firebase\\JWT\\": "src"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "BSD-3-Clause"
+            ],
+            "authors": [
+                {
+                    "name": "Neuman Vong",
+                    "email": "neuman+pear@twilio.com",
+                    "role": "Developer"
+                },
+                {
+                    "name": "Anant Narayanan",
+                    "email": "anant@php.net",
+                    "role": "Developer"
+                }
+            ],
+            "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
+            "homepage": "https://github.com/firebase/php-jwt",
+            "keywords": [
+                "jwt",
+                "php"
+            ],
+            "support": {
+                "issues": "https://github.com/firebase/php-jwt/issues",
+                "source": "https://github.com/firebase/php-jwt/tree/v5.2.1"
+            },
+            "time": "2021-02-12T00:02:00+00:00"
+        },
         {
             "name": "guzzlehttp/guzzle",
             "version": "6.5.5",
@@ -1960,16 +2020,16 @@
         },
         {
             "name": "laravel/tinker",
-            "version": "v2.6.0",
+            "version": "v2.6.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/laravel/tinker.git",
-                "reference": "daae1c43f1300fe88c05d83db6f3d8f76677ad88"
+                "reference": "04ad32c1a3328081097a181875733fa51f402083"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/laravel/tinker/zipball/daae1c43f1300fe88c05d83db6f3d8f76677ad88",
-                "reference": "daae1c43f1300fe88c05d83db6f3d8f76677ad88",
+                "url": "https://api.github.com/repos/laravel/tinker/zipball/04ad32c1a3328081097a181875733fa51f402083",
+                "reference": "04ad32c1a3328081097a181875733fa51f402083",
                 "shasum": "",
                 "mirrors": [
                     {
@@ -2028,9 +2088,9 @@
             ],
             "support": {
                 "issues": "https://github.com/laravel/tinker/issues",
-                "source": "https://github.com/laravel/tinker/tree/v2.6.0"
+                "source": "https://github.com/laravel/tinker/tree/v2.6.1"
             },
-            "time": "2021-01-26T20:35:18+00:00"
+            "time": "2021-03-02T16:53:12+00:00"
         },
         {
             "name": "laravel/ui",
@@ -3551,16 +3611,16 @@
         },
         {
             "name": "phpoffice/phpspreadsheet",
-            "version": "1.16.0",
+            "version": "1.17.1",
             "source": {
                 "type": "git",
                 "url": "https://github.com/PHPOffice/PhpSpreadsheet.git",
-                "reference": "76d4323b85129d0c368149c831a07a3e258b2b50"
+                "reference": "c55269cb06911575a126dc225a05c0e4626e5fb4"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/76d4323b85129d0c368149c831a07a3e258b2b50",
-                "reference": "76d4323b85129d0c368149c831a07a3e258b2b50",
+                "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/c55269cb06911575a126dc225a05c0e4626e5fb4",
+                "reference": "c55269cb06911575a126dc225a05c0e4626e5fb4",
                 "shasum": "",
                 "mirrors": [
                     {
@@ -3594,7 +3654,7 @@
             },
             "require-dev": {
                 "dompdf/dompdf": "^0.8.5",
-                "friendsofphp/php-cs-fixer": "^2.16",
+                "friendsofphp/php-cs-fixer": "^2.18",
                 "jpgraph/jpgraph": "^4.0",
                 "mpdf/mpdf": "^8.0",
                 "phpcompatibility/php-compatibility": "^9.3",
@@ -3652,9 +3712,9 @@
             ],
             "support": {
                 "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues",
-                "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/1.16.0"
+                "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/1.17.1"
             },
-            "time": "2020-12-31T18:03:49+00:00"
+            "time": "2021-03-02T17:54:11+00:00"
         },
         {
             "name": "phpoption/phpoption",
@@ -8425,16 +8485,16 @@
         },
         {
             "name": "mockery/mockery",
-            "version": "1.3.3",
+            "version": "1.3.4",
             "source": {
                 "type": "git",
                 "url": "https://github.com/mockery/mockery.git",
-                "reference": "60fa2f67f6e4d3634bb4a45ff3171fa52215800d"
+                "reference": "31467aeb3ca3188158613322d66df81cedd86626"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/mockery/mockery/zipball/60fa2f67f6e4d3634bb4a45ff3171fa52215800d",
-                "reference": "60fa2f67f6e4d3634bb4a45ff3171fa52215800d",
+                "url": "https://api.github.com/repos/mockery/mockery/zipball/31467aeb3ca3188158613322d66df81cedd86626",
+                "reference": "31467aeb3ca3188158613322d66df81cedd86626",
                 "shasum": "",
                 "mirrors": [
                     {
@@ -8494,9 +8554,9 @@
             ],
             "support": {
                 "issues": "https://github.com/mockery/mockery/issues",
-                "source": "https://github.com/mockery/mockery/tree/1.3.3"
+                "source": "https://github.com/mockery/mockery/tree/1.3.4"
             },
-            "time": "2020-08-11T18:10:21+00:00"
+            "time": "2021-02-24T09:51:00+00:00"
         },
         {
             "name": "myclabs/deep-copy",
@@ -10458,7 +10518,8 @@
     "prefer-stable": true,
     "prefer-lowest": false,
     "platform": {
-        "php": "^7.2.34",
+        "php": "^7.2.14",
+        "ext-bcmath": "*",
         "ext-json": "*",
         "ext-mbstring": "*",
         "ext-openssl": "*",

+ 1 - 2
routes/api.php

@@ -16,10 +16,9 @@ use Illuminate\Support\Facades\Route;
 Route::group(['prefix' => 'procurement','middleware'=>'procurement.auth.api'], function ($router) {
     Route::post('logout', 'api\procurement\wechat\AuthController@logout');
     Route::post('refresh', 'api\procurement\wechat\AuthController@refresh');
-    Route::post('me', 'api\procurement\wechat\AuthController@me');
+    Route::get('getQuotation', 'api\procurement\wechat\ProcurementController@getQuotation');
 });
 Route::group(['prefix' => 'procurement'], function ($router) {
     Route::post('login', 'api\procurement\wechat\AuthController@login');
-    Route::get('getQuotation', 'api\procurement\wechat\ProcurementController@getQuotation');
 });