项目场景:后台项目管理,基于JWT的Token登录认证
提示:这里简述项目相关背景:
例如:php5.6
问题描述
提示:这里描述项目中遇到的问题:
例如:错误提示
源码如下
<?php
namespace app\adminapi\controller;
use think\Controller;
class Login extends BaseApi
{
/**
* 验证码接口
*/
public function captcha()
{
//验证码唯一标识
$uniqid = uniqid(mt_rand(100000, 999999));
//生成验证码地址
$src = captcha_src($uniqid);
//返回数据
$res = [
'src' => $src,
'uniqid' => $uniqid,
];
$this->ok($res);
}
/**
* 登录接口
*/
public function login()
{
//接收数据
$params = input();
//参数检测
$validate = $this->validate($params, [
'username|用户名' => 'require',
'password|密码' => 'require',
'code|验证码' => 'require',
// 'code|验证码' => 'require|captcha:' . $params['uniqid'], //验证码自动校验
'uniqid|验证码标识' => 'require',
]);
if ($validate !== true) {
//参数验证失败
$this->fail($validate, 401);
}
//效验验证码 手动校验
//从缓存中根据uniqid获取session_id, 设置session_id, 用于验证码校验
session_id(cache('session_id_' .$params['uniqid']));
if(!captcha_check($params['code'], $params['uniqid'])) {
//验证码错误
$this->fail('验证码错误', 402);
} else {
$this->success('正确');
}
//查询用户表进行认证
$password = encrypt_password($params['password']);
$info = \app\common\model\Admin::where('username', $params['username'])
->where('password', md5($params['password']))
->find();
if (empty($info)) {
//用户名或密码错误
$this->fail('用户名或密码错误', 403);
} else {
echo '正确';
}
//生成token令牌
$token = \tools\jwt\Token::getToken($info['id']);
//返回数据
$date = [
'token' => $token,
'user_id' => $info['id'],
'username' => $info['username'],
'nickname' => $info['nickname'],
'email' => $info['email'],
];
$this->ok($date);
}
}
–