Compare commits

...
Sign in to create a new pull request.

3 commits
master ... api

Author SHA1 Message Date
Petr Bena
e2a3a5d776 implemented api list 2019-04-03 16:49:46 +02:00
Petr Bena
0bee4e4ad1 implemented list zones 2019-04-03 16:29:17 +02:00
Petr Bena
c8352777ae initial api 2019-04-01 11:04:43 +02:00
10 changed files with 295 additions and 28 deletions

179
api.php Normal file
View file

@ -0,0 +1,179 @@
<?php
// This program 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.
// This program 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.
// This is useful for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
define('G_DNSTOOL_ENTRY_POINT', 'api.php');
require("definitions.php");
require("config.default.php");
require("config.php");
require("includes/record_list.php");
require("includes/zone_list.php");
require("includes/login.php");
require_once("psf/psf.php");
if ($g_api_enabled !== true)
die('API subsystem is disabled, change $g_api_enabled to true in your config.php file to enable this');
function print_result($result)
{
global $api;
$result = [ 'result' => 'success' ];
$api->PrintObj($result);
}
function print_success()
{
print_result('success');
}
function api_call_login($api)
{
global $api, $g_login_failed, $g_login_failure_reason;
ProcessLogin();
if ($g_login_failed)
{
$api->ThrowError("Login failed", $g_login_failure_reason);
return true;
}
print_success();
return true;
}
function api_call_logout($api)
{
session_unset();
print_success();
return true;
}
function api_call_login_token($api)
{
global $api, $g_login_failed, $g_login_failure_reason;
if (!isset($_POST['token']))
{
$api->ThrowError('No token', 'You need to provide a token');
return true;
}
ProcessTokenLogin();
if ($g_login_failed)
{
$api->ThrowError("Login failed", $g_login_failure_reason);
return true;
}
print_success();
return true;
}
function api_call_list($api)
{
global $api;
$api->PrintObj(GetZoneList());
return true;
}
function api_call_list_records($api)
{
global $api, $g_domains;
$zone = NULL;
if (isset($_GET['zone']))
$zone = $_GET['zone'];
else if (isset($_POST['zone']))
$zone = $_POST['zone'];
else
$api->ThrowError('No zone', 'You provided no zone name to list records for');
if (!array_key_exists($zone, $g_domains))
$api->ThrowError('No such zone', 'This zone is not in configuration file');
$api->PrintObj(GetRecordList($zone));
return true;
}
function api_call_is_logged($api)
{
global $api, $g_auth_roles_map;
$logged = is_authenticated($api->AuthenticationBackend);
$result = [ 'is_logged' => $logged ];
if ($logged)
{
$result['user'] = $_SESSION['user'];
if ($g_auth_roles_map !== NULL && array_key_exists($_SESSION['user'], $g_auth_roles_map))
$result['role'] = implode (',', $g_auth_roles_map[$_SESSION['user']]);
}
$api->PrintObj($result);
return true;
}
function register_api($name, $short_desc, $long_desc, $callback, $auth = true, $required_params = [], $optional_params = [], $example = NULL, $post_only = false)
{
global $api;
$call = new PsfApi($name, $callback, $short_desc, $long_desc, $required_params, $optional_params);
$call->Example = $example;
$call->RequiresAuthentication = $auth;
$call->POSTOnly = $post_only;
$api->RegisterAPI_Action($call);
return $call;
}
function is_authenticated($backend)
{
global $api, $g_login_failed, $g_login_failure_reason;
$require_login = RequireLogin();
if (!$require_login)
return true;
if ($require_login && !isset($_POST['token']))
return false;
// User is not logged in, but provided a token, let's validate it
ProcessTokenLogin();
if ($g_login_failed)
{
$api->ThrowError("Login failed", $g_login_failure_reason);
return false;
}
return true;
}
function is_privileged($backend, $privilege)
{
return true;
}
RefreshSession();
$api = new PsfApiBase_JSON();
$api->ExamplePrefix = "/api.php";
$api->AuthenticationBackend = new PsfCallbackAuth($api);
$api->AuthenticationBackend->callback_IsAuthenticated = "is_authenticated";
$api->AuthenticationBackend->callback_IsPrivileged = "is_privileged";
register_api("is_logged", "Returns information whether you are currently logged in, or not", "Returns information whether you are currently logged in or not.", "api_call_is_logged", false, [], [], '?action=is_logged');
register_api("login", "Logins via username and password", "Login into API via username and password using exactly same login method as index.php. This API can be only accessed via POST method", "api_call_login", false,
[ new PsfApiParameter("loginUsername", PsfApiParameterType::String, "Username to login"), new PsfApiParameter("loginPassword", PsfApiParameterType::String, "Password") ],
[], '?action=login', true);
register_api("logout", "Logs you out", "Logs you out and clear your session data", "api_call_logout", true, [], [], '?action=logout');
register_api("login_token", "Logins via token", "Login into API via application token", "api_call_login_token", false,
[ new PsfApiParameter("token", PsfApiParameterType::String, "Token that is used to login with") ],
[], '?action=login_token&token=123ngfshegkernker5', true);
register_api("list_zones", "List all existing zones that you have access to", "List all existing zones that you have access to.", "api_call_list", true,
[], [], '?action=list_zones');
register_api("list_records", "List all existing records for a specified zone", "List all existing records for a specified zone", "api_call_list_records", true,
[ new PsfApiParameter("zone", PsfApiParameterType::String, "Zone to list records for") ],
[], '?action=list_records&zone=domain.org');
$api->Process();

