简体   繁体   中英

Laravel authenticate users when their school is active

We are making a laravel project that is for schools. We got a database for schools and inside it are the the users like teachers,staffs ect. My problem is how do I prevent the specific user from a specific school from logging in where their school status is marked = 0 or as inactive in our database?

Schools table +--------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(191) | NO | UNI | NULL | | | description | text | NO | | NULL | | | logo | varchar(191) | YES | | NULL | | | status | int(11) | NO | | 1 | | | updated_by | varchar(191) | YES | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +--------------+------------------+------+-----+---------+----------------+ +--------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(191) | NO | UNI | NULL | | | description | text | NO | | NULL | | | logo | varchar(191) | YES | | NULL | | | status | int(11) | NO | | 1 | | | updated_by | varchar(191) | YES | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +--------------+------------------+------+-----+---------+----------------+

Users table +-------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(191) | NO | | NULL | | | email | varchar(191) | NO | UNI | NULL | | | password | varchar(191) | NO | | NULL | | | role | int(11) | NO | | 0 | | | school_id | int(11) | NO | | NULL | | | gender | int(11) | NO | | 1 | | | birthdate | date | YES | | NULL | | | address | varchar(191) | NO | | | | | phone | varchar(191) | YES | | NULL | | | remember_token | varchar(100) | YES | | NULL | | +-------------------+------------------+------+-----+---------+----------------+ +-------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(191) | NO | | NULL | | | email | varchar(191) | NO | UNI | NULL | | | password | varchar(191) | NO | | NULL | | | role | int(11) | NO | | 0 | | | school_id | int(11) | NO | | NULL | | | gender | int(11) | NO | | 1 | | | birthdate | date | YES | | NULL | | | address | varchar(191) | NO | | | | | phone | varchar(191) | YES | | NULL | | | remember_token | varchar(100) | YES | | NULL | | +-------------------+------------------+------+-----+---------+----------------+

LoginController.php

class LoginController extends Controller
{

    use AuthenticatesUsers;

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

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



}```

User model

  public function schools()
    {
        return $this->belongsTo('App\School', 'school_id');
    }

School model

 public function users(){
        return $this->hasMany(User::class);
    }

My LoginController only uses the AuthenticateUsers function and I dont know a way how to override it or make a new function for me. Thanks in advance.

I suggest creating a middleware to the login route, that will look after the user's status value for his school. If it's not valid, you should handle it for example, that you throw an exception back to user, that the school is inactive.

More about it here: https://laravel.com/docs/master/middleware


Updated:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param \Illuminate\Contracts\Auth\Guard $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->schools()->status == 0) {
            return response('School is inactive!', 401);
        }

        return $next($request);
    }
}

And add the newly created middleware to the App\Http Kernel.php class.

Add the following line to the variable $routeMiddleWare :

'auth'                => \TIM\Http\Middleware\Authenticate::class,

Now the last thing to do is to add the 'auth' key to the Route group .

Route::group([
    'middleware' => ['auth'],
], function () {
// your routes
}

You could override the attemptLogin function to also check for this field.

protected function attemptLogin(Request $request)
{
    //
    // Query the school status here and return false if status === 0.
    //

    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

In LoginController you can override the authenticated method, this function fires when the user has successfully signed in.

public function authenticated(Request $request, $user)
{
    if ($user->schools()->status === 0) {
        Auth::logout($user);

        abort(403, 'Your school is not active.');
    }
}
  1. I'm assuming here that you've setup relationships, if not then just select the school which the user is enrolled and check from that.
  2. The reason why I suggest to override the authenticated method as opposed to other methods is that at this point you know the user has signed in correctly so it is the correct place to handle it as opposed to the attemptLogin .

use join query. just add school_id in users table. for example

self::where('users.school_id', $id)->where('schools.status',0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM