Commit 07553a50 authored by xiabin's avatar xiabin

添加逻辑

parent 4988f39c
......@@ -15,6 +15,12 @@ return [
'password' => 'mysql123',
'charset' => 'utf8',
],
'redis' => [
'class' => 'yii\redis\Connection',
'hostname' => 'localhost',
'port' => 6379,
'database' => 0,
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
......
......@@ -3,4 +3,6 @@ return [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
'captchaId' => '4d6ad870bf63a30be3d22c92925b04ca',
'privateKey' => 'a2ca5e5139d1f43ac4e1cd248f3e52e4'
];
<?php
namespace common\libs;
/**
* 极验行为式验证安全平台,php 网站主后台包含的库文件
*
* @author Tanxu
*/
class Geetest
{
const GT_SDK_VERSION = 'php_3.2.0';
public static $connectTimeout = 1;
public static $socketTimeout = 1;
private $response;
public function __construct($captcha_id, $private_key)
{
$this->captcha_id = $captcha_id;
$this->private_key = $private_key;
}
/**
* 判断极验服务器是否down机
*
* @param null $user_id
* @return int
*/
public function pre_process($user_id = NULL)
{
$url = "http://api.geetest.com/register.php?gt=" . $this->captcha_id;
if (($user_id != NULL) and (is_string($user_id))) {
$url = $url . "&user_id=" . $user_id;
}
$challenge = $this->send_request($url);
if (strlen($challenge) != 32) {
$this->failback_process();
return 0;
}
$this->success_process($challenge);
return 1;
}
/**
* @param $challenge
*/
private function success_process($challenge)
{
$challenge = md5($challenge . $this->private_key);
$result = array(
'success' => 1,
'gt' => $this->captcha_id,
'challenge' => $challenge
);
$this->response = $result;
}
/**
*
*/
private function failback_process()
{
$rnd1 = md5(rand(0, 100));
$rnd2 = md5(rand(0, 100));
$challenge = $rnd1 . substr($rnd2, 0, 2);
$result = array(
'success' => 0,
'gt' => $this->captcha_id,
'challenge' => $challenge
);
$this->response = $result;
}
/**
* @return mixed
*/
public function get_response_str()
{
return json_encode($this->response);
}
/**
* 返回数组方便扩展
*
* @return mixed
*/
public function get_response()
{
return $this->response;
}
/**
* 正常模式获取验证结果
*
* @param $challenge
* @param $validate
* @param $seccode
* @param null $user_id
* @return int
*/
public function success_validate($challenge, $validate, $seccode, $user_id = NULL)
{
if (!$this->check_validate($challenge, $validate)) {
return 0;
}
$data = array(
"seccode" => $seccode,
"sdk" => self::GT_SDK_VERSION,
);
if (($user_id != NULL) and (is_string($user_id))) {
$data["user_id"] = $user_id;
}
$url = "http://api.geetest.com/validate.php";
$codevalidate = $this->post_request($url, $data);
if ($codevalidate == md5($seccode)) {
return 1;
} else {
if ($codevalidate == "false") {
return 0;
} else {
return 0;
}
}
}
/**
* 宕机模式获取验证结果
*
* @param $challenge
* @param $validate
* @param $seccode
* @return int
*/
public function fail_validate($challenge, $validate, $seccode)
{
if ($validate) {
$value = explode("_", $validate);
$ans = $this->decode_response($challenge, $value['0']);
$bg_idx = $this->decode_response($challenge, $value['1']);
$grp_idx = $this->decode_response($challenge, $value['2']);
$x_pos = $this->get_failback_pic_ans($bg_idx, $grp_idx);
$answer = abs($ans - $x_pos);
if ($answer < 4) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
/**
* @param $challenge
* @param $validate
* @return bool
*/
private function check_validate($challenge, $validate)
{
if (strlen($validate) != 32) {
return FALSE;
}
if (md5($this->private_key . 'geetest' . $challenge) != $validate) {
return FALSE;
}
return TRUE;
}
/**
* GET 请求
*
* @param $url
* @return mixed|string
*/
private function send_request($url)
{
if (function_exists('curl_exec')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
if (curl_errno($ch)) {
$err = sprintf("curl[%s] error[%s]", $url, curl_errno($ch) . ':' . curl_error($ch));
$this->triggerError($err);
}
curl_close($ch);
} else {
$opts = array(
'http' => array(
'method' => "GET",
'timeout' => self::$connectTimeout + self::$socketTimeout,
)
);
$context = stream_context_create($opts);
$data = file_get_contents($url, FALSE, $context);
}
return $data;
}
/**
*
* @param $url
* @param array $postdata
* @return mixed|string
*/
private function post_request($url, $postdata = '')
{
if (!$postdata) {
return FALSE;
}
$data = http_build_query($postdata);
if (function_exists('curl_exec')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout);
//不可能执行到的代码
if (!$postdata) {
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
} else {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
$err = sprintf("curl[%s] error[%s]", $url, curl_errno($ch) . ':' . curl_error($ch));
$this->triggerError($err);
}
curl_close($ch);
} else {
if ($postdata) {
$opts = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
'timeout' => self::$connectTimeout + self::$socketTimeout
)
);
$context = stream_context_create($opts);
$data = file_get_contents($url, FALSE, $context);
}
}
return $data;
}
/**
* 解码随机参数
*
* @param $challenge
* @param $string
* @return int
*/
private function decode_response($challenge, $string)
{
if (strlen($string) > 100) {
return 0;
}
$key = array();
$chongfu = array();
$shuzi = array("0" => 1, "1" => 2, "2" => 5, "3" => 10, "4" => 50);
$count = 0;
$res = 0;
$array_challenge = str_split($challenge);
$array_value = str_split($string);
for ($i = 0; $i < strlen($challenge); $i++) {
$item = $array_challenge[$i];
if (in_array($item, $chongfu)) {
continue;
} else {
$value = $shuzi[$count % 5];
array_push($chongfu, $item);
$count++;
$key[$item] = $value;
}
}
for ($j = 0; $j < strlen($string); $j++) {
$res += $key[$array_value[$j]];
}
$res = $res - $this->decodeRandBase($challenge);
return $res;
}
/**
* @param $x_str
* @return int
*/
private function get_x_pos_from_str($x_str)
{
if (strlen($x_str) != 5) {
return 0;
}
$sum_val = 0;
$x_pos_sup = 200;
$sum_val = base_convert($x_str, 16, 10);
$result = $sum_val % $x_pos_sup;
$result = ($result < 40) ? 40 : $result;
return $result;
}
/**
* @param $full_bg_index
* @param $img_grp_index
* @return int
*/
private function get_failback_pic_ans($full_bg_index, $img_grp_index)
{
$full_bg_name = substr(md5($full_bg_index), 0, 9);
$bg_name = substr(md5($img_grp_index), 10, 9);
$answer_decode = "";
// 通过两个字符串奇数和偶数位拼接产生答案位
for ($i = 0; $i < 9; $i++) {
if ($i % 2 == 0) {
$answer_decode = $answer_decode . $full_bg_name[$i];
} elseif ($i % 2 == 1) {
$answer_decode = $answer_decode . $bg_name[$i];
}
}
$x_decode = substr($answer_decode, 4, 5);
$x_pos = $this->get_x_pos_from_str($x_decode);
return $x_pos;
}
/**
* 输入的两位的随机数字,解码出偏移量
*
* @param $challenge
* @return mixed
*/
private function decodeRandBase($challenge)
{
$base = substr($challenge, 32, 2);
$tempArray = array();
for ($i = 0; $i < strlen($base); $i++) {
$tempAscii = ord($base[$i]);
$result = ($tempAscii > 57) ? ($tempAscii - 87) : ($tempAscii - 48);
array_push($tempArray, $result);
}
$decodeRes = $tempArray['0'] * 36 + $tempArray['1'];
return $decodeRes;
}
/**
* @param $err
*/
private function triggerError($err)
{
trigger_error($err);
}
}
......@@ -3,23 +3,48 @@
namespace frontend\assets;
use yii\web\AssetBundle;
use yii\web\View;
use Yii;
/**
* Main frontend application asset bundle.
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $basePath = '@webroot/assets';
public $baseUrl = '@web/assets';
public $css = [
'css/site.css',
];
public $js = [
['common/common.js', 'position' => View::POS_BEGIN]
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
//定义按需加载JS方法,注意加载顺序在最后
public static function addScript($view, $jsfile)
{
$jsfile = self::appendTimestamp($jsfile);
$view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'frontend\assets\AppAsset']);
}
//定义按需加载css方法,注意加载顺序在最后
public static function addCss($view, $cssfile)
{
$cssfile = self::appendTimestamp($cssfile);
$view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'frontend\assets\AppAsset']);
}
public static function appendTimestamp($url)
{
if (Yii::$app->assetManager->appendTimestamp && strncmp($url, '@web/', 5) === 0) {
$fileToCacheBust = Yii::getAlias(str_replace('@web', '@webroot', $url));
if (($timestamp = @filemtime("$fileToCacheBust")) > 0)
$url .= "?v={$timestamp}";
}
return $url;
}
}
......@@ -15,7 +15,11 @@ return [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'assetManager' => [
'appendTimestamp' => TRUE
],
'session' => [
'timeout' => 3600,
'name' => 'zuiektang-frontend',
'class' => 'yii\redis\Session',
'redis' => [
......@@ -28,6 +32,11 @@ return [
'identityClass' => 'common\models\User',
'enableAutoLogin' => TRUE,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => TRUE],
'on afterLogin' => function ($event) {
$user = $event->identity;
$user->logged_at = time();
$user->save();
}
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
......
<?php
namespace frontend\controllers;
use common\libs\Geetest;
use common\models\User;
use frontend\models\TokenInputForm;
use Yii;
use yii\base\InvalidParamException;
use yii\helpers\HtmlPurifier;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
......@@ -26,7 +28,8 @@ class SiteController extends Controller
const RESET_PASSWORD_FIRST = 'rp_first';
const RESET_PASSWORD_SECOND = 'rp_second';
const RESET_PASSWORD_THREE = 'rp_three';
const GT_SERVER = 'gt_server';
const GT_USER_ID = 'gt_user_id';
/**
* @inheritdoc
......@@ -159,8 +162,25 @@ class SiteController extends Controller
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
$request = Yii::$app->request;
$from = $request->get('from', 0);
$from = HtmlPurifier::process($from);
$model->from = (int)$from;
if ($model->load($request->post())) {
$geetestChallenge = $request->post('geetest_challenge');
$geetestSeccode = $request->post('geetest_seccode');
$geetestValidate = $request->post('geetest_validate');
$GtSdk = new Geetest(Yii::$app->params['captchaId'], Yii::$app->params['privateKey']);
$user_id = Yii::$app->session->get(self::GT_USER_ID);
if (Yii::$app->session->get(self::GT_SERVER) == 1) { //服务器正常
$gtResult = $GtSdk->success_validate($geetestChallenge, $geetestValidate, $geetestSeccode, $user_id);
} else { //服务器宕机,走failback模式
$gtResult = $GtSdk->fail_validate($geetestChallenge, $geetestValidate, $geetestSeccode);
}
if ($gtResult && $user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
......@@ -177,7 +197,8 @@ class SiteController extends Controller
*
* @return mixed
*/
public function actionRequestPasswordReset()
public
function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
......@@ -198,7 +219,8 @@ class SiteController extends Controller
/**
* @return mixed
*/
public function actionTokenInput()
public
function actionTokenInput()
{
if (!Yii::$app->session->has(self::RESET_PASSWORD_FIRST)) {
$this->redirect('request-password-reset');
......@@ -222,7 +244,8 @@ class SiteController extends Controller
* Resets password.
* @return mixed
*/
public function actionResetPassword()
public
function actionResetPassword()
{
if (!Yii::$app->session->has(self::RESET_PASSWORD_SECOND)) {
$this->redirect('request-password-reset');
......@@ -244,7 +267,8 @@ class SiteController extends Controller
* 密码设置成功
* @return string
*/
public function actionResetPasswordSuccess()
public
function actionResetPasswordSuccess()
{
if (!Yii::$app->session->has(self::RESET_PASSWORD_THREE)) {
$this->redirect('request-password-reset');
......@@ -252,4 +276,28 @@ class SiteController extends Controller
Yii::$app->session->remove(self::RESET_PASSWORD_THREE);
return $this->render('resetPasswordSuccess');
}
/**
* 极验证开始
* ajax
*/
public
function actionStartCaptcha()
{
if (Yii::$app->request->isAjax) {
$type = Yii::$app->request->get('type');
if ($type == 'pc') {
$GtSdk = new Geetest(Yii::$app->params['captchaId'], Yii::$app->params['privateKey']);
} else {
throw new \yii\web\ForbiddenHttpException('参数错误');
}
$user_id = Yii::$app->security->generateRandomString(16);
$status = $GtSdk->pre_process($user_id);
Yii::$app->session->set(self::GT_SERVER, $status);
Yii::$app->session->set(self::GT_USER_ID, $user_id);
echo $GtSdk->get_response_str();
} else {
throw new \yii\web\ForbiddenHttpException('非法请求');
}
}
}
......@@ -9,8 +9,11 @@
namespace frontend\controllers;
use common\libs\Test;
use yii\filters\AccessControl;
use yii\web\Controller;
use Yii;
use yii\helpers\HtmlPurifier;
class UserCenterController extends Controller
{
......@@ -26,17 +29,23 @@ class UserCenterController extends Controller
'rules' => [
[
'allow' => TRUE,
'roles' => ['teacher'],
'roles' => ['?'],
],
],
],
];
}
public function actionTest()
{
$test = new Test();
$test->index();
}
public function actionIndex()
{
echo \Yii::$app->user->identity->role;
echo 'index';
// echo Yii::$app->user->identity->role;
}
}
\ No newline at end of file
......@@ -10,6 +10,9 @@ use common\models\User;
*/
class LoginForm extends Model
{
const MAX_LOGIN_NUM = 5;
const LOGIN_CYCLE = 15 * 60;//second
const REDIS_KEY_PREFIX = 'login_ip';
public $telephone;
public $password;
public $rememberMe = TRUE;
......@@ -42,9 +45,23 @@ class LoginForm extends Model
*/
public function validatePassword($attribute, $params)
{
$redis = Yii::$app->redis;
$key = self::REDIS_KEY_PREFIX . '::' . Yii::$app->request->getUserIP();
$value = $redis->get($key);
if ($value === NULL) {
$redis->setex($key, self::LOGIN_CYCLE, self::MAX_LOGIN_NUM);
} else {
if ($value <= 0) {
$this->addError('password', '登陆已经被限制了.');
}
}
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
if ($value !== NULL) {
$redis->decr($key);
}
$this->addError($attribute, 'Incorrect telephone or password.');
}
}
......
......@@ -13,10 +13,11 @@ class SignupForm extends Model
{
const USERNAME_PREFIX = 'ZK_';
public $telephone;
public $password;
public $rePassword;
public $from;
/**
* @inheritdoc
......@@ -25,14 +26,14 @@ class SignupForm extends Model
{
return [
['telephone', 'trim'],
['telephone', 'required'],
[['telephone', 'from'], 'required'],
['telephone', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This telephone has already been taken.'],
['telephone', 'string', 'length' => 11],
[['password', 'rePassword'], 'required'],
['password', 'string', 'min' => 6],
['rePassword', 'string', 'min' => 6],
['rePassword', 'compare', 'compareAttribute' => 'rePassword'],
['from', 'integer']
];
}
......@@ -43,6 +44,7 @@ class SignupForm extends Model
*/
public function signup()
{
if (!$this->validate()) {
return NULL;
}
......@@ -62,4 +64,12 @@ class SignupForm extends Model
}
return $user;
}
public function formName()
{
return '';
}
}
......@@ -6,9 +6,12 @@
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use frontend\assets\AppAsset;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
AppAsset::addScript($this, '@web/assets/signup.js');
$this->registerJsFile('http://static.geetest.com/static/tools/gt.js');
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
......@@ -26,8 +29,12 @@ $this->params['breadcrumbs'][] = $this->title;
<?= $form->field($model, 'rePassword')->passwordInput() ?>
<div id="embed-captcha"></div>
<p id="wait" class="show">正在加载验证码......</p>
<p id="notice" class="hide">请先拖动验证码到相应位置</p>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'id' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
......
/**
* Created by xiabin on 16/9/24.
*/
alert(123);
\ No newline at end of file
/**
* Created by xiabin on 2016/9/26.
*/
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment