Sso.php 16.4 KB
<?php

/**
 * Created by PhpStorm.
 * User: liuziyang
 * Date: 14-2-17
 * Time: 23:59
 */
class YHMAuth_User_Sso extends YHMAuth_User_Abstract {

    public function isExistAuth($profile) {
        $ssoAuth = YHMAuth_Package_Yoho_Uuc::getUserinfo($profile);
        if ($ssoAuth['code'] == 200) {
            return true;
        }
        return false;
    }

    public function signin($profile, $inputPassword = '', $persistent = 'Y', $append = array()) {
        ######################  登录开始触发 ######################
        $this->signinPreDispatch($profile, $inputPassword);
        ######################  登录开始触发 ######################
        $validateEmail = Q_Utils_Validate_EmailAddress::isValid($profile);
        $validateMobile = Q_Utils_Validate_Mobile::isValid($profile);
        if ($validateEmail == false && $validateMobile == false) {
            throw new Exception('账户必须是邮箱或手机号', 421);
        }
        //判断账户是否可登录
        if ($validateEmail == true) {
            $_profile = YHMPassport_Models_Auth_Client::getProfileByEmail($profile);
        } else {
            $_profile = YHMPassport_Models_Auth_Client::getProfileByMobile($profile);
        }
        $userInfo = YHMPassport_Models_Profile_Client::getByUid($_profile['uid']);
        if (empty($userInfo['status']) && isset($userInfo['status'])) {
            throw new Exception('您输入的帐号无法登录,如有疑问请咨询客服', 427);
        }
        $ssoProfile = YHMAuth_Package_Yoho_Uuc::login($profile, $inputPassword);
        if ($ssoProfile['code'] == 50101) {
            //在sso用户中心没有找到该用户,判断本地是否有该用户,有则在sso用户中心添加
            if ($validateEmail == true) {
                $_profile = YHMPassport_Models_Auth_Client::getProfileByEmail($profile);
            } else {
                $_profile = YHMPassport_Models_Auth_Client::getProfileByMobile($profile);
            }
            if (!empty($_profile)) {
                $password = $userInfo['password'];
                $authPass = Q_Utils_AuthCode::authPassword($inputPassword, $password);
                if ($authPass == true) {
                    $ssoProfile = YHMAuth_Package_Yoho_Uuc::register($profile, $inputPassword);
                    if ($ssoProfile['code'] != 20100) {
                        throw new Exception($ssoProfile['message'], 432);
                    }
                } else {
                    throw new Exception('密码错误.', 422);
                }
            } else {
                throw new Exception('此用户不存在.', 421);
            }
        } elseif ($ssoProfile['code'] != 20101) {
            if ($ssoProfile['code'] == 50200 || $ssoProfile['code'] == 50201) {
                throw new Exception($ssoProfile['message'], 422);
            } else {
                throw new Exception($ssoProfile['message'], 421);
            }
        }
        //在sso中心已经找到该用户,判断本地是否有,没有则添加
        $ssoUid = $ssoProfile['data']['uid'];
        if ($validateEmail == true) {
            $_userAuth = YHMPassport_Models_Auth_Client::getProfileByEmail($profile);
        } else {
            $mobile = $profile;
            $_userAuth = YHMPassport_Models_Auth_Client::getProfileByMobile($profile);
        }
        #################### 如果用户不存在 ################
        if (empty($_userAuth)) {
            //通过sso中心获取用户信息
            $ssoUserInfo = YHMAuth_Package_Yoho_Uuc::getUserinfo($profile, $ssoUid);
            $nickName = empty($ssoUserInfo['data']['nick']) ? YHMConfig_Passport::DEFAULT_NICK_NAME : $ssoUserInfo['data']['nick'];
            $birthday = date('Y-m-d', $ssoUserInfo['data']['birthday']);
            $gender = 3;
            if (isset($ssoUserInfo['data']['gender'])) {
                if ($ssoUserInfo['data']['gender'] == 0) {
                    $gender = 2; //女
                } elseif ($ssoUserInfo['data']['gender'] == 1) {
                    $gender = 1; //男
                }
            }
            $_password = Q_Utils_AuthCode::makePass($inputPassword);
            $uid = YHMPassport_Models_Profile_Client::addUserProfile($_password, $nickName, $birthday, $gender);

            $this->uploadHead($ssoUserInfo['data']['head_pic']);
            if (empty($uid)) {
                throw new Exception('添加用户失败');
            }
            $profileType = empty($mobile) ? YHMConfig_Passport::PROFILE_TYPE_MAIL : YHMConfig_Passport::PROFILE_TYPE_MOBILE;
            YHMPassport_Models_Auth_Client::addAuth($uid, $profile, '', $profileType, $this->_channel, $this->_channelMap['channel_code']);
        } else {
            $uid = $_userAuth['uid'];
            $userProfile = YHMPassport_Models_Profile_Client::getByUid($uid);
            $password = $userProfile['password'];
            #如果不是64位密码,则修改为64位密码
            if (strpos($password, ':') === false) {
                $authPass = md5($inputPassword) === strtolower($password) ? true : false;
                $authPass === true ? YHMPassport_Models_Profile_Client::updatePassword($uid, $inputPassword) : false;
            }
        }
        ######################## 关联SSO ########################
        $ssoRelation = YHMPassport_Models_Sso_Client::getByUidAndSsouid($uid, $ssoUid);
        if (empty($ssoRelation)) {
            YHMPassport_Models_Sso_Client::setRelation($uid, $ssoUid);
        }
        ######################## 关联SSO ########################
        $package = array(
            'email' => ($validateEmail == true ? $profile : ''),
            'sso_uid' => $ssoUid
        );
        $package = array_merge($package, $append);
        $this->signinEndDispatch($uid, $package);
        #################### 登录结束触发 ####################
        return $this->_uid = $uid;
    }

