Giter Site home page Giter Site logo

directorytree / ldaprecord-laravel Goto Github PK

View Code? Open in Web Editor NEW
482.0 482.0 51.0 1.87 MB

Multi-domain LDAP Authentication & Management for Laravel.

Home Page: https://ldaprecord.com/docs/laravel/v3

License: MIT License

PHP 100.00%
activerecord laravel ldap ldap-auth ldap-authentication

ldaprecord-laravel's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ldaprecord-laravel's Issues

Any way to Sync Groups to Database like Users

This is a question.
I am trying to set up a section that would manage a many to many relationship between Titles and Groups. I figured, the best way to do this would be to sync AD groups to a DB table and create a joining table.

The purpose of this is when a user is created they become members of the groups that are tied to the title.

I can do this manually but I was wondering if I could repurposed existing code to accomplish the syncing.

  • ActiveDirectory
  • PHP 7.3
  • Laravel Version: 7.4

Interception when User must change password at next logon

I'm trying to figure out the most elegant way of intercepting when a user logs in, and seeing if their account is set to require a password change. I am using Active Directory and when a user attempts to login with this attribute set on their account, authentication fails completely until it is removed. What would the best way of doing this be if the response I always get back within this Laravel package for the user handler is just false? Should I check the user with AccountControl first to see if their password expired/forcing change, or is there a better way?

Thanks!

Migrating from Adldap2 Laravel...

  • Laravel Version: 6.13
  • PHP Version: 7.3
  • LDAP Type: ActiveDirectory

Description:

Just curious about migrating from Adldap2. I have been developing a tool for a little while now on and off, but haven't released into production yet, so I should be able to tinker with the new version.

Wondering if there are any features missing, and if just ripping and replacing will work ok.

Is there a way to customize LDAP error messages?

Hello.

Is there a way to customize/translate default "These credentials do not match our records" on failed LDAP authentication?

And is there a way to display different messages for different reasons of authentication failure (ie. different message when user not found and different message when wrong password supplied)?

Thank you!

Question: howto bind as authenticated user when using the laravel driver?

I know this is documented in core docs and it is clear how to achieve this when manually connecting - simply pass true as the 3rd argument to the attempt function call. However, I could not find a way to bind and stay bind as the authenticated user when using the laravel driver. Since there is no call to any attempt function when using the driver...Any ideas?

Upgrading from ADLDAP2

Describe the bug
`

(1/1) BadMethodCallExceptionCall to undefined method Illuminate\Database\Eloquent\Builder::getSelects()

in ForwardsCalls.php line 50
at Builder::throwBadMethodCallException()in ForwardsCalls.php line 36
at Builder->forwardCallTo()in Builder.php line 1369
at Builder->__call()in LdapUserRepository.php line 149
at LdapUserRepository->newModelQuery()in LdapUserRepository.php line 107
at LdapUserRepository->query()in LdapUserRepository.php line 63
at LdapUserRepository->findByGuid()in NoDatabaseUserProvider.php line 14
at NoDatabaseUserProvider->retrieveById()in SessionGuard.php line 139
at SessionGuard->user()in AuthManager.php line 54
at AuthManager->Illuminate\Auth{closure}()
at call_user_func()in AuthServiceProvider.php line 84
at AuthServiceProvider->Illuminate\Auth{closure}()
at call_user_func()in Request.php line 522
at Request->user()in LaravelRequestContext.php line 20
at LaravelRequestContext->getUser()in LaravelRequestContext.php line 68
at LaravelRequestContext->toArray()in Report.php line 229
at Report->allContext()in AnonymizeIp.php line 11
at AnonymizeIp->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in AddGlows.php line 24
at AddGlows->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in Pipeline.php line 105
at Pipeline->then()in Flare.php line 247
at Flare->applyMiddlewareToReport()in Flare.php line 221
at Flare->createReport()in ErrorPageHandler.php line 39
at ErrorPageHandler->handle()in IgnitionWhoopsHandler.php line 25
at IgnitionWhoopsHandler->handle()in Run.php line 296
at Run->handleException()in Handler.php line 362
at Handler->renderExceptionWithWhoops()in Handler.php line 341
at Handler->renderExceptionContent()in Handler.php line 325
at Handler->convertExceptionToResponse()in Handler.php line 304
at Handler->prepareResponse()in Handler.php line 209
at Handler->render()in Handler.php line 82
at Handler->render()in Pipeline.php line 51
at Pipeline->handleException()in Pipeline.php line 132
at Pipeline->Illuminate\Pipeline{closure}()in SubstituteBindings.php line 41
at SubstituteBindings->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in VerifyCsrfToken.php line 76
at VerifyCsrfToken->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in StartSession.php line 56
at StartSession->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in EncryptCookies.php line 66
at EncryptCookies->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in Pipeline.php line 105
at Pipeline->then()in Router.php line 683
at Router->runRouteWithinStack()in Router.php line 658
at Router->runRoute()in Router.php line 624
at Router->dispatchToRoute()in Router.php line 613
at Router->dispatch()in Kernel.php line 170
at Kernel->Illuminate\Foundation\Http{closure}()in Pipeline.php line 130
at Pipeline->Illuminate\Pipeline{closure}()in TransformsRequest.php line 21
at TransformsRequest->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in TransformsRequest.php line 21
at TransformsRequest->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in ValidatePostSize.php line 27
at ValidatePostSize->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in CheckForMaintenanceMode.php line 63
at CheckForMaintenanceMode->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in TrustProxies.php line 57
at TrustProxies->handle()in Pipeline.php line 171
at Pipeline->Illuminate\Pipeline{closure}()in Pipeline.php line 105
at Pipeline->then()in Kernel.php line 145
at Kernel->sendRequestThroughRouter()in Kernel.php line 110
at Kernel->handle()in index.php line 55

`
Already got rid of the old ldap file in config.

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4.3
  • Laravel Version: 6.18.2

PDO error on login

Environment:

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4.4
  • Laravel Version: 7.3.0

Hello.
Thanks so much for this project.

Configured everything according to the documentation.

  • Plain Authentication - working
  • Importing Users - working

But if "Synchronized Database Authentication" is enabled, then an error during login

auth.php
        'ldap' => [
            'driver' => 'ldap',
            'model' => LdapRecord\Models\ActiveDirectory\User::class,
            'database' => [
                'model' => App\User::class,
                'sync_passwords' => false,
                'sync_attributes' => [
                    'name' => 'cn',
                    'username' => 'samaccountname',
                ],
            ],
        ],
User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;

//use LdapRecord\Laravel\Auth\HasLdapUser;

class User extends Authenticatable implements LdapAuthenticatable
{
    use Notifiable,AuthenticatesWithLdap;
stacktrace
[previous exception] [object] (PDOException(code: 0): could not find driver at /home/vagrant/Projects/hub2/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)
[stacktrace]
#0 /home/vagrant/Projects/hub2/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php(27): PDO->__construct()
#1 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php(67): Doctrine\\DBAL\\Driver\\PDOConnection->__construct()
#2 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php(46): Illuminate\\Database\\Connectors\\Connector->createPdoConnection()
#3 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connectors/MySqlConnector.php(24): Illuminate\\Database\\Connectors\\Connector->createConnection()
#4 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php(182): Illuminate\\Database\\Connectors\\MySqlConnector->connect()
#5 [internal function]: Illuminate\\Database\\Connectors\\ConnectionFactory->Illuminate\\Database\\Connectors\\{closure}()
#6 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(924): call_user_func()
#7 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(959): Illuminate\\Database\\Connection->getPdo()
#8 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(404): Illuminate\\Database\\Connection->getReadPdo()
#9 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(330): Illuminate\\Database\\Connection->getPdoForSelect()
#10 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(662): Illuminate\\Database\\Connection->Illuminate\\Database\\{closure}()
#11 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(629): Illuminate\\Database\\Connection->runQueryCallback()
#12 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Connection.php(338): Illuminate\\Database\\Connection->run()
#13 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2159): Illuminate\\Database\\Connection->select()
#14 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2147): Illuminate\\Database\\Query\\Builder->runSelect()
#15 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2619): Illuminate\\Database\\Query\\Builder->Illuminate\\Database\\Query\\{closure}()
#16 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2148): Illuminate\\Database\\Query\\Builder->onceWithColumns()
#17 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(539): Illuminate\\Database\\Query\\Builder->get()
#18 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(523): Illuminate\\Database\\Eloquent\\Builder->getModels()
#19 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Database/Concerns/BuildsQueries.php(143): Illuminate\\Database\\Eloquent\\Builder->get()
#20 /home/vagrant/Projects/hub2/vendor/directorytree/ldaprecord-laravel/src/LdapUserImporter.php(119): Illuminate\\Database\\Eloquent\\Builder->first()
#21 /home/vagrant/Projects/hub2/vendor/directorytree/ldaprecord-laravel/src/LdapUserImporter.php(52): LdapRecord\\Laravel\\LdapUserImporter->createOrFindEloquentModel()
#22 /home/vagrant/Projects/hub2/vendor/directorytree/ldaprecord-laravel/src/Auth/DatabaseUserProvider.php(108): LdapRecord\\Laravel\\LdapUserImporter->run()
#23 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php(357): LdapRecord\\Laravel\\Auth\\DatabaseUserProvider->retrieveByCredentials()
#24 /home/vagrant/Projects/hub2/vendor/laravel/ui/auth-backend/AuthenticatesUsers.php(83): Illuminate\\Auth\\SessionGuard->attempt()
#25 /home/vagrant/Projects/hub2/vendor/laravel/ui/auth-backend/AuthenticatesUsers.php(46): App\\Http\\Controllers\\Auth\\LoginController->attemptLogin()
#26 [internal function]: App\\Http\\Controllers\\Auth\\LoginController->login()
#27 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array()
#28 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction()
#29 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Route.php(225): Illuminate\\Routing\\ControllerDispatcher->dispatch()
#30 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Route.php(182): Illuminate\\Routing\\Route->runController()
#31 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\\Routing\\Route->run()
#32 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}()
#33 /home/vagrant/Projects/hub2/app/Http/Middleware/RedirectIfAuthenticated.php(25): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#34 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): App\\Http\\Middleware\\RedirectIfAuthenticated->handle()
#35 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#36 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle()
#37 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(76): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#38 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle()
#39 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#40 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle()
#41 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(56): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#42 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Session\\Middleware\\StartSession->handle()
#43 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#44 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle()
#45 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#46 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle()
#47 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#48 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\\Pipeline\\Pipeline->then()
#49 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->runRouteWithinStack()
#50 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\\Routing\\Router->runRoute()
#51 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\\Routing\\Router->dispatchToRoute()
#52 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Routing\\Router->dispatch()
#53 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}()
#54 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#55 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle()
#56 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#57 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle()
#58 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#59 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle()
#60 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#61 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle()
#62 /home/vagrant/Projects/hub2/vendor/fruitcake/laravel-cors/src/HandleCors.php(36): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#63 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\\Cors\\HandleCors->handle()
#64 /home/vagrant/Projects/hub2/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#65 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\\Proxy\\TrustProxies->handle()
#66 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#67 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\\Pipeline\\Pipeline->then()
#68 /home/vagrant/Projects/hub2/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter()
#69 /home/vagrant/Projects/hub2/public/index.php(55): Illuminate\\Foundation\\Http\\Kernel->handle()
#70 {main}
"}

Errors with /vendor/directorytree/ldaprecord-laravel/src/Hydrators/PasswordHydrator.php

Describe the bug
I am trying to configure without the use of password syncing.

I get the following error:
Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in /srv/sites/dev/steve/projects/doav3/site/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 675 and exactly 2 expected

This is resulting from lines 43 - 51 of the PasswordHydrator.php file
protected function setPassword(EloquentModel $model, $password)
{
// If the model has a mutator for the password field, we
// can assume hashing passwords is taken care of.
// Otherwise, we will hash it normally.
$password = $model->hasSetMutator($this->passwordColumn()) ? $password : Hash::make($password);

    $model->setAttribute($this->passwordColumn(), $password);
}

My config is here :

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'ldap' => [
        'driver' => 'ldap',
        'model' => LdapRecord\Models\ActiveDirectory\User::class,
        'rules' => [],
        'database' => [
            'model' => App\User::class,
            'password_column' => null,
            'sync_passwords' => false,
            'sync_attributes' => [
                'name' => 'cn',
                'username' => 'samaccountname',
                'email' => 'mail',
            ],
        ],
    ],

If I comment out those lines of code in the PasswordHydrator.php file, it works fine .. but I am not comfortable with that option going forward.

Love the library by the way.

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.2.17
  • Laravel Version: 7.6.1

Trying to create a model with cache enabled results in a CacheManager error

Describe the bug
Trying to create a model with cache enabled results in a CacheManager error. I'm trying to install and set up following the docs.

To Reproduce
Steps to reproduce the behavior:

  1. Install using composer require
  2. Publish configuration file using artisan publish
  3. Copy the configuration settings from the Installation page to .env and set correct values. LDAP_CACHE is set to true and CACHE_DRIVER is set to file
  4. Run php artisan make:ldap-model User
    5: Getting this error:
    `Symfony\Component\Debug\Exception\FatalThrowableError : Argument 1 passed to Illuminate\Cache\CacheManager::repository() must implement interface Illuminate\Contracts\Cache\Store, string given, called in ~vendor\directorytree\ldaprecord-laravel\src\LdapServiceProvider.php on line 46

at ~vendor\laravel\framework\src\Illuminate\Cache\CacheManager.php:259
255| *
256| * @param \Illuminate\Contracts\Cache\Store $store
257| * @return \Illuminate\Cache\Repository
258| */

259| public function repository(Store $store)
260| {
261| return tap(new Repository($store), function ($repository) {
262| $this->setEventDispatcher($repository);
263| });`

These lines in try to set the store using the string "file" from the config file:

if (config('ldap.cache.enabled', false)) { $connection->setCache( cache()->repository(config('ldap.cache.driver')) ); }

Expected behavior
I expect a model to be created without errors

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.3.11
  • Laravel Version: 6.18.0

Restricted authentication

Does this new package not allow restricted authentication to the users table?

On the LDAP package, I was setting it so anyone in the users table that I added had access to the application, and it was then using AD to authenticate those users.

With this new package it seems to be anyone with an AD account can auth, and can only be restriced by AD groups?

Am I missing something?

rrorException: ldap_search(): Search: Operations error in directorytree/ldaprecord/src/Ldap.php:476

Describe the bug
If I do not have LDAP_USERNAME and LDAP_USERNAME set in my .env I receive the error when using the Laravel authentication.

ErrorException: ldap_search(): Search: Operations error in directorytree/ldaprecord/src/Ldap.php:476

I am able to successfully authenticate using the non-Laravel method detailed at https://ldaprecord.com/docs/tutorials/authentication/

This code works and authenticates successfully in an Artisan command:

$connection = new \LdapRecord\Connection([
            'hosts' => ['*removed*'],
            'base_dn' => '*removed*',
]);

$connection->connect();

$connection->auth()->attempt($email, $password, $stayAuthenticated = true)

To Reproduce

