UserToken.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace app\middleware;
  15. use app\business\UserBusiness;
  16. use plugin\admin\app\model\User;
  17. use support\Db;
  18. use support\Redis;
  19. use Webman\MiddlewareInterface;
  20. use Webman\Http\Response;
  21. use Webman\Http\Request;
  22. /**
  23. * Class StaticFile
  24. * @package app\middleware
  25. */
  26. class UserToken implements MiddlewareInterface
  27. {
  28. public function process(Request $request, callable $handler): Response
  29. {
  30. Db::beginTransaction();
  31. try {
  32. $token=$request->header('token');
  33. if(empty($token)){
  34. throw new \Exception('请登录!');
  35. }
  36. $jwtDecode=jwtDecode($token);
  37. if(empty($jwtDecode)){
  38. throw new \Exception('请登录!');
  39. }
  40. if(Redis::get(getenv('PROJECTWEB').'_'.$jwtDecode->id) != $token){
  41. throw new \Exception('当前账号已被其他人强登!');
  42. }
  43. $adminUser=UserBusiness::userData(['id'=>$jwtDecode->id]);
  44. if(empty($adminUser)){
  45. throw new \Exception('非法操作!');
  46. }
  47. if(empty(Redis::get('token_'.$jwtDecode->id))){
  48. Db::table('wa_users')->where('id',$jwtDecode->id)->update([
  49. 'last_login' =>bcadd(time(),60)
  50. ]);
  51. Redis::setEx('token_'.$jwtDecode->id,50,$jwtDecode->id);
  52. }
  53. $request->user_data=$adminUser;
  54. Db::commit();
  55. }catch (\Throwable $exception){
  56. Db::rollBack();
  57. return error($exception->getMessage(),[],4008);
  58. }
  59. return $handler($request);
  60. }
  61. }