<commit_before><?php

namespace Ccovey\LdapAuth;

use adLDAP;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Auth\UserProvider;

/**
 * Class to build array to send to GenericUser
 * This allows the fields in the array to be
 * accessed through the Auth::user() method.
 */
class LdapAuthUserProvider implements UserProvider
{
    /**
     * Active Directory Object.
     *
     * @var adLDAP\adLDAP
     */
    protected $ad;

    /**
     * @var type string
     */
    protected $model;

    /**
     * DI in adLDAP object for use throughout.
     *
     * @param adLDAP\adLDAP $conn
     */
    public function __construct(adLDAP\adLDAP $conn, $config, $model = null)
    {
        $this->ad = $conn;
        $this->config = $config;
        $this->model = $model;
    }

    /**
     * Retrieve a user by their unique idenetifier.
     *
     * @param mixed $identifier
     *
     * @return Illuminate\Auth\GenericUser|null
     */
    public function retrieveByID($identifier)
    {
        $ldapUserInfo = null;
        $userNameField = $this->getUsernameField();

        if ($this->model) {
            $model = $this->createModel()->newQuery()->find($identifier);
        }

        if (isset($model)) {
            $username = $model->$userNameField;
        } else {
            $username = $identifier;
        }

        //recursive groups fix
        if ($this->ad->getRecursiveGroups()) {
            $info = $this->ad->user()->info($username, ['*']);
            $groups = $this->ad->user()->groups($username);
            $info[0]['memberof'] = $groups;
            $info[0]['memberof']['count'] = count($groups);

            $infoCollection = new \adLDAP\collections\adLDAPUserCollection($info, $this->ad);
        } else {
            $infoCollection = $this->ad->user()->infoCollection($username, ['*']);
        }

        if ($infoCollection) {
            $ldapUserInfo = $this->setInfoArray($infoCollection);

            if ($this->model) {
                if (!is_null($model)) {
                    return $this->addLdapToModel($model, $ldapUserInfo);
                }
            }


            return new LdapUser((array) $ldapUserInfo);
        }
    }

    /**
     * Retrieve a user by by their unique identifier and "remember me" token.
     *
     * @param mixed  $identifier
     * @param string $token
     *
     * @return UserContract|null
     */
    public function retrieveByToken($identifier, $token)
    {
        return; // this shouldn't be needed as user / password is in ldap
    }

    /**
     * @return void
     */
    public function updateRememberToken(UserContract $user, $token)
    {
        return; // this shouldn't be needed as user / password is in ldap
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param array $credentials
     *
     * @return Illuminate\Auth\GenericUser|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // dd( $credentials );
        if (!$user = $credentials[$this->getUsernameField()]) {
            throw new \InvalidArgumentException();
        }

        //recursive groups fix
        if ($this->ad->getRecursiveGroups()) {
            $info = $this->ad->user()->info($user, ['*']);
            $groups = $this->ad->user()->groups($user);
            $info[0]['memberof'] = $groups;
            $info[0]['memberof']['count'] = count($groups);

            $infoCollection = new \adLDAP\collections\adLDAPUserCollection($info, $this->ad);
        } else {
            // dd( $this->ad->user());
            $infoCollection = $this->ad->user()->infoCollection($user, ['*']);
        }

        if ($infoCollection) {
            $ldapUserInfo = $this->setInfoArray($infoCollection);
            if ($this->model) {
                $query = $this->createModel()->newQuery();

                foreach ($credentials as $k => $credential) {
                    if (!str_contains($k, 'password') && !str_contains($k, '_token')) {
                        $query->where($k, $credential);
                    }
                }

                if ($model = $query->first()) {
                    return $this->addLdapToModel($model, $ldapUserInfo);
                } else {
                    $ldapUserInfo = $this->ad->user()->info($user, ['*'])[0];
                }
            }


            return new LdapUser((array) $ldapUserInfo);
        }
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param UserContract $user
     * @param array        $credentials
     *
     * @throws adLDAP\adLDAPException
     *
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        return $this->ad->authenticate($credentials['uid'], $credentials['password']);
    }

    /**
     * Build the array sent to GenericUser for use in Auth::user().
     *
     * @param adLDAP\adLDAP $infoCollection
     *
     * @return array $info
     */<commit_msg>Correctly bind LDAP users to our User model<commit_after><?php

namespace Ccovey\LdapAuth;

use adLDAP;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Auth\UserProvider;

/**
 * Class to build array to send to GenericUser
 * This allows the fields in the array to be
 * accessed through the Auth::user() method.
 */
class LdapAuthUserProvider implements UserProvider
{
    /**
     * Active Directory Object.
     *
     * @var adLDAP\adLDAP
     */
    protected $ad;

