2023-10-27 11:58:21 +08:00
|
|
|
|
<?php
|
|
|
|
|
/**
|
|
|
|
|
* @copyright Copyright (c) 2021 勾股工作室
|
|
|
|
|
* @license https://opensource.org/licenses/Apache-2.0
|
|
|
|
|
* @link https://www.gougucms.com
|
|
|
|
|
*/
|
|
|
|
|
declare (strict_types = 1);
|
|
|
|
|
namespace app\api\controller;
|
|
|
|
|
|
|
|
|
|
use app\api\BaseController;
|
|
|
|
|
use app\api\middleware\Auth;
|
|
|
|
|
use Firebase\JWT\JWT;
|
|
|
|
|
use Firebase\JWT\Key;
|
|
|
|
|
use think\facade\Db;
|
|
|
|
|
use think\facade\Request;
|
|
|
|
|
|
|
|
|
|
class User extends BaseController
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* 控制器中间件 [登录、注册 不需要鉴权]
|
|
|
|
|
* @var array
|
|
|
|
|
*/
|
|
|
|
|
protected $middleware = [
|
|
|
|
|
Auth::class => ['except' => ['login']]
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param $user_id
|
|
|
|
|
* @return string
|
|
|
|
|
*/
|
|
|
|
|
public function getToken($user_id){
|
|
|
|
|
$time = time(); //当前时间
|
|
|
|
|
$conf = $this->jwt_conf;
|
|
|
|
|
$token = [
|
|
|
|
|
'iss' => $conf['iss'], //签发者 可选
|
|
|
|
|
'aud' => $conf['aud'], //接收该JWT的一方,可选
|
|
|
|
|
'iat' => $time, //签发时间
|
|
|
|
|
'nbf' => $time-1 , //(Not Before):某个时间点后才能访问,比如设置time+30,表示当前时间30秒后才能使用
|
|
|
|
|
'exp' => $time+$conf['exptime'], //过期时间,这里设置2个小时
|
|
|
|
|
'data' => [
|
|
|
|
|
//自定义信息,不要定义敏感信息
|
|
|
|
|
'userid' =>$user_id,
|
|
|
|
|
]
|
|
|
|
|
];
|
|
|
|
|
return JWT::encode($token, $conf['secrect'], 'HS256'); //输出Token 默认'HS256'
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function login()
|
|
|
|
|
{
|
|
|
|
|
$param = get_params();
|
|
|
|
|
if (empty($param['username']) || empty($param['password'])) {
|
2023-10-27 12:03:32 +08:00
|
|
|
|
$this->apiError('用户名密码不能为空');
|
2023-10-27 11:58:21 +08:00
|
|
|
|
}
|
|
|
|
|
// 校验用户名密码
|
|
|
|
|
$user = Db::name('Admin')->where(['username' => $param['username']])->find();
|
|
|
|
|
if (empty($user)) {
|
|
|
|
|
$this->apiError('帐号或密码错误');
|
|
|
|
|
}
|
|
|
|
|
$param['pwd'] = set_password($param['password'], $user['salt']);
|
|
|
|
|
if ($param['pwd'] !== $user['pwd']) {
|
|
|
|
|
$this->apiError('帐号或密码错误');
|
|
|
|
|
}
|
|
|
|
|
if ($user['status'] == -1) {
|
|
|
|
|
$this->apiError('该用户禁止登录,请于平台联系');
|
|
|
|
|
}
|
|
|
|
|
$data = [
|
|
|
|
|
'last_login_time' => time(),
|
|
|
|
|
'last_login_ip' => request()->ip(),
|
|
|
|
|
'login_num' => $user['login_num'] + 1,
|
|
|
|
|
];
|
|
|
|
|
$res = Db::name('Admin')->where(['id' => $user['id']])->update($data);
|
|
|
|
|
if ($res) {
|
|
|
|
|
$token = self::getToken($user['id']);
|
|
|
|
|
$this->apiSuccess('登录成功', ['token' => $token]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function userinfo(Request $request)
|
|
|
|
|
{
|
|
|
|
|
$uid = $this->uid;
|
|
|
|
|
$userInfo = Db::name('Admin')->where(['id' => $uid])->find();
|
|
|
|
|
$this->apiSuccess('请求成功', ['user' => $userInfo]);
|
|
|
|
|
}
|
|
|
|
|
}
|