You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB
PHP

<?php
namespace Isekai\AIToolbox\Api\AIToolbox;
use ApiBase;
use Config;
use Isekai\AIToolbox\Api\ApiAIToolbox;
use MediaWiki\MediaWikiServices;
use Firebase\JWT\JWT;
class ApiCreateToken extends ApiBase {
/** @var MediaWikiServices */
private $services;
/** @var Config */
private $config;
/** @var ApiAIToolbox */
private $mParent;
public function __construct(ApiAIToolbox $main, $method) {
parent::__construct($main->getMain(), $method);
$this->mParent = $main;
$this->services = MediaWikiServices::getInstance();
$this->config = $this->getConfig();
}
public function execute() {
$user = $this->getUser();
if (!$user->isRegistered()) {
$this->addError('apierror-isekai-ai-toolbox-nopermission', 'nopermission');
return false;
}
$result = $this->getResult();
$permissionMap = ApiAIToolbox::$permissionMap;
$permissions = [];
foreach ($permissionMap as $key => $permissionKey) {
if ($user->isAllowed($permissionKey)) {
$permissions[] = $key;
}
}
// if (!$user->isAllowedAny(...array_values($permissionMap))) {
// $this->addError('apierror-isekai-ai-toolbox-nopermission', 'nopermission');
// return false;
// }
// Create JWT
$tokenId = $this->config->get('IsekaiAIToolboxTokenId');
$token = $this->config->get('IsekaiAIToolboxToken');
$currentTime = time();
$expireTime = $currentTime + 86400; // 1 day
$payload = [
'iss' => 'mw-ai-toolbox',
'sub' => $user->getId(),
'userName' => $user->getName(),
'iat' => $currentTime,
'exp' => $expireTime,
'permissions' => $permissions,
];
$jwt = JWT::encode($payload, $token, 'HS256', $tokenId);
$result->addValue(['aitoolbox', $this->getModuleName()], 'token', $jwt);
return true;
}
public function getCacheMode($params) {
return 'private';
}
public function getParent() {
return $this->mParent;
}
public function needsToken() {
return 'csrf';
}
}