Index.php 13.4 KB
<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use app\common\library\Token;
use think\Config;
use think\Db;
use think\Hook;
use think\Validate;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login','forget','send_ems','verify_code','reset_password'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general'   => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        $user = \think\Session::get('user');
        if(!empty($user['id'])){
            $store_id = Db::name('store')->where(['user_id'=>$user['id']])->value('store_id');
            if(!empty($store_id)){
                $admin = Db::name('admin')->where(['store_id'=>$store_id])->find();
                $this->assign('admin',$admin);
            }
        }
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), 'index/login');
    }

    /**
     * 忘记密码
     */
    public function forget(){
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $url = $this->request->get('url', 'index/forget');
            $mobile = $this->request->post('mobile');
            $rule = [
                'mobile'  => 'require',
//                '__token__' => 'require|token',
            ];
            $data = [
                'mobile'  => $mobile,
//                '__token__' => $token,
            ];
            $validate = new Validate($rule, [], ['mobile' => __('mobile')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            //根据mobile获取商户信息
            $admin = Db::name('admin')->where(['phone'=>$mobile])->find();
            if(empty($admin)){
                $this->error('当前手机号尚未绑定');
            }
            if(empty($admin['store_id'])){
                $this->error('平台管理员忘记密码请联系总管理员');
            }
            if($admin['status'] != 'normal'){
                $this->error('您已被拉黑,请联系客服');
            }
            //生成验证码
            $code = generateCode(6);
            //储存验证码
            $admin_code = Db::name('admin_code')->where(['mobile'=>$mobile])->find();
            $arr['code'] = $code;
            $arr['pasttime'] = time()+600;
            $arr['is_use'] = 0;
            if(empty($admin_code)){
                $arr['mobile'] = $mobile;
                $arr['createtime'] = time();
                $result1 = Db::name('admin_code')->insert($arr);
            }else{
                $arr['updatetime'] = time();
                $result1 = Db::name('admin_code')->where(['id'=>$admin_code['id']])->update($arr);
            }
            if(empty($result1)){
                $this->error('sql执行失败');
            }
            $content = array(
                'content' => "【工企邦】您的验证码是:" . $code . ",请于10分钟内使用,如非本人操作,可忽略此消息。",//短信内容
                'mobile' => $mobile,//手机号码
                'tKey' => time(),
            );
            $result2 = json_decode(send_sms2($content),true);
            if ($result2['code'] != 200) {
                Db::rollback();
                $this->error('发送失败');
            }
            $this->success('发送成功');
            /*AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }*/
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('忘记密码'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /*public function send_ems($receiver,$code){
        \think\Config::set('site', \think\Config::get('site'));
        $email = new Email();
        $str = "验证码:$code,10分钟内有效。";
        $result = $email
            ->to($receiver)
            ->subject("金点网-找回密码")
            ->message($str)
            ->send();
        return $result;
    }*/

    /**
     * 验证验证码是否正确
     */
    public function verify_code(){
        if ($this->request->isPost()) {
            $url = $this->request->get('url', 'index/forget');
            $mobile = $this->request->post('mobile');
            $code = $this->request->post('code');
            $rule = [
                'mobile'  => 'require',
                'code'   => 'require',
//                '__token__' => 'require|token',
            ];
            $data = [
                'mobile'  => $mobile,
                'code'   => $code,
//                '__token__' => $token,
            ];
            $validate = new Validate($rule, [], ['mobile' => __('mobile'), 'code' => '请输入验证码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            $admin_code = Db::name('admin_code')->where(['mobile'=>$mobile])->find();
            if(empty($admin_code)){
                $this->error('404');
            }
            if(!empty($admin_code['is_use'])){
                $this->error('验证码已被使用');
            }
            if($admin_code['pasttime'] < time()){
                $this->error('验证码已过期');
            }
            if($admin_code['code'] != $code){
                $this->error('验证码错误');
            }
            $result = Db::name('admin_code')->where(['id'=>$admin_code['id']])->update(['is_use'=>1]);
            if(empty($result)){
                $this->error('sql执行失败');
            }
            //生成令牌(为了安全)
            $str = "Bronet";
            $auth_code = config('auth_code');
            $token = rawurlencode(sha1(md5($str.$auth_code).md5($mobile)));
            $this->success('验证通过',url('reset_password',['token'=>$token,'mobile'=>$mobile],false,true));
        }
    }

    /**
     * 重置密码页面
     */
    public function reset_password(){
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if($this->request->isPost()){
            $password = $this->request->param('password');
            $affirm_password = $this->request->param('affirm_password');
            $mobile = $this->request->param('mobile');
            $token = $this->request->param('token');
            $rule = [
                'password'  => 'require|length:3,30',
                'affirm_password'  => 'require|length:3,30',
                'mobile' => 'require',
                'token' => 'require',
            ];
            $data = [
                'password'  => $password,
                'affirm_password'  => $affirm_password,
                'mobile' => $mobile,
                'token' => $token,
            ];
            $validate = new Validate($rule, [], ['password' => __('password'), 'affirm_password' => __('Password'), 'mobile' => __('mobile')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            if($password != $affirm_password){
                $this->error('两次密码不一致');
            }
            $str = "Bronet";
            $auth_code = config('auth_code');
            $token2 = rawurlencode(sha1(md5($str.$auth_code).md5($mobile)));
            if($token != $token2){
                $this->error('令牌错误','','','');
            }
            $admin = Db::name('admin')->where(['phone'=>$mobile])->find();
            $pwd = $password;
            $password = md5(md5($password) . $admin['salt']);
            $result = Db::name('admin')->where(['id'=>$admin['id']])->update(['password'=>$password,'pwd'=>$pwd]);
            if(empty($result)){
                $this->error('sql执行失败');
            }

            $this->success('重置成功',$url);
        }else{
            $token = $this->request->param('token');
            $mobile = $this->request->param('mobile');
            $str = "Bronet";
            $auth_code = config('auth_code');
            $token2 = rawurlencode(sha1(md5($str.$auth_code).md5($mobile)));
            if($token != $token2){
                $this->error('令牌错误','','','');
            }
            $background = Config::get('fastadmin.login_background');
            $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
            $this->view->assign('background', $background);
            $this->view->assign('title', __('重置密码'));
            Hook::listen("admin_login_init", $this->request);
            return $this->view->fetch();
        }
    }

}