    /**
     * @param $profile email | mobile
     * @param $password
     * @param array $append
     * @throws Exception
     */
    public function register($profile, $password, array $append = array()) {
        ######################  注册开始触发 ######################
        $this->registerPreDispatch($profile, $password, $append);
        ######################  注册开始触发 ######################
        if (empty($profile)) {
            throw new Exception('账户不能为空.', 422);
        }
        if (empty($password)) {
            throw new Exception('密码不能为空.', 422);
        }
        $validateEmail = Q_Utils_Validate_EmailAddress::isValid($profile);
        $validateMobile = Q_Utils_Validate_Mobile::isValid($profile);
        if ($validateEmail == false && $validateMobile == false) {
            throw new Exception('账户必须是邮箱或手机号', 10001);
        }
        //判断sso中心是否存在该用户
        $isExist = $this->isExistAuth($profile);
        if ($isExist) {
            throw new Exception('您输入的账号已存在,请重新输入 ', 421);
        }
        //检查昵称
        $existNick = YHMPassport_Models_Profile_Client::getByNickname($append['nick_name']);
        if (!empty($existNick)) {
            throw new Exception('昵称已存在!', 425);
        }
        $ssoProfile = YHMAuth_Package_Yoho_Uuc::register($profile, $password);
        if ($ssoProfile['code'] != 20100) {
            throw new Exception($ssoProfile['message'], 421);
        }
        $ssoUid = $ssoProfile['data']['uid'];

        $email = $mobile = '';
        if ($validateEmail == true) {
            $email = $profile;
            $profileInfo = YHMPassport_Models_Auth_Client::getProfileByEmail($profile);
        } else {
            $mobile = $profile;
            $profileInfo = YHMPassport_Models_Auth_Client::getProfileByMobile($profile);
        }
        if (empty($profileInfo)) {
            //添加用户
            $_password = Q_Utils_AuthCode::makePass($password);
            $nickName = empty($append['nick_name']) ? YHMConfig_Passport::DEFAULT_NICK_NAME : $append['nick_name'];
            $uid = YHMPassport_Models_Profile_Client::addUserProfile($_password, $nickName);
            if (empty($uid)) {
                throw new Exception('添加用户失败');
            }
            $profileType = empty($mobile) ? YHMConfig_Passport::PROFILE_TYPE_MAIL : YHMConfig_Passport::PROFILE_TYPE_MOBILE;
            YHMPassport_Models_Auth_Client::addAuth($uid, $profile, '', $profileType, $this->_channel, $this->_channelMap['channel_code'], 'N');
        }

        ######################## 关联SSO ########################
        $ssoRelation = YHMPassport_Models_Sso_Client::getByUidAndSsouid($uid, $ssoUid);
        if (empty($ssoRelation)) {
            YHMPassport_Models_Sso_Client::setRelation($uid, $ssoUid);
        }
        ######################## 关联SSO ########################
        #################### 注册结束触发 ####################
        $append['password'] = $_password;
        $append['mobile'] = $mobile;
        $append['email'] = $email;
        $append['sso_uid'] = $ssoUid;
        $this->registerEndDispatch($uid, $append);
        $this->_uid = $uid;
        return $uid;
    }

