Skip to content

Instantly share code, notes, and snippets.

@thuydao
Last active September 5, 2021 04:28
Show Gist options
  • Save thuydao/297ea8dfa9a43616b99aaf566566b0ef to your computer and use it in GitHub Desktop.
Save thuydao/297ea8dfa9a43616b99aaf566566b0ef to your computer and use it in GitHub Desktop.
Flutter firebase OTP Service
///
/// OTPService
/// cloud_firestore: ^0.12.9
/// firebase_storage: ^3.0.6
/// firebase_auth: ^0.14.0
///
import 'package:firebase_auth/firebase_auth.dart';
typedef void PhoneSubmitCallBack(String status);
class OTPService {
late FirebaseUser _firebaseUser;
late AuthCredential _phoneAuthCredential;
late String _verificationId;
static final OTPService _singleton = OTPService._internal();
factory OTPService() {
return OTPService._singleton;
}
OTPService._internal() {
// _getFirebaseUser();
}
Future<void> _getFirebaseUser() async {
this._firebaseUser = await FirebaseAuth.instance.currentUser();
String status =
(_firebaseUser == null) ? 'Not Logged In\n' : 'Already LoggedIn\n';
print(status);
}
void _handleError(e) {
print(e.message);
}
Future<String> submitPhoneNumber(phone, PhoneSubmitCallBack callBack) async {
String phoneNumber = phone;
print(phoneNumber);
String _status = "";
void verificationCompleted(AuthCredential phoneAuthCredential) {
print('verificationCompleted');
_status = 'verificationCompleted\n';
this._phoneAuthCredential = phoneAuthCredential;
print(phoneAuthCredential);
callBack(_status);
}
void verificationFailed(AuthException error) {
_status = 'verificationFailed';
_handleError(error);
callBack(_status);
}
void codeSent(String verificationId, [int? code]) {
_status = 'codeSent';
this._verificationId = verificationId;
print(verificationId);
print(code.toString());
print('Code Sent\n');
callBack(_status);
}
void codeAutoRetrievalTimeout(String verificationId) {
_status = 'codeAutoRetrievalTimeout';
print(verificationId);
callBack(_status);
}
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: Duration(milliseconds: 10000),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
);
return _status;
}
Future<String> submitOTP(otp) async {
String smsCode = otp;
this._phoneAuthCredential = PhoneAuthProvider.getCredential(
verificationId: this._verificationId, smsCode: smsCode);
return _login();
}
Future<String> _login() async {
try {
return FirebaseAuth.instance
.signInWithCredential(this._phoneAuthCredential)
.then((AuthResult authRes) {
_firebaseUser = authRes.user;
return _firebaseUser.toString();
}).catchError((e) {
return e.toString();
});
} catch (e) {
return e.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment