librenms-librenms/app/Providers/TokenUserProvider.php
Tony Murray e8cf6bb385 Fix API auth issues (#9185)
* Fix API auth issues
Api access page now creates tokens with the correct ID.
Correctly creates users for legacy user tokens.
Fix Ldap comparison
Laravel Util class to make code easier to access/read

* More api access page fixes

* fix style
2018-09-11 22:36:52 -05:00

100 lines
2.9 KiB
PHP

<?php
/**
* TokenUserProvider.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 Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
class TokenUserProvider extends LegacyUserProvider implements UserProvider
{
/**
* 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)
{
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)
{
return;
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
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 assuming legacy auth_id
$api_token = ApiToken::where('token_hash', $credentials['api_token'])->first();
$user = $this->retrieveByLegacyId($api_token->user_id);
// update token user_id
if ($user) {
$api_token->user_id = $user->user_id;
$api_token->save();
}
return $user;
}
/**
* 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)
{
return ApiToken::isValid($credentials['api_token'], $user->user_id);
}
}