    /**
     * @var type string
     */
    protected $model;

    /**
     * DI in adLDAP object for use throughout.
     *
     * @param adLDAP\adLDAP $conn
     */
    public function __construct(adLDAP\adLDAP $conn, $config, $model = null)
    {
        $this->ad = $conn;
        $this->config = $config;
        $this->model = $model;
    }

    /**
     * Retrieve a user by their unique idenetifier.
     *
     * @param mixed $identifier
     *
     * @return Illuminate\Auth\GenericUser|null
     */
    public function retrieveByID($identifier)
    {
        $ldapUserInfo = null;
        $userNameField = $this->getUsernameField();

        if ($this->model) {
            $model = $this->createModel()->newQuery()->find($identifier);
        }

        if (isset($model)) {
            $username = $model->$userNameField;
        } else {
            $username = $identifier;
        }

        //recursive groups fix
        if ($this->ad->getRecursiveGroups()) {
            $info = $this->ad->user()->info($username, ['*']);
            $groups = $this->ad->user()->groups($username);
            $info[0]['memberof'] = $groups;
            $info[0]['memberof']['count'] = count($groups);

            $infoCollection = new \adLDAP\collections\adLDAPUserCollection($info, $this->ad);
        } else {
            $infoCollection = $this->ad->user()->infoCollection($username, ['*']);
        }

        if ($infoCollection) {
            $ldapUserInfo = $this->setInfoArray($infoCollection);

            if ($this->model) {
                dd( $this->model ) ;
                if (!is_null($model)) {
                    return $this->addLdapToModel($model, $ldapUserInfo);
                }
            }


            return new LdapUser((array) $ldapUserInfo);
        }
    }

    /**
     * Retrieve a user by by their unique identifier and "remember me" token.
     *
     * @param mixed  $identifier
     * @param string $token
     *
     * @return UserContract|null
     */
    public function retrieveByToken($identifier, $token)
    {
        return; // this shouldn't be needed as user / password is in ldap
    }

    /**
     * @return void
     */
    public function updateRememberToken(UserContract $user, $token)
    {
        return; // this shouldn't be needed as user / password is in ldap
    }

    /**
     * Retrieve a user by the given credentials.
     *
     * @param array $credentials
     *
     * @return Illuminate\Auth\GenericUser|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // dd( $credentials );
        if (!$user = $credentials[$this->getUsernameField()]) {
            throw new \InvalidArgumentException();
        }

        //recursive groups fix
        if ($this->ad->getRecursiveGroups()) {
            $info = $this->ad->user()->info($user, ['*']);
            $groups = $this->ad->user()->groups($user);
            $info[0]['memberof'] = $groups;
            $info[0]['memberof']['count'] = count($groups);

            $infoCollection = new \adLDAP\collections\adLDAPUserCollection($info, $this->ad);
        } else {
            // dd( $this->ad->user());
            $infoCollection = $this->ad->user()->info($user, ['*']);
        }

        if ($infoCollection != null) {
            // $ldapUserInfo = $this->setInfoArray($infoCollection);
            if ($this->model) {
                $query = $this->createModel()->newQuery();

                foreach ($credentials as $k => $credential) {
                    if (!str_contains($k, 'password') && !str_contains($k, '_token')) {
                        $query->where($k, $credential);
                    }
                }

                $ldapUserInfo = $this->ad->user()->info($user, ['*'])[0];
                $userinfo = [
                    'home_directory' => $ldapUserInfo["homedirectory"][0],
                    'password' => str_replace('{crypt}', '', $ldapUserInfo['userpassword'][0]),
                    'uidnumber' => $ldapUserInfo['uidnumber'][0],
                    'uid' => $ldapUserInfo['uid'][0],
                    'gid' => $ldapUserInfo['gidnumber'][0]
                ];

                if ($model = $query->first()) {
                    \App\User::find( $model->id )->update( $userinfo );
                    return $model;
                } else {
                    // If the student is registered on LDAP but isn't 
                    // in our database
                    $user = \App\User::create($userinfo);
                    return $user;
                }                
            }

        }
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param UserContract $user
     * @param array        $credentials
     *
     * @throws adLDAP\adLDAPException
     *
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        return $this->ad->authenticate($credentials['uid'], $credentials['password']);
    }

    /**
     * Build the array sent to GenericUser for use in Auth::user().
     *
     * @param adLDAP\adLDAP $infoCollection
     *
     * @return array $info
     */
{'fraction_non_alphanumeric': 0.14650274750861508, 'fraction_numerical': 0.0013970382788488405, 'mean_word_length': 1.837737843551797, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 114, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2764958', 'n_tokens_mistral': 3099, 'n_tokens_neox': 3022, 'n_words': 661}