Commit e43b86d7 authored by 王源's avatar 王源 🎧

添加当前用户相关方法

parent 8ce6d0b6
<?php
/**
* Created by PhpStorm.
* User: zero
* Date: 2020/3/17
*/
namespace Meibuyu\Micro\Exceptions;
use Throwable;
class ObjectNotExistException extends \Exception
{
public function __construct($message, $code = 0, Throwable $previous = null)
{
parent::__construct($message . ' Not Exist!', $code, $previous);
}
}
\ No newline at end of file
<?php
namespace Meibuyu\Micro\Model;
use Hyperf\Utils\Context;
use Meibuyu\Micro\Exceptions\ObjectNotExistException;
class Auth
{
/**
* @return bool|mixed|string|null
* @throws ObjectNotExistException
*/
private static function init()
{
if (Context::has('auth')) {
return Context::get('auth');
} else {
$token = token();
if (!$token) throw new ObjectNotExistException('Token');
$auth = redis()->get($token);
if ($auth) {
$auth = json_decode($auth, true);
Context::set('auth', $auth);
return $auth;
} else {
throw new ObjectNotExistException('User');
}
}
}
/**
* @return object
* @throws ObjectNotExistException
*/
public static function user()
{
return self::init();
}
/**
* @return integer
* @throws ObjectNotExistException
*/
public static function id()
{
return self::init()['id'];
}
}
......@@ -18,16 +18,36 @@ if (!function_exists('container')) {
}
}
/**
* redis 客户端实例
*/
if (!function_exists('redis')) {
/**
* 获取redis客户端实例
* @return Redis|mixed
*/
function redis()
{
return container(Redis::class);
}
}
/**
* token
*/
if (!function_exists('token')) {
function token()
{
$token = request()->getHeader('Authorization')[0] ?? '';
if (strlen($token) > 0) {
$token = ucfirst($token);
$arr = explode('Bearer ', $token);
$token = $arr[1] ?? '';
if (strlen($token) > 0) {
return $token;
}
}
return false;
}
}
if (!function_exists('request')) {
/**
* 请求实例
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment