TP5谷歌验证

 

 

 把 GoogleAuthenticator.php 放到插件库

GoogleAuthenticator.php

<?php

/**
 * PHP Class for handling Google Authenticator 2-factor authentication.
 *
 * @author Michael Kliewe
 * @copyright 2012 Michael Kliewe
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @link http://www.phpgangsta.de/
 */
namespace googleAuth;
class GoogleAuthenticator
{
    protected $_codeLength = 6;

    /**
     * Create new secret.
     * 16 characters, randomly chosen from the allowed base32 characters.
     *
     * @param int $secretLength
     *
     * @return string
     */
    public function createSecret($secretLength = 16)
    {
        $validChars = $this->_getBase32LookupTable();

        // Valid secret lengths are 80 to 640 bits
        if ($secretLength < 16 || $secretLength > 128) {
            throw new Exception('Bad secret length');
        }
        $secret = '';
        $rnd = false;
        if (function_exists('random_bytes')) {
            $rnd = random_bytes($secretLength);
        } elseif (function_exists('mcrypt_create_iv')) {
            $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
            if (!$cryptoStrong) {
                $rnd = false;
            }
        }
        if ($rnd !== false) {
            for ($i = 0; $i < $secretLength; ++$i) {
                $secret .= $validChars[ord($rnd[$i]) & 31];
            }
        } else {
            throw new Exception('No source of secure random');
        }

        return $secret;
    }

    /**
     * Calculate the code, with given secret and point in time.
     *
     * @param string   $secret
     * @param int|null $timeSlice
     *
     * @return string
     */
    public function getCode($secret, $timeSlice = null)
    {
        if ($timeSlice === null) {
            $timeSlice = floor(time() / 30);
        }

        $secretkey = $this->_base32Decode($secret);

        // Pack time into binary string
        $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
        // Hash it with users secret key
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        // Use last nipple of result as index/offset
        $offset = ord(substr($hm, -1)) & 0x0F;
        // grab 4 bytes of the result
        $hashpart = substr($hm, $offset, 4);

        // Unpak binary value
        $value = unpack('N', $hashpart);
        $value = $value[1];
        // Only 32 bits
        $value = $value & 0x7FFFFFFF;

        $modulo = pow(10, $this->_codeLength);

        return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
    }

    /**
     * Get QR-Code URL for image, from google charts.
     *
     * @param string $name
     * @param string $secret
     * @param string $title
     * @param array  $params
     *
     * @return string
     */
    public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret);
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return "https://api.qrserver.com/v1/create-qr-code/?data=$urlencoded&size=${width}x${height}&ecc=$level";
    }

    /**
     * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
     *
     * @param string   $secret
     * @param string   $code
     * @param int      $discrepancy      This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
     * @param int|null $currentTimeSlice time slice if we want use other that time()
     *
     * @return bool
     */
    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Set the code length, should be >=6.
     *
     * @param int $length
     *
     * @return PHPGangsta_GoogleAuthenticator
     */
    public function setCodeLength($length)
    {
        $this->_codeLength = $length;

        return $this;
    }

    /**
     * Helper class to decode base32.
     *
     * @param $secret
     *
     * @return bool|string
     */
    protected function _base32Decode($secret)
    {
        if (empty($secret)) {
            return '';
        }

        $base32chars = $this->_getBase32LookupTable();
        $base32charsFlipped = array_flip($base32chars);

        $paddingCharCount = substr_count($secret, $base32chars[32]);
        $allowedValues = array(6, 4, 3, 1, 0);
        if (!in_array($paddingCharCount, $allowedValues)) {
            return false;
        }
        for ($i = 0; $i < 4; ++$i) {
            if ($paddingCharCount == $allowedValues[$i] &&
                substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
                return false;
            }
        }
        $secret = str_replace('=', '', $secret);
        $secret = str_split($secret);
        $binaryString = '';
        for ($i = 0; $i < count($secret); $i = $i + 8) {
            $x = '';
            if (!in_array($secret[$i], $base32chars)) {
                return false;
            }
            for ($j = 0; $j < 8; ++$j) {
                $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for ($z = 0; $z < count($eightBits); ++$z) {
                $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
            }
        }

        return $binaryString;
    }

    /**
     * Get array with all 32 characters for decoding from/encoding to base32.
     *
     * @return array
     */
    protected function _getBase32LookupTable()
    {
        return array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
            'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
            '=',  // padding char
        );
    }

    /**
     * A timing safe equals comparison
     * more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html.
     *
     * @param string $safeString The internal (safe) value to be checked
     * @param string $userString The user submitted (unsafe) value
     *
     * @return bool True if the two strings are identical
     */
    private function timingSafeEquals($safeString, $userString)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($safeString, $userString);
        }
        $safeLen = strlen($safeString);
        $userLen = strlen($userString);

        if ($userLen != $safeLen) {
            return false;
        }

        $result = 0;

        for ($i = 0; $i < $userLen; ++$i) {
            $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
        }

        // They are only identical strings if $result is exactly 0...
        return $result === 0;
    }
}

 控制器

    use googleAuth\GoogleAuthenticator; //引入

    /**
     * 绑定谷歌验证
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function googleAuth(){
        $googleAuth = new GoogleAuthenticator();
        $uid = $this->userId;
        $secret = Db::table('words_tmp')->where(['uid'=>$uid])->field('goog_secret,goog_url')->find();

        if(!$secret['goog_secret']){
            $secret = $googleAuth->createSecret();  //谷歌密钥


            if($secret){
               $key = Db::table('user_invite_code')->where(['user_id'=>$uid])->value('invite_code');
                $qrCodeUrl = $googleAuth->getQRCodeGoogleUrl('ALI@'.trim($key),$secret); //谷歌二维码
                $oneCode = $googleAuth->getCode($secret);
//                dump($secret);
//                dd($qrCodeUrl);
                Db::table('words_tmp')->where(['uid'=>$uid])->update(['goog_secret'=>$secret,'goog_url'=>$qrCodeUrl]);

                $re['goog_secret'] = $secret;
                $re['goog_url'] = $qrCodeUrl;
            }else{
                return json(['code' => 1, 'msg' => get_lang('fail')]);
            }
        }else{
            $re['goog_secret'] = $secret['goog_secret'];
            $re['goog_url'] = $secret['goog_url'];
        }
        return json(['code' => 0, 'msg' => get_lang('success'),'info'=>$re]);

    }

    /**
     *  谷歌验证
     * @param Request $request
     * @return \think\response\Json
     */
    public function check_code(Request $request){
        $googleAuth = new GoogleAuthenticator();

        $uid = $this->userId;

        $secret = Db::table('words_tmp')->where(['uid'=>$uid])->value('goog_secret');

        $checkResult = $googleAuth->verifyCode($secret, $request->post('code'), 2);    // 2 = 2*30sec clock tolerance
        if($checkResult){
            return json()->data(['code' => 0, 'msg' => '验证成功']);

        }else{
            return json()->data(['code' => 1, 'msg' => '验证码错误,请重新填写']);
        }
    }

 

 

