doujuanju3076 2019-03-27 01:28 采纳率: 0%
浏览 92

如何使用动态数据库登录?

I am making project on laravel 5.7. where i have to manage login with dynamic database. where one master database and another is sub database. So when user give login detail that first check on master database if login not found on master then it will look email on App_clients table on master_db and find database name of that email id and check login .if it gone success then move to dashboard. and every time till logged in sub database ( client_2) database will active.

Main goal of this concept is that there two different logins.

1) Login for Master Database that will be only for Software Owner. 2) Another Login is for Client who are using This software.

So when client will login then their database name will come form App_client table using their email. So Laravel Database Config will change and set new database for their use and database will be active til client logged in else default database will active .

For Example

Database:: Master_db , Client_2_db , Client_3_db ,etc. email:abc@ex.com and password :1234 is stored in Client_2_db.

First it will check on Master_db. it will fail. then it's email will look on Master_db.App_clients and will get it database name that stored on Master_db.App_clients. So after that will try to login from Client_2_db.

So for this i am using this code on myLoginController.

   if( $request->client == '1111111'  )
    {
        Config::set('database.default', 'mysql');
        DB::reconnect('mysql');
        $loginCheck=  Auth::attempt( ["email" =>$request->username , "password" => $request->password ] );
        if( $loginCheck  )
        {
            // Store Collage ID on session variable.
            $client = SettingClient::where('client_CODE',$request->client_code)->first();
            $request->session()->put('client', $client->ID );
            $request->session()->put('cclient_code', $client->client_CODE );
            $request->session()->put('client_name', $client->client_NAME );
            $request->session()->put('database_name', 'col_master' );
            return redirect('dashboard');
        }
        goto InvalidLoginFound;

    }
    elseif (  $request-> client_code != '1111111'  )
    {
           $clientCheck =  AppClient::where("client_code" , $request->client_code )->orderBy('id','desc')->first();
        if( !$clientCheck   )
        {
            goto clientCodeNotFound ;
        }
        DB::purge('mysql');
        Config::set("database.connections.mysql", [
            "driver" => "mysql",
            "host" => env('DB_HOST'),
            "database" => $clientCheck->database_name,
            "username" => env('DB_USERNAME'),
            "password" => env('DB_PASSWORD'),
            "engine"=>"InnoDB",
        ]);
        Config::set('database.default', 'mysql');
        DB::reconnect('mysql');

        $loginCheck=  Auth::attempt( ["email" =>$request->username , "password" => $request->password ] );
        if( $loginCheck  )
        {
            // Store client ID on session variable.
            $client = SettingClient::where('client_CODE',$request->client_code)->first();
            if( !$client )
            {
                goto clientCodeNotFound;
            }
            $request->session()->put('client', $client->ID );
            $request->session()->put('login_id', $request->username  );
            $request->session()->put('password',  $request->password  );
            $request->session()->put('client_code', $client->client_CODE );
            $request->session()->put('client_name', $client->client_NAME );
            $request->session()->put('database_name', $clientCheck->database_name );
            return redirect('dashboard');
        }

        $request->session()->flush();
        Auth::logout();
        goto InvalidLoginFound;

    }

also created a middle-ware for this that manage database on each request.

 class DynamicDatabaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if( session()->get('login_id')  )
        {
            DB::purge('mysql');
            Config::set("database.connections.mysql", [
                "driver" => "mysql",
                "host" => '127.0.0.1',
                "database" => session()->get('database_name')?session()->get('database_name'):'',
                "username" => 'root',
                "password" => '',
                "engine"=>"InnoDB",
            ]);
           // Config::set('database.default', 'mysql');
            DB::reconnect('mysql');


        }
        return $next($request);
    }
}

on Karnel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\SessionDataMiddleware::class,
        \App\Http\Middleware\StoreExceptionMiddleware::class,


        \App\Http\Middleware\DynamicDatabaseMiddleware::class, 
    ],

after this is working but problem is that when i try to check login-in Auth::user() then i always get login detail from Master_db( col_master ) form from client_db. why? i do't know. please correct this code.

  • 写回答

2条回答 默认 最新

  • douwang4374 2019-03-27 10:45
    关注

    you are on the right path. Just not there yet.

    you need to add the whole login request in the middleware, and for each database connection you want to check, you put a switch or try/catch (with -> continue) or an if/elseif statement to go throw evry database connection you have and if the user is found in 1 of them then it will connect him and go to the next request if not then it will show an error. notice that in your statements (database connection switch) you need to purge your connection and connect again to a new database username/pass. you can use (

            DB::purge('mysql');
    
     config(['database.connection.mysql' => 
    'driver' => 'mysql',
    'host' => ''.
    'database' =>,
    etc.....
    ]));
            DB::reconnect('mysql');
            Schema::connection('mysql')->getConnection()->reconnect();
    

    )

    Good luck

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度