  1. Install as per https://ldaprecord.com/docs/laravel/quickstart/
  2. Enabled synchronized auth as per https://ldaprecord.com/docs/laravel/auth/configuration/#database
  3. Unset/remove LDAP_USERNAME and LDAP_USERNAME in your .env
  4. Attempt to login as a valid user

This error also occurs when running the artisan command php artisan ldap:import ldap

Expected behavior
Authentication should succeed and create a local user matching the LDAP user.
Authentication should use the provided email and password, not a hardcoded environment variable.

Environment (please complete the following information):

  • LDAP Server Type: OpenLDAP
  • PHP Version: 7.4
  • Laravel Version: 6.0

Issue to few arguments to setAttribute()

I encounter the following error when I try to connect with Ldap and sync the user in the local database.
Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in [2020-03-25 11:51:56] local.INFO: User [mastoica] has been successfully located for authentication.
[2020-03-25 11:51:56] local.INFO: User [mastoica] is being imported.
[2020-03-25 11:51:56] local.INFO: User [mastoica] is being synchronized.
[2020-03-25 11:51:56] local.ERROR: Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 674 and exactly 2 expected {"exception":"[object] (ArgumentCountError(code: 0): Too few arguments to function Illuminate\Database\Eloquent\Model::setAttribute(), 1 passed in /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 674 and exactly 2 expected at /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php:616)
[stacktrace]
#0 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(674): Illuminate\Database\Eloquent\Model->setAttribute('IHzTkhMigIYSs69...')
DirectoryTree/LdapRecord#1 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(622): Illuminate\Database\Eloquent\Model->setMutatedAttributeValue(NULL, 'IHzTkhMigIYSs69...')
DirectoryTree/LdapRecord#2 /Users/mastoica/Sites/woc/laravel-woc/vendor/directorytree/ldaprecord-laravel/src/LdapUserImporter.php(179): Illuminate\Database\Eloquent\Model->setAttribute(NULL, 'IHzTkhMigIYSs69...')
DirectoryTree/LdapRecord#3 /Users/mastoica/Sites/woc/laravel-woc/vendor/directorytree/ldaprecord-laravel/src/LdapUserImporter.php(74): LdapRecord\Laravel\LdapUserImporter->setPassword(Object(App\User), 'IHzTkhMigIYSs69...')
DirectoryTree/LdapRecord#4 /Users/mastoica/Sites/woc/laravel-woc/vendor/directorytree/ldaprecord-laravel/src/Auth/DatabaseUserProvider.php(108): LdapRecord\Laravel\LdapUserImporter->run(Object(LdapRecord\Models\ActiveDirectory\User), 'IHzTkhMigIYSs69...')
DirectoryTree/LdapRecord#5 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php(357): LdapRecord\Laravel\Auth\DatabaseUserProvider->retrieveByCredentials(Array)
DirectoryTree/LdapRecord#6 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/ui/auth-backend/AuthenticatesUsers.php(83): Illuminate\Auth\SessionGuard->attempt(Array, false)
DirectoryTree/LdapRecord#7 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/ui/auth-backend/AuthenticatesUsers.php(46): App\Http\Controllers\Auth\LoginController->attemptLogin(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#8 [internal function]: App\Http\Controllers\Auth\LoginController->login(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#9 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)
DirectoryTree/LdapRecord#10 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('login', Array)
DirectoryTree/LdapRecord#11 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Route.php(225): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\Auth\LoginController), 'login')
DirectoryTree/LdapRecord#12 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Route.php(182): Illuminate\Routing\Route->runController()
DirectoryTree/LdapRecord#13 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\Routing\Route->run()
DirectoryTree/LdapRecord#14 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#15 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#16 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#17 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(76): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#18 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#19 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#20 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#21 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(56): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#22 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#23 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#24 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#25 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#26 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#27 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#28 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\Pipeline\Pipeline->then(Object(Closure))
DirectoryTree/LdapRecord#29 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#30 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
DirectoryTree/LdapRecord#31 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#32 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#33 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#34 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#35 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#36 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#37 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#38 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#39 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#40 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#41 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#42 /Users/mastoica/Sites/woc/laravel-woc/vendor/fruitcake/laravel-cors/src/HandleCors.php(36): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#43 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fruitcake\Cors\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#44 /Users/mastoica/Sites/woc/laravel-woc/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#45 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
DirectoryTree/LdapRecord#46 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#47 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\Pipeline\Pipeline->then(Object(Closure))
DirectoryTree/LdapRecord#48 /Users/mastoica/Sites/woc/laravel-woc/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#49 /Users/mastoica/Sites/woc/laravel-woc/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
DirectoryTree/LdapRecord#50 /Users/mastoica/Sites/woc/laravel-woc/server.php(21): require_once('/Users/mastoica...')
DirectoryTree/LdapRecord#51 {main}
"}

Handle authorization, not just authentication

Is your feature request related to a problem? Please describe.
Recently I played around with spaties laravel-permission (i hope it is okay to mention it here).
It is pretty useful if you don't already have a permission system. Since this package is made to work with ldap (hence a directory service), you probably want to handle permissions with groups/ous from your directory service.
I know there are rules in this package, but they don't offer the flexibility I needed.

Describe the solution you'd like
I more or less copied the idea from spaties laravel-permission and created a config and middleware (it's just for OU's but I guess would be pretty similar for groups). This is what i came up with:

Created a config file config/permission.php

<?php
/**
 * Specify aliases for groups and ous in your domain,
 * so you can use them as middleware to authorize users.
 */
return [
    'ou' => [
        'aliases' => [
            // 'admin' could now be used with our middleware
            'admin' => [
                'dn' => 'ou=exampleOU,dc=example,dc=com',
            ],
        ],
        // There should be user DNs in th uniquemember attribute of the OU
        'membersAttribute' => 'uniquemember',

        // Since you sometimes need to modify the model, lets specify it in the here
        'class' => LdapRecord\Models\OpenLDAP\OrganizationalUnit::class,
    ],
];

Created a middleware to authorize users based on ther ou-membership

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class OrganizationalUnitMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, ...$aliases)
    {
        $errorMessage = 'User is not in necessary OU/s.';

        if (Auth::guest()) {
            return abort(403, $errorMessage);
        }

        $ouConfig = config('permissions.ou');
        $ouClass = config('permissions.ou.class');

        // Go through each alias and check wether the Auth::user() is in the configured ou.
        foreach ($aliases as $alias) {
            if (!array_key_exists($alias, $ouConfig['aliases'])) {
                // This normally should throw an Exception
                dd($alias . ' not found');
            }

            $aliasConfig = $ouConfig['aliases'][$alias];

            $ou = $ouClass::findOrFail($aliasConfig['dn']);

            if (!in_array(Auth::user()->ldap->getDn(), $ou->getAttribute($ouConfig['membersAttribute']))) {
                continue;
            }

            return $next($request);
        }

        return abort(403, $errorMessage);
    }
}

