Added user API key system

This commit is contained in:
Matthew Barbour
2020-06-16 19:03:03 -05:00
committed by Shish
parent ea34d9b756
commit 919a3039c4
6 changed files with 160 additions and 39 deletions

View File

@ -21,7 +21,18 @@ class InitUserConfigEvent extends Event
class UserConfig extends Extension
{
private const VERSION = "ext_user_config_version";
/** @var UserConfigTheme */
protected $theme;
public const VERSION = "ext_user_config_version";
public const ENABLE_API_KEYS = "ext_user_config_enable_api_keys";
public const API_KEY = "api_key";
public function onInitExt(InitExtEvent $event)
{
global $config;
$config->set_default_bool(self::ENABLE_API_KEYS, false);
}
public function onUserLogin(UserLoginEvent $event)
{
@ -49,6 +60,66 @@ class UserConfig extends Extension
}
}
public function onPageRequest(PageRequestEvent $event)
{
global $user, $database, $config, $page;
if ($config->get_bool(self::ENABLE_API_KEYS)) {
if (!empty($_GET["api_key"]) && $user->is_anonymous()) {
$user_id = $database->get_one(
"SELECT user_id FROM user_config WHERE value=:value AND name=:name",
["value" => $_GET["api_key"], "name" => self::API_KEY]
);
if (!empty($user_id)) {
$user = User::by_id($user_id);
if ($user !== null) {
send_event(new UserLoginEvent($user));
}
}
}
global $user_config;
if ($event->page_matches("user_admin")) {
if (!$user->check_auth_token()) {
return;
}
switch ($event->get_arg(0)) {
case "reset_api_key":
$user_config->set_string(self::API_KEY, "");
$page->set_mode(PageMode::REDIRECT);
$page->set_redirect(make_link("user"));
break;
}
}
}
}
public function onUserOptionsBuilding(UserOptionsBuildingEvent $event)
{
global $config, $user_config;
if ($config->get_bool(self::ENABLE_API_KEYS)) {
$key = $user_config->get_string(self::API_KEY, "");
if (empty($key)) {
$key = generate_key();
$user_config->set_string(self::API_KEY, $key);
}
$event->add_html($this->theme->get_user_options($key));
}
}
public function onSetupBuilding(SetupBuildingEvent $event)
{
$sb = new SetupBlock("User Options");
$sb->start_table();
$sb->end_table();
$event->panel->add_block($sb);
}
// This needs to happen before any other events, but after db upgrade
public function get_priority(): int