<?php
namespace App\Contracts;
/**
* 处理Token的Contracts
* @package App\Contracts
*/
interface TokenHandler
{
/**
* 创建一个token
* @param $userId integer 用户Id
* @return string
*/
public function createToken($userId);
/**
* 得到该token的用户
* @param $token string token值
* @return \App\User 拥有该token的用户
*/
public function getTokenUser($token);
/**
* 删除一个token
* @param $token string token值
* @return bool 是否成功
*/
public function removeToken($token);
}
<?php
namespace App\Services;
use App\Contracts\TokenHandler;
use App\Orm\Token;
/**
* 处理Token的Contracts对应的Mysql Service
* @package App\Services
*/
class MysqlTokenHandler implements TokenHandler
{
/**
* @var int 一个用户能够拥有的token最大值
*/
protected $userTokensMax = 10;
/**
* @inheritdoc
*/
public function createToken($userId)
{
while (Token::where('user_id', $userId)->count() >= $this->userTokensMax) {
Token::where('user_id', $userId)->orderBy('updated_at', 'asc')->first()->delete();
}
$token = \Illuminate\Support\Str::random(32);
if (!Token::create(['token' => $token, 'user_id' => $userId])) {
return false;
}
return $token;
}
/**
* @inheritdoc
*/
public function getTokenUser($token)
{
$tokenObject = Token::where('token', $token)->first();
return $tokenObject && $tokenObject->user ? $tokenObject->user : false;
}
/**
* @inheritdoc
*/
public function removeToken($token)
{
return Token::find($token)->delete();
}
}
$app->singleton( App\Contracts\TokenHandler::class, App\Services\MysqlTokenHandler::class );
public function logout(Request $request, TokenHandler $tokenHandler)
{
if ($tokenHandler->removeToken($request->input('api_token'))) {
return $this->success([]);
} else {
return $this->error(Lang::get('messages.logout_fail'));
}
}
$currentUser = app(\App\Contracts\TokenHandler::class)->getTokenUser($request->input('api_token'));
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有