Files
fcs/lib/fcs/common/data/providers/auth_fb.dart

240 lines
7.3 KiB
Dart
Raw Normal View History

2020-08-27 22:32:40 +06:30
import 'dart:async';
2020-09-04 01:42:58 +06:30
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/fcs/common/domain/constants.dart';
import 'package:fcs/fcs/common/domain/entities/auth_result.dart' as fcs;
2020-08-27 22:32:40 +06:30
import 'package:fcs/fcs/common/domain/entities/auth_status.dart';
2020-09-04 01:42:58 +06:30
import 'package:fcs/fcs/common/domain/entities/setting.dart';
import 'package:fcs/fcs/common/domain/entities/user.dart';
import 'package:fcs/fcs/common/domain/exceiptions/signin_exception.dart';
2020-08-27 22:32:40 +06:30
import 'package:firebase_auth/firebase_auth.dart';
2020-09-13 21:49:39 +06:30
import 'package:logging/logging.dart';
2020-08-27 22:32:40 +06:30
2020-09-04 15:30:10 +06:30
import '../../helpers/api_helper.dart';
2020-08-30 21:26:37 +06:30
2020-08-27 22:32:40 +06:30
class AuthFb {
2020-09-13 21:49:39 +06:30
final log = Logger('AuthFb');
2020-08-27 22:32:40 +06:30
static final AuthFb instance = AuthFb._();
AuthFb._();
2020-08-30 21:26:37 +06:30
static final FirebaseAuth _fb = FirebaseAuth.instance;
2020-08-27 22:32:40 +06:30
static String _verificationId;
2020-09-04 01:42:58 +06:30
Future<fcs.AuthResult> sendSmsCodeToPhoneNumber(String phoneNumber) {
Completer<fcs.AuthResult> completer = Completer();
2020-09-13 21:49:39 +06:30
bool codeSentCompleted = false;
2020-08-27 22:32:40 +06:30
final PhoneVerificationCompleted verificationCompleted =
2020-09-04 01:42:58 +06:30
(AuthCredential credential) async {
2020-09-13 21:49:39 +06:30
AuthResult _authResult;
try {
_authResult = await _fb.signInWithCredential(credential);
print("PhoneVerificationCompleted :$_authResult");
if (_authResult == null) {
throw SigninException("Sigin error!");
}
} catch (e) {
print("Exception:$e");
// throw e;
completer.completeError(SigninException(e.toString()));
return;
2020-09-04 01:42:58 +06:30
}
fcs.AuthResult auth =
fcs.AuthResult(authStatus: AuthStatus.AUTH_VERIFIED);
2020-08-30 21:26:37 +06:30
completer.complete(auth);
2020-08-27 22:32:40 +06:30
print(
2020-09-04 01:42:58 +06:30
'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: ${_authResult.user}');
2020-08-27 22:32:40 +06:30
};
final PhoneVerificationFailed verificationFailed =
(AuthException authException) async {
print(
'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
2020-09-13 21:49:39 +06:30
completer.completeError(SigninException(
"Phone number verification failed:${authException.message}"));
2020-08-27 22:32:40 +06:30
};
final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
_verificationId = verificationId;
2020-09-13 21:49:39 +06:30
print("codeSent " + phoneNumber);
codeSentCompleted = true;
2020-09-16 02:29:50 +06:30
completer.complete(fcs.AuthResult(authStatus: AuthStatus.SMS_SENT));
2020-08-27 22:32:40 +06:30
};
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) {
2020-09-13 21:49:39 +06:30
print("codeAutoRetrievalTimeout $verificationId ");
2020-08-27 22:32:40 +06:30
_verificationId = verificationId;
2020-09-13 21:49:39 +06:30
if (codeSentCompleted) {
completer.complete(fcs.AuthResult(authStatus: AuthStatus.SMS_SENT));
} else {
completer.completeError(SigninException("SMS code failed"));
}
2020-08-27 22:32:40 +06:30
};
_fb.verifyPhoneNumber(
phoneNumber: phoneNumber,
2020-09-13 21:49:39 +06:30
timeout: const Duration(seconds: 0),
2020-08-27 22:32:40 +06:30
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
return completer.future;
}
2020-09-04 01:42:58 +06:30
Future<fcs.AuthResult> signInWithPhoneNumber(String smsCode) async {
User user;
2020-08-27 22:32:40 +06:30
try {
final AuthCredential credential = PhoneAuthProvider.getCredential(
verificationId: _verificationId,
smsCode: smsCode,
);
2020-09-04 01:42:58 +06:30
AuthResult _authResult = await _fb.signInWithCredential(credential);
if (_authResult == null) {
throw SigninException("Sigin error!");
}
2020-08-27 22:32:40 +06:30
} on Exception catch (e) {
2020-09-04 01:42:58 +06:30
return Future.error(SigninException(e.toString()));
2020-08-27 22:32:40 +06:30
}
2020-09-04 01:42:58 +06:30
if (user == null) Future.error(SigninException("No current user!"));
return Future.value(fcs.AuthResult(authStatus: AuthStatus.AUTH_VERIFIED));
2020-08-27 22:32:40 +06:30
}
2020-08-30 21:26:37 +06:30
Future<void> signout() {
2020-08-27 22:32:40 +06:30
return _fb.signOut();
}
2020-08-30 21:26:37 +06:30
2020-09-04 01:42:58 +06:30
Stream<User> get onAuthStatus async* {
await for (FirebaseUser firebaseUser in _fb.onAuthStateChanged) {
if (firebaseUser == null) {
yield null;
}
yield await getUser();
}
2020-08-30 21:26:37 +06:30
}
2020-09-04 01:42:58 +06:30
Future<User> getUser({bool refreshIdToken = false}) async {
FirebaseUser firebaseUser = await _fb.currentUser();
if (firebaseUser == null) return null;
IdTokenResult idToken =
await firebaseUser.getIdToken(refresh: refreshIdToken);
2020-09-13 21:49:39 +06:30
log.info("Claims:${idToken.claims}");
2020-09-04 01:42:58 +06:30
User user = User();
2020-09-17 06:02:48 +06:30
user.status = idToken.claims["st"];
2020-09-04 01:42:58 +06:30
user.phoneNumber = firebaseUser.phoneNumber;
2020-09-11 16:14:36 +06:30
// add privileges
2020-09-17 06:02:48 +06:30
String privileges = idToken.claims["pr"];
2020-09-11 16:14:36 +06:30
if (privileges != null && privileges != "") {
user.privileges = privileges.split(":").toList();
}
2020-09-17 06:02:48 +06:30
String cid = idToken.claims["cid"];
if (cid != null && cid != "") {
User _user = await getUserFromFirestore(cid);
if (_user != null) {
user.id = cid;
user.fcsID = _user.fcsID;
user.name = _user.name;
}
2020-09-16 02:29:50 +06:30
}
2020-09-04 01:42:58 +06:30
return user;
2020-08-30 21:26:37 +06:30
}
2020-09-13 21:49:39 +06:30
Future<User> getUserFromFirestore(String userID) async {
DocumentSnapshot snap = await Firestore.instance
.collection(user_collection)
.document(userID)
.get();
if (snap.exists) {
User user = User.fromMap(snap.data, snap.documentID);
return user;
}
return null;
}
2020-09-04 01:42:58 +06:30
Future<bool> isLogin() async {
final FirebaseUser firebaseUser = await _fb.currentUser();
return Future.value(firebaseUser != null);
2020-08-30 21:26:37 +06:30
}
2020-09-04 01:42:58 +06:30
Future<User> signup(String userName) async {
2020-08-30 21:26:37 +06:30
await requestAPI("/signup", "POST",
payload: {
2020-09-04 01:42:58 +06:30
'user_name': userName,
2020-08-30 21:26:37 +06:30
},
token: await getToken());
// refresh token once signup
2020-09-04 01:42:58 +06:30
return getUser(refreshIdToken: true);
2020-08-30 21:26:37 +06:30
}
2020-09-17 06:02:48 +06:30
Future<User> joinInvite(String userName) async {
await requestAPI("/join_invite", "POST",
payload: {
'user_name': userName,
},
token: await getToken());
// refresh token once signup
return getUser(refreshIdToken: true);
}
2020-09-13 21:49:39 +06:30
Future<bool> hasInvite() async {
var invited =
await requestAPI("/check_invitation", "GET", token: await getToken());
return invited["invited"];
}
Future<void> updateProfile(String newUserName) async {
return await requestAPI("/profile", "PUT",
payload: {"user_name": newUserName}, token: await getToken());
}
2020-09-07 16:05:28 +06:30
Future<String> getToken() async {
2020-08-30 21:26:37 +06:30
FirebaseUser firebaseUser = await _fb.currentUser();
IdTokenResult token = await firebaseUser.getIdToken();
return token.token;
}
2020-09-04 01:42:58 +06:30
Future<Setting> getSetting() async {
var snap = await Firestore.instance
.collection(config_collection)
.document(setting_doc_id)
.get();
if (!snap.exists) {
return null;
}
// _listSetting();
return Setting.fromMap(snap.data);
}
2020-09-07 16:05:28 +06:30
Stream<Setting> settings() async* {
Stream<DocumentSnapshot> snapshot = Firestore.instance
.collection(config_collection)
.document(setting_doc_id)
.snapshots();
await for (var snap in snapshot) {
Setting setting = Setting.fromMap(snap.data);
yield setting;
}
}
2020-09-17 06:02:48 +06:30
Stream<User> user(String userID) async* {
Stream<DocumentSnapshot> snapshot = Firestore.instance
.collection(user_collection)
.document(userID)
.snapshots();
await for (var snap in snapshot) {
User user = User.fromMap(snap.data, snap.documentID);
user = await getUser(refreshIdToken: true);
yield user;
}
}
2020-08-27 22:32:40 +06:30
}