<?php
// +----------------------------------------------------------------------
// | 奇乐自媒体内容管理系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com
// +----------------------------------------------------------------------
// | 官方论坛：http://bbs.qilecms.com
// +----------------------------------------------------------------------
// | Author:奇乐网络
// +----------------------------------------------------------------------
// | 版权说明：本产品为免费版，使用请保留底部版权
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\Controller;
use think\Captcha;
class Login extends Controller
{
	public function index(){
		if(session('?admin_uid')){
           $this->redirect('index/index');
		}
         
         //判断获取的GET 登陆授权码是否正确
         $param = $this->request->param();
         $authValue = md5('qilecms'.$_SESSION['login_auth_value']);
		if($param['authcode'] != $authValue){
           $this->error('非法操作','/index/index');
		}
         
		return $this->fetch();
	}
	public function check(){
		if(!$this->request->isPost()){ return error_json('非法请求');}

		$post = input('post.');
		//表单数据验证
		    $rule = [
		    'username'  => 'require|min:3|max:15|chsDash',
		    'password'   => 'require|min:6',
		    'verify_code'   => 'require',
		    
			];
			$msg = [
			    'username.require' => '账号不能为空',
			    'username.min'     => '账号至少3个字符',
			    'username.max'     => '账号不能超过15个字符',
			    'username.chsDash'     => '账号只能是汉字、字母、数字和下划线_及破折号-',
			    'password.require'   => '密码不能为空',
			    'password.min'       => '密码至少6位数',
			    'verify_code.require'  => '验证码不能为空',
			];
			$validate = Validate()->make($rule)->message($msg);
			$result = $validate->check($post);
			if(!$result){
			   return error_json($validate->getError());
			}
        $username = $post['username'];
		$where = "username = '$username'";
       //验证验证码
        $captcha  = $post['verify_code'];
        if(!captcha_check($captcha)){
		   return  error_json('验证码错误');
		};

		// 数据库验证
		$Admin = model('admin')->getAdminInfo($where);
		$uid      = $Admin['uid'];
		$username = $Admin['username'];
		$password_key   = password_key($post['username'],$post['password'],$Admin['passsalt']);
    
		if(!$Admin || $Admin['password'] != $password_key){
           return  error_json('账号或密码错误');
		}
         session('admin_uid',$uid);
         session('admin_username',$username);


         //获得管理员角色表
        
         $res = model('adminRoleAccess')->alias('a')->join('admin_role b','b.role_id = a.role_id','LEFT')->where("a.uid = '$uid'")->find();
         session('role_id',$res['role_id']);
         session('role_name',$res['role_name']);
         //保存登陆日志

         //更新登陆时间和IP
         $info['last_time'] = time();
         $info['last_ip'] = get_client_ip();      
         model('Admin')->updateInfo($admin_id,$info);
		 return  success_json('登录成功');

	}

}