Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

public function generateOtp(Request $request)

{
$request->validate([
'email' => 'required|email',
'password' => 'required|string',
]);

$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials)) {
$email = $request->email;
$otp = (new Otp)->generate($email, 'alpha_numeric', 7, 15);

// Generate a temporary token for OTP verification (using Laravel Cache


for simplicity)
$tempToken = Str::random(60);
Cache::put($tempToken, $email, now()->addMinutes(15));

return response()->json([
'message' => 'OTP SENT TO YOUR EMAIL ADDRESS',
'otp' => $otp,
'temp_token' => $tempToken
]);
}

return response()->json(['message' => 'Invalid credentials'], 401);


}
public function verifyOtp(Request $request)
{
$request->validate([
'otp' => 'required|string',
'temp_token' => 'required|string',
]);

$tempToken = $request->temp_token;
$email = Cache::get($tempToken);

if (!$email) {
return response()->json(['message' => 'Invalid or expired temporary
token'], 401);
}

$otp = $request->otp;
$response = (new Otp)->validate($email, $otp);

if ($response->status) {
// Remove the temporary token after successful verification
Cache::forget($tempToken);

$user = User::where('email', $email)->first();


if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}

Auth::login($user);

$tokens = $user->tokens;
foreach ($tokens as $token) {
$token->revoke();
RefreshToken::where('access_token_id', $token->id)-
>update(['revoked' => true]);
}

$tokenResult = $user->createToken('Personal Access Token');


$token = $tokenResult->accessToken;

$cookie = cookie(
'access_token', $token, 60 * 24 * 7, '/', 'localhost', false,
true // HttpOnly
);

return response()->json([
'token' => $token,
])->cookie($cookie);
}

return response()->json(['message' => 'Invalid OTP code'], 401);


}

You might also like