View file

@ -91,3 +91,10 @@ $g_use_local_bootstrap = false;
// For this to work download compressed jquery 3.3.1 to root folder for example:
// /jquery-3.3.1.min.js
$g_use_local_jquery = false;
// Whether API interface is available or not
$g_api_enabled = false;
// List of access tokens that can be used with API calls (together with classic login)
// This is a simple list of secrets. Each secret is a string that is used to authenticate for API subsystem.
$g_api_tokens = [ ];

View file

@ -47,7 +47,7 @@ function WriteToAuditFile($operation, $text)
// Prepare audit log line
$log_line = date('m/d/Y h:i:s a', time());
$log_line .= " user: " . GetCurrentUserName() . " ip: " . $_SERVER['REMOTE_ADDR'] . " operation: " . $operation . " record: " . $text . "\n";
$log_line .= ' entry point: ' . G_DNSTOOL_ENTRY_POINT . ' user: ' . GetCurrentUserName() . " ip: " . $_SERVER['REMOTE_ADDR'] . " operation: " . $operation . " record: " . $text . "\n";
$my_file = $g_audit_log;
$handle = fopen($my_file, 'a') or die('Cannot open file: ' . $my_file);

View file

@ -34,7 +34,7 @@ function IsEditable($domain)
function LoginRequired()
{
global $g_auth;
if ($g_auth === NULL || $g_auth !== "ldap")
if ($g_auth === NULL || $g_auth !== 'ldap')
return false;
return true;
}
@ -47,9 +47,9 @@ function IsAuthorized($domain, $privilege)
return true;
$roles = [ $g_auth_default_role ];
$user = $_SESSION["user"];
if ($user === NULL || $user === "")
Error("Invalid username in session");
$user = $_SESSION['user'];
if ($user === NULL || $user === '')
Error('Invalid username in session');
if (array_key_exists($user, $g_auth_roles_map))
$roles = $g_auth_roles_map[$user];

View file

@ -41,25 +41,60 @@ function RefreshSession()
function GetLoginInfo()
{
global $g_auth_roles_map;
$role_info = "";
if ($g_auth_roles_map !== NULL && array_key_exists($_SESSION["user"], $g_auth_roles_map))
$role_info = '';
if ($g_auth_roles_map !== NULL && array_key_exists($_SESSION['user'], $g_auth_roles_map))
{
$role_info = ' (' . implode (", ", $g_auth_roles_map[$_SESSION["user"]]) . ')';
$role_info = ' (' . implode (', ', $g_auth_roles_map[$_SESSION['user']]) . ')';
}
return '<div class="login_info"><span class="glyphicon glyphicon-user"></span>' . $_SESSION["user"] . $role_info . ' <a href="?logout">logout</a></div>';
}
function ProcessLogin_Error($reason)
{
global $g_login_failure_reason, $g_login_failed;
$g_login_failed = true;
$g_login_failure_reason = $reason;
$_SESSION['logged_in'] = false;
}
function ProcessTokenLogin()
{
global $g_auth, $g_login_failed, $g_api_tokens;
if (!isset($_POST['token']))
{
ProcessLogin_Error("No token");
return;
}
$token = $_POST['token'];
if (in_array($token, $g_api_tokens))
{
$_SESSION["user"] = $token;
$_SESSION["logged_in"] = true;
$g_logged_in = true;
return;
}
// Invalid token
$g_login_failed = true;
$_SESSION["logged_in"] = false;
}
function ProcessLogin()
{
global $g_auth, $g_auth_ldap_url, $g_login_failure_reason, $g_login_failed, $g_auth_allowed_users;
global $g_auth, $g_auth_ldap_url, $g_login_failed, $g_auth_allowed_users;
// We support LDAP at this moment only
if ($g_auth != "ldap")
Error("Unsupported authentication mechanism");
{
ProcessLogin_Error("Unsupported authentication mechanism");
return;
}
// Check if we have the credentials
if (!isset($_POST["loginUsername"]) || !isset($_POST["loginPassword"]))
Error("No credentials provided");
{
ProcessLogin_Error("No credentials provided");
return;
}
$ldap = ldap_connect($g_auth_ldap_url);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
@ -71,9 +106,7 @@ function ProcessLogin()
// Check if this user is allowed to login
if (!in_array($_POST["loginUsername"], $g_auth_allowed_users))
{
$g_login_failure_reason = "This user is not allowed to login to this tool (username not present in config.php)";
$g_login_failed = true;
$_SESSION["logged_in"] = false;
ProcessLogin_Error("This user is not allowed to login to this tool (username not present in config.php)");
return;
}
}

View file

@ -42,7 +42,7 @@ function ProcessNSUpdateForDomain($input, $domain)
function ShowError($form, $txt)
{
$msg = new BS_Alert("FATAL: " . $txt, "danger", $form);
$msg = new BS_Alert('FATAL: ' . $txt, 'danger', $form);
}
function Check($form, $label, $name)

View file

@ -67,6 +67,8 @@ function GetStatusOfZoneAsNote($domain)
function GetRecordList($domain)
{
$records = array();
if (!IsAuthorizedToRead($domain))
return $records;
$data = explode("\n", get_zone_data($domain));
foreach ($data as $line)
{
@ -93,8 +95,6 @@ function GetRecordListTable($parent, $domain)
$table->SetColumnWidth(2, '80px'); // Scope
$table->SetColumnWidth(3, '80px'); // Type
$table->SetColumnWidth(5, '80px'); // Options
if (!IsAuthorizedToRead($domain))
return $table;
$records = GetRecordList($domain);
$is_editable = IsEditable($domain) && IsAuthorizedToWrite($domain);
foreach ($records as $record)

42
includes/zone_list.php Normal file
View file

@ -0,0 +1,42 @@
<?php
// This program 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.
// This program 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.
// Security check
if (!defined('G_DNSTOOL_ENTRY_POINT'))
die("Not a valid entry point");
require_once("psf/psf.php");
require_once("common.php");
require_once("config.php");
function GetZoneList()
{
global $g_domains;
$result = [];
foreach ($g_domains as $domain => $properties)
{
if (!IsAuthorizedToRead($domain))
continue;
$result[$domain] = [ 'domain' => $domain, 'update_server' => $properties['update_server'], 'transfer_server' => $properties['transfer_server'] ];
if (isset($properties['in_transfer']))
$result[$domain]['in_transfer'] = $properties['in_transfer'];
if (isset($properties['maintenance_note']))
$result[$domain]['maintenance_note'] = $properties['maintenance_note'];
if (isset($properties['read_only']))
$result[$domain]['read_only'] = $properties['read_only'];
}
return $result;
}

View file

@ -10,6 +10,12 @@
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// This is useful for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Register index.php as valid entry point
define('G_DNSTOOL_ENTRY_POINT', 'index.php');
require("definitions.php");
@ -25,8 +31,8 @@ require_once("psf/psf.php");
if ($g_use_local_bootstrap)
{
// Use local bootstrap
$psf_bootstrap_js_url = "bootstrap-3.3.7/dist/js/bootstrap.min.js";
$psf_bootstrap_css_url = "bootstrap-3.3.7/dist/css/bootstrap.min.css";
$psf_bootstrap_js_url = 'bootstrap-3.3.7/dist/js/bootstrap.min.js';
$psf_bootstrap_css_url = 'bootstrap-3.3.7/dist/css/bootstrap.min.css';
}
RefreshSession();
@ -39,7 +45,7 @@ $g_selected_domain = null;
$g_action = null;
$website = new HtmlPage("DNS management");
$website->ExternalCss[] = "style.css";
$website->ExternalCss[] = 'style.css';
if (!$g_use_local_jquery)
$website->ExternalJs[] = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
else
@ -50,29 +56,29 @@ bootstrap_init($website);
$fc = new BS_FluidContainer($website);
if (isset($_GET["login"]))
if (isset($_GET['login']))
ProcessLogin();
if (isset($_GET["logout"]))
if (isset($_GET['logout']))
session_unset();
if (isset($_GET['action']))
$g_action = $_GET['action'];
if (isset($_GET['domain']))
$g_selected_domain = $_GET['domain'];
else if (isset($_POST["zone"]))
$g_selected_domain = $_POST["zone"];
else if (isset($_POST['zone']))
$g_selected_domain = $_POST['zone'];
// Check if login is needed
if (RequireLogin())
{
$fc->AppendHeader("Login to DNS management tool");
$fc->AppendHeader('Login to DNS management tool');
if ($g_login_failed)
$fc->AppendObject(new BS_Alert($g_login_failure_reason, "danger"));
$fc->AppendObject(new BS_Alert($g_login_failure_reason, 'danger'));
$fc->AppendObject(GetLogin());
} else
{
$fc->AppendHeader("DNS management tool");
$fc->AppendHeader('DNS management tool');
if ($g_logged_in)
$fc->AppendHtml(GetLoginInfo());
if (isset($_GET['action']))

2
psf

@ -1 +1 @@
Subproject commit a1c41215c16815110065f940782b3e9f6e4553d4
Subproject commit 969878a756ef623e1a9b820d2d6f3a91cada0135