123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- <?php
- namespace app\common;
- use think\facade\Cache;
- class User {
- protected static $instance;
- protected $logined = false;
- protected $error='';
- protected $errorCode="0";
- protected $token = '';
- protected $userinfo=null;
- protected $keeptime=3600;
- //获取用户信息
- public function __get($name){
- return $this->userinfo ? $this->userinfo[$name] : null;
- }
-
- public function getErroCode()
- {
- return $this->errorCode ?: 1;
- }
-
- public function getError()
- {
- return $this->error ?: '';
- }
- public function setError($error): User
- {
- $this->error = $error;
- return $this;
- }
- /**
- * 获取会员Token
- * @return string
- */
- public function getToken(): string
- {
- return $this->token;
- }
- public function getUser()
- {
- return $this->userinfo;
- }
-
- public function init($token): bool
- {
- if($token==''){
- $this->setError('token参数不能为空');
- $this->setErrorCode('102');
- return false;
- }
- $tokenData = Cache::get('user:info:'.$token);
- if (!$tokenData) {
- $this->token= $token;
- $this->setError('用户信息已失效');
- $this->setErrorCode('102');
- return false;
- }
- if ($this->error) {
- return false;
- }
- $userId = intval($tokenData['id']);
- if ($userId > 0) {
- $this->userinfo = $tokenData?:null;
- return $this->loginSuccessful();
- }
- $this->setError('登录失败');
- return false;
-
- }
-
- public function checkToken(){
- return false;
- }
-
- public function setErrorCode(int $code):User
- {
-
- $this->errorCode=$code;
- return $this;
- }
-
- /**
- * 登录失败
- * @return bool
- */
- public function loginFailed(): bool
- {
- if (!$this->userinfo) {
- return false;
- }
-
- $this->token = '';
- $this->userinfo = null;
- $this->logined = false;
- return true;
- }
- public function checkUser(){
- if(!$this->userinfo) return false;
-
- return true;
- }
- public function LoginUserInfo($userInfo,$token="",$keepTime){
- $this->keeptime= $keepTime;
- $this->userinfo =$userInfo;
- $this->token = $token;
- return $this->loginSuccessful();
- }
- /** 刷新token有效期
- * 登录成功
- * @return bool
- */
- public function loginSuccessful(): bool
- {
- if (!$this->userinfo) {
- return false;
- }
- $this->logined = true;
- if ($this->token!='') {
- Cache::set("user:info:{$this->token}",$this->userinfo,$this->keeptime);
- }
- return true;
- }
-
- public static function instance(): User
- {
- if (is_null(self::$instance)) {
- self::$instance = new static();
- }
- return self::$instance;
- }
- //是否已经登录标识
- public function isLogin(): bool
- {
- return $this->logined;
- }
- }
|