欢迎各位兄弟 发布技术文章
这里的技术是共享的
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Obj\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Cache;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class SendPhoneCheckMsgController extends Controller{
use ThrottlesPhoneCheck;
public function __construct()
{
$guard = $this->getGuard();
$this->middleware($guard ? 'guest:'.$guard : 'guest', ['except' => 'getLogout']);
$this->middleware('geetest', ['except' => ['postLogin']]);
$this->middleware('throttleIP:5,1,10', ['except' => ['postLogin']]);
}
protected function isValidPhoneNum($num = ''){
if(!$num)return false;
preg_match('/^1[0-9]{10}$/',$num,$res);
if($res[0]===$num)return true;
return false;
}
protected function sendInvalidPhoneNumberResponse(Request $request){
if ($request->ajax() || $request->wantsJson()) {
throw new AccessDeniedHttpException('手机号码输入不正确');
} else {
return redirect()->back()->withErrors(['手机号码输入不正确'])->withInput($request->all());
}
}
/**
* @param $num
*/
protected function checkPhoneRegistered($num){
if(count(User::where('phone_number',$num)->get())>0)throw new ConflictHttpException('该手机已注册,请直接登录');
}
/**
* Get the guard to be used during authentication.
*
* @return string|null
*/
protected function getGuard()
{
return property_exists($this, 'guard') ? $this->guard : null;
}
/**
* @param Request $request
* @return array
*/
public function sendRegistCheckMsg(Request $request)
{
$validator = \Validator::make($request->all(),[
'phone_number'=>'required'
]);
if($validator->fails()||!$this->isValidPhoneNum($request->input('phone_number')))$this->sendInvalidPhoneNumberResponse($request);
if($this->hasLocked($request))throw new AccessDeniedHttpException('请求发送短信频繁,请在'.$this->tryAfter($request).'秒后再试');
$this->checkPhoneRegistered($request->input('phone_number'));
$this->lockPhone($request,45/60);
$result = \PhoneMessage::regist($request->input('phone_number'));
if(!$result)return ['短信发送成功'];
throw new ServiceUnavailableHttpException(60,'服务器错误:'.json_encode($result));
}
}
trait ThrottlesPhoneCheck
{
protected function lockPhone(Request $request,$decayMinutes){
Cache::add($this->getPhoneKey($request).':lockout', time() + ($decayMinutes * 60), $decayMinutes);
}
protected function getPhoneKey(Request $request){
return 'phone_num'.$request->input($this->phoneNumFormName());
}
protected function hasLocked(Request $request){
return Cache::has($this->getPhoneKey($request).':lockout');
}
protected function tryAfter(Request $request)
{
return (int)Cache::get($this->getPhoneKey($request).':lockout') - time();
}
protected function phoneNumFormName()
{
return property_exists($this, 'phoneNumFormName') ? $this->phoneNumFormName : 'phone_number';
}
}
来自 https://git.oschina.net/peterq/nkt/raw/master/app/Http/Controllers/Api/SendPhoneCheckMsgController.php