Auth.php 1.06 KB
Newer Older
1 2 3 4 5
<?php

namespace Meibuyu\Micro\Model;

use Hyperf\Utils\Context;
6
use Meibuyu\Micro\Exceptions\HttpResponseException;
7 8 9

class Auth
{
10

11 12
    /**
     * @return bool|mixed|string|null
13
     * @throws HttpResponseException
14 15 16
     */
    private static function init()
    {
17
        if (Context::has('auth')) {
18 19 20
            return Context::get('auth');
        } else {
            $token = token();
21
            if (!$token) throw new HttpResponseException('Token不存在');
22 23 24 25 26 27
            $auth = redis()->get($token);
            if ($auth) {
                $auth = json_decode($auth, true);
                Context::set('auth', $auth);
                return $auth;
            } else {
28
                throw new HttpResponseException('用户不存在');
29 30 31 32 33 34
            }
        }
    }

    /**
     * @return object
35
     * @throws HttpResponseException
36 37 38 39 40 41 42 43
     */
    public static function user()
    {
        return self::init();
    }

    /**
     * @return integer
44
     * @throws HttpResponseException
45 46 47 48 49 50 51
     */
    public static function id()
    {
        return self::init()['id'];
    }

}