Files
firefly-iii/app/Console/Commands/VerifiesAccessToken.php

79 lines
2.3 KiB
PHP
Raw Normal View History

<?php
/**
* VerifiesAccessToken.php
2018-05-11 10:08:34 +02:00
* Copyright (c) 2018 thegrumpydictator@gmail.com
*
2017-10-21 08:40:00 +02:00
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2017-12-17 14:41:58 +01:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
2018-05-11 10:08:34 +02:00
declare(strict_types=1);
namespace FireflyIII\Console\Commands;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
2017-09-16 07:41:03 +02:00
/**
2017-11-15 12:25:49 +01:00
* Trait VerifiesAccessToken.
2017-09-16 07:41:03 +02:00
*
* Verifies user access token for sensitive commands.
*/
trait VerifiesAccessToken
{
2017-09-16 07:17:58 +02:00
/**
2017-09-16 07:41:03 +02:00
* Abstract method to make sure trait knows about method "option".
2017-10-05 11:49:06 +02:00
*
2018-01-25 18:41:27 +01:00
* @param string|null $key
2017-09-16 07:17:58 +02:00
*
* @return mixed
*/
abstract public function option($key = null);
/**
2017-09-16 07:41:03 +02:00
* Returns false when given token does not match given user token.
*
* @return bool
*/
protected function verifyAccessToken(): bool
{
2018-03-30 14:50:44 +02:00
$userId = (int)$this->option('user');
$token = (string)$this->option('token');
/** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class);
$user = $repository->findNull($userId);
2018-01-25 18:41:27 +01:00
if (null === $user) {
Log::error(sprintf('verifyAccessToken(): no such user for input "%d"', $userId));
return false;
}
2018-07-15 09:27:38 +02:00
$accessToken = app('preferences')->getForUser($user, 'access_token', null);
2017-11-15 12:25:49 +01:00
if (null === $accessToken) {
Log::error(sprintf('User #%d has no access token, so cannot access command line options.', $userId));
return false;
}
if (!($accessToken->data === $token)) {
Log::error(sprintf('Invalid access token for user #%d.', $userId));
2018-03-30 14:50:44 +02:00
Log::error(sprintf('Token given is "%s", expected something else.', $token));
return false;
}
return true;
}
2017-11-08 09:05:10 +01:00
}