3 namespace BookStack\Api;
5 use BookStack\Exceptions\ApiAuthException;
6 use Illuminate\Auth\GuardHelpers;
7 use Illuminate\Contracts\Auth\Authenticatable;
8 use Illuminate\Contracts\Auth\Guard;
9 use Illuminate\Support\Facades\Hash;
10 use Symfony\Component\HttpFoundation\Request;
12 class ApiTokenGuard implements Guard
18 * The request instance.
24 * The last auth exception thrown in this request.
25 * @var ApiAuthException
27 protected $lastAuthException;
30 * ApiTokenGuard constructor.
32 public function __construct(Request $request)
34 $this->request = $request;
41 public function user()
43 // Return the user if we've already retrieved them.
44 // Effectively a request-instance cache for this method.
45 if (!is_null($this->user)) {
51 $user = $this->getAuthorisedUserFromRequest();
52 } catch (ApiAuthException $exception) {
53 $this->lastAuthException = $exception;
61 * Determine if current user is authenticated. If not, throw an exception.
63 * @return \Illuminate\Contracts\Auth\Authenticatable
65 * @throws ApiAuthException
67 public function authenticate()
69 if (! is_null($user = $this->user())) {
73 if ($this->lastAuthException) {
74 throw $this->lastAuthException;
77 throw new ApiAuthException('Unauthorized');
81 * Check the API token in the request and fetch a valid authorised user.
82 * @throws ApiAuthException
84 protected function getAuthorisedUserFromRequest(): Authenticatable
86 $authToken = trim($this->request->headers->get('Authorization', ''));
87 if (empty($authToken)) {
88 throw new ApiAuthException(trans('errors.api_no_authorization_found'));
91 if (strpos($authToken, ':') === false || strpos($authToken, 'Token ') !== 0) {
92 throw new ApiAuthException(trans('errors.api_bad_authorization_format'));
95 [$id, $secret] = explode(':', str_replace('Token ', '', $authToken));
96 $token = ApiToken::query()
97 ->where('token_id', '=', $id)
98 ->with(['user'])->first();
100 if ($token === null) {
101 throw new ApiAuthException(trans('errors.api_user_token_not_found'));
104 if (!Hash::check($secret, $token->secret)) {
105 throw new ApiAuthException(trans('errors.api_incorrect_token_secret'));
108 if (!$token->user->can('access-api')) {
109 throw new ApiAuthException(trans('errors.api_user_no_api_permission'), 403);
118 public function validate(array $credentials = [])
120 if (empty($credentials['id']) || empty($credentials['secret'])) {
124 $token = ApiToken::query()
125 ->where('token_id', '=', $credentials['id'])
126 ->with(['user'])->first();
128 if ($token === null) {
132 return Hash::check($credentials['secret'], $token->secret);