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
This commit is contained in:
Tony Murray 2018-09-11 07:51:35 -05:00 committed by GitHub
parent 5dae25b48b
commit 32a7c50189
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
278 changed files with 2604 additions and 1816 deletions

View File

@ -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()
{

View File

@ -1,66 +0,0 @@
<?php
namespace LibreNMS\Authentication;
use LibreNMS\Config;
use LibreNMS\Interfaces\Authentication\Authorizer;
class Auth
{
protected static $_instance;
/**
* Gets the authorizer based on the config
*
* @return Authorizer
*/
public static function get()
{
if (!static::$_instance) {
$configToClassMap = array(
'mysql' => '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'];
}
}

View File

@ -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;
}
}

View File

@ -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 {

View File

@ -0,0 +1,101 @@
<?php
namespace LibreNMS\Authentication;
use LibreNMS\Config;
use LibreNMS\Interfaces\Authentication\Authorizer;
class LegacyAuth
{
protected static $_instance;
private static $configToClassMap = array(
'mysql' => '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();
}
}
}

View File

@ -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();
}
}

View File

@ -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 .= '
<div class="row">
<div class="col-md-offset-4 col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<img class="img-responsive" src="' . Config::get('title_image') . '">
</h3>
</div>
<div class="panel-body">
<div class="container-fluid">
<form class="form-horizontal" role="form" action="" method="post" name="twofactorform">';
}
$ret .= '
<div class="form-group">
<div class="col-md-12">
<input type="text" name="twofactor" id="twofactor" class="form-control" autocomplete="off" placeholder="Please enter auth token" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-default btn-block" name="submit">Submit</button>
</div>
</div>
</div>';
$ret .= '<script>document.twofactorform.twofactor.focus();</script>';
if ($form_tags) {
$ret .= '</form>';
}
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
*

View File

@ -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;

View File

@ -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.

View File

@ -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();
}

View File

@ -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 {

View File

@ -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("<a href='notifications/'>$notification->body</a>", $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('<a href="poll-log/filter=unpolled/">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 :)</a>', '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("<a href='notifications/'>$notification->body</a>", $notification->title);
}
if (Device::isUp()->whereTime('last_polled', '<=', Carbon::now()->subMinutes(15))->count() > 0) {
Toastr::warning('<a href="poll-log/filter=unpolled/">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 :)</a>', '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. <a href=" . url('validate') . ">Validate your install</a>");
}
$temp_dir = Config::get('temp_dir');
if (!is_dir($temp_dir)) {
Toastr::error("Temp Directory is missing ($temp_dir). Graphing may fail. <a href=" . url('validate') . ">Validate your install</a>");
} elseif (!is_writable($temp_dir)) {
Toastr::error("Temp Directory is not writable ($temp_dir). Graphing may fail. <a href='" . url('validate') . "'>Validate your install</a>");
}
}
}

View File

@ -0,0 +1,47 @@
<?php
/**
* ApiTokenGuard.php
*
* Override TokenGuard so we can use our non-standard header
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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;
}
}

View File

@ -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, [

View File

@ -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');
}
}

View File

@ -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();

View File

@ -0,0 +1,204 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\UserPref;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use LibreNMS\Authentication\TwoFactor;
use LibreNMS\Config;
use LibreNMS\Exceptions\AuthenticationException;
use Session;
use Toastr;
class TwoFactorController extends Controller
{
public function verifyTwoFactor(Request $request)
{
$this->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";
}
}

View File

@ -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,

View File

@ -0,0 +1,48 @@
<?php
namespace App\Http\Middleware;
use App\Models\User;
use Auth;
use Closure;
use LibreNMS\Authentication\LegacyAuth;
use LibreNMS\Config;
use LibreNMS\Exceptions\AuthenticationException;
use Log;
class LegacyExternalAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check() && LegacyAuth::get()->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);
}
}

View File

@ -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);

View File

@ -0,0 +1,40 @@
<?php
namespace App\Http\Middleware;
use App\Models\UserPref;
use Closure;
use LibreNMS\Config;
class VerifyTwoFactor
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// check twofactor
if (Config::get('twofactor') === true) {
// don't apply on 2fa checking routes
if (starts_with($request->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);
}
}

View File

@ -0,0 +1,61 @@
<?php
/**
* LayoutComposer.php
*
* Provides data for the main layout
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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);
}
}

View File

@ -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

View File

@ -0,0 +1,75 @@
<?php
namespace App\Listeners;
use App\Checks;
use App\Events\Event;
use App\Models\User;
use DB;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Request;
use Session;
use Toastr;
class AuthEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the login event.
*
* @param Login $event
* @return void
*/
public function login(Login $event)
{
/** @var User $user */
$user = $event->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();
}
}

