ApiAuthenticate.php
1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
namespace App\Http\Middleware;
use App\Modules\Enums\ErrorCode;
use App\Exceptions\Api\ApiException;
use App\Modules\Enums\LanguageType;
use App\Util\AuthUtil;
use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
/**
* Class ApiAuthenticate
* @package App\Http\Middleware
*/
class ApiAuthenticate
{
/**
* @param $request
* @param Closure $next
* @param null $guard
* @return mixed
* @throws ApiException
*/
//TODO:check whether user already disabled
public function handle($request, Closure $next, $guard = 'api')
{
if (! $token = Auth::setRequest($request)->getToken()) {
throw new ApiException(ErrorCode::TOKEN_NOT_PROVIDED, trans("api.error.token_not_provide"), array());
}
try {
$payload = AuthUtil::checkOrFail($guard);
} catch (TokenExpiredException $e) {
throw new ApiException(ErrorCode::TOKEN_EXPIRE, trans("api.error.token_expire"), array());
} catch (JWTException $e) {
throw new ApiException(ErrorCode::TOKEN_INVALID, trans("api.error.token_invalid"), array());
}
if (! $payload) {
throw new ApiException(ErrorCode::USER_NOT_EXIST, trans("api.error.user_not_exist"), array());
}
$user = Auth::guard($guard)->User();
if($guard == 'api'){
//设置用户默认语言
app('translator')->setLocale(LanguageType::get($user->language));
}else{
$data = ['user'=> $user];
$request->merge($data);
}
return $next($request);
}
}