fastadmin php jwt(token)登录

1.公共base接口 

request->filter('strip_tags');
        $this->auth = Auth::instance();
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());
        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin) && $this->noNeedLogin!='*')
        {
            $token = Db::name("devops_personnel_token")->where('token',$token)->find();
            //检测是否登录
            if (!$token['token'])
            {
                $this->error(__('Please login first'), null, 401);
            }
            // 检测是否过期
            if ($token['expiretime']!=0){
                if ($token['expiretime']error(__('Please login first'), null, 401);
                }else{
                    // 更新下token
                    Db('devops_personnel_token')->where('id',$token['id'])->update(['expiretime'=>time()+7200]);
                }
            }
            $user = Db::name("devops_personnel")->where(['id'=>$token['devops_id']])->find();
            $this->is_Login = true;
            $this->userInfo = $user;
        }
    }

    /**
     * Notes:获取本人用户信息
     * DateTime: 2021/5/13 16:36
     * @return array
     */
    public function getUserInfo()
    {
        if ($this->is_Login){
            return $this->userInfo;
        }else{
            $this->error(__('Please login first'), null, 401);
        }
    }

}

2.登录接口 

request->request('username')?trim($this->request->request('username')):'';
        $password = $this->request->request('password')?trim($this->request->request('password')):'';
        $user = Db::name("devops_personnel")->where(['username'=>$username])->find();
        $msg = "登录成功";
        if ($user) {
            // 判断密码
            if (md5(md5($password).'tg_') == $user['password']){
                // 存token
                $token = md5(md5($user['id'].'-'.'name').$this->salt);
                Db::name("devops_personnel_token")->insert(['devops_id'=>$user['id'],'token'=>$token,'createtime'=>time(),'expiretime'=>0]);
                $user['token'] = $token;
                $this->userInfo = $user;
                $data = ['userinfo' => $this->userInfo];
                $this->success($msg, $data,0);
            }else{
                $this->error('密码错误');
            }
        }else{
            $this->error('账号不存在');
        }
    }
}

3.token表结构

fastadmin php jwt(token)登录_第1张图片

你可能感兴趣的:(php笔记,php)