I want to make the code below prettier but I don't know what to change and how to change. I know that the controller should be easy, delegating actions related to models or to services or something else.
The task the code below solves is to authenticate a client with 2 factory authentication. If a client has 2fa enabled, then additional field 2faCode
is required, otherwise only email and password are required. I really don't like so many if
s for such a simple task. The code should be easy and readable.
/**
* Get a JWT via given credentials.
*
* @param LoginUserRequest $request
* @return JsonResponse
*/
public function login(LoginUserRequest $request): JsonResponse
{
$data = $request->validated();
if (!$token = auth()->attempt(['email' => $data['email'], 'password' => $data['password']])) {
return response()->json(['error' => 'Unauthorized. Credentials are wrong'], 401);
}
$user = auth()->user();
if (!$user->has2fa) {
return $this->respondWithToken($token);
}
if (!isset($data['2faCode'])) {
return response()->json(['error' => 'Unauthorized. 2faCode is not specified but it is required'], 401);
}
$checkResult = $this->googleAuthenticator->verifyCode(env('GOOGLE_AUTHENTICATOR_SECRET'), $data['2faCode'], 10);
if ($checkResult) {
return $this->respondWithToken($token);
} else {
return response()->json(['error' => 'Unauthorized. Wrong 2faCode.'], 401);
}}
$checkResult
is a single-use variable, right? I'd not declare it at all if you aren't going to use it more than once. (same with$user
) \$\endgroup\$env('GOOGLE_AUTHENTICATOR_SECRET')
in your code. You should useconfig('GOOGLE_AUTHENTICATOR_SECRET')
as it will be cached and is more optimized. \$\endgroup\$