LoginController.php 11.0 KB
<?php
/**
 * @remark :
 * @name   :LoginController.php
 * @author :lyh
 * @method :post
 * @time   :2023/8/19 9:11
 */

namespace App\Http\Controllers\Bside;

use App\Enums\Common\Code;
use App\Events\WebSocketMessage;
use App\Events\WebSocketMessageSent;
use App\Helper\Common;
use App\Helper\Translate;
use App\Helper\Wechat;
use App\Http\Logic\Bside\User\UserLoginLogic;
use App\Models\Domain\DomainInfo;
use App\Models\File\ErrorFile;
use App\Models\Project\Project;
use App\Models\Service\Service;
use App\Models\Sms\SmsLog;
use App\Models\User\DeptUser;
use App\Models\User\ProjectRole;
use App\Models\User\User;
use App\Services\CosService;
use App\Utils\EncryptUtils;
use http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Mrgoon\AliSms\AliSms;

class LoginController extends BaseController
{

    /**
     * @remark :登录
     * @name   :login
     * @author :lyh
     * @method :post
     * @time   :2023/8/19 9:12
     */
    public function login(){
        $this->request->validate([
            'mobile'=>['required'],
            'password'=>['required'],
        ],[
            'mobile.required'=>'电话号码必须填写',
            'password.required'=>'内容必须填写',
        ]);
        $userLogic = new UserLoginLogic();
        $project = $userLogic->login();
        $this->response('success',Code::SUCCESS,$project);
    }

    /**
     * @remark :根据选择的项目id登录
     * @name   :projectLogin
     * @author :lyh
     * @method :post
     * @time   :2023/8/29 15:21
     */
    public function projectLogin(){
        $this->request->validate([
            'project_id' => 'required',
            'mobile' => 'required'
        ],[
            'project_id.required' => '请选择项目',
            'mobile.required' => '参数错误',
        ]);
        $userLogic = new UserLoginLogic();
        $info = $userLogic->projectLogin();
        $this->response('success',Code::SUCCESS,$info);
    }

    /**
     * @remark :自动登录
     * @name   :autologin
     * @author :lyh
     * @method :post
     * @time   :2023/8/19 9:12
     */
    public function autologin(UserLoginLogic $logic, EncryptUtils $encrypt)
    {
        $this->request->validate([
            'code' => 'required',
        ],[
            'code.required' => 'code不能为空',
        ]);
        $serviceSettingModel = new Service();
        $info = $serviceSettingModel->read(['type'=>4]);
        if($info === false){
            $this->response('当前访问地址不存在',Code::USER_ERROR);
        }
        $data = $encrypt->unlock_url($this->param['code'], $info['values']);
        $data = json_decode($data, true);
        if(!isset($data['project_id']) && !isset($data['user_id'])){
            $this->response('无效Code',Code::USER_ERROR);
        }
        $res = $logic->autologin($data);
        $this->response('success',Code::SUCCESS, $res);
    }


    /**
     * @remark :发送验证码
     * @name   :sendLoginSms
     * @author :lyh
     * @method :post
     * @time   :2023/8/19 9:13
     */
    public function sendLoginSms()
    {
        $type = $this->request->post('type',SmsLog::TYPE_LOGIN);
        $this->request->validate([
            'mobile'=>['required', 'regex:/^1[3-9]\d{9}$/'],
        ],[
            'mobile.required' => '手机号码不能为空',
            'mobile.regex' => '请输入正确的手机号码',
        ]);
        $mobile = $this->param['mobile'];
        $user = User::where(['mobile' => $mobile])->first();
        if (empty($user)) {
            $this->response('请输入正确的手机号码!', Code::SYSTEM_ERROR);
        }
        $last_sms = SmsLog::getLastLog($mobile, $type);
        if ($last_sms && $last_sms->use = SmsLog::USE_USABLE && time() - strtotime($last_sms->created_at) < 60) {
            $this->response('请不要重复发送短信!', Code::SYSTEM_ERROR);
        }
        $template = config('aliyunsms.login_sms_temp');
        $code['code'] = rand(100000,999999);
        $ali_sms = new AliSms();
        $send = $ali_sms->sendSms(strval($mobile), $template, $code);
        if (empty($send->Code) && $send->Code != 'OK') {
            $this->response('发送失败, 请稍后重试!', Code::SYSTEM_ERROR);
        }
        SmsLog::createLog($mobile, $code['code'],$type);
        $this->response('success');
    }

    /**
     * @remark :根据关键字生成链接
     * @name   :pubLink
     * @author :lyh
     * @method :post
     * @time   :2023/6/28 16:13
     */
    public function stringTranslation(){
        $this->request->validate([
            'str'=>'required',
        ],[
            'str.required' => '翻译字符串不能为空',
        ]);
        $str = Translate::tran($this->param['str'], 'en') ?? '';
        if(is_array($str)){
            $str = $str[0];
        }
        $this->response('success',Code::SUCCESS,strtolower($str));
    }

    /**
     * @remark :微信登录
     * @name   :wechatLogin
     * @author :lyh
     * @method :post
     * @time   :2023/8/23 18:46
     */
    public function qrcode(){
        $this->request->validate([
            'type' => 'required',
        ],[
            'type.required' => '请选择项目',
        ]);
        if(!isset($this->param['id'])){
            $this->param['id'] = 0;
        }
        $wechat = new Wechat();
        $accessToken = $wechat->getAccessToken();
        $data = $wechat->setQrcode('global-v6_'.$this->param['type'].'_'.$this->param['id'],$accessToken);
        if(!empty($data)){
            $data['url'] = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$data['ticket'];
        }
        $this->response('success',Code::SUCCESS,$data);
    }