THINKPHP最全第三方登录(包括腾讯QQ、微信、新浪微博、Github、淘宝网、百度、搜狐微博、人人、360、网易等等) 使用方式: 1、使用命名空间 use Org\ThinkSDK\ThinkOauth; 2、设置三方登录的类别并赋予一个变量 $type = ThinkOauth::getInstance('qq'); 3、设置配置文件 'THINK_SDK_(TYPE)' => array( 'APP_KEY' => '', //应用注册成功后分配的 APP ID 'APP_SECRET' => '', //应用注册成功后分配的KEY 'CALLBACK' => '', //注册应用填写的callback ), 上文中的(TYPE)为设置的类别,其值目前有以下几个: //腾讯QQ登录配置 THINK_SDK_QQ // 用户基本信息API接口 user/get_user_info //腾讯微博配置 THINK_SDK_TENCENT // 用户基本信息API接口 user/info //新浪微博配 THINK_SDK_SINA // 用户基本信息API接口 users/show。附加参数:'uid='.$obj->openid() //网易微博配置 THINK_SDK_T163 // 用户基本信息API接口 users/show //人人网配置 THINK_SDK_RENREN // 用户基本信息API接口 users.getInfo //360配置 THINK_SDK_X360 // 用户基本信息API接口 user/me //豆瓣配置 THINK_SDK_DOUBAN // 用户基本信息API接口 user/~me //Github配置 THINK_SDK_GITHUB // 用户基本信息API接口 user //Google配置 THINK_SDK_GOOGLE // 用户基本信息API接口 userinfo //MSN配置 THINK_SDK_MSN // 用户基本信息API接口 msn。附加参数:token //点点配置 THINK_SDK_DIANDIAN // 用户基本信息API接口 user/info //淘宝网配置 THINK_SDK_TAOBAO // 用户基本信息API接口 taobao.user.buyer.get。附加参数:'fields=user_id,nick,sex,buyer_credit,avatar,has_shop,vip_info' //百度配置 THINK_SDK_BAIDU // 用户基本信息API接口 passport/users/getLoggedInUser // 注意,百度的头像位置是http://tb.himg.baidu.com/sys/portrait/item/{$data['portrait']} //开心网配置 THINK_SDK_KAIXIN // 用户基本信息API接口 users/me //搜狐微博配置 THINK_SDK_SOHU // 用户基本信息API接口 i/prv/1/user/get-basic-info 4、实例化一个登录页面 redirect($type->getRequestCodeURL()); 这里的$type是第二部获取的结果 5、回调页面 $code = $this->get('code'); $type = 'QQ'; $sns = ThinkOauth::getInstance($type); //腾讯微博需传递的额外参数 $extend = null; if($type == 'tencent'){ $extend = array('openid' => $this->_get('openid'), 'openkey' => $this->_get('openkey')); } //请妥善保管这里获取到的Tok
ThinkPHP 6 (TP6) 中发送Google验证码通常涉及到第三方库的集成,例如使用PHP的库来发送短信验证码。这里提供一种基本的思路和几种常见的实现方法: 1. 使用`guzzlehttp/psr7` 和 `twilio-php` 库 (如果使用短信验证服务) ```php // 引入依赖 use GuzzleHttp\Client; use Twilio\Rest\Client as TwilioClient; // 设置环境变量或配置 $twilio_account_sid = 'your_twilio_account_sid'; $twilio_auth_token = 'your_twilio_auth_token'; $google_recaptcha_secret = 'your_google_recaptcha_secret'; // 验证码生成和显示 $captcha = create_google_recaptcha(); // 自定义函数生成验证码 // 发送短信验证码(假设使用Twilio) $client = new TwilioClient($twilio_account_sid, $twilio_auth_token); $message = "您的Google验证码是: {$captcha}"; try { $client->messages->create( '+recipient_phone_number', // 替换为您需要发送的电话号码 ['body' => $message] ); } catch (\Exception $e) { echo '发送失败: ', $e->getMessage(); } function create_google_recaptcha() { // Google reCAPTCHA API请求并返回验证码 // 实际代码应替换为Google reCAPTCHA的API请求,并处理返回结果 } ``` 2. 如果你需要的是邮件验证码,可以使用PHPMailer 或 SwiftMailer等邮件库: ```php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $mail = new PHPMailer(true); // Use force TLS encryption $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; // 这里假设是Gmail SMTP $mail->SMTPAuth = true; $mail->Username = 'your_email@gmail.com'; $mail->Password = 'your_email_password'; $mail->SMTPSecure = 'tls'; $mail->Port = 587; $captcha = generate_email_captcha(); // 自定义函数生成验证码 $mail->setFrom('your_email@example.com', 'Your Name'); $mail->addAddress('+recipient_email@example.com'); // 收件人邮箱 $mail->Subject = 'Google验证码'; $mail->Body = "您的Google验证码是: {$captcha}"; if (!$mail->send()) { echo 'Email发送失败: ' . $mail->ErrorInfo; } else { echo '验证码已发送至指定邮箱'; } function generate_email_captcha() { // Google reCAPTCHA的HTML标签,将验证码数据隐藏 return '<img src="https://www.google.com/recaptcha/api/image?size=normal&hl=en" style="display:none">'; } ``` 请注意,实际应用中需要根据Google reCAPTCHA的具体文档进行API集成,并且上述示例代码仅供参考,你可能需要根据实际需求调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值