I'm building an API for a mobile app where login is achieved through OTP sen via SMS to mobile phone devices. The user can login after he enters his phone number and an OTP code sent to his device.
What am I trying to do? I'm trying to use otp code to authenticate users without passwords.
How to disable passwords in laravel ? What is the best approach? Or if there's a way to use otp field instead of password for authentication.
public function generateOtp(Request $request)
{
$identifier = $request->phone;
$otp = new Otp();
$code = $otp->generate($identifier, 6, 15);
User::create([
'phone'=>$request->phone,
'otp'=>$code
]);
//Todo::Send OTP number to sms
return response()->json(['otp' => $code]);
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'phone' => 'required',
'otp' => 'required|min:6',
]);
if ($validator->fails()) {
return response()->json(['success' => false, 'data' => $validator->errors()], 400);
}
$otp = new Otp();
$otp = $otp->validate($request->phone, $request->otp);
if ($otp->status == true) {
$credentials = [
'phone' => $request->phone,
];
if (auth()->attempt($credentials)) {
$user = new UserResource(User::find($user->id));
$this->revokeTokens($user->id);
$token = $user->createToken('AccessToken')->accessToken;
$user->token = $token;
unset($user->code, $user->id, $user->created_at, $user->updated_at);
return response()->json(['success' => true, 'code' => 1500, 'user' => $user, 'token' => $token]);
} else {
return ResponseHelper::notSuccessful(1502, 'login credentials are wrong');
}
}
if ($otp->status == false) {
return response()->json(['code'=>2, 'message'=>'OTP Expired. Generate New Code']);
}
}