Specify middleware in the Kernel.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'ou' => \App\Http\Middleware\OrganizationalUnitMiddleware::class, // <== here
    ];

You can now use the middleware like this in your web.php

Route::get('/home', 'HomeController@index')->middleware('ou:admin');

You could also pass multiple ou-aliases by sperating them with a comma

Route::get('/home', 'HomeController@index')->middleware('ou:admin,managers');

There is one downsite to all of this. You have to use the HasLdapUser trait in you're usermodel. So you would make an LDAP query for every request. For example:

use LdapRecord\Laravel\Auth\HasLdapUser;

class User extends Authenticatable implements LdapAuthenticatable
{
    use Notifiable, AuthenticatesWithLdap, HasLdapUser;

    // ...rest of the class

Describe alternatives you've considered
As I said, spaties laravel-permission could be used to handle user permissions, but isn't optimal since you don't use your already existing permission system (e.g. Active Directory).

Summary
This is what I came up with to handle authorization directly from your directory service. I didn't test it with multiple domains or anything else. I know it needs some refactoring and optimization.

artisan make:ldap-model command is not working for me

Describe the bug
the artisan make commands are not working for me. e.g.:

php artisan make:ldap-model User

outputs

Illuminate\Contracts\Filesystem\FileNotFoundException  : File does not exist at path [...]/vendor/directorytree/ldaprecord-laravel/src/Commands/Stubs/model.stub

To Reproduce
Steps to reproduce the behavior:
I just followed the quickstart tutorial.

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4
  • Laravel Version: 6.0

Is that a typo? the folder name "src/Commands/stubs/" is uncapitalized, but in src/Commands/MakeLdapModel.php in the method getStub() it is stated as "return __DIR__.'/Stubs/model.stub';"
Maybe I'm doing something wrong, I kinda feel stupid... 😉

DN not being escaped

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.3
  • Laravel Version: ^7.0

When creating a user I am getting A

0000208F: NameErr: DSID-03100225, problem 2006 (BAD_NAME), data 8350, best match of:
\t'Test,CN=Users,DC=comlivserv,DC=com'

There is a requirement for the the name format be:
LastName, firstname

This is causing issues because of the comma not being excaped.

The code that produces this format is:

$nameFormat = $lastname . ', ' . $firstname;

I have also tried:

$nameFormat = $lastname . '\, ' . $firstname;

and:

$nameFormat = $lastname . '"\", ' . $firstname;

Any suggestions on how to make this work?

thank you

Allow usage without admin user

Is your feature request related to a problem? Please describe.
The primary problem is that all use cases don't support the use of an admin user. In our case, we don't have, and can not get, an admin user to verify against. We'd thus like to use the to-be authenticated user instead.

Describe the solution you'd like
Support of the $bindAsUser parameter as a configurable option - meaning that the library will, in all instances, disregard any specified LDAP_USERNAME/LDAP_PASSWORD, and instead bind as the user we're attempting to log in through.

Describe alternatives you've considered
An alternative would be to override the implemented attemptLogin() method in the LoginController and utilize the underlying LdapRecord library to manually authenticate with the $bindAsUser parameter.

Additional context
No context necessary - but huge kudos for an amazing library! :)

Need help configuring

Laravel Version : 5.8
PHP 7.2
Using Active Directory

Hi,

I have opened an issue yesterday about my authentication problem but i don't give enough informations so i'll do my best on this one for fixing quickly my problem :)

So as i said yesterday i have a login issue : when i enter my credentials for login into my app it return always the 'Invalid Credential Error'

Here is my configuration - auth.php :

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Ldap\User::class,
        ],
        'ldap' => [
            'driver' => 'ldap',
            'model' => LdapRecord\Models\ActiveDirectory\User::class,
            'rules' => [],
            'database' => [
                'model' => App\Ldap\User::class,
                'sync_passwords' => false,
                'sync_attributes' => [
                    'LASTNAME' => 'sn',
                    'FIRSTNAME' => 'givenname',
                    'ACTIVE_DIRECTORY_USER' => 'comptent'
                ]
            ]
        ]

Here is the user model - User.php :

<?php

namespace App\Ldap;

//use Illuminate\Database\Eloquent\Model;
use LdapRecord\Laravel\Auth\HasLdapUser;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Models\Model;

/**
 * Class User
 * 
 * @property int $ID_USER
 * @property string $LASTNAME
 * @property string $FIRSTNAME
 * @property string $ACTIVE_DIRECTORY_USER
 * @property int $ID_ROLE
 * 
 * @property Role $role
 *
 * @package App\Models
 */
class User extends Model
{

	use Notifiable, AuthenticatesWithLdap;
	
	/**
     * The object classes of the LDAP model.
     *
     * @var array
     */
    public static $objectClasses = [];
	protected $table = 'user';
	protected $primaryKey = 'ID_USER';
	public $incrementing = false;
	public $timestamps = false;

	protected $casts = [
		'ID_USER' => 'int',
		'ID_ROLE' => 'int'
	];

	protected $fillable = [
		'LASTNAME',
		'FIRSTNAME',
		'ACTIVE_DIRECTORY_USER',
		'ID_ROLE'
	];

	public function role()
	{
		return $this->belongsTo(Role::class, 'ID_ROLE');
	}
}

Then the LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use LdapRecord\Container;
use Illuminate\Http\Request;
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;

    /**
     * LDAP Connection 
     */
    private $connection;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->connection = Container::getConnection('default');
        $this->middleware('guest')->except('logout');
    }

    public function username() {
        return 'username';
    }

    protected function credentials(Request $request)
    {
        return [
            'comptent' => $request->username,
            'password' => $request->password,
        ];
    }
}

I use the comptent attribute and not the samaccountname here is a screenshot of the users attributes :

image

And here is the laravel log that i got when i try to log into my application :

[2020-02-20 09:49:01] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Binding - Username: dmdName=userLDAP,ou=applications,dc=rms,dc=fr  
[2020-02-20 09:49:01] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Bound - Username: dmdName=userLDAP,ou=applications,dc=rms,dc=fr  
[2020-02-20 09:49:01] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Search - Base DN: ou=utilisateurs,dc=rms,dc=fr - Filter: (&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=user)(comptent=hippolyte.massicot)(!(objectclass=computer))(!(objectclass=computer))) - Selected: (*,objectguid,objectclass) - Time Elapsed: 18.19  

Previously i got also that logs :