    /**
     * @remark :微信回调方法
     * @name   :wechatLogin
     * @author :lyh
     * @method :post
     * @time   :2023/8/24 9:30
     */
    public function eventMessage(){
        $message = file_get_contents("php://input");
        $message = simplexml_load_string($message, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR);
        $jsonData = json_encode($message);
        $arrayData = json_decode($jsonData, true);
        //gh_27174ac5c9d8,gh_27174ac5c9d8
        $data = $this->setWechat($arrayData['FromUserName'],$arrayData['EventKey']);
        if($data['code'] == 0){//登录失败,请先绑定
            $resMessage = $data['message'];
        }elseif($data['code'] == 1){
            $resMessage = $data['message'];
        }elseif($data['code'] == 2){
            $resMessage = $data['message'];
        }else{
            $resMessage = $data['message'];
        }
        Cache::add($arrayData['Ticket'],$data,300);
        return "<xml>
                <ToUserName><![CDATA[$message->FromUserName]]></ToUserName>
                <FromUserName><![CDATA[$message->ToUserName]]></FromUserName>
                <CreateTime>".time()."</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[$resMessage]]></Content>
            </xml>";
    }

    /**
     * @remark :登录成功响应
     * @name   :getWechatLoginInfo
     * @author :lyh
     * @method :post
     * @time   :2023/9/1 10:12
     */
    public function getWechatLoginInfo(){
        $this->param = $this->request->validate([
            'ticket' => 'required',
        ],[
            'ticket.required' => 'ticket不能为空',
        ]);
        $info = Cache::get($this->param['ticket']);
        $this->response('success',Code::SUCCESS,$info);
    }

    /**
     * @remark :解token
     * @name   :globalSo_v6_login
     * @author :lyh
     * @method :post
     * @time   :2023/8/24 17:37
     */
    public function globalSo_v6_login(UserLoginLogic $logic){
        $this->param = $this->request->validate([
            'token' => 'required',
        ],[
            'token.required' => 'token不能为空',
        ]);
        try {
            $common = new Common();
            $arr = $common->decrypt(urldecode($this->param['token']));
        }catch (\Exception $e){
            $this->response('非法请求!',Code::USER_ERROR);
        }
        if (empty($arr['timestamp']) || time() - $arr['timestamp'] > 60) {
            $this->response('授权已过期,请重新获取授权码!',Code::USER_ERROR);
        }
        //没有from_order_id的项目  进入演示版 运营中心
        $arr['from_order_id'] = $arr['from_order_id'] ?? 0;
        $arr['phone'] = $arr['phone'] ?? '';
        if(!$arr['from_order_id']){
            //有账号就直接登录, 没有账号创建账号登录
            $user = (new User())->where('project_id', Project::DEMO_PROJECT_ID)->where('mobile', $arr['phone'])->first();
            if(!$user){
                $user = new User();
                $user->project_id = Project::DEMO_PROJECT_ID;
                $user->role_id = ProjectRole::OPERATION_CENTER_ID;
                $user->mobile = $arr['phone'];
                $user->password = base64_encode(md5('v6.' . substr($arr['phone'], -6)));
                $user->name = $arr['name'] ?? $arr['phone'];
                $user->save();
                //运营中心组织
                $dept_user = new DeptUser();
                $dept_user->dept_id = DeptUser::OPERATION_CENTER_ID;
                $dept_user->project_id = Project::DEMO_PROJECT_ID;
                $dept_user->user_id = $user->id;
                $dept_user->save();
            }
            $data = [
                'user_id'=>$user['id'],
                'manager_id'=>0,
            ];
        }else{
            //有from_order_id, 找到对应的项目并登录对应账号
            $project = (new Project())->read(['from_order_id'=>$arr['from_order_id'], 'delete_status' => Project::IS_DEL_FALSE]);
            if(!$project){
                $this->response('项目不存在,请联系管理员',Code::USER_ERROR);
            }
            $user =  (new User())->where('project_id', $project['id'])->where('mobile', $arr['phone'])->first();
            if(!$user){
                $data = [
                    'project_id'=>$project['id'],
                    'manager_id'=>0,
                ];
            }else{
                $data = [
                    'user_id'=>$user['id'],
                    'manager_id'=>0,
                ];
            }
        }
        $info = $logic->autologin($data,User::LOGIN_OTHER_SOURCE);
        $this->response('success',Code::SUCCESS,['info'=>$info]);
    }

    /**
     * @remark :微信登录处理数据
     * @name   :wechatLogin
     * @author :lyh
     * @method :post
     * @time   :2023/8/31 9:13
     */
    public function setWechat($wechat,$eventKey){
        $userLoginLogic = new UserLoginLogic();
        $key = explode("_",$eventKey);
        if($key[1] == 'login'){
            $data = $userLoginLogic->wechatLogin($wechat);
        }elseif($key[1] == 'bind'){
            $data = $userLoginLogic->wechatBind($wechat,$key[2]);
        }else{
            $data = [
                'code'=>0,
                'message'=>'关注成功,请登录后绑定账号后扫码,如已绑定,请再次扫码',
            ];
        }
        return $data;
    }
    
}