配置信息
-
安装插件
-
配置腾讯云短信信息
代码实现
-
新建页面/application/admin/view/index/phone_login.html(
我直接复制登录login.html魔改的
)<form method="post" id="login-form" action="{:url('index/phone_login')}"><!--@AdminLoginFormBegin--><div id="errtips" class="hide"></div>{:token()}<div class="input-group"><div class="input-group-addon"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div><input type="text" id="mobile" name="mobile" class="form-control" placeholder="{:__('Phone')}" data-rule="{:__('Phone')}:required;mobile"/><br></div><div class="input-group"><div class="input-group-addon"><span class="glyphicon glyphicon-option-horizontal" aria-hidden="true"></span></div><input type="text" name="captcha" id="mobile-captcha" class="form-control" data-rule="required;length(4);" placeholder="{:__('验证码')}"/><input type="hidden" value="changemobile" name="event"><span class="input-group-addon" style="padding:0;border:none;cursor:pointer;"><a href="javascript:;" class="btn btn-info btn-captcha" data-url="/api/sms/send" data-type="mobile" data-event="changemobile">获取验证码</a></span></div><div class="form-group checkbox"><label class="inline" for="keeplogin"><a href="{:url('login')}" style="float: left;">账号密码登录</a></label></div><div class="form-group"><button type="submit" class="btn btn-success btn-lg btn-block" style="background:#708eea;">{:__('Sign in')}</button></div><!--@AdminLoginFormEnd--> </form>
-
在/public/assets/js/backend-init.js绑定发送短信事件
define(['backend'], function (Backend) {var Frontend = {api: Fast.api,init: function () {var si = {};//发送验证码$(document).on("click", ".btn-captcha", function (e) {var type = $(this).data("type") ? $(this).data("type") : 'mobile';var btn = this;Frontend.api.sendcaptcha = function (btn, type, data, callback) {$(btn).addClass("disabled", true).text("发送中...");Frontend.api.ajax({url: $(btn).data("url"), data: data}, function (data, ret) {clearInterval(si[type]);var seconds = 60;si[type] = setInterval(function () {seconds--;if (seconds <= 0) {clearInterval(si);$(btn).removeClass("disabled").text("发送验证码");} else {$(btn).addClass("disabled").text(seconds + "秒后可再次发送");}}, 1000);if (typeof callback == 'function') {callback.call(this, data, ret);}}, function () {$(btn).removeClass("disabled").text('发送验证码');});};if (['mobile', 'email'].indexOf(type) > -1) {var element = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : $("input[name='" + type + "']", $(this).closest("form"));var text = type === 'email' ? '邮箱' : '手机号码';if (element.val() === "") {Layer.msg(text + "不能为空!");element.focus();return false;} else if (type === 'mobile' && !element.val().match(/^1[3-9]\d{9}$/)) {Layer.msg("请输入正确的" + text + "!");element.focus();return false;} else if (type === 'email' && !element.val().match(/^[\w\+\-]+(\.[\w\+\-]+)*@[a-z\d\-]+(\.[a-z\d\-]+)*\.([a-z]{2,4})$/)) {Layer.msg("请输入正确的" + text + "!");element.focus();return false;}element.isValid(function (v) {if (v) {var data = {event: $(btn).data("event")};data[type] = element.val();Frontend.api.sendcaptcha(btn, type, data);} else {Layer.msg("请确认已经输入了正确的" + text + "!");}});} else {var data = {event: $(btn).data("event")};Frontend.api.sendcaptcha(btn, type, data, function (data, ret) {Layer.open({title: false, area: ["400px", "430px"], content: "<img src='" + data.image + "' width='400' height='400' /><div class='text-center panel-title'>扫一扫关注公众号获取验证码</div>", type: 1});});}return false;});}};Frontend.init(); });
-
实际操作时,你会发现前端提示有问题,在/public/assets/js/backend/index.js让phone_login的错误提示框绑定toastr弹窗即可(
这里我也是直接复制前面login的方法而已
)phone_login: function () {var lastlogin = localStorage.getItem("lastlogin");if (lastlogin) {lastlogin = JSON.parse(lastlogin);$("#profile-img").attr("src", Backend.api.cdnurl(lastlogin.avatar));$("#profile-name").val(lastlogin.username);}//让错误提示框居中Fast.config.toastr.positionClass = "toast-top-center";//本地验证未通过时提示$("#login-form").data("validator-options", {invalid: function (form, errors) {$.each(errors, function (i, j) {Toastr.error(j);});},target: '#errtips'});//为表单绑定事件Form.api.bindevent($("#login-form"), function (data) {localStorage.setItem("lastlogin", JSON.stringify({id: data.id,username: data.username,avatar: data.avatar}));location.href = Backend.api.fixurl(data.url);}, function (data) {$("input[name=captcha]").next(".input-group-addon").find("img").trigger("click");}); }
-
在/application/admin/controller/Index.php写phone_login方法
/*** 手机号登录*/ public function phone_login() {if (request()->isPost()) {$url = $this->request->get('url', 'index/index');$mobile = $this->request->post('mobile');$captcha = $this->request->post('captcha');$event = $this->request->post('event');if (!\app\common\library\Sms::check($mobile, $captcha, $event)) {$this->error(__('验证码不正确'));}$admin = Admin::get(['mobile' => $mobile]);if(!$admin){$this->error('该手机号还没有绑定账号');}if ($admin['status'] == 'hidden') {$this->error('Admin is forbidden');} $admin->loginfailure = 0;$admin->logintime = time();$admin->loginip = request()->ip();$this->token = Random::uuid();$admin->token = $this->token;$admin->save();Session::set("admin", $admin->toArray());$this->keeplogin(86400);Hook::listen("admin_login_after", $this->request);$this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $admin->username, 'avatar' => $this->auth->avatar]);} else {$background = Config::get('fastadmin.login_background');$background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';$this->view->assign('background', $background);$url = $this->request->get('url', 'index/index');}// 根据客户端的cookie,判断是否可以自动登录if ($this->auth->autologin()) {Session::delete("referer");$this->redirect($url);}return $this->view->fetch(); }/*** 刷新保持登录的Cookie** @param int $keeptime* @return boolean*/ protected function keeplogin($keeptime = 0) {$expiretime = time() + $keeptime;$key = md5(md5($this->auth->id) . md5($keeptime) . md5($expiretime) . $this->token . config('token.key'));$data = [$this->auth->id, $keeptime, $expiretime, $key];Cookie::set('keeplogin', implode('|', $data), 86400 * 7); }
-
记得前面先引入类库,配置新方法免登录验证,以及token,做登录刷新
use think\Cookie; use fast\Random;
protected $noNeedLogin = ['login', 'phone_login','keeplogin']; protected $noNeedRight = ['index', 'logout']; protected $token = '';
-
数据库admin表新增手机字段