<?php

namespace App\Http\Controllers\API\CAS;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use JWT;


class CasLoginController extends Controller
{
    public static $CasUrl='http://192.168.80.53:8085/cas/serviceValidate';
    public function login(Request $request){
        $ticket = $request->query('ticket');
        $url=env('APP_URL').'/casLogin';
        $response = Http::get(self::$CasUrl, [
            'service' => $url,
            'ticket' => $ticket,
        ]);

        if (!$response->successful()) {
            return \Yz::JsonError("请求CAS失败");
        }

        $xml = simplexml_load_string($response->body());
        // 注册命名空间
        $namespaces = $xml->getNamespaces(true);

// 获取 cas 命名空间下的元素
        $cas = $xml->children($namespaces['cas']);

        if ($cas === false) {
            return \Yz::JsonError("解析CAS响应失败");
        }


        if (isset($cas->authenticationFailure)) {
            return \Yz::JsonError("认证失败");
        }

        $casResponse = $cas->authenticationSuccess;

        if (!$casResponse) {
            return \Yz::JsonError("认证失败");
        }

        $res_user = (string)$casResponse->user;

        $user=DB::table('users')->where(['cas_code'=>$res_user,'status'=>1])->first();
        if(!!$user){
            $jwt= new JWT();
            $accessTimeout = $jwt -> GetGetSecretTimeOut();
            $refreshTimeout = $jwt -> GetRefreshTokenTimeOut();
            $access_token = $jwt->BuildJWT('yz','access',$user->id,$user->group,$accessTimeout);
            $refresh_token = $jwt->BuildJWT('yz','refresh',$user->id,'',$refreshTimeout);
            DB::table('users')->where(['id'=>$user->id,'status'=>1])->update(['token'=>md5($refresh_token)]);
            return redirect(env('APP_URL')."/admin/#/caslogin?access_token=".$access_token."&refresh_token=".$refresh_token);
        }else{
            echo "登录失败，未授权或者已注销";
        }




    }
}
