laravel-admin使用短信验证码登录后台的方法
2020-01-11 admin laravel 1749
laravel-admin默认使用用户名username和密码password登录,前文已加入微信和QQ互联登录,这篇文章再讲述如何添加手机短信验证码登录。登录界面如下:
首先,安装短信发送组件easy-sms,特点:支持目前市面多家服务商,一套写法兼容所有平台,简单配置即可灵活增减服务商,内置多种服务商轮询策略、支持自定义轮询策略,统一的返回值格式,便于日志与监控,自动轮询选择可用的服务商。执行命令安装:
composer require "overtrue/easy-sms"
使用方法,先在.env中将供应商的id、key和签名填写好,在config目录中添加配置文件easysms.php:
return [ // HTTP 请求的超时时间(秒) 'timeout' => 5.0, // 默认发送配置 'default' => [ // 网关调用策略,默认:顺序调用 'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class, // 默认可用的发送网关 'gateways' => [ 'aliyun', 'errorlog', ], ], // 可用的网关配置 'gateways' => [ // 失败日志 'errorlog' => [ 'channel' => 'smslog', ], // 阿里云 'aliyun' => [ 'access_key_id' => env('ALIYUN_ACCESSKEYID'), // accessKey 'access_key_secret' => env('ALIYUN_ACCESSKEYSECRET'), // accessSecret 'sign_name' => env('ALIYUN_SMS_SIGN_NAME'), // 签名 ], // ], 'custom_gateways' => [ 'errorlog' => \Leonis\Notifications\EasySms\Gateways\ErrorLogGateway::class, 'winic' => \Leonis\Notifications\EasySms\Gateways\WinicGateway::class, ], ];
然后在控制器中引用并加入代码:
use Overtrue\EasySms\EasySms;//短信 //手机短信注册登录 public function phone(){ return view('auth.adminphone'); } public function phonelogin(Request $request){ session()->forget('dxyzm');//清空验证码session $dz = $request->dz; if($dz == 'hqyzm'){ //发送验证码 $phone = $request->phone; $dxconfig = config('easysms'); $easySms = new EasySms($dxconfig); $yzm = mt_rand(100000, 999999);//随机生成的验证码 $result = $easySms->send($phone, [ 'content' => '您的验证码为:'.$yzm, 'template' => 'SMS_179165012', 'data' => ['code' => $yzm], ]); session(['hqyzm' => $yzm]);//设置验证码session $fhyzm = array('status' => '200'); echo json_encode($fhyzm,JSON_UNESCAPED_UNICODE); }elseif($dz == 'login'){ $phone = $request->phone; $yzm = $request->yzm; $yyzm = session('hqyzm');//从session中获取正确的验证码 session()->forget('hqyzm'); if($yzm == $yyzm and $phone !== ''){ //验证码正确,查找数据库中是否有该手机号 $check = AdminUserModel::where('phone', $phone)->first(); if (!$check) {//如果第一次访问,跳转到绑定账号页面 $bd = url("/admin/bdyyzh?timestamp=".time()."&phone=".$phone); return redirect($bd); } else { //登录 $this->guard()->login($check); admin_toastr(trans('admin.login_successful')); $request->session()->regenerate(); return redirect()->intended($this->redirectPath()); } }else{ session()->flash('danger', '验证码错误!'); return redirect()->back()->withInput(); } //dd($request->all()); } }
前端加上短信发送按钮,并用Js倒计时adminphone.blade.php:
@extends('layouts.app') @section('content')@endsection手机短信登录
最后,在app/Models中添加后台model:AdminUserModel.php
namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class AdminUserModel extends Authenticatable { use Notifiable; protected $table = 'admin_users'; protected $fillable = [ 'username', 'password', 'name', 'openid','qqid','phone','avatar', 'remember_token', ]; protected $hidden = [ 'password', 'remember_token', ]; }
这样就实现了,用户短信验证码登录了。初次登录会跳转到绑定账号页面,绑定后会自动登录。