Skip to content

Instantly share code, notes, and snippets.

@mohammad-fouladgar
Last active February 18, 2022 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohammad-fouladgar/a02af640d155acacea1f66b7d9ac62e1 to your computer and use it in GitHub Desktop.
Save mohammad-fouladgar/a02af640d155acacea1f66b7d9ac62e1 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Fouladgar\OTP\Exceptions\InvalidOTPTokenException;
use Fouladgar\OTP\OTPBroker as OTPService;
use Illuminate\Http\Request;
use Throwable;
class AuthController
{
public function __construct(private OTPService $OTPService)
{
}
public function sendOTP(Request $request)
{
// validate incoming requets.
try {
/** @var User $user */
$user = $this->OTPService->send($request->get('mobile'));
} catch (Throwable $ex) {
// or return a view.
return response()->json(['message'=>'An Occurred unexpected error.'], 500);
}
return response()->json(['message'=>'A token sent to:'. $user->mobile]);
}
public function verifyOTPAndLogin(Request $request)
{
// Validate incoming requests.
try {
/** @var User $user */
$user = $this->OTPService->validate($request->get('mobile'), $request->get('token'));
// and do login actions (session base or token base) ...
} catch (InvalidOTPTokenException $exception){
return response()->json(['error' => $exception->getMessage()], $exception->getCode());
} catch (Throwable $ex) {
return response()->json(['message' => 'An Occurred unexpected error.'], 500);
}
return response()->json(['message'=>'Login has been successfully.']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment