2023-01-29 10:26:52 +08:00

106 lines
2.6 KiB
PHP

<?php
namespace app\api\service;
use app\api\exception\ApiException;
use app\common\repository\UserReposotpry;
use app\common\exception\EnumCode;
use Firebase\JWT\JWT;
use think\Cache;
class UserService
{
private $userReposotpry;
public function __construct()
{
$this->userReposotpry = new UserReposotpry;
}
/**
* 注册过程 function
*
* @author dotdotdot <6383846@qq.com>
* @date 2022-08-06
* @param array $params
* @return array
*/
public function register(array $params)
{
$phone = $params['phone'];
$passWord = md5($params['phone'] . $params['password']);
$userFields = ['uid'];
$userData = $this->userReposotpry->selectByPhone($userFields, $phone);
if (!empty($userData)) {
throw new ApiException('账号已存在', EnumCode::UserIsExist);
}
$userInsertData = [
'phone' => $phone,
'password' => $passWord
];
if (!$this->userReposotpry->insert($userInsertData)) {
throw new ApiException('系统异常,请稍后再试!', EnumCode::ServiceError);
}
}
/**
* 登录过程 function
*
* @author dotdotdot <6383846@qq.com>
* @date 2022-08-06
* @param array $params
* @return array
*/
public function login(array $params)
{
$phone = $params['phone'];
$passWord = md5($params['phone'] . $params['password']);
$userFields = ['uid', 'password'];
$userData = $this->userReposotpry->selectByPhone($userFields, $phone);
if (empty($userData)) {
throw new ApiException('用户不存在', EnumCode::UserNotExist);
}
if ($passWord != $userData['password']) {
throw new ApiException('账号或密码错误', EnumCode::PassWordError);
}
$issuedAtTime = time();
$expirationTime = $issuedAtTime + config('jwt.expiration_time');
$payLoad = [
'iat' => $issuedAtTime,
'exp' => $expirationTime,
'data' => [
'uid' => $userData['uid']
]
];
$jwt = JWT::encode($payLoad, config('jwt.key'), config('jwt.sign_type'));
$preFix = config('jwt.pre_fix') . $userData['uid'];
if (!Cache::set($preFix, $jwt, config('jwt.expiration_time'))) {
throw new ApiException('系统异常,请稍后再试!', EnumCode::ServiceError);
}
return [
'uid' => $userData['uid'],
'iat' => $issuedAtTime,
'exp' => $expirationTime,
'token' => $jwt
];
}
}