HomeBase.php 3.0 KB
<?php

namespace app\common\controller;

use app\common\library\Auth;
use app\index\model\User;
use think\Controller;
use think\Db;
use think\Lang;

/**
 * 前台控制器基类
 */
class HomeBase extends Controller
{
    /**
     * token
     * @var string
     */
    protected $token = '';

    /**
     * 用户id
     * @var int
     */
    protected $userId = 0;

    /**
     * 用户信息
     * @var
     */
    protected $user;

    /**
     * 布局模板
     * @var string
     */
    protected $layout = '';

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    public function _initialize()
    {
        parent::_initialize();
        $token = $this->request->param('token',get_current_user_token());
        if(!empty($token)){
            $user_token = Db::name('user_token')->where(['token'=>$token])->find();
            if(empty($user_token)){
                session('token',null);
                $this->error('令牌失效','','','');
            }
            $userModel = new User();
            $user = $userModel->findData(['id'=>$user_token['user_id']]);
            if(empty($user)){
                session('token',null);
                $this->error('查无此人','','','');
            }
            $this->token = $token;
            $this->user = $user;
            $this->userId = $user['id'];
            if($user['status'] == 'hidden'){
                $this->error('您已被拉黑','','','');
            }
        }
        $this->assign('token',$token);
        $this->assign('user',$this->user);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 渲染配置信息
     * @param mixed $name  键名或数组
     * @param mixed $value 值
     */
    protected function assignconfig($name, $value = '')
    {
        $this->view->config = array_merge($this->view->config ? $this->view->config : [], is_array($name) ? $name : [$name => $value]);
    }

    /**
     * 获取当前用户id
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserId(){
        if (empty($this->userId)) {
            if($this->request->isAjax()){
                $this->error('用户未登录~',url("user/login_view"));
            }else{
                $this->redirect("user/login_view");
            }
        }
        $user = Db::name('user')->where(['id'=>$this->userId])->find();
        if($user['status'] != 'normal'){
            $this->error('您已被拉黑');
        }
        return $this->userId;
    }
}