php管理和接口
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.
 
 
 
 
 
 

117 lines
3.3 KiB

<?php
declare (strict_types=1);
namespace app\api\service;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use DateTimeImmutable;
use Lcobucci\JWT\Token\Plain;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
/**
* 用户表
*/
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;
}
/**
* 根据uid,nick_name 换取JWT
* @param int $userId
* @param string $uname
* @return string
* @throws \Exception
*/
public function getToken(int $userId,string $uname): string
{
static $token = '';
if (empty($token)) {
$token = $this->makeToken($userId,$uname);
}
return $token;
}
/**
* 生成JWT
* @param int $userId
* @param string $uname
* @return string
* @throws \Exception
*/
private function makeToken(int $userId,string $uname): string
{
$signer = new Sha256();
$key = InMemory::plainText(config('jwt.secret'));
//
$config = Configuration::forSymmetricSigner($signer,$key);
$now = new DateTimeImmutable(); // 当前时间
//
$token = $config->builder()
// 签发人
->issuedBy('https://douyin.xingtongworld.com/')
// 受众
->permittedFor('https://douyin.xingtongworld.com/')
// JWT ID 编号 唯一标识
->identifiedBy($userId)
// 签发时间
->issuedAt($now)
// 在1分钟后才可使用
// ->canOnlyBeUsedAfter($now->modify('+1 minute'))
// 过期时间1小时
->expiresAt($now->modify('+1 hour'))
// 自定义uid 额外参数
->withClaim('uid', $userId)
->withClaim('name',$uname)
// 自定义header 参数
// ->withHeader('foo', 'bar')
// 生成token
->getToken($config->signer(), $config->signingKey());
return $token->toString();
}
}