thesimons's avatar

Logic behind authentication only if role is 'admin'

Hello,

In previous project I created a code to authenticate everybody and restrict access to some pages if - in example - the role wasn't 'admin'.

Now I'm working on a new project where I have a login page just for admins and I'd like to not authenticate users - even if pwd and email match - in case role isn't "admin".

Here the code from the old project:

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

        $validated['status'] = 'active';

        if(auth()->attempt($validated,)){
            request()->session()->regenerate();
            return "logged in";
        } else {
            return "not logged in";
        }
    }

How can I include the condition if role='admin'?

Thanks for helping

Simon

0 likes
9 replies
tykus's avatar

If role is a column on the users table, then you can treat it as you did with status above:

$validated['status'] = 'active';
$validated['role'] = 'admin';

if(auth()->attempt($validated)) {

Otherwise, you could need to query the relation separately to the Auth::attempt, but we would need to understand the relation type in that case.

thesimons's avatar

@tykus Hello,

Thanks for your reply. In fact I had the solution into my code :/

Snapey's avatar

Why do users that are not admins even have an account that they can login with?

1 like
thesimons's avatar

@Snapey It's s sort of subscription website. The same instance of Laravel handles siteA.com (the "pay site") and siteB.com (the billing / admin / css domain). I use the table users both for admins both for "normal" users. I'd like to prevent non admin users from logging into siteB.com.

To reply to your previous question, admin is a field of the users table with enum value 'user' and 'admin'.

Using an extra conditions to login will be used in the near future where just "paid" users can get access to siteA.com. In this case I'm going to add an extra field to the table users, something like status with values 'subscribed', 'paid', 'expired', 'cancelled'.

Thanks, Simon

puklipo's avatar

Learn about the Authorization feature. You can restrict access when viewing a page, not when logging in.

amitsolanki24_'s avatar
    $validated = request()->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
		
	abort_if(User::where('email', $request->email)->where('role', 'Admin')->exists(), 403);

        $validated['status'] = 'active';

        if(auth()->attempt($validated,)){
            request()->session()->regenerate();
            return "logged in";
        } else {
            return "not logged in";
        }
tykus's avatar

@amitsolanki24_ not necessary to execute that extra query; the Auth::attempt approach I showed above will impose the role constraint anyway.

Please or to participate in this conversation.