I built a login backend where I want to check some conditions before allowing the login.
I could check all conditions in one shoot but I need to send a different response for every failed attempt.
In the index
method below all check methods are called, the specific thing I need is that if any condition is true then the request should terminate and the response should be sent back without calling other methods after it.
Currently the return
at every method seems not respected.
public function index(LoginRequest $request){
$user = User::select('leave','role','id','isActive')->find(request('username'));
$this->checkRole($user);
$this->checkAnnualLeave($user);
$this->checkAccountDisabled($user);
}
public function checkRole($user){
$Condition1=true;
if($Condition1){
return response()->json(['message'=>'user is anauthorized !']);
}
}
public function checkAnnualLeave($user){
$Condition2=true;
if($Condition2){
return response()->json(['message'=>'user is in Annual leave']);
}
}
public function checkAccountDisabled($user){
$ConditioN3=true;
if($ConditioN3){
return response()->json(['message'=>'user account is disabled']);
}
}
CodePudding user response:
However, I think using 'Laravel Middleware' can simplify your code, but even in your current code you can use die()
in each of your functions after return to stop the script from running. Like bellow:
if($Condition1){
return response()->json(['message'=>'user is anauthorized !']);
die();
}
Another option is that check all conditions in one function. For instance, consider the following code:
public function index(LoginRequest $request){
$user = User::select('leave','role','id','isActive')->find(request('username'));
$this->checkUser($user);
}
public function checkUser($user) {
Switch ($user) {
case condition1:
return response()->json(['message'=>'user is anauthorized !']);
break;
case condition2:
return response()->json(['message'=>'user is in Annual leave']);
break;
case condition3:
return response()->json(['message'=>'user account is disabled']);
break;
default:
}
}
Or you can use 'if statement' instead of 'switch statement'
CodePudding user response:
You can abort within every conditional returning the wanted error code and message.
public function index(LoginRequest $request){
$user = User::select('leave','role','id','isActive')->find(request('username'));
$this->checkRole($user);
$this->checkAnnualLeave($user);
$this->checkAccountDisabled($user);
}
public function checkRole($user){
$Condition1=true;
if($Condition1){
abort(403, 'user is anauthorized !');
}
}
public function checkAnnualLeave($user){
$Condition2=true;
if($Condition2){
abort(404, 'user is in Annual leave');
}
}
public function checkAccountDisabled($user){
$ConditioN3=true;
if($ConditioN3){
abort(401, 'user account is disabled');
}
}