87
app/Models/ApiToken.php Normal file
View File

@ -0,0 +1,87 @@
<?php
/**
* ApiToken.php
*
* api_tokens simple tokens for api
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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');
}
}

View File

@ -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');
}
}

View File

@ -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)) {

View File

@ -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 ----

View File

@ -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');
}
}

128
app/Models/UserPref.php Normal file
View File

@ -0,0 +1,128 @@
<?php
/**
* UserPref.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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);
}
}

41
app/Models/UserWidget.php Normal file
View File

@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Auth;
use Illuminate\Database\Eloquent\Model;
class UserWidget extends Model
{
public $timestamps = false;
protected $table = 'users_widgets';
protected $primaryKey = 'user_widget_id';
protected $fillable = ['user_id', 'widget_id', 'col', 'row', 'size_x', 'size_y', 'title', 'refresh', 'settings', 'dashboard_id'];
protected $casts = ['settings' => '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');
}
}

View File

@ -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);
}
}
}
}

View File

@ -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);
});
}
}

View File

@ -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');
}

View File

@ -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'],
];
/**

View File

@ -0,0 +1,210 @@
<?php
/**
* LegacyUserProvider.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
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 .= '<br /> ' . $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;
}
}

View File

@ -1,6 +1,6 @@
<?php
/**
* LegacyAuth.php
* TokenUserProvider.php
*
* -Description-
*
@ -23,36 +23,14 @@
* @author Tony Murray <murraytony@gmail.com>
*/
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);
}
}

View File

@ -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,
],
],

View File

@ -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

View File

@ -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

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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;
}

View File

@ -15,12 +15,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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.');
}

View File

@ -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;
}

View File

@ -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.');
}

View File

@ -1,13 +1,13 @@
<?php
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\n";
exit;
}
@ -45,10 +45,10 @@ if (isset($_REQUEST['search'])) {
die(json_encode($results));
} elseif ($_REQUEST['type'] == 'device') {
// Device search
if (Auth::user()->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);

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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();

View File

@ -1,87 +0,0 @@
<?php
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\TwoFactor;
use LibreNMS\Config;
use LibreNMS\Exceptions\AuthenticationException;
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1); // php >= 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 .= '<br /> ' . $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);

View File

