Как использовать несколько таблиц базы данных (нативное Laravel и другое устаревшее приложение) для входа в Laravel? - PullRequest
0 голосов
/ 13 февраля 2019

Я очень новичок в Laravel (это важно)))

Мое приложение должно использовать данные в существующей базе данных (только для чтения).Поэтому я подключил к своему приложению две базы данных: одну для Laravel, а другую - для чтения данных.Мне нужно сделать аутентификацию для пользователей, существующих во второй базе данных, и сохранить их в таблице «родных» пользователей Laravel.Например:

1004 Пользователь пытается войти Приложение выполняет поиск учетных данных пользователя в собственной таблице 'пользователей' Laravel в БД Laravel Если пользователь существует, войдите Иначе, приложение ищет учетные данные пользователя в БД 'Legacy' (ВАЖНО! Приложение 'Legacy' использует md5 для хеширования пароля) Если пользователь существует в базе данных 'legacy', сохраните учетные данные пользователя в Laravel DB и войдите в систему Еще одна ошибка повышения

В моем DEV базы данных подключены следующими способами

в .env:

...
DB_CONNECTION=sqlite
DB_DATABASE=/path/to/app/db.sqlite

DB_CONNECTION_LEGACY=sqlite
DB_DATABASE_LEGACY=/path/to/app/legacy.sqlite
...

в config/database.php:

...
'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => env('DB_DATABASE', database_path('database.sqlite')),
        'prefix' => '',
        'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
    ],

    'sqlite_legacy' => [
        'driver' => 'sqlite',
        'database' => env('DB_DATABASE_LEGACY', database_path('database.sqlite')),
        'prefix' => '',
        'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
    ],
...

Пожалуйста, помогите мне.Я застрял.

Извините за плохой английский, это не мой родной язык.

1 Ответ

0 голосов
/ 15 февраля 2019

Готово.

Создана модель для моей старой БД:

php artisan make:model OldUsers

в app\OldUsers.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class eboard_user extends Model
{
    /**
     * Connection for old 'users' table
     *
     * @var string
     */

    protected $connection = 'sqlite_legacy';

    /**
     * The table associated with the model.
     *
     * @var string
     */

    protected $table = 'users';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */

    public $timestamps = false;

    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */

    protected $dateFormat = 'U';
}

в app/Http/Controllers/Auth/LoginController.php:

<?php

namespace App\Http\Controllers\Auth;

use App\OldUsers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;

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;

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

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

    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        } else {

        $checkedUser = OldUsers::whereEmail($request->input('email'))->wherePass(md5($request->input('password')))->whereStatus('2')->first(); //Selecting user from old DB via needed criteria
        if ($checkedUser !== null) { //If old user exists:
            $newUser = new User; //Create Laravel native user
            $newUser->name = $checkedUser->name;
            $newUser->email = $checkedUser->email;
            $newUser->password = Hash::make($request->input('password'));
            $newUser->save();

            if ($this->attemptLogin($request)) {
                return $this->sendLoginResponse($request);
            }
        }
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...