<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\middleware;

use Closure;
use think\Request;
use app\common\library\jwt\Token;
use app\common\service\Users as UsersService;
use app\common\model\chat\ChatUsers as ChatUsersModel;

/**
 * @package app\common\middleware
 * @class Admin
 * @author xzncit 2023-09-04
 */
class Online extends Base {

    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request,Closure $next){
        try{
            $controller  = $request->action();
            if($controller == "login"){
                return $next($request);
            }

            $user = ChatUsersModel::where("id",Token::get("id"))->find();
            if(empty($user)){
                throw new \Exception("您还没有登录，请先登录",401);
            }

            UsersService::init($user);
            return $next($request);
        }catch(\Exception $ex){
            return returnAjax($ex->getMessage(),$ex->getCode());
        }
    }

}