lundi 8 juillet 2019

Error trying to authenticate user with Auth::attempt in Laravel 5.8

The application uses different databases for each company.

Authentication receives a username (not email) of type username@company where after explode, company is an alias to find the company in the "default" database of the application and retrieve the data of the specific database. After connecting to that particular database, username is used to log into the application. At the time of trying to log in, I get the error.

$credentials = [
    'username' => $username, // string
    'password' => $password, // string
    'active' => 1
];

if (Auth::attempt($credentials)) { // <-- The error originates here
    //...
}

The error obtained is:

ErrorException (E_WARNING) substr() expects parameter 1 to be string, array given

The error is reported in: \vendor\laravel\framework\src\Illuminate\Support\Str.php line 143

I understand that the password should be sent without Hash, but applying the Hash had no effect.

class UserController extends Controller
{
    public function login()
{
    return view('auth.login');
}

public function authenticate(Request $request)
{
    $request->validate([
        'username' => 'required|string',
        'password' => 'required|string',
    ]);

    $data = explode('@', $request->username);
    $username = $data[0];
    $company = $data[1];

    $client = SysClient::where('company', $company)->first();

    // database data connection
    $connection = [
        "driver" => $client->driver,
        "host" => $client->host,
        "port" => $client->port,
        "database" => $client->database,
        "username" => $client->username,
        "password" => $client->password,
        "unix_socket" => $client->unix_socket,
        "charset" => $client->charset,
        "collation" => $client->collation,
        "prefix" => $client->prefix,
        "prefix_indexes" => $client->prefix_indexes,
        "strict" => $client->strict,
        "engine" => $client->engine
    ];

    $request->session()->put('database.default', $client->database);

    \Config::set('database.connections.' . $cliente->database, $connection);

    $db = \Config::get('database.connections.' . $cliente->database);

    if($db) {
        \Config::set('database.default', $db);
    } else {
        //...
    }

    $credentials = [
        'username' => $username, // string
        'password' => $password, // string
        'active' => 1
    ];

    Up to this line, everything is fine.
    The problem comes now ...

    if (Auth::attempt($credentials)) {  // <-- The error originates here
        // Authentication passed...
        return redirect()->intended('/target');
    } else {
        //...
    }
}

I just need to get Auth::attempt back true or false but the error prevents the return.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire