<?php

namespace Server\sso\api;

use Server\sso\library\signature\SignerVerifier;
use Server\sso\SsoService;

class AuthController extends SsoService
{
    public function users(){
        global $_W,$_GPC;

        $code=$_GPC['code'];
        $sign=$_GPC['sign'];

        if(!$_W['ispost']){
            $this->apiMessage(null,-8);
        }

        if(empty($code)){
            $this->apiMessage(null,-2);
        }
        //获取code信息
        $usersCode=pdo_get('sso_users_code',array('code'=>$code));

        if(empty($usersCode)){
           $this->apiMessage(null,-3);
        }
        $this->uniacid=$usersCode['uniacid'];

        if(empty($sign)){
            $this->apiMessage(null,-10);
        }

        if($usersCode['type']==1){
            $setting=pdo_get('sso_setting',array('uniacid'=>$usersCode['uniacid']));
            $secret=$setting['secret'];
        }else{
            $secret=$this->getMasterSecret();
        }

        //验证secret
        if(empty($secret)){
            $this->apiMessage(null,-4);
        }

        $signerVerifier=new SignerVerifier($secret);

        $signParams=[
            'code'=>$code,
            'time'=>$_GPC['time']
        ];
        if(!$signerVerifier->verifySignature($signParams,$sign)){
            $this->apiMessage(null,-9);
        }
        //校验是否过期
        if($usersCode['status']==0){
            $this->apiMessage(null,-7);
        }

        //获取用户信息
        $users=pdo_get('users',array('uid'=>$usersCode['uid']));
        $ssoUser=pdo_get('sso_users',array('uid'=>$usersCode['uid'],'uniacid'=>$usersCode['uniacid']));
        if(empty($users)){
            $this->apiMessage(null,-6);
        }

        $identity='default';

        if(!empty($ssoUser['identity'])){
            $identity=$ssoUser['identity'];
        }elseif(!empty($users['founder_groupid'])){
            $identity='founder';
        }

        $results=[
            'uniacid'=>$this->uniacid,
            'uid'=>$users['uid'],
            'username'=>$users['username'],
            'identity'=>$identity
        ];
        $this->apiMessage($results,0,'success');
    }
}
