You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.6 KiB
96 lines
2.6 KiB
<?php
|
|
declare (strict_types=1);
|
|
namespace app\api\service;
|
|
|
|
use app\api\model\User;
|
|
use Lcobucci\JWT\Parser;
|
|
use Lcobucci\JWT\Builder;
|
|
use Lcobucci\JWT\Signer\Hmac\Sha256;
|
|
use Lcobucci\JWT\Signer\Key\InMemory;
|
|
use Lcobucci\JWT\Token;
|
|
/**
|
|
* 用户表
|
|
*/
|
|
class UserService {
|
|
public function mktoken(){
|
|
// jwt
|
|
$guid = get_guid_v4();
|
|
$dtime = time();
|
|
return md5(uniqid($guid.$dtime,true));
|
|
}
|
|
/**
|
|
* 用户登录操作,传入用户查询后才对比密码
|
|
*/
|
|
public function login(string $uname,string $pass){
|
|
// query db
|
|
$drs = User::where(['nick_name'=>$uname,'delete_time'=>0])->find();
|
|
// 异常处理
|
|
if(!isset($drs)){
|
|
throwError('用户不存在');
|
|
return -1;
|
|
}else{
|
|
$fpass = password($pass.$drs['salt']);
|
|
// 对比密码
|
|
if($drs['password'] != $fpass){
|
|
throwError('密码错误');
|
|
return false;
|
|
}
|
|
// 返回用户信息
|
|
return $drs;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* @param array $arr
|
|
* @return bool
|
|
*/
|
|
public function register(array $arr){
|
|
$salt = makeSalt(6);
|
|
// 密码加密
|
|
$arr['password'] = password($arr['password'].$salt);
|
|
// 生成salt
|
|
$arr['salt'] = $salt;
|
|
$dtime =time();
|
|
$arr['create_time'] = $dtime;
|
|
$arr['update_time'] = $dtime;
|
|
// 保存
|
|
$model = new User;
|
|
$uid = $model->save($arr);
|
|
return isset($uid)?true:false;
|
|
}
|
|
|
|
/**
|
|
* 获取登录的token
|
|
* @param int $userId
|
|
* @return string
|
|
*/
|
|
public function getToken(int $userId): string
|
|
{
|
|
static $token = '';
|
|
if (empty($token)) {
|
|
$token = $this->makeToken($userId);
|
|
}
|
|
return $token;
|
|
}
|
|
/**
|
|
* 生成用户认证的token
|
|
* @param int $userId
|
|
* @return string
|
|
*/
|
|
private function makeToken(int $userId): string
|
|
{
|
|
$signer = new Sha256();
|
|
$key = InMemory::plainText(config('jwt.secret'));
|
|
//
|
|
$config = Configuration::forSymmetricSigner($signer,$key);
|
|
$now = new DateTimeImmutable(); // 当前时间
|
|
//
|
|
$token = $config->builder()
|
|
->issuedAt($now) // iat: 发行时间
|
|
->expiresAt($now->add(new \DateInterval('PT' . config('jwt.token_ttl') . 'S'))) // exp: 过期时间
|
|
->withClaim('user_id', $userId) // 自定义声明
|
|
->getToken($config->signer(), $config->signingKey()); // 签名
|
|
return $token->toString();
|
|
}
|
|
}
|