[2020-02-19 08:14:35] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Binding - Username: dmdName=userLDAP,ou=applications,dc=rms,dc=fr  
[2020-02-19 08:14:35] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Bound - Username: dmdName=userLDAP,ou=applications,dc=rms,dc=fr  
[2020-02-19 08:14:35] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Search - Base DN: ou=utilisateurs,dc=rms,dc=fr - Filter: ([email protected]) - Selected: (*) - Time Elapsed: 161.51  
[2020-02-19 08:14:35] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Attempting - Username: uid=Utilisateur17285,ou=utilisateurs,dc=rms,dc=fr  
[2020-02-19 08:14:35] local.INFO: LDAP (ldap://srvil-ldap1:389) - Operation: Binding - Username: uid=Utilisateur17285,ou=utilisateurs,dc=rms,dc=fr  
[2020-02-19 08:14:35] local.WARNING: LDAP (ldap://srvil-ldap1:389) - Operation: Failed - Username: uid=Utilisateur17285,ou=utilisateurs,dc=rms,dc=fr - Reason: Invalid credentials 

Thank you in advance for your time :)

Authenticating with No Sync

I currently use adldap2/laravel for a project and one of the things I liked about it was the ability to authenticate without syncing users into a database.

Having looked through the ldaprecord docs I couldn't quite work out if the same thing was possible. In a world of GDPR, having user details stored in multiple locations is problematic.

Have I missed something in the docs or do users have to be sync'd either on mass or as they authenticate?

Can't get LdapRecord UserModel from eloquent model saved objectguid

Describe the bug
I use LdapRecord-Laravel for authenticating my users over the synchronized database authentication. Now I needed to cast the Eloquent UserModel into a LdapRecord-Laravel UserModel to get some information about the user. When I try to do this by searching the user over it's objectguid via LdapUserModel::findByGuid( $eloquentUser->getLdapGuid() ) the return is always null. I checked that $eloquentUser->getLdapGuid() returns the right objectguid.

Can you please tell me why this isn't working?

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.3.7
  • Laravel Version: 7.0
  • LdapRecord-Laravel Version: 1.0

Resilient LDAP Servers

I am not sure if this is supported today?
I know that multiple domains is supported. I want to be able to use a single domain, but have multiple servers that I can connect to - in case the primary server is unavailable.

I attempted to setup two LDAP servers for resilience purposes.
If the primary is unavailable, it should fail-over an attempt to connect to the secondary server.
I am unsure of where the connection code is located?

I updated ldap.php as follows:
'hosts' => [env('LDAP_HOST1', 'LDAP_HOST2')],

Note: this was originally:
'hosts' => [env('LDAP_HOST', '127.0.0.1')],

And the env file as follows:
LDAP_HOST1=ad1.mydomain.com
LDAP_HOST2=ad2.mydomain.com

It only attempts to connect to the primary server. No attempt to made to connect to the secondary server, if app fails to connect to the primary server.

Gerry

Defining Attribute for username

Describe the bug
Using OpenLDAP model, I'm not seeing where to define what attribute to use for username in the documentation. In Adldap2-laravel this was done in the config/ldap_auth.php:

'ldap' => [
            'locate_users_by' => 'uid',
            'bind_users_by' => 'dn',
        ],

I'm not seeing where this exists in LdapRecord-Laravel

Previous LdapRecord-Laravel(Not working):

[2020-02-27 13:44:13] local.INFO: LDAP (ldap://192.168.0.10:389) - Operation: Search - Base DN: dc=testing,dc=net - Filter: (&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=inetorgperson)(username=jsmith)) - Selected: (*,entryuuid,objectclass)

Adldap2-Laravel(Working):

[2020-02-27 13:47:29] local.INFO: LDAP (ldap://192.168.0.10:389) - Connection: default - Operation: Search - Base DN: dc=testing,dc=net - Filter: (&(objectclass=inetorgperson)(objectclass=person)(uid=*)(uid=jsmith)) - Selected: (*,entryuuid) - Time Elapsed: 87.51

Expected behavior
Need to be able to define what attribute to use for username on login (uid/cn)

Environment (please complete the following information):

  • LDAP Server Type: OpenLDAP
  • PHP Version: 7.4
  • Laravel Version: 6.2

Composer installation failed

Dear Steve,

Laravel version : 6.0
PHP version : 7.2.29
LdapRecord-Laravel : v1.0.9

I tried to install LdapRecord-Laravel using composer :
composer require directorytree/ldaprecord-laravel

But this error appears :
`Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating optimized autoload files

Illuminate\Foundation\ComposerScripts::postAutoloadDump
@php artisan package:discover --ansi

LdapRecord\Configuration\ConfigurationException : Option auto_connect does not exist.

at /var/www/html/gide-insylva/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php:105
101| if ($this->has($key)) {
102| return $this->options[$key];
103| }
104|

105| throw new ConfigurationException("Option {$key} does not exist.");
106| }
107|
108| /**
109| * Checks if a configuration option exists.

Exception trace:

1 LdapRecord\Configuration\DomainConfiguration::get("auto_connect")
/var/www/html/gide-insylva/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php:132

2 LdapRecord\Configuration\DomainConfiguration::validate("auto_connect")
/var/www/html/gide-insylva/vendor/directorytree/ldaprecord/src/Configuration/DomainConfiguration.php:85

Please use the argument -v to see more details.
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1`

Any idea ?

Thanks a lot for your help and your work !

Getting error on login

Describe the bug
I have updated to the latest version.(1.2)
When I try to login im getting this error:
Argument 1 passed to LdapRecord\Models\Model::serializeDate() must implement interface DateTimeInterface, null given, called in /vendor/directorytree/ldaprecord/src/Models/Concerns/HasAttributes.php on line 105

When I change the code of this file to this:
protected function serializeDate(?DateTimeInterface $date) { return optional($date)->format($this->getDateFormat()); }

it works.

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4
  • Laravel Version: 7

get AD Model by GUID

Hi

Authentication is working fine and the GUID and domain is written to DB user model.

Now I want to retrieve the User Model plus LDAP Details for a user which is not the current authenticated one.

If I retrieve the User Model with App\User::find(1)->ldap it is null.

\LdapRecord\Models\ActiveDirectory\User::findByGUID($guid)
seems to return all users

I created App\Ldap\User and tried findByGUID() ,but it seems not to work as well

Tinker results:

\App\Ldap\User::findByGuid( "8e2215b0-1c73-4013-8bb8-75d6202c084f" )->getQuery();

=> "(&(objectclass=\74\6f\70)(objectclass=\70\65\72\73\6f\6e)(objectclass=\6f\72\67\61\6e\69\7a\61\74\69\6f\6e\61\6c\70\65\72\73\6f\6e)(objectclass=\75\73\65\72)(!(objectclass=\63\6f\6d\70\75\74\65\72)))"

No Filter by GUID is shown

What is the correct way to search for LDAP user in Laravel by GUID?
Or how to get ldap data from the User Model when the selected user is not the actual one?

Rules are ignored when using SSO

Describe the bug
Rules for Authentication are working fine when I login throught LoginController but with SSO (WindowsAuthenticate Middleware) they are ignored.

To Reproduce
Steps to reproduce the behavior:

  1. Create a LDAP-Rule (php artisan make:ldap-rule)
  2. Load the rule in auth config: providers -> ldap -> rules
  3. Deny access in rule:
    public function isValid() { return false; }
  4. Sign in using SSO (WindowsAuthenticate Middleware)

Expected behavior
Access is denied like when signing in without SSO (using LoginController)

Environment:

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4
  • Laravel Version: 6.18.2

Import via Controller

Having issues importing from a controller. I used this with ADLDAP2 to allow the Super Admin / Site Admins to import users directly thru HTTP calls.

Can you give me a basic syntax for making this call with
\Artisan::call();

I've tried
ldap:import, ldap, [--options]
ldap:import ldap, [--options]
ldap:import, [ldap, --options]

Each with no success. I appreciate the help in advance.

WindowsAuthenticate middleware should accept `guard` params to use proper LDAP domain

  • Laravel Version: N/A
  • PHP Version: N/A
  • LDAP Type: All

Description:

If someone's default guard isn't set to an LdapRecord provider, then the WindowsAuthenticate middleware will fail to lookup the user as the provider instance will never be an LdapRecord one.

Steps To Reproduce:

  1. Setup another auth guard using the ldap provider that is not the default
  2. Use WindowsAuthenticate middleware
  3. The user will not be logged in

Login is not working.

Describe the bug
I implemented LdapRecord-Laravel as described in the documentation but I'm still not able to login via LDAP to my app.

To Reproduce
LDAP Connection
image

Auth.php
image
image

LoginController.php
image

User Migration
image

Expected behavior
That I can login with my LDAP data.

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.3.7
  • Laravel Version: 7.0
  • LdapRecord-Laravel Version: 1.0

Unable to Determine Accurate Account Control Flags

LDAP Server: ActiveDirectory
PHP Version: 7.3
Laravel: 7

Hello,
I am having a difficult time Determining Set Account Control Flags.
If I use the example exactly as listed here:
https://ldaprecord.com/docs/tutorials/activedirectory/user-management/#user-account-control

use LdapRecord\Models\ActiveDirectory\User;
use LdapRecord\Models\Attributes\AccountControl;

$user = User::find('cn=John Doe,ou=Users,dc=acme,dc=org');

$uac = new AccountControl($user->userAccountControl);

if ($uac->has(AccountControl::LOCKOUT)) {
    // This account is locked out.
} elseif ($uac->has(AccountControl::ACCOUNTDISABLE)) {
    // This account is disabled.
} elseif ($uac->has(AccountControl::DONT_EXPIRE_PASSWORD)) {
    // This accounts password does not expire.
}

If I swap in my own info (which is enabled) like so:

$user = User::find('CN=Tyler\, Casey,CN=Users,DC=comlivserv,DC=com');
$uac = new AccountControl($user->userAccountControl);
if ($uac->has(AccountControl::LOCKOUT)) {
    dd('Locked') ;
} elseif ($uac->has(AccountControl::ACCOUNTDISABLE)) {
    dd('Disabled');
} elseif ($uac->has(AccountControl::DONT_EXPIRE_PASSWORD)) {
    dd('Dont Expire');
} elseif ($uac->has(AccountControl::NORMAL_ACCOUNT)) {
    dd('Normal');
}

I get no ou put. If DD $uac I get:

LdapRecord\Models\Attributes\AccountControl {#335 ▼
  #values: array:1 [▼
    1 => 1
  ]
}

I get the same result if I swap in a disabled user’s DN;
If I:

dd($user->getFirstAttribute('userAccountControl'));

On my own enabled account, I get “512”
I think that is correct. However, if I swap out the DN for a user who is disabled I get “514”. I do not think that is correct.

I am confused on the best way to determine the Account Control Flags. Any assisted would be appreciated

Cannot use object of type Illuminate\Support\Facades\Config as array

Describe the bug
Testing authentication doesn't work.

$ldapUser = User::create([
            'mail'       => $this->faker->email,
            'cn'         => $this->faker->name,
            'objectguid' => $this->faker->uuid,
        ]);

produces this error:

1) Modules\Auth\Tests\Feature\LoginTest::it_authenticates_a_user_with_ldap
Error: Cannot use object of type Illuminate\Support\Facades\Config as array

/Users/justustheis/code/ds_ticket/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:449
/Users/justustheis/code/ds_ticket/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:98
/Users/justustheis/code/ds_ticket/vendor/laravel/framework/src/Illuminate/Log/LogManager.php:591
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Log/EventLogger.php:96
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Log/EventLogger.php:41
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Container.php:68
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php:265
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php:111
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Events/Dispatcher.php:93
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Models/Concerns/HasEvents.php:19
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Models/Model.php:897
/Users/justustheis/code/ds_ticket/vendor/directorytree/ldaprecord/src/Models/Model.php:992
/Users/justustheis/code/ds_ticket/Modules/Auth/Tests/Feature/LoginTest.php:23

To Reproduce
Steps to reproduce the behavior:

  1. DB Connection: sqlite
  2. Database :memory:
  3. Using the test from https://ldaprecord.com/docs/laravel/auth/testing/

Expected behavior
Am I missing something here?

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.3
  • Laravel Version: 7.0.2

Pushishing fails

  • Laravel Version: 6.11
  • PHP Version: PHP 7.3.13-1+ubuntu18.04.1+deb.sury.org+1
  • LDAP Type: ActiveDirectory

Description:

after the composer require the publishing is failing

php artisan vendor:publish --provider LdapRecord\Laravel\LdapServiceProvider
Unable to locate publishable resources.
Publishing complete.

when I run php artisan vendor:publish
and select LdapRecord\Laravel\LdapServiceProvider
it works

Copied File [/vendor/directorytree/ldaprecord-laravel/config/ldap.php] To [/config/ldap.php]
Publishing complete.
Publishing complete.

Some happens with

php artisan vendor:publish --provider LdapRecord\Laravel\LdapAuthServiceProvider

where here the DB Migration is not copied (also not with php artisan vendor:publish)

I guess it is not finished for testing yet

userIsApartOfDomain() breaks WindowsAuthenticate

I'm no AD pro. So sorry for the sloppy explanation.
In our domain, we log on like this: "dnt1\username"
Now, if i try and use the WindowsAuthenticate middleware the userIsApartOfDomain() method can never return true, because there is no "dnt1" in the distinguished name.
I have been told the "dnt1" is a leftover from when ActiveDirectory was pretty new and we can not get rid of it.

Expected behavior
I created a workaround by creating a middleware WindowsAuthenticateFix and overrode the userIsApartOfDomain() method as followed:

namespace App\Http\Middleware;

use LdapRecord\Laravel\Middleware\WindowsAuthenticate;

class WindowsAuthenticateFix extends WindowsAuthenticate
{
    protected function userIsApartOfDomain(\LdapRecord\Models\Model $user, $domain)
    {
        return true;
    }
}

Maybe you could add a switch to the config/ldap.php which disables this check.

Environment:

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.2

integration with spatie permission

Hi, when you try to integrate with spatie permission, it not work beacuse it not get correct guard.
In config/auth.php

'ldap' => [
           'driver' => 'ldap',
           **'model' => LdapRecord\Models\ActiveDirectory\User::class,**
           'database' => [

Spatie Guard.php try to get '$guard_name' in ldap.model (with
return config("auth.providers.{$guard['provider']}.model");
and your model 'LdapRecord\Models\ActiveDirectory\User::class' don't have $guard_name

Sorry for english

Question about using multiple schemas

In Adldap, I had an env variable:
LDAP_SCHEMA=Adldap\Schemas\OpenLDAP
And used it in the ldap.php config:
'schema' => env('LDAP_SCHEMA', 'Adldap\Schemas\ActiveDirectory')

I am not sure if you have a suggested way of how to accomplish this in LdapRecord because I see you need to use the ldap fields in the credentials method: https://ldaprecord.com/docs/laravel/auth/usage/#using-usernames

For example, in OpenLdap I would need 'uid' for the username key, but in Active Directory I need 'samaccountname'.

I suppose I could create a custom env variable and put a new key in the config file, which I can reference in the Login Controller, but I was wondering if there was a better way:

protected function credentials(Request $request)
{
    return [
        config('ldap.username_key') => $request->username,
        'password' => $request->password,
    ];
}

The directory emulator looks really cool. Is there a reason why that can't be used locally?

How to get ldap:import to respect global scope

  • Laravel Version: 6.2
  • PHP Version: 7.3
  • LDAP Type: ActiveDirectory

Is there any way to get ldap:import to respect the a global scope? If there is not, I need a way to check two attributes to make sure they have values. In the global scope I have:

public function apply(Builder $query, Model $model)
{
$query->whereHas('clssyncuser')->whereHas('clsSyncPhoto');
}

This works good. However I am not sure how to import using the same criteria.

The documentation state:
The --filter (or -f) option allows you to enter in a raw filter to further narrow down the users who are imported:

However that does not seem to work. I tried
php artisan ldap:import ldap --filter "(clsSyncUser='')"

And
php artisan ldap:import ldap --filter "(clsSyncUser IS NOT NULL')" (I know this one wouldn't work)

Any suggestion on how to do this?

Authentication not working - Invalid Credentials Error always return

Laravel Version: 5.8
PHP: 7.2
Using Active Directory

Hi,

I have an issue that i try to resolve sinces hours... I can't sign in into my application and i got always the same error Invalid Credential and i don't understand why.

So heres is my config - auth.php :

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'ldap' => [
            'driver' => 'ldap',
            'model' => LdapRecord\Models\ActiveDirectory\User::class,
            'rules' => [],
            'database' => [
                'model' => App\User::class,
                'sync_passwords' => false,
                'sync_attributes' => [
                    'LASTNAME' => 'sn',
                    'FIRSTNAME' => 'givenname',
                    'ACTIVE_DIRECTORY_USER' => 'comptent'
                ]
            ]
        ]`

The LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use LdapRecord\Container;
use Illuminate\Http\Request;
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    use AuthenticatesUsers;

    /**
     * LDAP Connection 
     */
    private $connection;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->connection = Container::getConnection('default');
        $this->middleware('guest')->except('logout');
    }

    public function username() {
        return 'username';
    }

    protected function credentials(Request $request)
    {
        return [
            'comptent' => $request->username,
            'password' => $request->password,
        ];
    }
}

And the model User.php :

<?php

/**
 * Created by Reliese Model.
 */

namespace App;

//use Illuminate\Database\Eloquent\Model;
use LdapRecord\Laravel\Auth\HasLdapUser;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Models\Model;

/**
 * Class User
 * 
 * @property int $ID_USER
 * @property string $LASTNAME
 * @property string $FIRSTNAME
 * @property string $ACTIVE_DIRECTORY_USER
 * @property int $ID_ROLE
 * 
 * @property Role $role
 *
 * @package App\Models
 */
class User extends Authenticatable implements LdapAuthenticatable
{

	use Notifiable, AuthenticatesWithLdap;
	
	/**
     * The object classes of the LDAP model.
     *
     * @var array
     */
    public static $objectClasses = [];
	protected $table = 'user';
	protected $primaryKey = 'ID_USER';
	public $incrementing = false;
	public $timestamps = false;

	protected $casts = [
		'ID_USER' => 'int',
		'ID_ROLE' => 'int'
	];

	protected $fillable = [
		'LASTNAME',
		'FIRSTNAME',
		'ACTIVE_DIRECTORY_USER',
		'ID_ROLE'
	];

	public function role()
	{
		return $this->belongsTo(Role::class, 'ID_ROLE');
	}
}

Thanks in advance :)

EDIT: Sorry for the display of the code the github text editor is awful.

Make it possible to hide some attributes for serialization

Similar to the possibility which exists with Eloquent models, I think it should be possible to hide some attributes for serialization purposes. For example, I currently serialize models for logging purposes and don't really want userPassword attribute to be included.

Is this possible?

Add new data to meta field after first login

Hi, congrats for your library. Very handful.

I'm using PHP 7.2, Laravel 6.0 and LdapRecord 1.0 and I would like to know if is it possible to obligate the user to add more info into User models.

I have a meta field which would have info that doesn't came from Active Directory, so my idea it's to redirect the logged in user to another form if it was the first his/her login.

Is it possible to do this using LdapRecord?

Thanks

Can't install: Option auto_connect does not exist

  • Laravel Version: 6.14
  • PHP Version: 7.3.11
  • LDAP Type: ActiveDirectory

Description:

I can't install the software. When I run composer require directorytree/ldaprecord-laravel I get this error: LdapRecord\Configuration\ConfigurationException : Option auto_connect does not exist.

Installation fails and composer.json gets reverted to its original status.

Steps To Reproduce:

Run composer require directorytree/ldaprecord-laravel

Fallback to database when LDAP connection is missing

Hello,

I am migrating from Adldap2-Laravel and there were fallback option. How I understand that new library also supports "sync_passwords" option, but I don't understand how to enable fallback and I always receive "Unable to bind to server" error. When I am developing I don't have connection to LDAP and app should fallback to database. How I can enable it?

Ldap sync - remove deleted accounts

I have confirmed that when syncing as per below documentation - that any Active Directory account which is disabled will gets soft deleted - so this is great.

However if the account has been deleted from AD, there is no update on this account on the Laravel User Sync. Ideally deleted AD accounts - would get soft deleted in Laravel Users Table.

I assume this be achieved that after a sync - any accounts which have not been confirmed existing - get soft deleted.

In summary - the below soft deletes disabled AD accounts - but not deleted AD accounts.
Ref: https://ldaprecord.com/docs/laravel/auth/importing/

protected function schedule(Schedule $schedule)
{
// Import LDAP users hourly.
$schedule->command('ldap:import ldap', [
'--no-interaction',
'--restore',
'--delete',
'--filter' => '(objectclass=user)',
])->hourly();
}

How to Sync Data from a field to another table using a foreign key

  • Laravel Version: 6.2
  • PHP Version: 7.3
  • LDAP Type: ActiveDirectory

I love the ldap:import. However, is there a suggested way of syncing multiple tables.
For instance:
There is a field for title (OMG there are so many titles). I am currently storing those in a separate table with and using a foreign key in the users tables. I do not want to sync the foreign key with AD but rather the entire title.

Do you have a suggested way of doing that or do you have any recommendations?

permission management based on AD Groups

  • Laravel Version: #.#
  • PHP Version: #.#
  • LDAP Type: ActiveDirectory

Description:

Hey @stevebauman,
it would be cool if there is a simple way to manage group-based permissions

I'm mainly thinking about blade and routes

Steps To Reproduce:

Is it possible to use Laravel Passport with LdapRecord-Laravel?

Hi, thanks in advance and sorry to use this channel to ask a question and not report a bug.

I'm trying to setup Passport in a project that already works with LdapRecord. I followed the initial official documentation from Laravel Passport site and then I changed the files specified in LdapRecord docs like guards and providers in config/auth.php:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'ldap',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'ldap',
            'hash' => false,
        ],
    ],
...
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        'ldap' => [
            'driver' => 'ldap',
            'model' => LdapRecord\Models\ActiveDirectory\User::class,
            'rules' => [],
            'database' => [
                'model' => App\User::class,
                'sync_passwords' => false
            ],
        ],
]

I think I must create another LoginController that handles the Ldap auth and create the Passport token, but don't know if when I use Auth::attempt (see below) I'm already using LdapRecord methods to authenticate using ldap provider.

public function login(Request $request)
    {
            if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
            $user = Auth::user();
            $success['token'] =  $user->createToken('intranet')-> accessToken;
            return response()->json(['success' => $success], 200);
        }
        else {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
    }

LdapRecord-Laravel Return Empty Results

Laravel Version: 6.2
PHP Version: 7.3
LDAP Type: ActiveDirectory

For some reason when I set up LdapRecord without Laravel I get results, however, when I connect in a Laravel project I get an empty result.

This is my configuration for LDAP record stand alone that returns my record in AD as expected:

<?php

use LdapRecord\Connection;
require __DIR__ . '/vendor/autoload.php';
$config = [
    // Mandatory Configuration Options
    'hosts'            => ['xx.xx.xx.x'],
    'base_dn'          => 'DC=comlivserv,DC=com',
    'username'         => '[email protected]',
    'password'         => 'xxxxxxxxxx',
     'use_ssl'          => true,
];

$connection = new Connection($config);

try {
    $connection->connect();
    echo "Successfully connected!";
} catch (\LdapRecord\Auth\BindException $e) {
    $error = $e->getDetailedError();

    echo $error->getErrorCode();
    echo $error->getErrorMessage();
    echo $error->getDiagnosticMessage();
}
$query = $connection->query();
$results = $connection->query()->where('cn', '=', 'Tyler, Casey')->get();
echo '<pre>';
print_r($results);
echo '</pre>';
?>

However, when I add the same info to my Laravel project:

LDAP_LOGGING=true
LDAP_CONNECTION=default
LDAP_HOST=xx.xx.xx.xx
LDAP_USERNAME="[email protected]"
LDAP_PASSWORD=xxxxxxxxxx
LDAP_PORT=636
LDAP_BASE_DN="dc=comlivserv,dc=com"
LDAP_TIMEOUT=5
LDAP_SSL=true
LDAP_TLS=false

I create my user model using: php artisan make:ldap-model User

Here is the model:

namespace App\Ldap;

use LdapRecord\Models\ActiveDirectory\Entry;

class User extends Entry
{
    public static $objectClasses = [
        'top',
        'person',
        'organizationalperson',
        'user',
    ];

    //protected $connection = 'default';
}

Now in my web.php route file i add:

use App\Ldap\User;

Route::get('/', function () {
    //$users = User::get();
    //$users = User::where('givenName', '=', 'Casey')->get();
    //$user = User::find('cn=Tyler/, Casey,dc=comlivserv,dc=com');
   //$user = User::findByAnr('ctyler');
    $user = User::findByOrFail('samaccountname', 'ctyler');
    dd($user);
    return view('welcome');
});

All of the comment queries returned no results. This uncommented one is returning:
LdapRecord\Models\ModelNotFoundException
No LDAP query results for filter: [(&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=user)(samaccountname=ctyler))] in: [dc=comlivserv,dc=com]

Any help would be appreciated.

Type Error when trying to login with a user after configuring module with composer

Describe the bug
This is possibly an isolated issue.

Earlier today I tried to configure LdapRecord-Laravel.
As soon as I tried to login with a user a TypeError exception was thrown with the following text:
Argument 1 passed to LdapRecord\Models\Model::serializeDate() must implement interface DateTimeInterface, null given, called in C:\Users\bruno.martins\source\repos\outono\vendor\directorytree\ldaprecord\src\Models\Concerns\HasAttributes.php on line 105

Se screenshot below
image

To fix this I dug arround a bit and found that some of the user attributes, like 'lockouttime' and 'lastlogoff were set to "0", and when put throught the $this->asDateTime() were being returned as null.

Following my discovery I added a simple check, see below:

No fix:

protected function addDateAttributesToArray(array $attributes)
    {
        foreach ($this->getDates() as $attribute => $type) {
            if (!isset($attributes[$attribute]) || $attributes[$attribute] === 0) {
                continue;
            }

            $date = $this->serializeDate(
                $this->asDateTime($type, $attributes[$attribute])
            );

            $attributes[$attribute] = Arr::wrap($date);
        }

        return $attributes;
    }

Fix:

protected function addDateAttributesToArray(array $attributes)
    {
        foreach ($this->getDates() as $attribute => $type) {

            if (!isset($attributes[$attribute])) {
                continue;
            }

            $attributeAsDateTime = $this->asDateTime($type, $attributes[$attribute]);

            if ($attributeAsDateTime === null) {
                continue;
            }

            $date = $this->serializeDate(
                $attributeAsDateTime
            );

            $attributes[$attribute] = Arr::wrap($date);
        }

        return $attributes;
    }

After this, I could login with a user and use the app, again, I do not know if this is an isolated issue or not, If it's not, I am more than happy to file a merge request and tweak the code for a fix.

Thanks!

To Reproduce
Steps to reproduce the behavior:

  1. Create a new laravel project
  2. Add this module
  3. Configure according to the configuration documentation
  4. Try Logging in

Expected behavior
The user is logged in and created in the database

Environment (please complete the following information):

  • LDAP Server Type: ActiveDirectory
  • PHP Version: 7.4
  • Laravel Version: 7.x

where statement with dn attribute creates a malformed filter

Using versions:
directorytree/ldaprecord v1.2.10 A fully-featured LDAP ORM.
directorytree/ldaprecord-laravel v1.0.9 LDAP Authentication & Management for Laravel.

When you query using a where statement for the dn attribute, for example:

...->where("dn","=","blah blah")->get()

creates a malformed filter on LDAP server. Logs show that it adds a question mark like this:

...SRCH base="..." scope=2 deref=0 filter="(?dn=Giritli)"

which cause queries fail to find results I believe.

Gracefully falling back to DB authentication

I've got LdapRecord-Laravel successfully set up and working with Synchronized Database Authentication - and I can't compliment you enough on how easy that was!

One thing I've noticed, however, is that if the LDAP server is unreachable my application throws an exception. What I'd like to do in that case is to gracefully fallback to database authentication - as the docs hint at - as and when this occurs. I'm not entirely sure where to start or what the best approach to this is.

Any guidance greatly accepted - and congratulations on this excellent package!

login is not possible

  • Laravel Version: 6.15.1
  • PHP Version: 7.4.1
  • LDAP Type: ActiveDirectory

Description:

I am currently trying to log in with the samaccount name.
But i get the following error message.

config - auth.php
image

image

LoginController:

image

User.php
image

Commands:
the users are synced with php artisan ldap:import ldap --no-interaction and exist in the database.

Login Message:
image

Log Message on Login:
image
here i am wondering why it is filtered in the query for username?

I tried to debug something and wondered why the attempt method is not called under vendor / directorytree / ldaprecord / src / auth / guard.php. I tried to narrow the position here using dd ().

Any idea?

Greetings Daniel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.