json($this->authenticator->state($request->user())); } public function challenge(Request $request): JsonResponse { $user = $request->user(); $code = $request->validate(['code' => ['required', 'string', 'max:40']])['code']; abort_unless($this->authenticator->enrolled($user), 404); if (! $this->authenticator->attempt($user, $code)) { $this->authenticator->log('two_factor.failed', 'A wrong code for the second step', $user); return $this->wrong(); } $this->authenticator->mark($user); return response()->json($this->authenticator->state($user)); } /** A new secret for the app. Not for an account that has one: that one turns it off first, with a code. */ public function setup(Request $request): JsonResponse { abort_if($this->authenticator->enrolled($request->user()), 409, __('The second step is on already.')); return response()->json($this->authenticator->start($request->user())); } public function confirm(Request $request): JsonResponse { $user = $request->user(); $code = $request->validate(['code' => ['required', 'string', 'max:40']])['code']; $codes = $this->authenticator->confirm($user, $code); if ($codes === null) { return $this->wrong(); } $this->authenticator->mark($user); return response()->json(['recovery_codes' => $codes] + $this->authenticator->state($user)); } /** Off again: for an account that does not have to have it, with the password and a code. */ public function disable(Request $request): JsonResponse { $user = $request->user(); if ($this->authenticator->required($user)) { return response()->json(['message' => $no = __('You have to have the second step, so it cannot be turned off.'), 'errors' => ['code' => [$no]]], 403); } if (($failed = $this->fresh($request)) !== null) { return $failed; } $this->authenticator->reset($user); return response()->json($this->authenticator->state($user)); } public function recoveryCodes(Request $request): JsonResponse { abort_unless($this->authenticator->enrolled($request->user()), 404); if (($failed = $this->fresh($request)) !== null) { return $failed; } return response()->json(['recovery_codes' => $this->authenticator->newRecoveryCodes($request->user())] + $this->authenticator->state($request->user())); } /** What a change of the second step needs: the password and a code from this moment, so a session someone left open is not enough. */ private function fresh(Request $request): ?JsonResponse { $data = $request->validate(['password' => ['required', 'string', 'max:200'], 'code' => ['required', 'string', 'max:40']]); if (! Hash::check($data['password'], $request->user()->getAuthPassword())) { return response()->json(['message' => $wrong = __('The current password is not right.'), 'errors' => ['password' => [$wrong]]], 422); } return $this->authenticator->attempt($request->user(), $data['code']) ? null : $this->wrong(); } private function wrong(): JsonResponse { return response()->json(['message' => $wrong = __('That code is not right.'), 'errors' => ['code' => [$wrong]]], 422); } }