    /**
     * 退出
     * @param $token
     * @param string $sessionKey
     * @param null $domain
     * @return bool
     */
    public function signOut($token, $sessionKey = '_UID', $domain = null) {
        if (!empty($token) && $token == $this->getSession('token_session_key')) {
            $this->signOutPreDispatch($this->getSession());
            $this->setCookieID('', null, '_UID', -1);
            $this->unsetSession();
            $this->signOutEndDispatch($this->getSession());
            $link = YHMAuth_Package_Yoho_Uuc::getSyncStatusLink($this->getSession(), 2);
            @file_get_contents($link);
            return true;
        }
        return false;
    }

    /**
     * @param $profile
     * @param array $append
     * @throws Exception
     */
    public function associate($profile, array $append = array()) {
        ######################  登录开始触发 ######################
        $this->associatePreDispatch($profile, $append);
        ######################  登录开始触发 ######################
        if (empty($profile)) {
            throw new Exception('第三方登录Open ID为空.');
        }
        $ssoProfileType = 0;
        if (!empty(YHMAuth_Maps::$referToSso[$append['profile_type']])) {
            $ssoProfileType = YHMAuth_Maps::$referToSso[$append['profile_type']];
        }
        $ssoProfile = YHMAuth_Package_Yoho_Uuc::partnerLogin($ssoProfileType, $profile, '', '', 0, $append['nick_name'], $headpic = '', $profile);
        if ($ssoProfile['code'] != 200) {
            $ssoProfile['message']=(isset($ssoProfile['message']))?$ssoProfile['message']:"登录失败";
          //  echo $ssoProfile['message'];
            echo    "ssoProfileType------".$ssoProfileType."   nick_name------ " .$append['nick_name'].'   ------profile';
            print_r($profile);
           //throw new Exception($ssoProfile['message']);
        }
        $ssoUid = $ssoProfile['data']['uid'];
        //补充本地账户信息
        $authInfo = YHMPassport_Models_Auth_Client::getAuthByOpenID($profile, $append['profile_type']);
        if (!empty($authInfo)) {
            $uid = $authInfo['uid'];
        } else {
            //查看该ssouid是否关联的用户id
            $uid = YHMPassport_Models_Sso_Client::getUidBySsoUid($ssoUid);
            if (empty($uid)) {
                //添加用户
                $uid = YHMPassport_Models_Profile_Client::addUserProfile('nopassword', $append['nick_name'], $append['head_ico'], '0000-00-00', $append['gender']);
                $this->uploadHead($ssoProfile['data']['head_pic']);
            }
            $ret = YHMPassport_Models_Auth_Client::addAuth($uid, $profile, $append['nick_name'], $append['profile_type'], $this->_channel, $append['channel']);
            if (empty($ret)) {
                throw new Exception('添加用户认证方式失败', 412);
            }
        }
        ######################## 关联SSO ########################
        $ssoRelation = YHMPassport_Models_Sso_Client::getByUidAndSsouid($uid, $ssoUid);
        if (empty($ssoRelation)) {
            YHMPassport_Models_Sso_Client::setRelation($uid, $ssoUid);
        }
        ######################## 关联SSO ########################
        $append['sso_uid'] = $ssoUid;
        #################### 结束时触发 ####################
        $this->associateEndDispatch($uid, $append);
        $this->_uid = $uid;
        return $uid;
    }

    /**
     * (non-PHPdoc)
     * @see YHMAuth_User_Interface::updatePassword()
     */
    public function updatePassword($uid, $inputPassword, $profile = '', $profile_type = null) {
        $sso_uid = 0;
        if (!empty($uid)) {
            $sso_uid = YHMPassport_Models_Sso_Client::getSsouidByUid($uid);
        }
        if (empty($sso_uid)) {
            $ssoProfileType = YHMAuth_Maps::$referToSso[$profile_type];
            $ret = YHMAuth_Package_Yoho_Uuc::getAuth($profile, $ssoProfileType);
            if ($ret['code'] == 200) {
                $sso_uid = $ret['data']['uid'];
            }
        }
        if (empty($sso_uid)) {
            throw new Exception('没有找到关联的sso账户', 423);
        }
        YHMAuth_Package_Yoho_Uuc::changePassword($sso_uid, $inputPassword);
        $password = Q_Utils_AuthCode::makePass($inputPassword);
        return YHMPassport_Models_Profile_Client::updatePassword($uid, $password);
    }

    /**
     * (non-PHPdoc)
     * @see YHMAuth_User_Interface::updateInfo()
     */
    public function updateInfo($uid, $userInfo) {
        //先本地保存
        $nickName = !empty($userInfo['nickname']) ? $userInfo['nickname'] : '';
        $gender = $userInfo['gender'];
        $code_address = !empty($userInfo['area_code']) ? $userInfo['area_code'] : '';
        $existNick = YHMPassport_Models_Profile_Client::getByNickname($nickName);
        if (!empty($existNick) && $existNick['uid'] != $uid) {
            return false;
        }
        //如果修改昵称,修改状态进行后台审核
        if ($existNick['nick_name'] != $nickName) {
            YHMPassport_Models_Profile_Client::updateStatus($uid, 2);
        }
        $ret = YHMPassport_Models_Profile_Client::setUserInfoById($uid, $nickName, $gender, $code_address);
        if (empty($ret)) {
            return false;
        }
        //同步到uuc
        $ssoUid = YHMPassport_Models_Sso_Client::getSsouidByUid($uid);
        if (!empty($ssoUid)) {
            $syncData = array('nick' => $nickName);
            YHMAuth_Package_Yoho_Uuc::updateUserinfo($ssoUid, $syncData);
        }
        return true;
    }

    public function addAuth($uid, $profile, $profile_type, $channel, $password = '', $account_name = '') {
        $profileInfo = YHMPassport_Models_Profile_Client::getByUid($uid);
        if (empty($profileInfo)) {
            throw new Exception('没有找到该用户', 421);
        }
        $existAuth = YHMPassport_Models_Auth_Client::checkBindByOpenID($profile, $profile_type);
        if (!empty($existAuth)) {
            throw new Exception($profile . '已经被绑定', 425);
        }
        $ssoUid = YHMPassport_Models_Sso_Client::getSsouidByUid($uid);
        if (in_array($profile_type, array(1, 2))) {
            //绑定的是手机号或者邮箱,必须要设置密码
            if (strlen($profileInfo['password']) < 32 && empty($password)) {
                throw new Exception('必须设置一个密码才能完成绑定', 422);
            }
            $_password = Q_Utils_AuthCode::makePass($password);
            $ret = YHMPassport_Models_Profile_Client::updatePassword($uid, $_password);
            if (empty($ret)) {
                throw new Exception('更新本地密码不成功', 423);
            }
            //更新密码
            YHMAuth_Package_Yoho_Uuc::changePassword($ssoUid, $password);
        }
        $isActive = $profile_type == YHMConfig_Passport::PROFILE_TYPE_MAIL ? 'N' : 'Y';  //邮箱绑定默认为未激活,需要点击连接后才能激活
        $ret = YHMPassport_Models_Auth_Client::addAuth($uid, $profile, $account_name, $profile_type, $this->_channel, $channel, $isActive);
        if (!empty($ret)) {
            //同步到sso
            if (!empty($ssoUid)) {
                $auth_type = YHMAuth_Maps::$referToSso[$profile_type];
                YHMAuth_Package_Yoho_Uuc::setAuth($ssoUid, $profile, $auth_type);
            }
        }
        return true;
    }

}