@ -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) {

View File

@ -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)) {
"<option value=\"\">All devices</option>"+
';
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) {

View File

@ -1,6 +1,6 @@
<?php
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
$device_id = $widget_settings['device'];
$column = $widget_settings['columnsize'];
@ -25,12 +25,12 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
</div>
<div class="col-sm-6">
<select id="device" name="device" class="form-control">';
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$sql = "SELECT `devices`.`device_id`, `hostname` FROM `devices` WHERE disabled = 0 AND `type` = 'server' ORDER BY `hostname` ASC";
$param = array();
} else {
$sql = "SELECT `devices`.`device_id`, `hostname` FROM `devices` LEFT JOIN `devices_perms` AS `DP` ON `devices`.`device_id` = `DP`.`device_id` WHERE disabled = 0 AND `type` = 'server' AND `DP`.`user_id`=? ORDER BY `hostname` ASC";
$param = array(Auth::id());
$param = array(LegacyAuth::id());
}
foreach (dbFetchRows($sql, $param) as $dev) {
if ($dev['device_id'] == $cur_dev) {

View File

@ -18,7 +18,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
$top_query = $widget_settings['top_query'] ?: 'traffic';
$sort_order = $widget_settings['sort_order'];
@ -156,11 +156,11 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
$common_output[] = '<h4>Top ' . $device_count . ' devices (last ' . $interval . ' minutes)</h4>';
$params = ['interval' => $interval_seconds, 'count' => $device_count];
if (!Auth::user()->hasGlobalRead()) {
$params['user'] = Auth::id();
if (!LegacyAuth::user()->hasGlobalRead()) {
$params['user'] = LegacyAuth::id();
}
if ($top_query === 'traffic') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = '
SELECT *, sum(p.ifInOctets_rate + p.ifOutOctets_rate) as total
FROM ports as p, devices as d
@ -187,7 +187,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
';
}
} elseif ($top_query === 'uptime') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `uptime`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
@ -203,7 +203,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
LIMIT :count';
}
} elseif ($top_query === 'ping') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `last_ping_timetaken`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval
@ -219,7 +219,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
LIMIT :count';
}
} elseif ($top_query === 'cpu') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, avg(`processor_usage`) as `cpuload`, `d`.`sysName`
FROM `processors` AS `procs`, `devices` AS `d`
WHERE `d`.`device_id` = `procs`.`device_id`
@ -237,7 +237,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
LIMIT :count';
}
} elseif ($top_query === 'ram') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `mempool_perc`, `d`.`sysName`
FROM `mempools` as `mem`, `devices` as `d`
WHERE `d`.`device_id` = `mem`.`device_id`
@ -255,7 +255,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
LIMIT :count';
}
} elseif ($top_query === 'storage') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `hostname`, `last_polled`, `d`.`device_id`, `storage_perc`, `d`.`sysName`, `storage_descr`, `storage_perc_warn`, `storage_id`
FROM `storage` as `disk`, `devices` as `d`
WHERE `d`.`device_id` = `disk`.`device_id`
@ -273,7 +273,7 @@ if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
LIMIT :count';
}
} elseif ($top_query === 'poller') {
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = 'SELECT `last_polled_timetaken`, `hostname`, `last_polled`, `device_id`, `sysName`
FROM `devices`
WHERE unix_timestamp() - UNIX_TIMESTAMP(`last_polled`) < :interval

View File

@ -25,7 +25,7 @@
* @subpackage Widgets
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (defined('SHOW_SETTINGS') || empty($widget_settings)) {
$common_output[] = '
@ -102,11 +102,11 @@ $(function() {
(integer) $lastpoll_seconds = ($interval * 60) ?: 300;
(integer) $interface_count = $widget_settings['interface_count'] ?: 5;
$params = ['lastpoll' => $lastpoll_seconds, 'count' => $interface_count, 'filter1' => ($widget_settings['interface_filter']?:(int)1), 'filter2' => ($widget_settings['interface_filter']?:(int)1)];
if (!Auth::user()->hasGlobalRead()) {
$params['user1'] = Auth::id();
$params['user2'] = Auth::id();
if (!LegacyAuth::user()->hasGlobalRead()) {
$params['user1'] = LegacyAuth::id();
$params['user2'] = LegacyAuth::id();
}
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
$query = '
SELECT p.*, devices.*, p.ifInOctets_rate + p.ifOutOctets_rate as total
FROM ports as p

View File

@ -22,7 +22,7 @@
* @subpackage Frontpage
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
use LibreNMS\Config;
require_once $config['install_dir'] . '/includes/alerts.inc.php';
@ -171,7 +171,7 @@ var greenMarker = L.AwesomeMarkers.icon({
$status_select = explode(',', $widget_settings['status']);
// Checking user permissions
if (Auth::user()->hasGlobalRead()) {
if (LegacyAuth::user()->hasGlobalRead()) {
// Admin or global read-only - show all devices
$sql = "SELECT DISTINCT(`device_id`),`devices`.`location`,`sysName`,`hostname`,`os`,`status`,`lat`,`lng` FROM `devices`
LEFT JOIN `locations` ON `devices`.`location`=`locations`.`location`
@ -188,7 +188,7 @@ var greenMarker = L.AwesomeMarkers.icon({
AND `devices`.`device_id` = `devices_perms`.`device_id`
AND `devices_perms`.`user_id` = ? AND `status` IN " . dbGenPlaceholders(count($status_select)) .
" ORDER BY `status` ASC, `hostname`";
$param = array_merge([Auth::id()], $status_select);
$param = array_merge([LegacyAuth::id()], $status_select);
}
foreach (dbFetchRows($sql, $param) as $map_devices) {

View File

@ -23,7 +23,7 @@
* @author Neil Lathwood <gh+n@laf.io>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
use LibreNMS\Config;
header('Content-type: application/json');
@ -49,7 +49,7 @@ if (!is_numeric($alert_id)) {
$open = 1;
}
$username = Auth::user()->username;
$username = LegacyAuth::user()->username;
$data = ['state' => $state, 'open' => $open];
$note = dbFetchCell('SELECT note FROM alerts WHERE id=?', [$alert_id]);
if (!empty($note)) {

View File

@ -22,7 +22,7 @@
* @subpackage Dashboards
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
@ -31,7 +31,7 @@ $message = 'unknown error';
$dashboard_name = display($_REQUEST['dashboard_name']);
if (!empty($dashboard_name) && ($dash_id = dbInsert(['dashboard_name' => $dashboard_name, 'user_id' => Auth::id()], 'dashboards'))) {
if (!empty($dashboard_name) && ($dash_id = dbInsert(['dashboard_name' => $dashboard_name, 'user_id' => LegacyAuth::id()], 'dashboards'))) {
$status = 'ok';
$message = 'Created';
} else {

View File

@ -24,11 +24,11 @@
*/
use LibreNMS\Alerting\QueryBuilderParser;
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die(json_encode([
'status' => 'error',
'message' => 'ERROR: You need to be admin',

View File

@ -22,14 +22,14 @@
* @subpackage Alerts
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
$status = 'error';
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-Type: application/json');
$response = array('status' => $status, 'message' => 'You need to be admin');
die(_json_encode($response));
die(json_encode($response));
}
$template_id = 0;

View File

@ -23,18 +23,16 @@
* @author Vivia Nguyen-Tran <vivia@ualberta.ca>
*/
use LibreNMS\Authentication\Auth;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Container\Container;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Translation\FileLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\DatabasePresenceVerifier;
use Illuminate\Validation\Factory;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die(json_encode([
'status' => 'error',
'message' => 'You need to be admin'

View File

@ -23,9 +23,9 @@
* @author Tony Murray <murraytony@gmail.com>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$status = array('status' => 1, 'message' => 'You need to be admin');
} else {
$device_id = $_POST['device_id'];

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -1,10 +1,10 @@
<?php
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',

View File

@ -12,13 +12,13 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
// FUA
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,13 +12,13 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
// FUA
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',

View File

@ -24,11 +24,11 @@
* @author Tony Murray <murraytony@gmail.com>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die(json_encode([
'status' => 'error',
'message' => 'You need to be admin',

View File

@ -12,9 +12,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');
}

View File

@ -12,9 +12,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');
}

View File

@ -12,9 +12,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');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -10,11 +10,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die(json_encode([
'status' => 'error',
'message' => 'You need to be admin.'

View File

@ -23,9 +23,9 @@
* @author Tony Murray <murraytony@gmail.com>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$status = array('status' =>1, 'message' => 'ERROR: You need to be admin to delete poller entries');
} else {
$id = $vars['id'];

View File

@ -22,7 +22,7 @@
* @subpackage Dashboards
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
@ -32,8 +32,8 @@ $message = 'unknown error';
$dashboard_id = (int)$_REQUEST['dashboard_id'];
if ($dashboard_id) {
dbDelete('users_widgets', 'user_id = ? && dashboard_id = ?', [Auth::id(), $dashboard_id]);
if (dbDelete('dashboards', 'user_id = ? && dashboard_id = ?', [Auth::id(), $dashboard_id])) {
dbDelete('users_widgets', 'user_id = ? && dashboard_id = ?', [LegacyAuth::id(), $dashboard_id]);
if (dbDelete('dashboards', 'user_id = ? && dashboard_id = ?', [LegacyAuth::id(), $dashboard_id])) {
$status = 'ok';
$message = 'Deleted dashboard';
} else {

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$status = ['status' => 1, 'message' => 'You need to be admin'];
} else {
if ($_POST['device_id']) {

View File

@ -23,9 +23,9 @@
* @author Tony Murray <murraytony@gmail.com>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$status = array('status' =>1, 'message' => 'ERROR: You need to be admin to delete poller entries');
} else {
$id = $vars['id'];

View File

@ -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()) {
$status = array('status' =>1, 'message' => 'ERROR: You need to be admin to delete services');
} else {
if (!is_numeric($vars['service_id'])) {

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die(json_encode([
'status' => 'error',
'message' => 'ERROR: You need to be admin.'

View File

@ -1,12 +1,12 @@
<?php
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
// FUA
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -22,7 +22,7 @@
* @subpackage Dashboards
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
@ -34,7 +34,7 @@ $dashboard_name = display($_REQUEST['dashboard_name']);
$access = $_REQUEST['access'] ? 1 : 0;
if (isset($dashboard_id) && isset($dashboard_name) && isset($access)) {
if (dbUpdate(['dashboard_name'=> $dashboard_name,'access'=> $access], 'dashboards', '(user_id = ? || access = 2) && dashboard_id = ?', [Auth::id(), $dashboard_id]) >= 0) {
if (dbUpdate(['dashboard_name'=> $dashboard_name,'access'=> $access], 'dashboards', '(user_id = ? || access = 2) && dashboard_id = ?', [LegacyAuth::id(), $dashboard_id]) >= 0) {
$status = 'ok';
$message = 'Updated dashboard';
} else {

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$status = array('status' => 1, 'message' => 'You need to be admin');
} else {
if (isset($_POST['viewtype'])) {
@ -71,7 +71,7 @@ if (!Auth::user()->hasGlobalAdmin()) {
} else {
$parent = $myrow['parent'];
}
$hostname = get_device_name($myrow);
array_push($res_arr, array( "deviceid" => $myrow['id'], "hostname" => $myrow['hostname'], "sysname" => $hostname, "parent" => $parent, "parentid" => $myrow['parentid'] ));
}
@ -108,6 +108,6 @@ if (!Auth::user()->hasGlobalAdmin()) {
}
}
}
header('Content-Type: application/json');
echo _json_encode($status);

View File

@ -16,15 +16,15 @@
* @author Aldemir Akpinar <aldemir.akpinar@gmail.com>
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
$vm_query = "SELECT v.vmwVmDisplayName AS vmname, v.vmwVmState AS powerstat, v.device_id AS deviceid, d.hostname AS physicalsrv, d.sysname AS sysname, v.vmwVmGuestOS AS os, v.vmwVmMemSize AS memory, v.vmwVmCpus AS cpu FROM vminfo AS v LEFT JOIN devices AS d ON v.device_id = d.device_id";
$param = [];
if (!Auth::user()->hasGlobalRead()) {
if (!LegacyAuth::user()->hasGlobalRead()) {
$vm_query .= ' LEFT JOIN devices_perms AS DP ON d.device_id = DP.device_id';
$uidwhere = ' AND DP.user_id = ?';
$uid = [Auth::id()];
$uid = [LegacyAuth::id()];
} else {
$uidwhere = '';
$uid = [];

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',

View File

@ -22,35 +22,35 @@
* @subpackage Notifications
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
$status = 'error';
$message = 'unknown error';
if (isset($_REQUEST['notification_id']) && isset($_REQUEST['action'])) {
if ($_REQUEST['action'] == 'read' && dbInsert(array('notifications_id'=>$_REQUEST['notification_id'],'user_id'=>Auth::id(),'key'=>'read','value'=>1), 'notifications_attribs')) {
if ($_REQUEST['action'] == 'read' && dbInsert(array('notifications_id'=>$_REQUEST['notification_id'],'user_id'=>LegacyAuth::id(),'key'=>'read','value'=>1), 'notifications_attribs')) {
$status = 'ok';
$message = 'Set as Read';
} elseif ((!Auth::user()->hasGlobalAdmin() || Auth::user()->isDemoUser()) && $_REQUEST['action'] == 'stick' && dbInsert(array('notifications_id'=>$_REQUEST['notification_id'],'user_id'=>Auth::id(),'key'=>'sticky','value'=>1), 'notifications_attribs')) {
} elseif ((!LegacyAuth::user()->hasGlobalAdmin() || LegacyAuth::user()->isDemoUser()) && $_REQUEST['action'] == 'stick' && dbInsert(array('notifications_id'=>$_REQUEST['notification_id'],'user_id'=>LegacyAuth::id(),'key'=>'sticky','value'=>1), 'notifications_attribs')) {
$status = 'ok';
$message = 'Set as Sticky';
} elseif ((!Auth::user()->hasGlobalAdmin() || Auth::user()->isDemoUser()) && $_REQUEST['action'] == 'unstick' && dbDelete('notifications_attribs', "notifications_id = ? && user_id = ? AND `key`='sticky'", array($_REQUEST['notification_id'],Auth::id()))) {
} elseif ((!LegacyAuth::user()->hasGlobalAdmin() || LegacyAuth::user()->isDemoUser()) && $_REQUEST['action'] == 'unstick' && dbDelete('notifications_attribs', "notifications_id = ? && user_id = ? AND `key`='sticky'", array($_REQUEST['notification_id'],LegacyAuth::id()))) {
$status = 'ok';
$message = 'Removed Sticky';
}
} elseif ($_REQUEST['action'] == 'create' && (!Auth::user()->hasGlobalAdmin() || Auth::user()->isDemoUser()) && (isset($_REQUEST['title']) && isset($_REQUEST['body']))) {
if (dbInsert(array('title'=>$_REQUEST['title'],'body'=>$_REQUEST['body'],'checksum'=>hash('sha512', Auth::id().'.LOCAL.'.$_REQUEST['title']),'source'=>Auth::id()), 'notifications')) {
} elseif ($_REQUEST['action'] == 'create' && (!LegacyAuth::user()->hasGlobalAdmin() || LegacyAuth::user()->isDemoUser()) && (isset($_REQUEST['title']) && isset($_REQUEST['body']))) {
if (dbInsert(array('title'=>$_REQUEST['title'],'body'=>$_REQUEST['body'],'checksum'=>hash('sha512', LegacyAuth::id().'.LOCAL.'.$_REQUEST['title']),'source'=>LegacyAuth::id()), 'notifications')) {
$status = 'ok';
$message = 'Created';
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'read-all-notif') {
$unread = dbFetchColumn("SELECT `notifications_id` FROM `notifications` AS N WHERE NOT EXISTS ( SELECT 1 FROM `notifications_attribs` WHERE `notifications_id` = N.`notifications_id` AND `user_id`=? AND `key`='read' AND `value`=1)", array(Auth::id()));
$unread = dbFetchColumn("SELECT `notifications_id` FROM `notifications` AS N WHERE NOT EXISTS ( SELECT 1 FROM `notifications_attribs` WHERE `notifications_id` = N.`notifications_id` AND `user_id`=? AND `key`='read' AND `value`=1)", array(LegacyAuth::id()));
foreach ($unread as $notification_id) {
dbInsert(
array(
'notifications_id' => $notification_id,
'user_id' => Auth::id(),
'user_id' => LegacyAuth::id(),
'key' => 'read',
'value' => 1
),

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: application/json');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
$response = array(
'status' => 'error',
'message' => 'Need to be admin',

View File

@ -13,9 +13,9 @@
*/
use LibreNMS\Alerting\QueryBuilderParser;
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}

View File

@ -12,9 +12,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');
}

View File

@ -12,9 +12,9 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
header('Content-type: text/plain');
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

View File

@ -12,11 +12,11 @@
* the source code distribution for details.
*/
use LibreNMS\Authentication\Auth;
use LibreNMS\Authentication\LegacyAuth;
header('Content-type: text/plain');
if (!Auth::user()->hasGlobalAdmin()) {
if (!LegacyAuth::user()->hasGlobalAdmin()) {
die('ERROR: You need to be admin');
}

Some files were not shown because too many files have changed in this diff Show More