如何使用 Laravel 在登录中添加 Spatie 角色条件

问题描述

我正在使用 Laravel-8、laravel-passport 和 spatie-permission 来创建restful api。我已经在控制器中有这个代码了。

我为管理员设置了这个控制器:

public function adminLogin(Request $request)
{
    if(Auth::attempt(['email' => $request->email,'password' => $request->password])){
        $user = Auth::user();
        $success['token'] =  $user->createtoken('MyApp')-> accesstoken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success,'User login successfully.');
    }
    else{
        return $this->sendError('Unauthorised.',['error'=>'Unauthorised']);
    }
}

我只希望“超级管理员”能够使用管理员控制器登录。如果不是“超​​级管理员”,则应表示未经授权。

如何将下面的代码包含在我上面已有的代码中或其他任何最佳方式中?

    if($user->hasRole('Super Admin'))
        $res = User::with(['roles','employee','company'])->find($user->id);
    else
        $res = User::with('roles')->find($user->id);

解决方法

您可以在尝试身份验证后检查用户的角色。

public function adminLogin(Request $request)
{
    if (Auth::attempt($request->only('email','password'))) {
        $user = Auth::user();

        if (!$user->hasRole('Super Admin') {
            Auth::logout();

            return $this->sendError('Unauthorised.',['error'=>'Unauthorised']);
        }

        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success,'User login successfully.');
    }

    return $this->sendError('Unauthorised.',['error'=>'Unauthorised']);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...