From 32a7c50189b46058d53b8a1de6c2846a16f5e549 Mon Sep 17 00:00:00 2001 From: Tony Murray Date: Tue, 11 Sep 2018 07:51:35 -0500 Subject: [PATCH] Use Laravel authentication (#8702) * Use Laravel for authentication Support legacy auth methods Always create DB entry for users (segregate by auth method) Port api auth to Laravel restrict poller errors to devices the user has access to Run checks on every page load. But set a 5 minute (configurable) timer. Only run some checks if the user is an admin Move toastr down a few pixels so it isn't as annoying. Fix menu not loaded on laravel pages when twofactor is enabled for the system, but disabled for the user. Add two missing menu entries in the laravel menu Rewrite 2FA code Simplify some and verify code before applying Get http-auth working Handle legacy $_SESSION differently. Allows Auth::once(), etc to work. * Fix tests and mysqli extension check * remove duplicate Toastr messages * Fix new items * Rename 266.sql to 267.sql --- .../ActiveDirectoryAuthorizer.php | 30 --- LibreNMS/Authentication/Auth.php | 66 ------ LibreNMS/Authentication/AuthorizerBase.php | 180 +-------------- LibreNMS/Authentication/LdapAuthorizer.php | 15 -- LibreNMS/Authentication/LegacyAuth.php | 101 +++++++++ LibreNMS/Authentication/MysqlAuthorizer.php | 118 +++++++--- LibreNMS/Authentication/TwoFactor.php | 122 +--------- LibreNMS/IRCBot.php | 16 +- .../Interfaces/Authentication/Authorizer.php | 36 --- LibreNMS/ObjectCache.php | 2 +- adduser.php | 8 +- app/Checks.php | 46 ++-- app/Guards/ApiTokenGuard.php | 47 ++++ app/Http/Controllers/AjaxController.php | 2 + app/Http/Controllers/Auth/LoginController.php | 18 +- app/Http/Controllers/LegacyController.php | 4 + app/Http/Controllers/TwoFactorController.php | 204 +++++++++++++++++ app/Http/Kernel.php | 3 + app/Http/Middleware/LegacyExternalAuth.php | 48 ++++ .../Middleware/RedirectIfAuthenticated.php | 2 +- app/Http/Middleware/VerifyTwoFactor.php | 40 ++++ app/Http/ViewComposers/LayoutComposer.php | 61 +++++ app/Http/ViewComposers/MenuComposer.php | 2 +- app/Listeners/AuthEventListener.php | 75 +++++++ app/Models/ApiToken.php | 87 ++++++++ app/Models/Dashboard.php | 2 +- app/Models/Device.php | 48 ++++ app/Models/NotificationAttrib.php | 17 +- app/Models/User.php | 63 +++++- app/Models/UserPref.php | 128 +++++++++++ app/Models/UserWidget.php | 41 ++++ app/Providers/AppServiceProvider.php | 6 +- app/Providers/AuthServiceProvider.php | 26 ++- app/Providers/ComposerServiceProvider.php | 1 + app/Providers/EventServiceProvider.php | 6 +- app/Providers/LegacyUserProvider.php | 210 ++++++++++++++++++ .../TokenUserProvider.php} | 55 ++--- config/auth.php | 9 +- config/debugbar.php | 5 +- doc/Developing/Code-Structure.md | 2 +- html/ajax_dash.php | 4 +- html/ajax_form.php | 4 +- html/ajax_list.php | 4 +- html/ajax_listports.php | 4 +- html/ajax_ossuggest.php | 4 +- html/ajax_output.php | 4 +- html/ajax_rulesuggest.php | 4 +- html/ajax_search.php | 36 +-- html/ajax_table.php | 4 +- html/css/styles.css | 8 +- html/includes/api_functions.inc.php | 65 +++--- html/includes/authenticate.inc.php | 87 -------- html/includes/common/availability-map.inc.php | 10 +- html/includes/common/graylog.inc.php | 6 +- html/includes/common/server-stats.inc.php | 6 +- html/includes/common/top-devices.inc.php | 20 +- html/includes/common/top-interfaces.inc.php | 10 +- html/includes/common/worldmap.inc.php | 6 +- html/includes/forms/ack-alert.inc.php | 4 +- html/includes/forms/add-dashboard.inc.php | 4 +- html/includes/forms/alert-rules.inc.php | 4 +- html/includes/forms/alert-templates.inc.php | 6 +- html/includes/forms/alert-transports.inc.php | 6 +- .../includes/forms/application-update.inc.php | 4 +- .../forms/attach-alert-template.inc.php | 4 +- html/includes/forms/callback-clear.inc.php | 4 +- .../forms/callback-statistics.inc.php | 4 +- html/includes/forms/component.inc.php | 4 +- .../forms/config-item-disable.inc.php | 4 +- .../includes/forms/config-item-update.inc.php | 4 +- html/includes/forms/config-item.inc.php | 4 +- html/includes/forms/convert-template.inc.php | 4 +- html/includes/forms/create-alert-item.inc.php | 4 +- .../forms/create-device-group.inc.php | 4 +- html/includes/forms/create-service.inc.php | 4 +- html/includes/forms/delete-alert-rule.inc.php | 4 +- .../forms/delete-alert-template.inc.php | 4 +- .../forms/delete-alert-transport.inc.php | 4 +- .../forms/delete-cluster-poller.inc.php | 4 +- html/includes/forms/delete-dashboard.inc.php | 6 +- .../forms/delete-device-group.inc.php | 4 +- .../forms/delete-host-dependency.inc.php | 4 +- html/includes/forms/delete-poller.inc.php | 4 +- html/includes/forms/delete-service.inc.php | 4 +- .../forms/delete-transport-group.inc.php | 4 +- .../forms/discovery-module-update.inc.php | 4 +- html/includes/forms/edit-dashboard.inc.php | 4 +- .../forms/get-host-dependencies.inc.php | 8 +- html/includes/forms/get-vmlist.inc.php | 6 +- html/includes/forms/mempool-update.inc.php | 4 +- html/includes/forms/notifications.inc.php | 16 +- html/includes/forms/override-config.inc.php | 4 +- html/includes/forms/parse-alert-rule.inc.php | 4 +- .../forms/parse-alert-template.inc.php | 4 +- .../includes/forms/parse-device-group.inc.php | 4 +- .../forms/parse-poller-groups.inc.php | 4 +- html/includes/forms/parse-service.inc.php | 4 +- .../forms/parse-template-rules.inc.php | 4 +- .../forms/poller-group-remove.inc.php | 4 +- html/includes/forms/poller-groups.inc.php | 4 +- .../forms/poller-module-update.inc.php | 4 +- html/includes/forms/processor-update.inc.php | 4 +- html/includes/forms/rediscover-device.inc.php | 4 +- .../forms/refresh-oxidized-node.inc.php | 6 +- .../forms/reload-oxidized-nodes-list.inc.php | 4 +- .../forms/save-host-dependency.inc.php | 4 +- .../forms/schedule-maintenance.inc.php | 18 +- .../includes/forms/sensor-alert-reset.inc.php | 4 +- .../forms/sensor-alert-update.inc.php | 4 +- html/includes/forms/sensor-update.inc.php | 4 +- .../forms/show-alert-transport.inc.php | 4 +- .../forms/show-transport-group.inc.php | 4 +- .../forms/sql-from-alert-collection.inc.php | 4 +- html/includes/forms/storage-update.inc.php | 4 +- html/includes/forms/test-transport.inc.php | 4 +- html/includes/forms/token-item-create.inc.php | 4 +- .../includes/forms/token-item-disable.inc.php | 4 +- html/includes/forms/token-item-remove.inc.php | 4 +- html/includes/forms/transport-groups.inc.php | 4 +- html/includes/forms/update-alert-rule.inc.php | 4 +- .../includes/forms/update-config-item.inc.php | 4 +- .../forms/update-dashboard-config.inc.php | 12 +- html/includes/forms/update-notes.inc.php | 4 +- html/includes/forms/update-ports.inc.php | 4 +- html/includes/forms/widget-settings.inc.php | 4 +- .../forms/wireless-sensor-alert-reset.inc.php | 4 +- .../wireless-sensor-alert-update.inc.php | 4 +- .../forms/wireless-sensor-update.inc.php | 4 +- html/includes/front/top_device_bits.inc.php | 6 +- html/includes/front/top_ports.inc.php | 8 +- html/includes/functions.inc.php | 20 +- html/includes/graphs/customer/auth.inc.php | 4 +- html/includes/graphs/global/auth.inc.php | 4 +- html/includes/hostbox-public.inc.php | 67 ------ html/includes/list/devices.inc.php | 6 +- html/includes/list/groups.inc.php | 4 +- html/includes/list/transport_groups.inc.php | 4 +- html/includes/list/transports.inc.php | 4 +- .../modal/alert_rule_collection.inc.php | 4 +- html/includes/modal/alert_schedule.inc.php | 22 +- html/includes/modal/alert_template.inc.php | 4 +- .../modal/attach_alert_template.inc.php | 4 +- html/includes/modal/delete_alert_rule.inc.php | 4 +- .../modal/delete_alert_template.inc.php | 4 +- .../modal/delete_device_group.inc.php | 4 +- .../modal/delete_host_dependency.inc.php | 4 +- html/includes/modal/delete_poller.inc.php | 4 +- html/includes/modal/delete_service.inc.php | 4 +- .../modal/edit_alert_transport.inc.php | 4 +- .../modal/edit_host_dependency.inc.php | 4 +- .../modal/edit_transport_group.inc.php | 4 +- .../modal/manage_host_dependencies.inc.php | 8 +- html/includes/modal/new_alert_rule.inc.php | 4 +- html/includes/modal/new_bill.inc.php | 4 +- html/includes/modal/new_device_group.inc.php | 4 +- html/includes/modal/new_service.inc.php | 4 +- html/includes/modal/poller_groups.inc.php | 4 +- .../modal/remove_alert_schedule.inc.php | 4 +- html/includes/output/capture.inc.php | 4 +- html/includes/output/query.inc.php | 4 +- html/includes/print-alert-rules.php | 10 +- html/includes/print-alert-templates.php | 4 +- html/includes/print-alert-transports.php | 4 +- html/includes/print-graph-alerts.inc.php | 8 +- html/includes/print-interface.inc.php | 4 +- html/includes/print-map.inc.php | 6 +- html/includes/print-menubar.php | 16 +- html/includes/reports/alert-log.pdf.inc.php | 6 +- html/includes/table/address-search.inc.php | 6 +- html/includes/table/alert-schedule.inc.php | 6 +- html/includes/table/alertlog.inc.php | 6 +- html/includes/table/alerts.inc.php | 6 +- html/includes/table/arp-search.inc.php | 6 +- html/includes/table/bills.inc.php | 8 +- html/includes/table/devices.inc.php | 10 +- html/includes/table/eventlog.inc.php | 6 +- html/includes/table/fdb-search.inc.php | 8 +- html/includes/table/inventory.inc.php | 6 +- html/includes/table/mempool.inc.php | 6 +- html/includes/table/poll-log.inc.php | 10 +- html/includes/table/ports.inc.php | 10 +- html/includes/table/processor.inc.php | 6 +- html/includes/table/sensors-common.php | 8 +- html/includes/table/storage.inc.php | 6 +- html/includes/table/syslog.inc.php | 6 +- html/includes/table/toner.inc.php | 4 +- html/install.php | 8 +- html/legacy_index.php | 60 +---- html/netcmd.php | 6 +- html/network-map.php | 6 +- html/pages/about.inc.php | 12 +- html/pages/addhost.inc.php | 6 +- html/pages/addsrv.inc.php | 6 +- html/pages/adduser.inc.php | 12 +- html/pages/alert-schedule.inc.php | 4 +- html/pages/api-access.inc.php | 6 +- html/pages/authlog.inc.php | 4 +- html/pages/bill.inc.php | 12 +- html/pages/bills.inc.php | 6 +- html/pages/delhost.inc.php | 6 +- html/pages/deluser.inc.php | 18 +- html/pages/device-dependencies.inc.php | 4 +- html/pages/device.inc.php | 8 +- html/pages/device/capture.inc.php | 4 +- html/pages/device/edit.inc.php | 4 +- html/pages/device/edit/alerts.inc.php | 4 +- html/pages/device/edit/device.inc.php | 6 +- html/pages/device/edit/ipmi.inc.php | 4 +- html/pages/device/edit/services.inc.php | 6 +- html/pages/device/edit/snmp.inc.php | 4 +- html/pages/device/notes.inc.php | 4 +- html/pages/device/performance.inc.php | 6 +- html/pages/device/port.inc.php | 4 +- html/pages/device/services.inc.php | 6 +- html/pages/device/showconfig.inc.php | 6 +- html/pages/devices.inc.php | 6 +- html/pages/edituser.inc.php | 22 +- html/pages/eventlog.inc.php | 4 +- html/pages/front/default.php | 28 +-- html/pages/front/example2.php | 4 +- html/pages/front/globe.php | 6 +- html/pages/front/jt.php | 4 +- html/pages/front/map.php | 6 +- html/pages/front/tiles.php | 16 +- html/pages/front/traffic.php | 4 +- html/pages/locations.inc.php | 14 +- html/pages/logon.inc.php | 66 ------ html/pages/notifications.inc.php | 14 +- html/pages/plugin/admin.inc.php | 4 +- html/pages/pollers/pollers.inc.php | 9 +- html/pages/ports.inc.php | 22 +- html/pages/preferences.inc.php | 114 +++------- html/pages/public.inc.php | 58 ----- html/pages/routing/bgp.inc.php | 4 +- html/pages/routing/vrf.inc.php | 10 +- html/pages/search/arp.inc.php | 6 +- html/pages/search/fdb.inc.php | 6 +- html/pages/search/ipv4.inc.php | 6 +- html/pages/search/ipv6.inc.php | 6 +- html/pages/search/mac.inc.php | 6 +- html/pages/search/packages.inc.php | 6 +- html/pages/services.inc.php | 8 +- html/pages/settings.inc.php | 6 +- html/pages/settings/alerting.inc.php | 4 +- html/pages/syslog.inc.php | 4 +- html/pages/vminfo.inc.php | 2 - includes/alerts.inc.php | 6 +- includes/caches/alerts.inc.php | 6 +- includes/caches/devices.inc.php | 14 +- includes/caches/notifications.inc.php | 8 +- includes/caches/ports.inc.php | 16 +- includes/caches/services.inc.php | 14 +- includes/caches/toner.inc.php | 6 +- includes/common.php | 6 +- includes/defaults.inc.php | 2 - includes/functions.php | 4 +- includes/init.php | 27 ++- misc/db_schema.yaml | 4 +- resources/views/auth/2fa.blade.php | 104 +++++++++ .../views/auth/external-auth-failed.blade.php | 14 ++ resources/views/auth/login-form.blade.php | 53 +++++ resources/views/auth/login.blade.php | 9 + resources/views/auth/public-status.blade.php | 86 +++++++ resources/views/home.blade.php | 23 ++ resources/views/layouts/app.blade.php | 80 +++++++ resources/views/layouts/librenmsv1.blade.php | 12 +- resources/views/layouts/menu.blade.php | 20 +- routes/api.php | 7 +- routes/web.php | 83 ++++--- scripts/auth_test.php | 57 ++--- sql-schema/254.sql | 2 +- sql-schema/261.sql | 2 +- sql-schema/267.sql | 5 + tests/AuthHTTPTest.php | 12 +- tests/AuthSSOTest.php | 32 ++- tests/DBTestCase.php | 2 +- tests/bootstrap.php | 1 + tests/config/config.test.php | 1 - 278 files changed, 2604 insertions(+), 1816 deletions(-) delete mode 100644 LibreNMS/Authentication/Auth.php create mode 100644 LibreNMS/Authentication/LegacyAuth.php create mode 100644 app/Guards/ApiTokenGuard.php create mode 100644 app/Http/Controllers/TwoFactorController.php create mode 100644 app/Http/Middleware/LegacyExternalAuth.php create mode 100644 app/Http/Middleware/VerifyTwoFactor.php create mode 100644 app/Http/ViewComposers/LayoutComposer.php create mode 100644 app/Listeners/AuthEventListener.php create mode 100644 app/Models/ApiToken.php create mode 100644 app/Models/UserPref.php create mode 100644 app/Models/UserWidget.php create mode 100644 app/Providers/LegacyUserProvider.php rename app/{Extensions/LegacyUserProvider.php => Providers/TokenUserProvider.php} (66%) delete mode 100644 html/includes/authenticate.inc.php delete mode 100644 html/includes/hostbox-public.inc.php delete mode 100644 html/pages/logon.inc.php delete mode 100644 html/pages/public.inc.php create mode 100644 resources/views/auth/2fa.blade.php create mode 100644 resources/views/auth/external-auth-failed.blade.php create mode 100644 resources/views/auth/login-form.blade.php create mode 100644 resources/views/auth/login.blade.php create mode 100644 resources/views/auth/public-status.blade.php create mode 100644 resources/views/home.blade.php create mode 100644 resources/views/layouts/app.blade.php create mode 100644 sql-schema/267.sql diff --git a/LibreNMS/Authentication/ActiveDirectoryAuthorizer.php b/LibreNMS/Authentication/ActiveDirectoryAuthorizer.php index 17a8484e06..dad1dc5c52 100644 --- a/LibreNMS/Authentication/ActiveDirectoryAuthorizer.php +++ b/LibreNMS/Authentication/ActiveDirectoryAuthorizer.php @@ -55,27 +55,6 @@ class ActiveDirectoryAuthorizer extends AuthorizerBase throw new AuthenticationException(ldap_error($this->ldap_connection)); } - public function reauthenticate($sess_id, $token) - { - if ($this->bind(false, true)) { - $sess_id = clean($sess_id); - $token = clean($token); - list($username, $hash) = explode('|', $token); - - if (!$this->userExists($username)) { - if (Config::get('auth_ad_debug', false)) { - throw new AuthenticationException("$username is not a valid AD user"); - } - throw new AuthenticationException(); - } - - return $this->checkRememberMe($sess_id, $token); - } - - return false; - } - - protected function userInGroup($username, $groupname) { // check if user is member of the given group or nested groups @@ -223,15 +202,6 @@ class ActiveDirectoryAuthorizer extends AuthorizerBase return array(); } - public function deleteUser($userid) - { - dbDelete('bill_perms', '`user_id` = ?', array($userid)); - dbDelete('devices_perms', '`user_id` = ?', array($userid)); - dbDelete('ports_perms', '`user_id` = ?', array($userid)); - dbDelete('users_prefs', '`user_id` = ?', array($userid)); - return 0; - } - public function getUserlist() { diff --git a/LibreNMS/Authentication/Auth.php b/LibreNMS/Authentication/Auth.php deleted file mode 100644 index acbd53e815..0000000000 --- a/LibreNMS/Authentication/Auth.php +++ /dev/null @@ -1,66 +0,0 @@ - 'LibreNMS\Authentication\MysqlAuthorizer', - 'active_directory' => 'LibreNMS\Authentication\ActiveDirectoryAuthorizer', - 'ldap' => 'LibreNMS\Authentication\LdapAuthorizer', - 'radius' => 'LibreNMS\Authentication\RadiusAuthorizer', - 'http-auth' => 'LibreNMS\Authentication\HttpAuthAuthorizer', - 'ad-authorization' => 'LibreNMS\Authentication\ADAuthorizationAuthorizer', - 'ldap-authorization' => 'LibreNMS\Authentication\LdapAuthorizationAuthorizer', - 'sso' => 'LibreNMS\Authentication\SSOAuthorizer', - ); - - $auth_mechanism = Config::get('auth_mechanism'); - if (!isset($configToClassMap[$auth_mechanism])) { - throw new \RuntimeException($auth_mechanism . ' not found as auth_mechanism'); - } - - static::$_instance = new $configToClassMap[$auth_mechanism](); - } - return static::$_instance; - } - - /** - * Destroy the existing instance and get a new one - required for tests. - * - * @return Authorizer - */ - public static function reset() - { - static::$_instance = null; - return static::get(); - } - - public static function check() - { - return static::get()->sessionAuthenticated(); - } - - public static function user() - { - return new UserProxy; - } - - public static function id() - { - return $_SESSION['user_id']; - } -} diff --git a/LibreNMS/Authentication/AuthorizerBase.php b/LibreNMS/Authentication/AuthorizerBase.php index 24b3455f5b..5ddaeb9f6b 100644 --- a/LibreNMS/Authentication/AuthorizerBase.php +++ b/LibreNMS/Authentication/AuthorizerBase.php @@ -24,9 +24,8 @@ */ namespace LibreNMS\Authentication; -use LibreNMS\Config; use LibreNMS\Interfaces\Authentication\Authorizer; -use LibreNMS\Exceptions\AuthenticationException; +use Session; abstract class AuthorizerBase implements Authorizer { @@ -35,175 +34,6 @@ abstract class AuthorizerBase implements Authorizer protected static $CAN_UPDATE_PASSWORDS = 0; protected static $AUTH_IS_EXTERNAL = 0; - /** - * Log out the user, unset cookies, destroy the session - * - * @param string $message The logout message. - */ - public function logOutUser($message = 'Logged Out') - { - global $auth_message; - - dbInsert(array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => 'Logged Out'), 'authlog'); - - $this->clearRememberMe($_SESSION['username']); - - unset($_SESSION['authenticated']); - session_destroy(); - - $auth_message = $message; // global variable used to display a message to the user - } - - /** - * Log in the user and set up a few login tasks - * $_SESSION['username'] must be set prior to calling this function - * If twofactor authentication is enabled, it will be checked here. - * - * If everything goes well, $_SESSION['authenticated'] will be true after this function completes. - * @return bool If the user was successfully logged in. - * @throws AuthenticationException if anything failed why trying to log in - */ - public function logInUser() - { - // set up variables, but don't override existing ones (ad anonymous bind can only get user_id at login) - if (!isset($_SESSION['userlevel'])) { - $_SESSION['userlevel'] = $this->getUserlevel($_SESSION['username']); - } - - if (!isset($_SESSION['user_id'])) { - $_SESSION['user_id'] = $this->getUserid($_SESSION['username']); - } - - // check for valid user_id - if ($_SESSION['user_id'] === false || $_SESSION['user_id'] < 0) { - throw new AuthenticationException('Invalid Credentials'); - } - - if (!$this->sessionAuthenticated()) { - // check twofactor - if (Config::get('twofactor') === true && !isset($_SESSION['twofactor'])) { - if (TwoFactor::showForm()) { - return false; // not done yet, one more cycle to show the 2fa form - } - } - - // if two factor isn't enabled or it has passed already ware are logged in - if (!Config::get('twofactor') || $_SESSION['twofactor']) { - $_SESSION['authenticated'] = true; - dbInsert(array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => 'Logged In'), 'authlog'); - } - } - - if ($this->sessionAuthenticated()) { - $this->setRememberMe(); - } - - return true; - } - - /** - * Check if the session is authenticated - * - * @return bool - */ - public function sessionAuthenticated() - { - return isset($_SESSION['authenticated']) && $_SESSION['authenticated']; - } - - /** - * Set or update the remember me cookie if $_SESSION['remember'] is set - * If setting a new cookie, $_SESSION['username'] must be set - */ - protected function setRememberMe() - { - if (!isset($_SESSION['remember'])) { - return; - } - unset($_SESSION['remember']); - - $sess_id = session_id(); - $expiration = time() + 60 * 60 * 24 * Config::get('auth_remember'); - - $db_entry = array( - 'session_value' => $sess_id, - 'session_expiry' => $expiration, - ); - - if (isset($_COOKIE['token'], $_COOKIE['auth'])) { - $token_id = $_COOKIE['token']; - $auth = $_COOKIE['auth']; - dbUpdate($db_entry, 'session', 'session_auth=?', array($_COOKIE['auth'])); - } else { - $token = strgen(); - $auth = strgen(); - $token_id = $_SESSION['username'] . '|' . password_hash($_SESSION['username'] . $token, PASSWORD_DEFAULT); - - $db_entry['session_username'] = $_SESSION['username']; - $db_entry['session_token'] = $token; - $db_entry['session_auth'] = $auth; - dbInsert($db_entry, 'session'); - } - - setcookie('sess_id', $sess_id, $expiration, '/', null, Config::get('secure_cookies'), true); - setcookie('token', $token_id, $expiration, '/', null, Config::get('secure_cookies'), true); - setcookie('auth', $auth, $expiration, '/', null, Config::get('secure_cookies'), true); - } - - /** - * Check the remember me cookie - * If the cookie is valid, $_SESSION['username'] will be set - * - * @param string $sess_id sess_id cookie value - * @param string $token token cookie value - * @return bool is the remember me token valid - * @throws AuthenticationException thrown if the cookie is invalid - */ - protected function checkRememberMe($sess_id, $token) - { - list($uname, $hash) = explode('|', $token); - $session = dbFetchRow( - "SELECT * FROM `session` WHERE `session_username`=? AND `session_value`=?", - array($uname, $sess_id) - ); - - if (password_verify($uname . $session['session_token'], $hash)) { - $_SESSION['username'] = $uname; - return true; - } - - $this->clearRememberMe($uname); - throw new AuthenticationException('Cookie invalid, please log in.'); - } - - /** - * Clear remember cookie and remove our database record - * - * @param $username - */ - protected function clearRememberMe($username) - { - dbDelete( - 'session', - '`session_username` = ? AND `session_value` = ?', - array($username, $_COOKIE['sess_id']) - ); - - unset($_COOKIE); - - $time = time() - 60 * 60 * 24 * Config::get('auth_remember'); // time in the past to make sure - - setcookie('sess_id', '', $time, '/', null, Config::get('secure_cookies')); - setcookie('token', '', $time, '/', null, Config::get('secure_cookies')); - setcookie('auth', '', $time, '/', null, Config::get('secure_cookies')); - } - - public function reauthenticate($sess_id, $token) - { - //not supported by default - return false; - } - public function canUpdatePasswords($username = '') { return static::$CAN_UPDATE_PASSWORDS; @@ -226,7 +56,7 @@ abstract class AuthorizerBase implements Authorizer return 0; } - public function deleteUser($userid) + public function deleteUser($user_id) { //not supported by default return 0; @@ -251,9 +81,11 @@ abstract class AuthorizerBase implements Authorizer public function getExternalUsername() { if (isset($_SERVER['REMOTE_USER'])) { - return clean($_SERVER['REMOTE_USER']); + return $_SERVER['REMOTE_USER']; } elseif (isset($_SERVER['PHP_AUTH_USER'])) { - return clean($_SERVER['PHP_AUTH_USER']); + return $_SERVER['PHP_AUTH_USER']; } + + return null; } } diff --git a/LibreNMS/Authentication/LdapAuthorizer.php b/LibreNMS/Authentication/LdapAuthorizer.php index 3d6ca3c2c3..fd62063285 100644 --- a/LibreNMS/Authentication/LdapAuthorizer.php +++ b/LibreNMS/Authentication/LdapAuthorizer.php @@ -53,21 +53,6 @@ class LdapAuthorizer extends AuthorizerBase throw new AuthenticationException(); } - - public function reauthenticate($sess_id, $token) - { - $sess_id = clean($sess_id); - $token = clean($token); - - list($username, $hash) = explode('|', $token); - - if (!$this->userExists($username, true)) { - throw new AuthenticationException(); - } - - return $this->checkRememberMe($sess_id, $token); - } - public function userExists($username, $throw_exception = false) { try { diff --git a/LibreNMS/Authentication/LegacyAuth.php b/LibreNMS/Authentication/LegacyAuth.php new file mode 100644 index 0000000000..4dd5c21944 --- /dev/null +++ b/LibreNMS/Authentication/LegacyAuth.php @@ -0,0 +1,101 @@ + 'LibreNMS\Authentication\MysqlAuthorizer', + 'active_directory' => 'LibreNMS\Authentication\ActiveDirectoryAuthorizer', + 'ldap' => 'LibreNMS\Authentication\LdapAuthorizer', + 'radius' => 'LibreNMS\Authentication\RadiusAuthorizer', + 'http-auth' => 'LibreNMS\Authentication\HttpAuthAuthorizer', + 'ad-authorization' => 'LibreNMS\Authentication\ADAuthorizationAuthorizer', + 'ldap-authorization' => 'LibreNMS\Authentication\LdapAuthorizationAuthorizer', + 'sso' => 'LibreNMS\Authentication\SSOAuthorizer', + ); + + /** + * Gets the authorizer based on the config + * + * @return Authorizer + */ + public static function get() + { + if (!static::$_instance) { + $class = self::getClass(); + static::$_instance = new $class; + } + return static::$_instance; + } + + /** + * The auth mechanism type. + * + * @return mixed + */ + public static function getType() + { + return Config::get('auth_mechanism'); + } + + /** + * Get class for the given or current authentication type/mechanism + * + * @param string $type + * @return string + */ + public static function getClass($type = null) + { + if (is_null($type)) { + $type = self::getType(); + } + + if (!isset(self::$configToClassMap[$type])) { + throw new \RuntimeException($type . ' not found as auth_mechanism'); + } + + return self::$configToClassMap[$type]; + } + + /** + * Destroy the existing instance and get a new one - required for tests. + * + * @return Authorizer + */ + public static function reset() + { + static::$_instance = null; + return static::get(); + } + + public static function check() + { + self::checkInitSession(); + return isset($_SESSION['authenticated']) && $_SESSION['authenticated']; + } + + public static function user() + { + self::checkInitSession(); + return new UserProxy(); + } + + public static function id() + { + self::checkInitSession(); + return isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0; + } + + protected static function checkInitSession() + { + if (!isset($_SESSION)) { + @session_start(); + session_write_close(); + } + } +} diff --git a/LibreNMS/Authentication/MysqlAuthorizer.php b/LibreNMS/Authentication/MysqlAuthorizer.php index 3480f3dbda..c476fd394f 100644 --- a/LibreNMS/Authentication/MysqlAuthorizer.php +++ b/LibreNMS/Authentication/MysqlAuthorizer.php @@ -2,6 +2,10 @@ namespace LibreNMS\Authentication; +use App\Models\Notification; +use App\Models\NotificationAttrib; +use App\Models\User; +use LibreNMS\DB\Eloquent; use LibreNMS\Exceptions\AuthenticationException; use Phpass\PasswordHash; @@ -13,7 +17,7 @@ class MysqlAuthorizer extends AuthorizerBase public function authenticate($username, $password) { - $hash = dbFetchCell('SELECT `password` FROM `users` WHERE `username`= ?', array($username)); + $hash = User::thisAuth()->where('username', $username)->value('password'); // check for old passwords if (strlen($hash) == 32) { @@ -44,11 +48,6 @@ class MysqlAuthorizer extends AuthorizerBase throw new AuthenticationException(); } - public function reauthenticate($sess_id, $token) - { - return $this->checkRememberMe($sess_id, $token); - } - public function canUpdatePasswords($username = '') { /* @@ -61,7 +60,7 @@ class MysqlAuthorizer extends AuthorizerBase } elseif (empty($username) || !$this->userExists($username)) { return 1; } else { - return dbFetchCell('SELECT can_modify_passwd FROM users WHERE username = ?', array($username)); + return User::thisAuth()->where('username', $username)->value('can_modify_passwd'); } } @@ -72,66 +71,115 @@ class MysqlAuthorizer extends AuthorizerBase return 0; } - $encrypted = password_hash($password, PASSWORD_DEFAULT); - return dbUpdate(array('password' => $encrypted), 'users', '`username` = ?', array($username)); + /** @var User $user */ + $user = User::thisAuth()->where('username', $username)->first(); + + if ($user) { + $user->password = password_hash($password, PASSWORD_DEFAULT); + + return $user->save(); + } + + return false; } - public function addUser($username, $password, $level = 0, $email = '', $realname = '', $can_modify_passwd = 1, $description = '') + public function addUser($username, $password, $level = 0, $email = '', $realname = '', $can_modify_passwd = 1, $descr = '') { - if (!$this->userExists($username)) { - $encrypted = password_hash($password, PASSWORD_DEFAULT); - $userid = dbInsert(array('username' => $username, 'password' => $encrypted, 'level' => $level, 'email' => $email, 'realname' => $realname, 'can_modify_passwd' => $can_modify_passwd, 'descr' => $description), 'users'); - if ($userid == false) { - return false; - } else { - foreach (dbFetchRows('select notifications.* from notifications where not exists( select 1 from notifications_attribs where notifications.notifications_id = notifications_attribs.notifications_id and notifications_attribs.user_id = ?) order by notifications.notifications_id desc', array($userid)) as $notif) { - dbInsert(array('notifications_id'=>$notif['notifications_id'],'user_id'=>$userid,'key'=>'read','value'=>1), 'notifications_attribs'); - } + $user_array = get_defined_vars(); + + // no nulls + $user_array = array_filter($user_array, function ($field) { + return !is_null($field); + }); + + $new_user = User::thisAuth()->firstOrNew(['username' => $username], $user_array); + + // only update new users + if (!$new_user->user_id) { + $new_user->auth_type = LegacyAuth::getType(); + $new_user->password = password_hash($password, PASSWORD_DEFAULT); + $new_user->email = (string)$new_user->email; + + $new_user->save(); + $user_id = $new_user->user_id; + + // set auth_id + $new_user->auth_id = $user_id; + $new_user->save(); + + if ($user_id) { + // mark pre-existing notifications as read + Notification::whereNotExists(function ($query) use ($user_id) { + return $query->select(Eloquent::DB()->raw(1)) + ->from('notifications_attribs') + ->whereRaw('notifications.notifications_id = notifications_attribs.notifications_id') + ->where('notifications_attribs.user_id', $user_id); + })->get()->each(function ($notif) use ($user_id) { + NotificationAttrib::create([ + 'notifications_id' => $notif->notifications_id, + 'user_id' => $user_id, + 'key' => 'read', + 'value' => 1 + ]); + }); + + return $user_id; } - return $userid; - } else { - return false; } + + return false; } public function userExists($username, $throw_exception = false) { - return (bool)dbFetchCell('SELECT COUNT(*) FROM users WHERE username = ?', array($username)); + return User::thisAuth()->where('username', $username)->exists(); } public function getUserlevel($username) { - return dbFetchCell('SELECT `level` FROM `users` WHERE `username` = ?', array($username)); + return User::thisAuth()->where('username', $username)->value('level'); } public function getUserid($username) { - return dbFetchCell('SELECT `user_id` FROM `users` WHERE `username` = ?', array($username)); + // for mysql user_id == auth_id + return User::thisAuth()->where('username', $username)->value('user_id'); } - public function deleteUser($userid) + public function deleteUser($user_id) { - dbDelete('bill_perms', '`user_id` = ?', array($userid)); - dbDelete('devices_perms', '`user_id` = ?', array($userid)); - dbDelete('ports_perms', '`user_id` = ?', array($userid)); - dbDelete('users_prefs', '`user_id` = ?', array($userid)); - dbDelete('users', '`user_id` = ?', array($userid)); + // could be used on cli, use Eloquent helper + Eloquent::DB()->table('bill_perms')->where('user_id', $user_id)->delete(); + Eloquent::DB()->table('devices_perms')->where('user_id', $user_id)->delete(); + Eloquent::DB()->table('ports_perms')->where('user_id', $user_id)->delete(); + Eloquent::DB()->table('users_prefs')->where('user_id', $user_id)->delete(); - return dbDelete('users', '`user_id` = ?', array($userid)); + return User::destroy($user_id); } public function getUserlist() { - return dbFetchRows('SELECT * FROM `users` ORDER BY `username`'); + return User::thisAuth()->orderBy('username')->get()->toArray(); } public function getUser($user_id) { - return dbFetchRow('SELECT * FROM `users` WHERE `user_id` = ?', array($user_id)); + $user = User::find($user_id); + if ($user) { + return $user->toArray(); + } + return null; } public function updateUser($user_id, $realname, $level, $can_modify_passwd, $email) { - dbUpdate(array('realname' => $realname, 'level' => $level, 'can_modify_passwd' => $can_modify_passwd, 'email' => $email), 'users', '`user_id` = ?', array($user_id)); + $user = User::find($user_id); + + $user->realname = $realname; + $user->level = (int)$level; + $user->can_modify_passwd = (int)$can_modify_passwd; + $user->email = $email; + + $user->save(); } } diff --git a/LibreNMS/Authentication/TwoFactor.php b/LibreNMS/Authentication/TwoFactor.php index 667d37695a..564264fc02 100644 --- a/LibreNMS/Authentication/TwoFactor.php +++ b/LibreNMS/Authentication/TwoFactor.php @@ -30,6 +30,7 @@ namespace LibreNMS\Authentication; use LibreNMS\Config; use LibreNMS\Exceptions\AuthenticationException; +use Session; class TwoFactor { @@ -123,127 +124,6 @@ class TwoFactor return $ret; } - /** - * Return the HTML for the TwoFactor Input-Form - * @param boolean $form_tags Include FORM-tags - * @return string - */ - public static function getForm($form_tags = true) - { - $ret = ''; - - if ($form_tags) { - $ret .= ' -
-
-
-
-

- -

-
-
-
-
'; - } - - $ret .= ' -
-
- -
-
-
-
- -
-
-
'; - - $ret .= ''; - - if ($form_tags) { - $ret .= ''; - } - - return $ret; - } - - /** - * Authenticate with two factor - * Will set $twofactorform if the token hasn't been requested yet (page will redirect to the logon page) - * - * @return bool returns false if the form is not needed - * @throws AuthenticationException - */ - public static function showForm() - { - global $twofactorform; - - $twofactor = get_user_pref('twofactor'); - - // no need to show the form, user doesn't have a token - if (empty($twofactor)) { - $_SESSION['twofactor'] = true; - return false; - } - - // lockout the user if there are too many failures - if ($twofactor['fails'] >= 3) { - if (!Config::get('twofactor_lock')) { - throw new AuthenticationException('Too many two-factor failures, please contact administrator.'); - } elseif ((time() - $twofactor['last']) < Config::get('twofactor_lock')) { - $msg = "Too many two-factor failures, please wait " . Config::get('twofactor_lock') . " seconds"; - throw new AuthenticationException($msg); - } - } - - // set $twofactorform to show the form in logon.inc.php - $twofactorform = true; - return true; - } - - /** - * Check a 2fa token this will be stored in $_POST['twofactor'] by the form - * If valid, $_SESSION['twofactor'] = true will be set and this will return true - * - * @param string $token The 2fa token, stored in $_POST['twofactor'] by the form - * @return bool If the token was valid - * @throws AuthenticationException Thrown if the token was invalid - */ - public static function authenticate($token) - { - if (!$token) { - throw new AuthenticationException("No Two-Factor Token entered."); - } - - $twofactor = get_user_pref('twofactor'); - - if (empty($twofactor)) { - throw new AuthenticationException('No Two-Factor settings, how did you get here?'); - } - - if (($server_c = self::verifyHOTP($twofactor['key'], $_POST['twofactor'], $twofactor['counter'])) === false) { - $twofactor['fails']++; - $twofactor['last'] = time(); - set_user_pref('twofactor', $twofactor); - throw new AuthenticationException("Wrong Two-Factor Token."); - } - - if ($twofactor['counter'] !== false) { - if ($server_c !== true && $server_c !== $twofactor['counter']) { - $twofactor['counter'] = $server_c + 1; - } else { - $twofactor['counter']++; - } - } - $twofactor['fails'] = 0; - set_user_pref('twofactor', $twofactor); - - $_SESSION['twofactor'] = true; - return true; - } - /** * Verify HOTP token honouring window * diff --git a/LibreNMS/IRCBot.php b/LibreNMS/IRCBot.php index 1ed2895daf..e864ac5286 100644 --- a/LibreNMS/IRCBot.php +++ b/LibreNMS/IRCBot.php @@ -20,8 +20,8 @@ namespace LibreNMS; -use LibreNMS\Authentication\Auth; use LibreNMS\DB\Eloquent; +use LibreNMS\Authentication\LegacyAuth; class IRCBot { @@ -539,11 +539,11 @@ class IRCBot foreach ($hosts as $host) { $host = preg_replace("/\*/", ".*", $host); if (preg_match("/$host/", $this->getUserHost($this->data))) { - $user_id = Auth::get()->getUserid(mres($nms_user)); - $user = Auth::get()->getUser($user_id); + $user_id = LegacyAuth::get()->getUserid(mres($nms_user)); + $user = LegacyAuth::get()->getUser($user_id); $this->user['name'] = $user['username']; $this->user['id'] = $user_id; - $this->user['level'] = Auth::get()->getUserlevel($user['username']); + $this->user['level'] = LegacyAuth::get()->getUserlevel($user['username']); $this->user['expire'] = (time() + ($this->config['irc_authtime'] * 3600)); if ($this->user['level'] < 5) { foreach (dbFetchRows('SELECT device_id FROM devices_perms WHERE user_id = ?', array($this->user['id'])) as $tmp) { @@ -578,8 +578,8 @@ class IRCBot if (strlen($params[0]) == 64) { if ($this->tokens[$this->getUser($this->data)] == $params[0]) { $this->user['expire'] = (time() + ($this->config['irc_authtime'] * 3600)); - $tmp_user = Auth::get()->getUser($this->user['id']); - $tmp = Auth::get()->getUserlevel($tmp_user['username']); + $tmp_user = LegacyAuth::get()->getUser($this->user['id']); + $tmp = LegacyAuth::get()->getUserlevel($tmp_user['username']); $this->user['level'] = $tmp; if ($this->user['level'] < 5) { foreach (dbFetchRows('SELECT device_id FROM devices_perms WHERE user_id = ?', array($this->user['id'])) as $tmp) { @@ -596,8 +596,8 @@ class IRCBot return $this->respond('Nope.'); } } else { - $user_id = Auth::get()->getUserid(mres($params[0])); - $user = Auth::get()->getUser($user_id); + $user_id = LegacyAuth::get()->getUserid(mres($params[0])); + $user = LegacyAuth::get()->getUser($user_id); if ($user['email'] && $user['username'] == $params[0]) { $token = hash('gost', openssl_random_pseudo_bytes(1024)); $this->tokens[$this->getUser($this->data)] = $token; diff --git a/LibreNMS/Interfaces/Authentication/Authorizer.php b/LibreNMS/Interfaces/Authentication/Authorizer.php index 728bc9c6b9..de8b9b4feb 100644 --- a/LibreNMS/Interfaces/Authentication/Authorizer.php +++ b/LibreNMS/Interfaces/Authentication/Authorizer.php @@ -17,17 +17,6 @@ interface Authorizer */ public function authenticate($username, $password); - /** - * Check for cookie token to see if this is a valid saved session - * Authorizers should check if the user is still valid then return checkRememberMe() - * - * @param int $sess_id - * @param string $token - * @return bool - * @throws AuthenticationException thrown if the cookie or user is invalid - */ - public function reauthenticate($sess_id, $token); - /** * Check if a $username exists. * @@ -143,31 +132,6 @@ interface Authorizer */ public function canUpdatePasswords($username = ''); - /** - * Log out the user, unset cookies, destroy the session - * - * @param string $message The logout message. - */ - public function logOutUser($message = 'Logged Out'); - - /** - * Log in the user and set up a few login tasks - * $_SESSION['username'] must be set prior to calling this function - * If twofactor authentication is enabled, it will be checked here. - * - * If everything goes well, $_SESSION['authenticated'] will be true after this function completes. - * @return bool If the user was successfully logged in. - * @throws AuthenticationException if anything failed why trying to log in - */ - public function logInUser(); - - /** - * Check if the session is authenticated - * - * @return bool - */ - public function sessionAuthenticated(); - /** * Indicates if the authentication happens within the LibreNMS process, or external to it. * If the former, LibreNMS provides a login form, and the user must supply the username. If the latter, the authenticator supplies it via getExternalUsername() without user interaction. diff --git a/LibreNMS/ObjectCache.php b/LibreNMS/ObjectCache.php index 909d1d8e7d..f964b2e3eb 100644 --- a/LibreNMS/ObjectCache.php +++ b/LibreNMS/ObjectCache.php @@ -114,7 +114,7 @@ class ObjectCache implements ArrayAccess */ public function offsetSet($obj, $value) { - if (!is_array($this->data[$obj])) { + if (!isset($this->data[$obj])) { $this->data[$obj] = array(); } diff --git a/adduser.php b/adduser.php index c7e8d8849c..b45b0310f1 100755 --- a/adduser.php +++ b/adduser.php @@ -12,7 +12,7 @@ * */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array(); if (php_sapi_name() != 'cli') { @@ -20,10 +20,10 @@ if (php_sapi_name() != 'cli') { } require __DIR__ . '/includes/init.php'; -if (Auth::get()->canManageUsers()) { +if (LegacyAuth::get()->canManageUsers()) { if (isset($argv[1]) && isset($argv[2]) && isset($argv[3])) { - if (!Auth::get()->userExists($argv[1])) { - if (Auth::get()->addUser($argv[1], $argv[2], $argv[3], @$argv[4])) { + if (!LegacyAuth::get()->userExists($argv[1])) { + if (LegacyAuth::get()->addUser($argv[1], $argv[2], $argv[3], @$argv[4])) { echo 'User '.$argv[1]." added successfully\n"; } } else { diff --git a/app/Checks.php b/app/Checks.php index 83ae73e199..ad20adc363 100644 --- a/app/Checks.php +++ b/app/Checks.php @@ -28,9 +28,10 @@ namespace App; use App\Models\Device; use App\Models\Notification; use Auth; +use Cache; use Carbon\Carbon; use Dotenv\Dotenv; -use Kamaln7\Toastr\Facades\Toastr; +use Toastr; use LibreNMS\Config; class Checks @@ -150,26 +151,37 @@ class Checks */ public static function postAuth() { - $notifications = Notification::isUnread(Auth::user())->where('severity', '>', 1)->get(); - foreach ($notifications as $notification) { - Toastr::error("$notification->body", $notification->title); + // limit popup messages frequency + if (Cache::get('checks_popup_timeout') || !Auth::check()) { + return; } - if (Device::isUp()->whereTime('last_polled', '<=', Carbon::now()->subMinutes(15))->count() > 0) { - Toastr::warning('It appears as though you have some devices that haven\'t completed polling within the last 15 minutes, you may want to check that out :)', 'Devices unpolled'); - } + Cache::put('checks_popup_timeout', true, Config::get('checks_popup_timer', 5)); - // Directory access checks - $rrd_dir = Config::get('rrd_dir'); - if (!is_dir($rrd_dir)) { - Toastr::error("RRD Directory is missing ($rrd_dir). Graphing may fail."); - } + $user = Auth::user(); - $temp_dir = Config::get('temp_dir'); - if (!is_dir($temp_dir)) { - Toastr::error("Temp Directory is missing ($temp_dir). Graphing may fail."); - } elseif (!is_writable($temp_dir)) { - Toastr::error("Temp Directory is not writable ($temp_dir). Graphing may fail."); + if ($user->isAdmin()) { + $notifications = Notification::isUnread($user)->where('severity', '>', 1)->get(); + foreach ($notifications as $notification) { + Toastr::error("$notification->body", $notification->title); + } + + if (Device::isUp()->whereTime('last_polled', '<=', Carbon::now()->subMinutes(15))->count() > 0) { + Toastr::warning('It appears as though you have some devices that haven\'t completed polling within the last 15 minutes, you may want to check that out :)', 'Devices unpolled'); + } + + // Directory access checks + $rrd_dir = Config::get('rrd_dir'); + if (!is_dir($rrd_dir)) { + Toastr::error("RRD Directory is missing ($rrd_dir). Graphing may fail. Validate your install"); + } + + $temp_dir = Config::get('temp_dir'); + if (!is_dir($temp_dir)) { + Toastr::error("Temp Directory is missing ($temp_dir). Graphing may fail. Validate your install"); + } elseif (!is_writable($temp_dir)) { + Toastr::error("Temp Directory is not writable ($temp_dir). Graphing may fail. Validate your install"); + } } } diff --git a/app/Guards/ApiTokenGuard.php b/app/Guards/ApiTokenGuard.php new file mode 100644 index 0000000000..592b3c1bb9 --- /dev/null +++ b/app/Guards/ApiTokenGuard.php @@ -0,0 +1,47 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +namespace App\Guards; + +use Illuminate\Auth\TokenGuard; + +class ApiTokenGuard extends TokenGuard +{ + /** + * Get the token for the current request. + * + * @return string + */ + public function getTokenForRequest() + { + $token = $this->request->header('X-Auth-Token'); + + if (empty($token)) { + $token = parent::getTokenForRequest(); + } + + return $token; + } +} diff --git a/app/Http/Controllers/AjaxController.php b/app/Http/Controllers/AjaxController.php index de1f344e8c..72b355cf71 100644 --- a/app/Http/Controllers/AjaxController.php +++ b/app/Http/Controllers/AjaxController.php @@ -6,6 +6,8 @@ use Illuminate\Http\Request; class AjaxController extends Controller { + // FIXME do not just pile functions on this controller, create separate controllers + public function setResolution(Request $request) { $this->validate($request, [ diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index b2ea669a0d..05764e9c27 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -3,7 +3,9 @@ namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; +use App\Models\Device; use Illuminate\Foundation\Auth\AuthenticatesUsers; +use LibreNMS\Config; class LoginController extends Controller { @@ -25,7 +27,7 @@ class LoginController extends Controller * * @var string */ - protected $redirectTo = '/home'; + protected $redirectTo = '/'; /** * Create a new controller instance. @@ -36,4 +38,18 @@ class LoginController extends Controller { $this->middleware('guest')->except('logout'); } + + public function username() + { + return 'username'; + } + + public function showLoginForm() + { + if (Config::get('public_status')) { + $devices = Device::isActive()->get(); + return view('auth.public-status')->with('devices', $devices); + } + return view('auth.login'); + } } diff --git a/app/Http/Controllers/LegacyController.php b/app/Http/Controllers/LegacyController.php index a5b3ff849e..97d904115d 100644 --- a/app/Http/Controllers/LegacyController.php +++ b/app/Http/Controllers/LegacyController.php @@ -2,10 +2,14 @@ namespace App\Http\Controllers; +use App\Checks; + class LegacyController extends Controller { public function index($path = '') { + Checks::postAuth(); + ob_start(); include base_path('html/legacy_index.php'); $html = ob_get_clean(); diff --git a/app/Http/Controllers/TwoFactorController.php b/app/Http/Controllers/TwoFactorController.php new file mode 100644 index 0000000000..7963db2688 --- /dev/null +++ b/app/Http/Controllers/TwoFactorController.php @@ -0,0 +1,204 @@ +validate($request, [ + 'twofactor' => 'required|numeric', + ]); + + try { + $this->checkToken($request->user(), $request->input('twofactor')); + } catch (AuthenticationException $e) { + return redirect()->route('2fa.form')->withErrors($e->getMessage()); + } + + // token validated + if (session('twofactorremove')) { + UserPref::forgetPref(auth()->user(), 'twofactor'); + $request->session()->forget(['twofactor', 'twofactorremove']); + + \Toastr::info(__('TwoFactor auth removed.')); + + return redirect('preferences'); + } + + $request->session()->put('twofactor', true); + + return redirect()->intended(); + } + + public function showTwoFactorForm(Request $request) + { + $twoFactorSettings = $this->loadSettings($request->user()); + + // don't allow visiting this page if not needed + if (empty($twoFactorSettings) || !Config::get('twofactor') || session('twofactor')) { + return redirect()->intended(); + } + + $errors = []; + + // lockout the user if there are too many failures + if (isset($twoFactorSettings['fails']) && $twoFactorSettings['fails'] >= 3) { + $lockout_time = Config::get('twofactor_lock', 0); + + if (!$lockout_time) { + $errors['lockout'] = __('Too many two-factor failures, please contact administrator.'); + } elseif ((time() - $twoFactorSettings['last']) < $lockout_time) { + $errors['lockout'] = __("Too many two-factor failures, please wait :time seconds", ['time' => $lockout_time]); + } + } + + return view('auth.2fa')->with([ + 'key' => $twoFactorSettings['key'], + 'uri' => $this->genUri($request->user(), $twoFactorSettings), + ])->withErrors($errors); + } + + /** + * Show the form for creating a new resource. + * + * @return \Illuminate\Http\Response + */ + public function create(Request $request) + { + $this->validate($request, [ + 'twofactor' => Rule::in('time', 'counter') + ]); + + $key = \LibreNMS\Authentication\TwoFactor::genKey(); + + // assume time based + $settings = [ + 'key' => $key, + 'fails' => 0, + 'last' => 0, + 'counter' => $request->get('twofactor') == 'counter' ? 0 : false, + ]; + + Session::put('twofactoradd', $settings); + + return redirect()->intended(); + } + + + /** + * Remove the specified resource from storage. + * + * @param int $id + * @return \Illuminate\Http\Response + */ + public function destroy(Request $request) + { + $request->session()->put('twofactorremove', true); + $request->session()->forget('twofactor'); + + return redirect()->intended(); + } + + /** + * Remove the specified resource from storage. + * + * @param int $id + * @return \Illuminate\Http\Response + */ + public function cancelAdd(Request $request) + { + $request->session()->forget('twofactoradd'); + + return redirect()->intended(); + } + + /** + * @param User $user + * @param string $token + * @throws AuthenticationException + * return true + */ + private function checkToken($user, $token) + { + if (!$token) { + throw new AuthenticationException(__("No Two-Factor Token entered.")); + } + + // check if this is new + $twoFactorSettings = $this->loadSettings($user); + + if (empty($twoFactorSettings)) { + throw new AuthenticationException(__('No Two-Factor settings, how did you get here?')); + } + + if (($server_count = TwoFactor::verifyHOTP($twoFactorSettings['key'], $token, $twoFactorSettings['counter'])) === false) { + if (isset($twoFactorSettings['fails'])) { + $twoFactorSettings['fails']++; + } else { + $twoFactorSettings['fails'] = 1; + } + $twoFactorSettings['last'] = time(); + UserPref::setPref($user, 'twofactor', $twoFactorSettings); + throw new AuthenticationException(__("Wrong Two-Factor Token.")); + } + + // update counter + if ($twoFactorSettings['counter'] !== false) { + if ($server_count !== true && $server_count !== $twoFactorSettings['counter']) { + $twoFactorSettings['counter'] = $server_count + 1; + } else { + $twoFactorSettings['counter']++; + } + } + + // success + $twoFactorSettings['fails'] = 0; + UserPref::setPref($user, 'twofactor', $twoFactorSettings); + + // notify if added + if (Session::has('twofactoradd')) { + Toastr::success(__('TwoFactor auth added.')); + Session::forget('twofactoradd'); + } + + return true; + } + + /** + * @param $user + * @return mixed + */ + private function loadSettings($user) + { + if (Session::has('twofactoradd')) { + return Session::get('twofactoradd'); + } + + return UserPref::getPref($user, 'twofactor'); + } + + private function genUri($user, $settings) + { + $title = urlencode("Librenms:" . $user->username); + $key = $settings['key']; + + // time based + if ($settings['counter'] === false) { + return "otpauth://totp/$title?issuer=LibreNMS&secret=$key"; + } + + // counter based + return "otpauth://hotp/$title?issuer=LibreNMS&counter=1&secret=$key"; + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index b112277b85..849adac104 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -34,12 +34,14 @@ class Kernel extends HttpKernel \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, + \App\Http\Middleware\LegacyExternalAuth::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', + 'auth:token' ], ]; @@ -52,6 +54,7 @@ class Kernel extends HttpKernel */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, + '2fa' => \App\Http\Middleware\VerifyTwoFactor::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, diff --git a/app/Http/Middleware/LegacyExternalAuth.php b/app/Http/Middleware/LegacyExternalAuth.php new file mode 100644 index 0000000000..36c3ce3a10 --- /dev/null +++ b/app/Http/Middleware/LegacyExternalAuth.php @@ -0,0 +1,48 @@ +authIsExternal()) { + try { + $username = LegacyAuth::get()->getExternalUsername(); + $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + + if (LegacyAuth::get()->authenticate($username, $password)) { + $user_id = User::thisAuth()->where('username', $username)->value('user_id'); + Auth::loginUsingId($user_id); + } + } catch (AuthenticationException $e) { + $message = $e->getMessage(); + Log::critical('HTTP Auth Error: ' . $message); + + if (!Config::get('auth.debug', false)) { + $message = ''; + } + + // force user to failure page + return response(view('auth.external-auth-failed')->with('message', $message)); + } + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index e4cec9c8b1..e27860e24e 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -18,7 +18,7 @@ class RedirectIfAuthenticated public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { - return redirect('/home'); + return redirect('/'); } return $next($request); diff --git a/app/Http/Middleware/VerifyTwoFactor.php b/app/Http/Middleware/VerifyTwoFactor.php new file mode 100644 index 0000000000..011dc6c0e3 --- /dev/null +++ b/app/Http/Middleware/VerifyTwoFactor.php @@ -0,0 +1,40 @@ +route()->getName(), '2fa.')) { + return $next($request); + } + + $twofactor = $request->session()->get('twofactoradd', UserPref::getPref($request->user(), 'twofactor')); + + if (!empty($twofactor)) { + // user has 2fa enabled + if (!$request->session()->get('twofactor')) { + // verification is needed + return redirect('/2fa'); + } + } + } + + return $next($request); + } +} diff --git a/app/Http/ViewComposers/LayoutComposer.php b/app/Http/ViewComposers/LayoutComposer.php new file mode 100644 index 0000000000..334bb338ce --- /dev/null +++ b/app/Http/ViewComposers/LayoutComposer.php @@ -0,0 +1,61 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +namespace App\Http\ViewComposers; + +use App\Checks; +use App\Models\UserPref; +use Illuminate\View\View; +use LibreNMS\Config; + +class LayoutComposer +{ + /** + * Bind data to the view. + * + * @param View $view + * @return void + */ + public function compose(View $view) + { + // build page title + if ($view->getFactory()->hasSection('title')) { + $title = str_replace(' ', ' : ', trim($view->getFactory()->getSection('title'))); + $title .= ' | ' . Config::get('page_title_suffix'); + } else { + $title = Config::get('page_title_suffix'); + } + + Checks::postAuth(); + + $show_menu = auth()->check(); + if ($show_menu && Config::get('twofactor') && !session('twofactor')) { + $show_menu = empty(UserPref::getPref(auth()->user(), 'twofactor')); + } + + $view->with('pagetitle', $title) + ->with('show_menu', $show_menu); + } +} diff --git a/app/Http/ViewComposers/MenuComposer.php b/app/Http/ViewComposers/MenuComposer.php index e4316319ca..358961b035 100644 --- a/app/Http/ViewComposers/MenuComposer.php +++ b/app/Http/ViewComposers/MenuComposer.php @@ -2,7 +2,7 @@ /** * Menu.php * - * -Description- + * Builds data for LibreNMS menu * * 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 diff --git a/app/Listeners/AuthEventListener.php b/app/Listeners/AuthEventListener.php new file mode 100644 index 0000000000..9d8173967f --- /dev/null +++ b/app/Listeners/AuthEventListener.php @@ -0,0 +1,75 @@ +user; + + DB::table('authlog')->insert(['user' => $user->username ?: '', 'address' => Request::ip(), 'result' => 'Logged In']); + + Toastr::info('Welcome ' . ($user->realname ?: $user->username)); + + // Authenticated, set up legacy session stuff. TODO Remove once ajax and graphs are ported to Laravel. + session_start(); + $_SESSION['username'] = $user->username; + + // set up legacy variables, but don't override existing ones (ad anonymous bind can only get user_id at login) + if (!isset($_SESSION['userlevel'])) { + $_SESSION['userlevel'] = $user->level; + } + + if (!isset($_SESSION['user_id'])) { + $_SESSION['user_id'] = $user->user_id; + } + + $_SESSION['authenticated'] = true; + session_write_close(); + } + + /** + * Handle the logout event. + * + * @param Logout $event + * @return void + */ + public function logout(Logout $event) + { + DB::table('authlog')->insert(['user' => $event->user->username ?: '', 'address' => Request::ip(), 'result' => 'Logged Out']); + + if (!isset($_SESSION)) { + session_start(); + } + unset($_SESSION['authenticated']); + session_destroy(); + } +} diff --git a/app/Models/ApiToken.php b/app/Models/ApiToken.php new file mode 100644 index 0000000000..9b300c6517 --- /dev/null +++ b/app/Models/ApiToken.php @@ -0,0 +1,87 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +namespace App\Models; + +class ApiToken extends BaseModel +{ + public $timestamps = false; + protected $table = 'api_tokens'; + + // ---- Helper Functions ---- + + /** + * Check if the given token is valid + * + * @param string $token + * @return bool + */ + public static function isValid($token, $user_id = null) + { + $query = self::query()->isEnabled()->where('token_hash', $token); + + if (!is_null($user_id)) { + $query->where('user_id', $user_id); + } + + return $query->exists(); + } + + /** + * Get User model based on the given API token (or null if invalid) + * + * @param string $token + * @return User|null + */ + public static function userFromToken($token) + { + return User::find(self::idFromToken($token)); + } + + /** + * Get the user_id for the given token. + * + * @param string $token + * @return int + */ + public static function idFromToken($token) + { + return self::query()->isEnabled()->where('token_hash', $token)->value('user_id'); + } + + // ---- Query scopes ---- + + public function scopeIsEnabled($query) + { + return $query->where('disabled', 0); + } + + // ---- Define Relationships ---- + + public function user() + { + return $this->belongsTo('App\Models\User', 'user_id'); + } +} diff --git a/app/Models/Dashboard.php b/app/Models/Dashboard.php index 137ff371fe..9296e91c82 100644 --- a/app/Models/Dashboard.php +++ b/app/Models/Dashboard.php @@ -39,6 +39,6 @@ class Dashboard extends Model */ public function widgets() { - return $this->hasMany('App\Models\UsersWidgets', 'dashboard_id'); + return $this->hasMany('App\Models\UserWidget', 'dashboard_id'); } } diff --git a/app/Models/Device.php b/app/Models/Device.php index 92d9b0fe8d..7b85c31f89 100644 --- a/app/Models/Device.php +++ b/app/Models/Device.php @@ -135,6 +135,53 @@ class Device extends BaseModel return null; } + /** + * Get the display name of this device (hostname) unless force_ip_to_sysname is set + * and hostname is an IP and sysName is set + * + * @return string + */ + public function displayName() + { + if (\LibreNMS\Config::get('force_ip_to_sysname') && $this->sysName && IP::isValid($this->hostname)) { + return $this->sysName; + } + + return $this->hostname; + } + + public function formatUptime($short = false) + { + $result = ''; + $interval = $this->uptime; + $data = [ + 'years' => 31536000, + 'days' => 86400, + 'hours' => 3600, + 'minutes' => 60, + 'seconds' => 1, + ]; + + foreach ($data as $k => $v) { + if ($interval >= $v) { + $diff = floor($interval / $v); + + $result .= " $diff"; + if ($short) { + $result .= substr($k, 0, 1); + } elseif ($diff > 1) { + $result .= $k; + } else { + $result .= substr($k, 0, -1); + } + + $interval -= $v * $diff; + } + } + + return $result; + } + /** * @return string */ @@ -224,6 +271,7 @@ class Device extends BaseModel } // ---- Accessors/Mutators ---- + public function getIconAttribute($icon) { if (isset($icon)) { diff --git a/app/Models/NotificationAttrib.php b/app/Models/NotificationAttrib.php index 09b1e135b0..5d3c1b0128 100644 --- a/app/Models/NotificationAttrib.php +++ b/app/Models/NotificationAttrib.php @@ -6,25 +6,10 @@ use Illuminate\Database\Eloquent\Model; class NotificationAttrib extends Model { - - /** - * Indicates if the model should be timestamped. - * - * @var bool - */ public $timestamps = false; - /** - * The table associated with the model. - * - * @var string - */ protected $table = 'notifications_attribs'; - /** - * The primary key column name. - * - * @var string - */ protected $primaryKey = 'attrib_id'; + protected $fillable = ['notifications_id', 'user_id', 'key', 'value']; // ---- Define Relationships ---- diff --git a/app/Models/User.php b/app/Models/User.php index b2eedc2cb0..c6c0331354 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,16 +2,24 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; +use LibreNMS\Authentication\LegacyAuth; class User extends Authenticatable { use Notifiable; protected $primaryKey = 'user_id'; - protected $fillable = ['realname', 'username', 'email', 'level', 'descr', 'can_modify_passwd']; + protected $fillable = ['realname', 'username', 'email', 'level', 'descr', 'can_modify_passwd', 'auth_type', 'auth_id']; protected $hidden = ['password', 'remember_token', 'pivot']; + protected $attributes = [ // default values + 'descr' => '', + 'realname' => '', + 'email' => '', + 'can_modify_passwd' => 0, + ]; // ---- Helper Functions ---- @@ -27,13 +35,34 @@ class User extends Authenticatable } /** - * Test if the User is an admin or demo. + * Test if this user has global admin access + * these users have a level of 10 or 11 (demo). + * + * @return boolean + */ + public function hasGlobalAdmin() + { + return $this->level >= 10; + } + + /** + * Test if the User is an admin. * * @return boolean */ public function isAdmin() { - return $this->level >= 10; + return $this->level == 10; + } + + /** + * Test if this user is the demo user + * + * @return bool + */ + public function isDemo() + { + return $this->level == 11; } /** @@ -47,6 +76,27 @@ class User extends Authenticatable return $this->hasGlobalRead() || $this->devices->contains($device); } + // ---- Query scopes ---- + + /** + * This restricts the query to only users that match the current auth method + * It is not needed when using user_id, but should be used for username and auth_id + * + * @param Builder $query + * @return Builder + */ + public function scopeThisAuth($query) + { + // find user including ones where we might not know the auth type + $type = LegacyAuth::getType(); + + return $query->where(function ($query) use ($type) { + $query->where('auth_type', $type) + ->orWhereNull('auth_type') + ->orWhere('auth_type', ''); + }); + } + // ---- Define Relationships ---- public function devices() @@ -75,8 +125,13 @@ class User extends Authenticatable return $this->hasMany('App\Models\Dashboard', 'user_id'); } + public function preferences() + { + return $this->hasMany('App\Models\UserPref', 'user_id'); + } + public function widgets() { - return $this->hasMany('App\Models\UsersWidgets', 'user_id'); + return $this->hasMany('App\Models\UserWidget', 'user_id'); } } diff --git a/app/Models/UserPref.php b/app/Models/UserPref.php new file mode 100644 index 0000000000..002db61592 --- /dev/null +++ b/app/Models/UserPref.php @@ -0,0 +1,128 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +namespace App\Models; + +use Illuminate\Database\Eloquent\Builder; + +class UserPref extends BaseModel +{ + public $timestamps = false; + public $incrementing = false; + protected $table = 'users_prefs'; + protected $primaryKey = ['user_id', 'pref']; + protected $fillable = ['user_id', 'pref', 'value']; + + // ---- Helper Functions ---- + public static function getPref(User $user, $pref) + { + return $user->preferences()->where('pref', $pref)->value('value'); + } + + public static function setPref(User $user, $pref, $value) + { + return UserPref::updateOrCreate(['user_id' => $user->user_id, 'pref' => $pref], ['value' => $value]); + } + + public static function forgetPref(User $user, $pref) + { + return $user->preferences()->where('pref', $pref)->delete(); + } + + // ---- Accessors/Mutators ---- + + public function getValueAttribute($value) + { + $decoded = json_decode($value, true); + if (json_last_error() == JSON_ERROR_NONE) { + return $decoded; + } + + return $value; + } + + public function setValueAttribute($value) + { + if (is_array($value)) { + $this->attributes['value'] = json_encode($value); + } else { + $this->attributes['value'] = $value; + } + } + + // ---- Query Scopes ---- + + public function scopePref($query, $pref) + { + return $query->where('pref', $pref); + } + + // ---- Define Relationships ---- + + public function user() + { + return $this->belongsTo('App\Models\User', 'user_id'); + } + + + /** + * Set the keys for a save update query. (no primary key) + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + protected function setKeysForSaveQuery(Builder $query) + { + $keys = $this->getKeyName(); + if (!is_array($keys)) { + return parent::setKeysForSaveQuery($query); + } + + foreach ($keys as $keyName) { + $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName)); + } + + return $query; + } + + /** + * Get the primary key value for a save query. (no primary key) + * + * @param mixed $keyName + * @return mixed + */ + protected function getKeyForSaveQuery($keyName = null) + { + if (is_null($keyName)) { + $keyName = $this->getKeyName(); + } + + if (isset($this->original[$keyName])) { + return $this->original[$keyName]; + } + + return $this->getAttribute($keyName); + } +} diff --git a/app/Models/UserWidget.php b/app/Models/UserWidget.php new file mode 100644 index 0000000000..3e2fd2f3ed --- /dev/null +++ b/app/Models/UserWidget.php @@ -0,0 +1,41 @@ + 'array']; + + // ---- Define Relationships ---- + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function user() + { + return $this->belongsTo('App\Models\User', 'user_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ + public function widget() + { + return $this->hasOne('App\Models\Widgets', 'widget_id'); + } + + /** + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function dashboard() + { + return $this->belongsTo('App\Models\Dashboard', 'dashboard_id'); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 570c4f24e1..e4db0b8e69 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Log; use Illuminate\Support\ServiceProvider; use LibreNMS\Config; use LibreNMS\Exceptions\DatabaseConnectException; +use Request; include_once __DIR__ . '/../../includes/dbFacile.php'; @@ -55,7 +56,10 @@ class AppServiceProvider extends ServiceProvider } if (config('app.debug') && class_exists(\Barryvdh\Debugbar\ServiceProvider::class)) { - $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class); + // disable debugbar for api routes + if (!Request::is('api/*')) { + $this->app->register(\Barryvdh\Debugbar\ServiceProvider::class); + } } } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 1e877c00b8..4b68ea66a5 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -2,7 +2,8 @@ namespace App\Providers; -use App\Extensions\LegacyUserProvider; +use App\Providers\LegacyUserProvider; +use App\Guards\ApiTokenGuard; use Auth; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; @@ -30,5 +31,28 @@ class AuthServiceProvider extends ServiceProvider Auth::provider('legacy', function ($app, array $config) { return new LegacyUserProvider(); }); + + Auth::provider('token_provider', function ($app, array $config) { + return new TokenUserProvider(); + }); + + Auth::extend('token_driver', function ($app, $name, array $config) { + $userProvider = $app->make(TokenUserProvider::class); + $request = $app->make('request'); + return new ApiTokenGuard($userProvider, $request); + }); + + Gate::define('global-admin', function ($user) { + return $user->hasGlobalAdmin(); + }); + Gate::define('admin', function ($user) { + return $user->isAdmin(); + }); + Gate::define('global-read', function ($user) { + return $user->hasGlobalRead(); + }); + Gate::define('device', function ($user, $device) { + return $user->canAccessDevice($device); + }); } } diff --git a/app/Providers/ComposerServiceProvider.php b/app/Providers/ComposerServiceProvider.php index 0ebb225c3e..d7bea5fc40 100644 --- a/app/Providers/ComposerServiceProvider.php +++ b/app/Providers/ComposerServiceProvider.php @@ -37,6 +37,7 @@ class ComposerServiceProvider extends ServiceProvider */ public function boot() { + View::composer('layouts.librenmsv1', 'App\Http\ViewComposers\LayoutComposer'); View::composer('layouts.menu', 'App\Http\ViewComposers\MenuComposer'); } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index fca6152c3a..883b7ba88c 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -2,7 +2,6 @@ namespace App\Providers; -use Illuminate\Support\Facades\Event; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider @@ -13,9 +12,8 @@ class EventServiceProvider extends ServiceProvider * @var array */ protected $listen = [ - 'App\Events\Event' => [ - 'App\Listeners\EventListener', - ], + 'Illuminate\Auth\Events\Login' => ['App\Listeners\AuthEventListener@login'], + 'Illuminate\Auth\Events\Logout' => ['App\Listeners\AuthEventListener@logout'], ]; /** diff --git a/app/Providers/LegacyUserProvider.php b/app/Providers/LegacyUserProvider.php new file mode 100644 index 0000000000..239325e9ef --- /dev/null +++ b/app/Providers/LegacyUserProvider.php @@ -0,0 +1,210 @@ +. + * + * @package LibreNMS + * @link http://librenms.org + * @copyright 2018 Tony Murray + * @author Tony Murray + */ + +namespace App\Providers; + +use App\Models\ApiToken; +use App\Models\User; +use DB; +use Illuminate\Contracts\Auth\Authenticatable; +use Illuminate\Contracts\Auth\UserProvider; +use LibreNMS\Authentication\LegacyAuth; +use LibreNMS\Exceptions\AuthenticationException; +use Request; +use Session; + +class LegacyUserProvider implements UserProvider +{ + /** + * Retrieve a user by their unique identifier. + * + * @param mixed $identifier + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveById($identifier) + { + $username = User::where('user_id', $identifier)->value('username'); + + return $this->fetchUserByName($username); + } + + /** + * Retrieve a user by their unique identifier and "remember me" token. + * + * @param mixed $identifier + * @param string $token + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByToken($identifier, $token) + { + $user = new User(); + $user = $user->where($user->getAuthIdentifierName(), $identifier)->first(); + + if (!$user) { + return null; + } + + $rememberToken = $user->getRememberToken(); + if ($rememberToken && hash_equals($rememberToken, $token)) { + if (LegacyAuth::get()->userExists($user->username)) { + return $user; + } + } + + return null; + } + + /** + * Update the "remember me" token for the given user in storage. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param string $token + * @return void + */ + public function updateRememberToken(Authenticatable $user, $token) + { + $user->setRememberToken($token); + $timestamps = $user->timestamps; + $user->timestamps = false; + $user->save(); + $user->timestamps = $timestamps; + } + + /** + * Retrieve a user by the given credentials. + * + * @param array $credentials + * @return \Illuminate\Contracts\Auth\Authenticatable|null + */ + public function retrieveByCredentials(array $credentials) + { + return $this->fetchUserByName($credentials['username'], $credentials['password']); + } + + /** + * Validate a user against the given credentials. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param array $credentials + * @return bool + */ + public function validateCredentials(Authenticatable $user, array $credentials) + { + error_reporting(0); + + $authorizer = LegacyAuth::get(); + + try { + // try authentication methods + // collect username and password + $password = null; + if (isset($credentials['username']) && isset($credentials['password'])) { + $username = $credentials['username']; + $password = $credentials['password']; + } elseif ($authorizer->authIsExternal()) { + $username = $authorizer->getExternalUsername(); + } + + if (!isset($username) || !$authorizer->authenticate($username, $password)) { + throw new AuthenticationException('Invalid Credentials'); + } + + return true; + } catch (AuthenticationException $ae) { + global $debug; + + $auth_message = $ae->getMessage(); + if ($debug) { + $auth_message .= '
' . $ae->getFile() . ': ' . $ae->getLine(); + } + \Toastr::error($auth_message); + + if (empty($username)) { + $username = Session::get('username', $credentials['username']); + } + DB::table('authlog')->insert(['user' => $username, 'address' => Request::ip(), 'result' => $auth_message]); + } finally { + error_reporting(-1); + } + + return false; + } + + /** + * Fetch user by username from legacy auth, update it or add it to the db then return it. + * + * @param string $username + * @return User|null + */ + protected function fetchUserByName($username, $password = null) + { + error_reporting(0); + + $auth = LegacyAuth::get(); + $type = LegacyAuth::getType(); + + $auth_id = $auth->getUserid($username); + $new_user = $auth->getUser($auth_id); + + error_reporting(-1); + + if (empty($new_user)) { + // some legacy auth create users in the authenticate method, if it doesn't exist yet, lets try authenticate (Laravel calls retrieveByCredentials first) + try { + error_reporting(0); + + $auth->authenticate($username, $password); + $auth_id = $auth->getUserid($username); + $new_user = $auth->getUser($auth_id); + + error_reporting(-1); + } catch (AuthenticationException $ae) { + // + } + + if (empty($new_user)) { + return null; + } + } + + unset($new_user['user_id']); + + // remove null fields + $new_user = array_filter($new_user, function ($var) { + return !is_null($var); + }); + + // always create an entry in the users table, but separate by type + $user = User::thisAuth()->firstOrNew(['username' => $username], $new_user); + /** @var User $user */ + + // doing this here in case it was null (legacy) + $user->auth_type = $type; + $user->auth_id = $auth_id; + $user->save(); + + return $user; + } +} diff --git a/app/Extensions/LegacyUserProvider.php b/app/Providers/TokenUserProvider.php similarity index 66% rename from app/Extensions/LegacyUserProvider.php rename to app/Providers/TokenUserProvider.php index 188af5856d..141f60f46f 100644 --- a/app/Extensions/LegacyUserProvider.php +++ b/app/Providers/TokenUserProvider.php @@ -1,6 +1,6 @@ */ -namespace App\Extensions; +namespace App\Providers; -use App\Models\User; +use App\Models\ApiToken; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; -use LibreNMS\Authentication\Auth as LegacyAuth; -use LibreNMS\Exceptions\AuthenticationException; -class LegacyUserProvider implements UserProvider +class TokenUserProvider extends LegacyUserProvider implements UserProvider { - - /** - * Retrieve a user by their unique identifier. - * - * @param mixed $identifier - * @return \Illuminate\Contracts\Auth\Authenticatable|null - */ - public function retrieveById($identifier) - { - $user_array = LegacyAuth::get()->getUser($identifier); - if (empty($user_array)) { - return null; - } - - $user = new User($user_array); - $user->user_id = $user_array['user_id']; - - return $user; - } - /** * Retrieve a user by their unique identifier and "remember me" token. * @@ -62,7 +40,7 @@ class LegacyUserProvider implements UserProvider */ public function retrieveByToken($identifier, $token) { - // TODO: Implement retrieveByToken() method. + return null; } /** @@ -74,7 +52,7 @@ class LegacyUserProvider implements UserProvider */ public function updateRememberToken(Authenticatable $user, $token) { - // TODO: Implement updateRememberToken() method. + return; } /** @@ -85,8 +63,17 @@ class LegacyUserProvider implements UserProvider */ public function retrieveByCredentials(array $credentials) { - $username = $credentials['username']; - $user_id = LegacyAuth::get()->getUserid($username); + if (!ApiToken::isValid($credentials['api_token'])) { + return null; + } + + $user = ApiToken::userFromToken($credentials['api_token']); + if (!is_null($user)) { + return $user; + } + + // missing user for existing token, create it + $user_id = ApiToken::idFromToken($credentials['api_token']); return $this->retrieveById($user_id); } @@ -100,12 +87,6 @@ class LegacyUserProvider implements UserProvider */ public function validateCredentials(Authenticatable $user, array $credentials) { - try { - return LegacyAuth::get()->authenticate($credentials['username'], $credentials['password']); - } catch (AuthenticationException $e) { - \Toastr::error($e->getMessage()); - } - - return null; + return ApiToken::isValid($credentials['api_token'], $user->user_id); } } diff --git a/config/auth.php b/config/auth.php index cc5256811a..aefe6ee379 100644 --- a/config/auth.php +++ b/config/auth.php @@ -41,9 +41,9 @@ return [ 'provider' => 'legacy', ], - 'api' => [ - 'driver' => 'token', - 'provider' => 'legacy', + 'token' => [ + 'driver' => 'token_driver', + 'provider' => 'token_provider', ], ], @@ -71,7 +71,8 @@ return [ ], 'legacy' => [ - 'driver' => 'legacy' + 'driver' => 'legacy', + 'model' => App\Models\User::class, ], ], diff --git a/config/debugbar.php b/config/debugbar.php index 0fb450fd83..bfcb819df7 100644 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -13,6 +13,9 @@ return [ */ 'enabled' => env('DEBUGBAR_ENABLED', null), + 'except' => [ + 'api*' // won't work until DebugBar 3.* + ], /* |-------------------------------------------------------------------------- @@ -74,7 +77,7 @@ return [ | */ 'error_handler' => false, - + /* |-------------------------------------------------------------------------- | Clockwork integration diff --git a/doc/Developing/Code-Structure.md b/doc/Developing/Code-Structure.md index c3dfd6f6ac..d740bef37a 100644 --- a/doc/Developing/Code-Structure.md +++ b/doc/Developing/Code-Structure.md @@ -20,7 +20,7 @@ All used css files are located here. Apart from legacy files, anything in here i ### html/css/custom This is a folder you can put custom css files into that won't interfere with auto updates ### html/forms -This folder contains all of the files that are dynamically included from an ajax call to html/ajax_form.php. +This folder contains all of the files that are dynamically included from an ajax call to ajax/form. ### html/includes This is where the majority of the website core files are located. These tend to be files that contain functions or often used code segments that can be included where needed rather than duplicating code. ### html/includes/api_functions.inc.php diff --git a/html/ajax_dash.php b/html/ajax_dash.php index 1c07620414..6d06202676 100644 --- a/html/ajax_dash.php +++ b/html/ajax_dash.php @@ -12,14 +12,14 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; set_debug($_REQUEST['debug']); -if (!Auth::check()) { +if (!LegacyAuth::check()) { echo 'unauthenticated'; exit; } diff --git a/html/ajax_form.php b/html/ajax_form.php index 50a0cec201..961121efa5 100644 --- a/html/ajax_form.php +++ b/html/ajax_form.php @@ -14,14 +14,14 @@ // FUA -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth', 'alerts', 'laravel'); require realpath(__DIR__ . '/..') . '/includes/init.php'; set_debug(isset($_REQUEST['debug']) ? $_REQUEST['debug'] : false); -if (!Auth::check()) { +if (!LegacyAuth::check()) { echo 'unauthenticated'; exit; } diff --git a/html/ajax_list.php b/html/ajax_list.php index 18892047df..08f77d5edc 100644 --- a/html/ajax_list.php +++ b/html/ajax_list.php @@ -13,12 +13,12 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; -if (!Auth::check()) { +if (!LegacyAuth::check()) { echo "Unauthenticated\n"; exit; } diff --git a/html/ajax_listports.php b/html/ajax_listports.php index 00db34c839..b9b022b777 100644 --- a/html/ajax_listports.php +++ b/html/ajax_listports.php @@ -10,14 +10,14 @@ * @copyright (C) 2006 - 2012 Adam Armstrong */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; set_debug($_REQUEST['debug']); -if (!Auth::check()) { +if (!LegacyAuth::check()) { echo 'unauthenticated'; exit; } diff --git a/html/ajax_ossuggest.php b/html/ajax_ossuggest.php index f3609a706f..f3418f59f0 100644 --- a/html/ajax_ossuggest.php +++ b/html/ajax_ossuggest.php @@ -15,12 +15,12 @@ * along with this program. If not, see . */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; -if (!Auth::check()) { +if (!LegacyAuth::check()) { die('Unauthorized.'); } diff --git a/html/ajax_output.php b/html/ajax_output.php index aa2a2d41f7..a032625393 100644 --- a/html/ajax_output.php +++ b/html/ajax_output.php @@ -12,7 +12,7 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; session_start(); if (isset($_SESSION['stage']) && $_SESSION['stage'] == 2) { @@ -22,7 +22,7 @@ if (isset($_SESSION['stage']) && $_SESSION['stage'] == 2) { $init_modules = array('web', 'auth', 'alerts'); require realpath(__DIR__ . '/..') . '/includes/init.php'; - if (!Auth::check()) { + if (!LegacyAuth::check()) { echo "Unauthenticated\n"; exit; } diff --git a/html/ajax_rulesuggest.php b/html/ajax_rulesuggest.php index 3afe8006c8..2fbc43f418 100644 --- a/html/ajax_rulesuggest.php +++ b/html/ajax_rulesuggest.php @@ -23,12 +23,12 @@ * @package LibreNMS/Alerts */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; -if (!Auth::check()) { +if (!LegacyAuth::check()) { die('Unauthorized.'); } diff --git a/html/ajax_search.php b/html/ajax_search.php index 99526fc7de..5347137b1a 100644 --- a/html/ajax_search.php +++ b/html/ajax_search.php @@ -1,13 +1,13 @@ hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT * FROM `devices` WHERE `hostname` LIKE '%".$search."%' OR `location` LIKE '%".$search."%' OR `sysName` LIKE '%".$search."%' OR `purpose` LIKE '%".$search."%' OR `notes` LIKE '%".$search."%' ORDER BY hostname LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT * FROM `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND (`hostname` LIKE '%".$search."%' OR `location` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(Auth::id())); + $results = dbFetchRows("SELECT * FROM `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND (`hostname` LIKE '%".$search."%' OR `location` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(LegacyAuth::id())); } if (count($results)) { @@ -70,10 +70,10 @@ if (isset($_REQUEST['search'])) { $highlight_colour = '#008000'; } - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $num_ports = dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE device_id = ?', array($result['device_id'])); } else { - $num_ports = dbFetchCell('SELECT COUNT(*) FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `I`.`device_id` = `D`.`device_id` AND device_id = ?', array(Auth::id(), $result['device_id'])); + $num_ports = dbFetchCell('SELECT COUNT(*) FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `I`.`device_id` = `D`.`device_id` AND device_id = ?', array(LegacyAuth::id(), $result['device_id'])); } $device[] = array( @@ -95,10 +95,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'ports') { // Search ports - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT `ports`.*,`devices`.* FROM `ports` LEFT JOIN `devices` ON `ports`.`device_id` = `devices`.`device_id` WHERE `ifAlias` LIKE '%".$search."%' OR `ifDescr` LIKE '%".$search."%' OR `ifName` LIKE '%".$search."%' ORDER BY ifDescr LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT DISTINCT(`I`.`port_id`), `I`.*, `D`.`hostname` FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` AND (`ifAlias` LIKE '%".$search."%' OR `ifDescr` LIKE '%".$search."%' OR `ifName` LIKE '%".$search."%') ORDER BY ifDescr LIMIT ".$limit, array(Auth::id(), Auth::id())); + $results = dbFetchRows("SELECT DISTINCT(`I`.`port_id`), `I`.*, `D`.`hostname` FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` AND (`ifAlias` LIKE '%".$search."%' OR `ifDescr` LIKE '%".$search."%' OR `ifName` LIKE '%".$search."%') ORDER BY ifDescr LIMIT ".$limit, array(LegacyAuth::id(), LegacyAuth::id())); } if (count($results)) { @@ -141,10 +141,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'bgp') { // Search bgp peers - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT `bgpPeers`.*,`devices`.* FROM `bgpPeers` LEFT JOIN `devices` ON `bgpPeers`.`device_id` = `devices`.`device_id` WHERE `astext` LIKE '%".$search."%' OR `bgpPeerIdentifier` LIKE '%".$search."%' OR `bgpPeerRemoteAs` LIKE '%".$search."%' ORDER BY `astext` LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT `bgpPeers`.*,`D`.* FROM `bgpPeers`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `bgpPeers`.`device_id`=`D`.`device_id` AND (`astext` LIKE '%".$search."%' OR `bgpPeerIdentifier` LIKE '%".$search."%' OR `bgpPeerRemoteAs` LIKE '%".$search."%') ORDER BY `astext` LIMIT ".$limit, array(Auth::id())); + $results = dbFetchRows("SELECT `bgpPeers`.*,`D`.* FROM `bgpPeers`, `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` AND `bgpPeers`.`device_id`=`D`.`device_id` AND (`astext` LIKE '%".$search."%' OR `bgpPeerIdentifier` LIKE '%".$search."%' OR `bgpPeerRemoteAs` LIKE '%".$search."%') ORDER BY `astext` LIMIT ".$limit, array(LegacyAuth::id())); } if (count($results)) { @@ -191,10 +191,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'applications') { // Device search - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT * FROM `applications` INNER JOIN `devices` ON devices.device_id = applications.device_id WHERE `app_type` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%' ORDER BY hostname LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT * FROM `applications` INNER JOIN `devices` AS `D` ON `D`.`device_id` = `applications`.`device_id` INNER JOIN `devices_perms` AS `P` ON `P`.`device_id` = `D`.`device_id` WHERE `P`.`user_id` = ? AND (`app_type` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(Auth::id())); + $results = dbFetchRows("SELECT * FROM `applications` INNER JOIN `devices` AS `D` ON `D`.`device_id` = `applications`.`device_id` INNER JOIN `devices_perms` AS `P` ON `P`.`device_id` = `D`.`device_id` WHERE `P`.`user_id` = ? AND (`app_type` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(LegacyAuth::id())); } if (count($results)) { @@ -232,10 +232,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'munin') { // Device search - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT * FROM `munin_plugins` INNER JOIN `devices` ON devices.device_id = munin_plugins.device_id WHERE `mplug_type` LIKE '%".$search."%' OR `mplug_title` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%' ORDER BY hostname LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT * FROM `munin_plugins` INNER JOIN `devices` AS `D` ON `D`.`device_id` = `munin_plugins`.`device_id` INNER JOIN `devices_perms` AS `P` ON `P`.`device_id` = `D`.`device_id` WHERE `P`.`user_id` = ? AND (`mplug_type` LIKE '%".$search."%' OR `mplug_title` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(Auth::id())); + $results = dbFetchRows("SELECT * FROM `munin_plugins` INNER JOIN `devices` AS `D` ON `D`.`device_id` = `munin_plugins`.`device_id` INNER JOIN `devices_perms` AS `P` ON `P`.`device_id` = `D`.`device_id` WHERE `P`.`user_id` = ? AND (`mplug_type` LIKE '%".$search."%' OR `mplug_title` LIKE '%".$search."%' OR `hostname` LIKE '%".$search."%') ORDER BY hostname LIMIT ".$limit, array(LegacyAuth::id())); } if (count($results)) { @@ -273,10 +273,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'iftype') { // Device search - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT `ports`.ifType FROM `ports` WHERE `ifType` LIKE '%".$search."%' GROUP BY ifType ORDER BY ifType LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT `I`.ifType FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` AND (`ifType` LIKE '%".$search."%') GROUP BY ifType ORDER BY ifType LIMIT ".$limit, array(Auth::id(), Auth::id())); + $results = dbFetchRows("SELECT `I`.ifType FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` AND (`ifType` LIKE '%".$search."%') GROUP BY ifType ORDER BY ifType LIMIT ".$limit, array(LegacyAuth::id(), LegacyAuth::id())); } if (count($results)) { $found = 1; @@ -293,10 +293,10 @@ if (isset($_REQUEST['search'])) { die($json); } elseif ($_REQUEST['type'] == 'bill') { // Device search - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT `bills`.bill_id, `bills`.bill_name FROM `bills` WHERE `bill_name` LIKE '%".$search."%' OR `bill_notes` LIKE '%".$search."%' LIMIT ".$limit); } else { - $results = dbFetchRows("SELECT `bills`.bill_id, `bills`.bill_name FROM `bills` INNER JOIN `bill_perms` ON `bills`.bill_id = `bill_perms`.bill_id WHERE `bill_perms`.user_id = ? AND (`bill_name` LIKE '%".$search."%' OR `bill_notes` LIKE '%".$search."%') LIMIT ".$limit, array(Auth::id())); + $results = dbFetchRows("SELECT `bills`.bill_id, `bills`.bill_name FROM `bills` INNER JOIN `bill_perms` ON `bills`.bill_id = `bill_perms`.bill_id WHERE `bill_perms`.user_id = ? AND (`bill_name` LIKE '%".$search."%' OR `bill_notes` LIKE '%".$search."%') LIMIT ".$limit, array(LegacyAuth::id())); } $json = json_encode($results); die($json); diff --git a/html/ajax_table.php b/html/ajax_table.php index 430e63e1ed..7c0631560b 100644 --- a/html/ajax_table.php +++ b/html/ajax_table.php @@ -12,12 +12,12 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $init_modules = array('web', 'auth'); require realpath(__DIR__ . '/..') . '/includes/init.php'; -if (!Auth::check()) { +if (!LegacyAuth::check()) { echo "Unauthenticated\n"; exit; } diff --git a/html/css/styles.css b/html/css/styles.css index 1349b5fd79..628aa41c91 100644 --- a/html/css/styles.css +++ b/html/css/styles.css @@ -2147,7 +2147,8 @@ label { } .device-table-icon img { - width: 32px; + width: 32px; + max-height: 32px; } .device-icon img { @@ -2171,6 +2172,7 @@ label { display: inline-block; width: 7px; min-height: 27px; + height: 32px; } .device-services-page { @@ -2199,3 +2201,7 @@ label { .select2-selection--multiple .select2-search--inline .select2-search__field { width: auto !important; } + +.toast-top-right { + top: 34px; +} diff --git a/html/includes/api_functions.inc.php b/html/includes/api_functions.inc.php index 21b730422e..fd5811a200 100644 --- a/html/includes/api_functions.inc.php +++ b/html/includes/api_functions.inc.php @@ -12,25 +12,22 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; function authToken(\Slim\Route $route) { global $permissions; - $app = \Slim\Slim::getInstance(); - $token = $app->request->headers->get('X-Auth-Token'); - if (!empty($token) - && ($user_id = dbFetchCell('SELECT `AT`.`user_id` FROM `api_tokens` AS AT WHERE `AT`.`token_hash`=? && `AT`.`disabled`=0', array($token))) - && ($user = Auth::get()->getUser($user_id)) - ) { + if (Auth::check()) { + $user = Auth::user(); + // Fake session so the standard auth/permissions checks work - $_SESSION = array( - 'username' => $user['username'], - 'user_id' => $user['user_id'], - 'userlevel' => $user['level'] - ); - $permissions = permissions_cache(Auth::id()); + $_SESSION = [ + 'username' => $user->username, + 'user_id' => $user->user_id, + 'userlevel' => $user->level + ]; + $permissions = permissions_cache($user->user_id); return; } @@ -109,14 +106,14 @@ function check_port_permission($port_id, $device_id) function check_is_admin() { - if (!Auth::user()->hasGlobalAdmin()) { + if (!LegacyAuth::user()->hasGlobalAdmin()) { api_error(403, 'Insufficient privileges'); } } function check_is_read() { - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { api_error(403, 'Insufficient privileges'); } } @@ -353,9 +350,9 @@ function list_devices() } - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= " AND `d`.`device_id` IN (SELECT device_id FROM devices_perms WHERE user_id = ?)"; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $devices = array(); $dev_query = "SELECT $select FROM `devices` AS d $join WHERE $sql GROUP BY d.`hostname` ORDER BY $order"; @@ -583,9 +580,9 @@ function list_cbgp() $sql = " AND `devices`.`device_id` = ?"; $sql_params[] = $device_id; } - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= " AND `bgpPeers_cbgp`.`device_id` IN (SELECT device_id FROM devices_perms WHERE user_id = ?)"; - $sql_params[] = Auth::id(); + $sql_params[] = LegacyAuth::id(); } $bgp_counters = array(); @@ -910,7 +907,7 @@ function get_port_graphs() $params = array($device_id); if (!device_permitted($device_id)) { $sql = 'AND `port_id` IN (select `port_id` from `ports_perms` where `user_id` = ?)'; - array_push($params, Auth::id()); + array_push($params, LegacyAuth::id()); } $ports = dbFetchRows("SELECT $columns FROM `ports` WHERE `device_id` = ? AND `deleted` = '0' $sql ORDER BY `ifIndex` ASC", $params); @@ -980,10 +977,10 @@ function get_all_ports() validate_column_list($columns, 'ports'); $params = array(); $sql = ''; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql = ' AND (device_id IN (SELECT device_id FROM devices_perms WHERE user_id = ?) OR port_id IN (SELECT port_id FROM ports_perms WHERE user_id = ?))'; - array_push($params, Auth::id()); - array_push($params, Auth::id()); + array_push($params, LegacyAuth::id()); + array_push($params, LegacyAuth::id()); } $ports = dbFetchRows("SELECT $columns FROM `ports` WHERE `deleted` = 0 $sql", $params); @@ -1322,9 +1319,9 @@ function list_bills() } else { $sql = '1'; } - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' AND `bill_id` IN (SELECT `bill_id` FROM `bill_perms` WHERE `user_id` = ?)'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } if ($period === 'previous') { @@ -1380,7 +1377,7 @@ function get_bill_graph() $bill_id = mres($router['bill_id']); $graph_type = $router['graph_type']; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { check_bill_permission($bill_id); } @@ -1406,7 +1403,7 @@ function get_bill_graphdata() $bill_id = mres($router['bill_id']); $graph_type = $router['graph_type']; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { check_bill_permission($bill_id); } @@ -1434,7 +1431,7 @@ function get_bill_history() $router = $app->router()->getCurrentRoute()->getParams(); $bill_id = mres($router['bill_id']); - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { check_bill_permission($bill_id); } @@ -1456,7 +1453,7 @@ function get_bill_history_graph() $bill_hist_id = mres($router['bill_hist_id']); $graph_type = $router['graph_type']; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { check_bill_permission($bill_id); } @@ -1500,7 +1497,7 @@ function get_bill_history_graphdata() $bill_hist_id = mres($router['bill_hist_id']); $graph_type = $router['graph_type']; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { check_bill_permission($bill_id); } @@ -1829,9 +1826,9 @@ function list_vrf() $sql = " AND `vrfs`.`vrf_name`=?"; $sql_params = array($vrfname); } - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= " AND `vrfs`.`device_id` IN (SELECT device_id FROM devices_perms WHERE user_id = ?)"; - $sql_params[] = Auth::id(); + $sql_params[] = LegacyAuth::id(); } $vrfs = array(); @@ -1902,9 +1899,9 @@ function list_vlans() $sql = " AND `devices`.`device_id` = ?"; $sql_params[] = $device_id; } - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= " AND `vlans`.`device_id` IN (SELECT device_id FROM devices_perms WHERE user_id = ?)"; - $sql_params[] = Auth::id(); + $sql_params[] = LegacyAuth::id(); } $vlans = array(); diff --git a/html/includes/authenticate.inc.php b/html/includes/authenticate.inc.php deleted file mode 100644 index e7d95ba638..0000000000 --- a/html/includes/authenticate.inc.php +++ /dev/null @@ -1,87 +0,0 @@ -= 5.5.2 -ini_set('session.use_trans_sid', 0); // insecure feature, be sure it is disabled - -// Clear up any old sessions -dbDelete('session', '`session_expiry` < ?', array(time())); - -session_start(); - -$authorizer = Auth::get(); -if ($vars['page'] == 'logout' && $authorizer->sessionAuthenticated()) { - $authorizer->logOutUser(); - header('Location: ' . Config::get('post_logout_action', Config::get('base_url'))); - exit; -} - -try { - if ($authorizer->sessionAuthenticated()) { - // session authenticated already - $authorizer->logInUser(); - } else { - // try authentication methods - - if (isset($_POST['twofactor']) && TwoFactor::authenticate($_POST['twofactor'])) { - // process two-factor auth tokens - $authorizer->logInUser(); - } elseif (isset($_COOKIE['sess_id'], $_COOKIE['token']) && - $authorizer->reauthenticate(clean($_COOKIE['sess_id']), clean($_COOKIE['token'])) - ) { - $_SESSION['remember'] = true; - $_SESSION['twofactor'] = true; // trust cookie - // cookie authentication - $authorizer->logInUser(); - } else { - // collect username and password - $password = null; - if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) { - $username = clean($_REQUEST['username']); - $password = $_REQUEST['password']; - } elseif ($authorizer->authIsExternal()) { - $username = $authorizer->getExternalUsername(); - } - - // form authentication - if (isset($username) && $authorizer->authenticate($username, $password)) { - $_SESSION['username'] = $username; - - if (isset($_POST['remember'])) { - $_SESSION['remember'] = $_POST['remember']; - } - - if ($authorizer->logInUser()) { - // redirect to original uri or home page. - header('Location: '.rtrim($config['base_url'], '/').$_SERVER['REQUEST_URI'], true, 303); - } - } - } - } -} catch (AuthenticationException $ae) { - $auth_message = $ae->getMessage(); - if ($debug) { - $auth_message .= '
' . $ae->getFile() . ': ' . $ae->getLine(); - } - - dbInsert( - array('user' => $_SESSION['username'], 'address' => get_client_ip(), 'result' => $auth_message), - 'authlog' - ); - $authorizer->logOutUser($auth_message); -} - -session_write_close(); - -// populate the permissions cache -if (isset($_SESSION['user_id'])) { - $permissions = permissions_cache($_SESSION['user_id']); -} - -unset($username, $password); diff --git a/html/includes/common/availability-map.inc.php b/html/includes/common/availability-map.inc.php index 70bb7375db..c57083f866 100644 --- a/html/includes/common/availability-map.inc.php +++ b/html/includes/common/availability-map.inc.php @@ -12,7 +12,7 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; if (isset($widget_settings['mode_select']) && $widget_settings['mode_select'] !== '') { $mode = $widget_settings['mode_select']; @@ -173,9 +173,9 @@ if (defined('SHOW_SETTINGS')) { $sql = 'SELECT `D`.`hostname`, `D`.`sysName`, `D`.`device_id`, `D`.`status`, `D`.`uptime`, `D`.`os`, `D`.`icon`, `D`.`ignore`, `D`.`disabled` FROM `devices` AS `D`'; - if (!Auth::user()->hasGlobalRead()) { + if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' , `devices_perms` AS P WHERE D.`device_id` = P.`device_id` AND P.`user_id` = ? AND '; - $param = [Auth::id()]; + $param = [LegacyAuth::id()]; } else { $sql .= ' WHERE '; $param = []; @@ -253,12 +253,12 @@ if (defined('SHOW_SETTINGS')) { } if (($mode == 1 || $mode == 2) && ($config['show_services'] != 0)) { - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $service_query = 'select `S`.`service_type`, `S`.`service_id`, `S`.`service_desc`, `S`.`service_status`, `D`.`hostname`, `D`.`sysName`, `D`.`device_id`, `D`.`os`, `D`.`icon` from services S, devices D where `S`.`device_id` = `D`.`device_id` ORDER BY '.$serviceOrderBy.';'; $service_par = array(); } else { $service_query = 'select `S`.`service_type`, `S`.`service_id`, `S`.`service_desc`, `S`.`service_status`, `D`.`hostname`, `D`.`sysName`, `D`.`device_id`, `D`.`os`, `D`.`icon` from services S, devices D, devices_perms P where `S`.`device_id` = `D`.`device_id` AND D.device_id = P.device_id AND P.user_id = ? ORDER BY '.$serviceOrderBy.';'; - $service_par = array(Auth::id()); + $service_par = array(LegacyAuth::id()); } $services = dbFetchRows($service_query, $service_par); if (count($services) > 0) { diff --git a/html/includes/common/graylog.inc.php b/html/includes/common/graylog.inc.php index d520f903a5..c99c802bac 100644 --- a/html/includes/common/graylog.inc.php +++ b/html/includes/common/graylog.inc.php @@ -17,7 +17,7 @@ * @author LibreNMS Contributors */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; if (empty($results_limit)) { $results_limit = 25; @@ -55,10 +55,10 @@ if (!empty($filter_device)) { ""+ '; - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $results = dbFetchRows("SELECT `hostname` FROM `devices` GROUP BY `hostname` ORDER BY `hostname`"); } else { - $results = dbFetchRows("SELECT `D`.`hostname` FROM `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` GROUP BY `hostname` ORDER BY `hostname`", array(Auth::id())); + $results = dbFetchRows("SELECT `D`.`hostname` FROM `devices` AS `D`, `devices_perms` AS `P` WHERE `P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id` GROUP BY `hostname` ORDER BY `hostname`", array(LegacyAuth::id())); } foreach ($results as $data) { diff --git a/html/includes/common/server-stats.inc.php b/html/includes/common/server-stats.inc.php index f14e052291..3fd3dfd890 100644 --- a/html/includes/common/server-stats.inc.php +++ b/html/includes/common/server-stats.inc.php @@ -1,6 +1,6 @@
No @@ -177,11 +177,11 @@ $('#schedule-maintenance').on('show.bs.modal', function (event) { $('#notes').val(output['notes']); if (output['recurring'] == 0){ $('#start').val(output['start']); - $('#end').val(output['end']); + $('#end').val(output['end']); $('#norecurringgroup').show(); $('#recurringgroup').hide(); - + $('#start_recurring_dt').val(''); $('#end_recurring_dt').val(''); $('#start_recurring_hr').val(''); @@ -189,13 +189,13 @@ $('#schedule-maintenance').on('show.bs.modal', function (event) { $("#recurring0").prop("checked", true); $('#recurring_day').prop('checked', false); }else{ - + $('#start_recurring_dt').val(output['start_recurring_dt']); $('#end_recurring_dt').val(output['end_recurring_dt']); $('#start_recurring_hr').val(output['start_recurring_hr']); $('#end_recurring_hr').val(output['end_recurring_hr']); $("#recurring1").prop("checked", true); - + var recdayupd = output['recurring_day']; if (recdayupd != ''){ var arrayrecdayupd = recdayupd.split(','); @@ -203,12 +203,12 @@ $('#schedule-maintenance').on('show.bs.modal', function (event) { $("input[name='recurring_day[]'][value="+checkedday+"]").prop('checked', true); }); }else{ - $('#recurring_day').prop('checked', false); + $('#recurring_day').prop('checked', false); } - + $('#norecurringgroup').hide(); $('#recurringgroup').show(); - + $('#start').val(''); $('#end').val(''); } @@ -219,7 +219,7 @@ $('#schedule-maintenance').on('show.bs.modal', function (event) { }); $('#sched-form input[name=recurring]').on('change', function() { - var isrecurring = $('input[name=recurring]:checked', '#sched-form').val(); + var isrecurring = $('input[name=recurring]:checked', '#sched-form').val(); if (isrecurring == 1){ $('#norecurringgroup').hide(); $('#recurringgroup').show(); diff --git a/html/includes/modal/alert_template.inc.php b/html/includes/modal/alert_template.inc.php index ba84c8e0a8..0f0e110686 100644 --- a/html/includes/modal/alert_template.inc.php +++ b/html/includes/modal/alert_template.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/attach_alert_template.inc.php b/html/includes/modal/attach_alert_template.inc.php index 5a8457f4a9..6f8ea71625 100644 --- a/html/includes/modal/attach_alert_template.inc.php +++ b/html/includes/modal/attach_alert_template.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/delete_alert_rule.inc.php b/html/includes/modal/delete_alert_rule.inc.php index 05c774728f..dbbd6ad932 100644 --- a/html/includes/modal/delete_alert_rule.inc.php +++ b/html/includes/modal/delete_alert_rule.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/delete_alert_template.inc.php b/html/includes/modal/delete_alert_template.inc.php index 3120b1de4f..ed31752b02 100644 --- a/html/includes/modal/delete_alert_template.inc.php +++ b/html/includes/modal/delete_alert_template.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/delete_device_group.inc.php b/html/includes/modal/delete_device_group.inc.php index e96453067f..c5f84c0183 100644 --- a/html/includes/modal/delete_device_group.inc.php +++ b/html/includes/modal/delete_device_group.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/delete_host_dependency.inc.php b/html/includes/modal/delete_host_dependency.inc.php index f1984a54d3..9f34b241e0 100644 --- a/html/includes/modal/delete_host_dependency.inc.php +++ b/html/includes/modal/delete_host_dependency.inc.php @@ -11,9 +11,9 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (!Auth::user()->hasGlobalAdmin()) { +if (!LegacyAuth::user()->hasGlobalAdmin()) { die('ERROR: You need to be admin'); } diff --git a/html/includes/modal/delete_poller.inc.php b/html/includes/modal/delete_poller.inc.php index 8710d799ea..bdd8b5a766 100644 --- a/html/includes/modal/delete_poller.inc.php +++ b/html/includes/modal/delete_poller.inc.php @@ -23,9 +23,9 @@ * @author Tony Murray */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; -if (Auth::user()->hasGlobalAdmin()) { +if (LegacyAuth::user()->hasGlobalAdmin()) { ?> "); } else { - if (Auth::user()->hasGlobalAdmin()) { + if (LegacyAuth::user()->hasGlobalAdmin()) { $query = "SELECT *,DATE_FORMAT(datetime, '".$config['dateformat']['mysql']['compact']."') as humandate FROM `eventlog` ORDER BY `datetime` DESC LIMIT 0,15"; } else { $query = "SELECT *,DATE_FORMAT(datetime, '".$config['dateformat']['mysql']['compact']."') as humandate FROM `eventlog` AS E, devices_perms AS P WHERE E.host = - P.device_id AND P.user_id = " . Auth::id() . " ORDER BY `datetime` DESC LIMIT 0,15"; + P.device_id AND P.user_id = " . LegacyAuth::id() . " ORDER BY `datetime` DESC LIMIT 0,15"; } echo('
diff --git a/html/pages/front/jt.php b/html/pages/front/jt.php index 61adfdf795..643c82ad62 100644 --- a/html/pages/front/jt.php +++ b/html/pages/front/jt.php @@ -3,7 +3,7 @@ '; // this stuff can be customised to show whatever you want.... -if (Auth::user()->hasGlobalRead()) { +if (LegacyAuth::user()->hasGlobalRead()) { $sql = "SELECT * FROM ports AS I, devices AS D WHERE `ifAlias` like 'Transit: %' AND I.device_id = D.device_id ORDER BY I.ifAlias"; unset($seperator); foreach (dbFetchRows($sql) as $interface) { diff --git a/html/pages/front/map.php b/html/pages/front/map.php index ce88edcfdc..418914a983 100644 --- a/html/pages/front/map.php +++ b/html/pages/front/map.php @@ -22,7 +22,7 @@ * @subpackage Frontpage */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; if ($config['map']['engine'] == 'leaflet') { require_once 'includes/common/worldmap.inc.php'; @@ -186,11 +186,11 @@ if ($config['enable_syslog']) { echo("
"); echo("
"); } else { - if (Auth::user()->hasGlobalAdmin()) { + if (LegacyAuth::user()->hasGlobalAdmin()) { $query = "SELECT *,DATE_FORMAT(datetime, '".$config['dateformat']['mysql']['compact']."') as humandate FROM `eventlog` ORDER BY `datetime` DESC LIMIT 0,15"; } else { $query = "SELECT *,DATE_FORMAT(datetime, '".$config['dateformat']['mysql']['compact']."') as humandate FROM `eventlog` AS E, devices_perms AS P WHERE E.host = - P.device_id AND P.user_id = " . Auth::id() . " ORDER BY `datetime` DESC LIMIT 0,15"; + P.device_id AND P.user_id = " . LegacyAuth::id() . " ORDER BY `datetime` DESC LIMIT 0,15"; } echo('
diff --git a/html/pages/front/tiles.php b/html/pages/front/tiles.php index 124b0e628b..337f4d2d56 100644 --- a/html/pages/front/tiles.php +++ b/html/pages/front/tiles.php @@ -16,7 +16,7 @@ * Code for Gridster.sort_by_row_and_col_asc(serialization) call is from http://gridster.net/demos/grid-from-serialize.html */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $no_refresh = true; $default_dash = get_user_pref('dashboard', 0); @@ -26,7 +26,7 @@ require_once 'includes/modal/alert_notes.inc.php'; // get all dashboards this user can access and put them into two lists user_dashboards and shared_dashboards $dashboards = get_dashboards(); list($user_dashboards, $shared_dashboards) = array_reduce($dashboards, function ($ret, $dash) { - if ($dash['user_id'] == Auth::id()) { + if ($dash['user_id'] == LegacyAuth::id()) { $ret[0][] = $dash; } else { $ret[1][] = $dash; @@ -44,16 +44,16 @@ if (!isset($dashboards[$default_dash])) { if ($default_dash == 0 && empty($user_dashboards)) { $new_dash = array( 'dashboard_name'=>'Default', - 'user_id'=>Auth::id(), + 'user_id'=>LegacyAuth::id(), ); $dashboard_id = dbInsert($new_dash, 'dashboards'); $new_dash['dashboard_id'] = $dashboard_id; - $new_dash['username'] = Auth::user()->username; + $new_dash['username'] = LegacyAuth::user()->username; $vars['dashboard'] = $new_dash; - if (dbFetchCell('select 1 from users_widgets where user_id = ? && dashboard_id = ?', array(Auth::id(),0)) == 1) { - dbUpdate(array('dashboard_id'=>$dashboard_id), 'users_widgets', 'user_id = ? && dashboard_id = ?', array(Auth::id(), 0)); + if (dbFetchCell('select 1 from users_widgets where user_id = ? && dashboard_id = ?', array(LegacyAuth::id(),0)) == 1) { + dbUpdate(array('dashboard_id'=>$dashboard_id), 'users_widgets', 'user_id = ? && dashboard_id = ?', array(LegacyAuth::id(), 0)); } } else { // load a dashboard @@ -93,7 +93,7 @@ if (empty($vars['bare']) || $vars['bare'] == "no") {
- -
-
- 'error','message'=>$auth_message,'title'=>'Login error'); - } - ?> - - - -
-
-
'.$config['login_message'].'
'); - } - ?> -
-
-
- diff --git a/html/pages/notifications.inc.php b/html/pages/notifications.inc.php index a6ef3ba986..369a57601e 100644 --- a/html/pages/notifications.inc.php +++ b/html/pages/notifications.inc.php @@ -22,7 +22,7 @@ * @subpackage Notifications */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; use LibreNMS\ObjectCache; $notifications = new ObjectCache('notifications'); @@ -35,7 +35,7 @@ $notifications = new ObjectCache('notifications'); ' . $notifications['count'] . ' Unread Notifications '; -if (Auth::user()->hasGlobalAdmin()) { +if (LegacyAuth::user()->hasGlobalAdmin()) { echo ''; } @@ -87,8 +87,8 @@ foreach ($notifications['sticky'] as $notif) { echo " ${notif['title']}"; echo ""; - if ($notif['user_id'] != Auth::id()) { - $sticky_user = Auth::get()->getUser($notif['user_id']); + if ($notif['user_id'] != LegacyAuth::id()) { + $sticky_user = LegacyAuth::get()->getUser($notif['user_id']); echo "Sticky by ${sticky_user['username']}"; } else { echo ''; @@ -114,7 +114,7 @@ foreach ($notifications['sticky'] as $notif) { getUser($notif['source']); + $source_user = LegacyAuth::get()->getUser($notif['source']); $notif['source'] = $source_user['username']; } echo '
'; @@ -127,7 +127,7 @@ foreach ($notifications['unread'] as $notif) { } echo "

${notif['title']}"; - if (Auth::user()->hasGlobalAdmin()) { + if (LegacyAuth::user()->hasGlobalAdmin()) { echo ''; } ?> @@ -170,7 +170,7 @@ foreach (array_reverse($notifications['read']) as $notif) { } echo " id='${notif['notifications_id']}'>${notif['title']}"; - if (Auth::user()->isAdmin()) { + if (LegacyAuth::user()->isAdmin()) { echo ''; } ?> diff --git a/html/pages/plugin/admin.inc.php b/html/pages/plugin/admin.inc.php index e5ca8ac428..ccb5a28866 100644 --- a/html/pages/plugin/admin.inc.php +++ b/html/pages/plugin/admin.inc.php @@ -1,8 +1,8 @@ hasGlobalAdmin()) { +if (LegacyAuth::user()->hasGlobalAdmin()) { // Scan for new plugins and add to the database $new_plugins = scan_new_plugins(); diff --git a/html/pages/pollers/pollers.inc.php b/html/pages/pollers/pollers.inc.php index 5b83a728b4..bf05930dcf 100644 --- a/html/pages/pollers/pollers.inc.php +++ b/html/pages/pollers/pollers.inc.php @@ -12,13 +12,12 @@ * the source code distribution for details. */ -use LibreNMS\Authentication\Auth; use LibreNMS\Config; require_once 'includes/modal/delete_poller.inc.php'; ?> -
+
hasGlobalAdmin() && $old > ($step * 2)) { + if (\Auth::user()->hasGlobalAdmin() && $old > ($step * 2)) { // missed 2 polls show delete button $actions .= ""; } @@ -109,7 +108,7 @@ if (count($rows) !== 0) { } $actions = ""; - if (Auth::user()->hasGlobalAdmin() && $old > ($step * 2)) { + if (\Auth::user()->hasGlobalAdmin() && $old > ($step * 2)) { // missed 2 polls show delete button $actions .= ""; } @@ -153,7 +152,7 @@ if (count($rows) !== 0) { $first_row = false; } } - echo ' + echo ' Worker seconds indicates the maximum polling throughput a node can achieve in perfect conditions. If the consumed is close to the maximum, consider adding more threads, or better tuning your groups.
diff --git a/html/pages/ports.inc.php b/html/pages/ports.inc.php index 601ef2d19f..bc72e96c48 100644 --- a/html/pages/ports.inc.php +++ b/html/pages/ports.inc.php @@ -13,7 +13,7 @@ * @author LibreNMS Contributors */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $pagetitle[] = "Ports"; @@ -93,10 +93,10 @@ if ((isset($vars['searchbar']) && $vars['searchbar'] != "hide") || !isset($vars[ $output .= ""; $output .= ""; - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $sql = "SELECT `ifSpeed` FROM `ports` GROUP BY `ifSpeed` ORDER BY `ifSpeed`"; } else { $sql = "SELECT `ifSpeed` FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` GROUP BY `ifSpeed` ORDER BY `ifSpeed`"; - $param[] = array(Auth::id(), Auth::id()); + $param[] = array(LegacyAuth::id(), LegacyAuth::id()); } foreach (dbFetchRows($sql, $param) as $data) { @@ -188,11 +188,11 @@ if ((isset($vars['searchbar']) && $vars['searchbar'] != "hide") || !isset($vars[ $output .= ""; $output .= ""; - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $sql = "SELECT `port_descr_type` FROM `ports` GROUP BY `port_descr_type` ORDER BY `port_descr_type`"; } else { $sql = "SELECT `port_descr_type` FROM `ports` AS `I`, `devices` AS `D`, `devices_perms` AS `P`, `ports_perms` AS `PP` WHERE ((`P`.`user_id` = ? AND `P`.`device_id` = `D`.`device_id`) OR (`PP`.`user_id` = ? AND `PP`.`port_id` = `I`.`port_id` AND `I`.`device_id` = `D`.`device_id`)) AND `D`.`device_id` = `I`.`device_id` GROUP BY `port_descr_type` ORDER BY `port_descr_type`"; - $param[] = array(Auth::id(), Auth::id()); + $param[] = array(LegacyAuth::id(), LegacyAuth::id()); } $ports = dbFetchRows($sql, $param); diff --git a/html/pages/preferences.inc.php b/html/pages/preferences.inc.php index df06c39673..ef1e42777f 100644 --- a/html/pages/preferences.inc.php +++ b/html/pages/preferences.inc.php @@ -1,6 +1,6 @@ User Preferences

'; echo '
'; -if (Auth::user()->isDemoUser()) { +if (LegacyAuth::user()->isDemoUser()) { demo_account(); } else { if ($_POST['action'] == 'changepass') { - if (Auth::get()->authenticate(Auth::user()->username, $_POST['old_pass'])) { + if (LegacyAuth::get()->authenticate(LegacyAuth::user()->username, $_POST['old_pass'])) { if ($_POST['new_pass'] == '' || $_POST['new_pass2'] == '') { $changepass_message = 'Password must not be blank.'; } elseif ($_POST['new_pass'] == $_POST['new_pass2']) { - Auth::get()->changePassword(Auth::user()->username, $_POST['new_pass']); + LegacyAuth::get()->changePassword(LegacyAuth::user()->username, $_POST['new_pass']); $changepass_message = 'Password Changed.'; } else { $changepass_message = "Passwords don't match."; @@ -36,7 +36,7 @@ if (Auth::user()->isDemoUser()) { include 'includes/update-preferences-password.inc.php'; - if (Auth::get()->canUpdatePasswords(Auth::user()->username)) { + if (LegacyAuth::get()->canUpdatePasswords(LegacyAuth::user()->username)) { echo '

Change Password

'; echo '
'; echo "
"; @@ -75,103 +75,61 @@ if (Auth::user()->isDemoUser()) { }//end if if ($config['twofactor'] === true) { - if ($_POST['twofactorremove'] == 1) { - if (!isset($_POST['twofactor'])) { - echo '
'; - echo ''; - echo TwoFactor::getForm(false); - echo '
'; - } else { - $twofactor = get_user_pref('twofactor'); - if (empty($twofactor)) { - echo '
Error: How did you even get here?!
'; - } - - if (TwoFactor::verifyHOTP($twofactor['key'], $_POST['twofactor'], $twofactor['counter'])) { - if (!set_user_pref('twofactor', array())) { - echo '
Error while disabling TwoFactor.
'; - } else { - echo '
TwoFactor Disabled.
'; - } - } else { - session_destroy(); - echo '
Error: Supplied TwoFactor Token is wrong, you\'ve been logged out.
'; - } - }//end if - } else { - $twofactor = get_user_pref('twofactor'); - echo ''; - echo '

Two-Factor Authentication

'; - if (!empty($twofactor)) { - $twofactor['text'] = "
+ $twofactor = get_user_pref('twofactor'); + echo ''; + echo '

Two-Factor Authentication

'; + echo '
'; + echo '
'; + if (!empty($twofactor)) { + $twofactor['text'] = "
"; - if ($twofactor['counter'] !== false) { - $twofactor['uri'] = 'otpauth://hotp/'.Auth::user()->username.'?issuer=LibreNMS&counter='.$twofactor['counter'].'&secret='.$twofactor['key']; - $twofactor['text'] .= "
+ if ($twofactor['counter'] !== false) { + $twofactor['uri'] = 'otpauth://hotp/'.LegacyAuth::user()->username.'?issuer=LibreNMS&counter='.$twofactor['counter'].'&secret='.$twofactor['key']; + $twofactor['text'] .= "
"; - } else { - $twofactor['uri'] = 'otpauth://totp/'.Auth::user()->username.'?issuer=LibreNMS&secret='.$twofactor['key']; - } + } else { + $twofactor['uri'] = 'otpauth://totp/'.LegacyAuth::user()->username.'?issuer=LibreNMS&secret='.$twofactor['key']; + } - echo '
+ echo '
'; - echo '
+ echo '
'.$twofactor['text'].'
'; - echo ''; - echo '
- + echo ''; + echo '
'; - } else { - if (isset($_POST['gentwofactorkey']) && isset($_POST['twofactortype'])) { - $chk = get_user_pref('twofactor'); - if (empty($chk)) { - $twofactor = array('key' => TwoFactor::genKey()); - if ($_POST['twofactortype'] == 'counter') { - $twofactor['counter'] = 1; - } else { - $twofactor['counter'] = false; - } - - if (!set_user_pref('twofactor', $twofactor)) { - echo '
Error inserting TwoFactor details. Please try again later and contact Administrator if error persists.
'; - } else { - echo '
Added TwoFactor credentials. Please reload page.
'; - } - } else { - echo '
TwoFactor credentials already exists.
'; - } - } else { - echo '
- + } else { + echo '
- +
- +
+
+ +
+
'; - }//end if - }//end if - echo '
'; }//end if + echo '
'; }//end if }//end if @@ -207,13 +165,13 @@ echo " echo "

Device Permissions

"; echo "
"; -echo "
"; -if (Auth::user()->hasGlobalAdmin()) { +echo '
'; +if (LegacyAuth::user()->hasGlobalAdmin()) { echo "Global Administrative Access"; -} elseif (Auth::user()->hasGlobalRead()) { +} elseif (LegacyAuth::user()->hasGlobalRead()) { echo "Global Viewing Access"; } else { - foreach (dbFetchRows('SELECT * FROM `devices_perms` AS P, `devices` AS D WHERE `user_id` = ? AND P.device_id = D.device_id', array(Auth::id())) as $perm) { + foreach (dbFetchRows('SELECT * FROM `devices_perms` AS P, `devices` AS D WHERE `user_id` = ? AND P.device_id = D.device_id', array(LegacyAuth::id())) as $perm) { // FIXME generatedevicelink? echo "".$perm['hostname'].'
'; $dev_access = 1; diff --git a/html/pages/public.inc.php b/html/pages/public.inc.php deleted file mode 100644 index 71181a977e..0000000000 --- a/html/pages/public.inc.php +++ /dev/null @@ -1,58 +0,0 @@ - - * - * 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. Please see LICENSE.txt at the top level of - * the source code distribution for details. - */ - -?> - - - - -

System Status

-
-
- - - - - - - - - - -
DevicePlatformUptime/Location
-
-
diff --git a/html/pages/routing/bgp.inc.php b/html/pages/routing/bgp.inc.php index ae20221acd..68a93ad719 100644 --- a/html/pages/routing/bgp.inc.php +++ b/html/pages/routing/bgp.inc.php @@ -1,10 +1,10 @@ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { include 'includes/error-no-perm.inc.php'; } else { $link_array = array( diff --git a/html/pages/routing/vrf.inc.php b/html/pages/routing/vrf.inc.php index d65b0c5793..d63e259d73 100644 --- a/html/pages/routing/vrf.inc.php +++ b/html/pages/routing/vrf.inc.php @@ -1,9 +1,9 @@ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { include 'includes/error-no-perm.inc.php'; } else { $link_array = array( @@ -53,12 +53,12 @@ if (!Auth::user()->hasGlobalRead()) { if ($vars['graph'] == $type) { echo ""; } - + echo generate_link($descr, $link_array, array('view' => 'graphs', 'graph' => $type)); if ($vars['graph'] == $type) { echo ''; } - + $type_sep = ' | '; } @@ -79,7 +79,7 @@ if (!Auth::user()->hasGlobalRead()) { array_push($vrf_devices[$vrf_device['vrf_name']][$vrf_device['mplsVpnVrfRouteDistinguisher']], $vrf_device); } } - + unset($ports); foreach (dbFetchRows("SELECT $port_fields FROM `ports` WHERE ifVrf<>0") as $port) { if (empty($ports[$port['ifvrf']][$port['device_id']])) { diff --git a/html/pages/search/arp.inc.php b/html/pages/search/arp.inc.php index 0ba7f361b6..132142ed35 100644 --- a/html/pages/search/arp.inc.php +++ b/html/pages/search/arp.inc.php @@ -30,15 +30,15 @@ var grid = $("#arp-search").bootgrid({ ""+ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' LEFT JOIN `devices_perms` AS `DP` ON `D`.`device_id` = `DP`.`device_id`'; $where .= ' AND `DP`.`user_id`=?'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $sql .= " WHERE M.port_id = P.port_id AND P.device_id = D.device_id $where GROUP BY `D`.`device_id`, `D`.`hostname`, `D`.`sysName` ORDER BY `hostname`"; diff --git a/html/pages/search/fdb.inc.php b/html/pages/search/fdb.inc.php index beb47ddb19..0e4fef9a30 100644 --- a/html/pages/search/fdb.inc.php +++ b/html/pages/search/fdb.inc.php @@ -31,16 +31,16 @@ var grid = $("#fdb-search").bootgrid({ ""+ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' LEFT JOIN `devices_perms` AS `DP` ON `D`.`device_id` = `DP`.`device_id`'; $where .= ' AND `DP`.`user_id`=?'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $sql .= " WHERE F.port_id = P.port_id AND P.device_id = D.device_id $where GROUP BY `D`.`device_id`, `D`.`hostname` ORDER BY `hostname`"; diff --git a/html/pages/search/ipv4.inc.php b/html/pages/search/ipv4.inc.php index b03432e3bf..77b54efbab 100644 --- a/html/pages/search/ipv4.inc.php +++ b/html/pages/search/ipv4.inc.php @@ -28,14 +28,14 @@ var grid = $("#ipv4-search").bootgrid({ ""+ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' LEFT JOIN `devices_perms` AS `DP` ON `devices`.`device_id` = `DP`.`device_id`'; $where .= ' WHERE `DP`.`user_id`=?'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $sql .= " $where ORDER BY `hostname`"; diff --git a/html/pages/search/ipv6.inc.php b/html/pages/search/ipv6.inc.php index 5a98221dc4..f185220d8d 100644 --- a/html/pages/search/ipv6.inc.php +++ b/html/pages/search/ipv6.inc.php @@ -27,14 +27,14 @@ var grid = $("#ipv6-search").bootgrid({ ""+ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' LEFT JOIN `devices_perms` AS `DP` ON `devices`.`device_id` = `DP`.`device_id`'; $where .= ' WHERE `DP`.`user_id`=?'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $sql .= " $where ORDER BY `hostname`"; diff --git a/html/pages/search/mac.inc.php b/html/pages/search/mac.inc.php index 4071bea5af..ccf05eb9d7 100644 --- a/html/pages/search/mac.inc.php +++ b/html/pages/search/mac.inc.php @@ -28,14 +28,14 @@ var grid = $("#mac-search").bootgrid({ ""+ hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $sql .= ' LEFT JOIN `devices_perms` AS `DP` ON `devices`.`device_id` = `DP`.`device_id`'; $where .= ' WHERE `DP`.`user_id`=?'; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $sql .= " $where ORDER BY `hostname`"; diff --git a/html/pages/search/packages.inc.php b/html/pages/search/packages.inc.php index 411b08d386..c2cdff870c 100644 --- a/html/pages/search/packages.inc.php +++ b/html/pages/search/packages.inc.php @@ -23,7 +23,7 @@ * @subpackage Search */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; print_optionbar_start(28); ?> @@ -76,10 +76,10 @@ $full_query = ""; $query = 'SELECT packages.name FROM packages,devices '; $param = array(); -if (!Auth::user()->hasGlobalRead()) { +if (!LegacyAuth::user()->hasGlobalRead()) { $query .= " LEFT JOIN `devices_perms` AS `DP` ON `devices`.`device_id` = `DP`.`device_id`"; $sql_where .= " AND `DP`.`user_id`=?"; - $param[] = Auth::id(); + $param[] = LegacyAuth::id(); } $query .= " WHERE packages.device_id = devices.device_id AND packages.name LIKE '%".mres($_POST['package'])."%' $sql_where GROUP BY packages.name"; diff --git a/html/pages/services.inc.php b/html/pages/services.inc.php index 227f4a0d79..0889214f36 100644 --- a/html/pages/services.inc.php +++ b/html/pages/services.inc.php @@ -15,7 +15,7 @@ * @author LibreNMS Contributors */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; $pagetitle[] = 'Services'; @@ -122,12 +122,12 @@ require_once 'includes/modal/delete_service.inc.php'; $sql_param[] = $state; } - if (Auth::user()->hasGlobalRead()) { + if (LegacyAuth::user()->hasGlobalRead()) { $host_sql = 'SELECT `D`.`device_id`,`D`.`hostname`,`D`.`sysName` FROM devices AS D, services AS S WHERE D.device_id = S.device_id GROUP BY `D`.`hostname`, `D`.`device_id`, `D`.`sysName` ORDER BY D.hostname'; $host_par = array(); } else { $host_sql = 'SELECT `D`.`device_id`,`D`.`hostname`,`D`.`sysName` FROM devices AS D, services AS S, devices_perms AS P WHERE D.device_id = S.device_id AND D.device_id = P.device_id AND P.user_id = ? GROUP BY `D`.`hostname`, `D`.`device_id`, `D`.`sysName` ORDER BY D.hostname'; - $host_par = array(Auth::id()); + $host_par = array(LegacyAuth::id()); } $shift = 1; @@ -190,7 +190,7 @@ require_once 'includes/modal/delete_service.inc.php'; echo '' . nl2br(display($service['service_desc'])) . ''; echo '' . nl2br(display($service['service_message'])) . ''; - if (Auth::user()->hasGlobalAdmin()) { + if (LegacyAuth::user()->hasGlobalAdmin()) { echo " diff --git a/html/pages/settings.inc.php b/html/pages/settings.inc.php index 5c6cbb77a7..7b90c89b31 100644 --- a/html/pages/settings.inc.php +++ b/html/pages/settings.inc.php @@ -24,7 +24,7 @@ * @author f0o */ -use LibreNMS\Authentication\Auth; +use LibreNMS\Authentication\LegacyAuth; ?> @@ -42,7 +42,7 @@ use LibreNMS\Authentication\Auth; hasGlobalAdmin()) { +if (LegacyAuth::user()->hasGlobalAdmin()) { echo '