240 lines
7.2 KiB
Dart
240 lines
7.2 KiB
Dart
import 'dart:async';
|
|
|
|
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;
|
|
import 'package:fcs/fcs/common/domain/entities/auth_status.dart';
|
|
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';
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
import 'package:logging/logging.dart';
|
|
|
|
import '../../helpers/api_helper.dart';
|
|
|
|
class AuthFb {
|
|
final log = Logger('AuthFb');
|
|
|
|
static final AuthFb instance = AuthFb._();
|
|
AuthFb._();
|
|
|
|
static final FirebaseAuth _fb = FirebaseAuth.instance;
|
|
static String _verificationId;
|
|
|
|
Future<fcs.AuthResult> sendSmsCodeToPhoneNumber(String phoneNumber) {
|
|
Completer<fcs.AuthResult> completer = Completer();
|
|
bool codeSentCompleted = false;
|
|
|
|
final PhoneVerificationCompleted verificationCompleted =
|
|
(AuthCredential credential) async {
|
|
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;
|
|
}
|
|
fcs.AuthResult auth =
|
|
fcs.AuthResult(authStatus: AuthStatus.AUTH_VERIFIED);
|
|
completer.complete(auth);
|
|
print(
|
|
'Inside _sendCodeToPhoneNumber: signInWithPhoneNumber auto succeeded: ${_authResult.user}');
|
|
};
|
|
|
|
final PhoneVerificationFailed verificationFailed =
|
|
(AuthException authException) async {
|
|
print(
|
|
'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
|
|
completer.completeError(SigninException(
|
|
"Phone number verification failed:${authException.message}"));
|
|
};
|
|
|
|
final PhoneCodeSent codeSent =
|
|
(String verificationId, [int forceResendingToken]) async {
|
|
_verificationId = verificationId;
|
|
print("codeSent " + phoneNumber);
|
|
codeSentCompleted = true;
|
|
completer.complete(fcs.AuthResult(authStatus: AuthStatus.SMS_SENT));
|
|
};
|
|
|
|
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
|
|
(String verificationId) {
|
|
print("codeAutoRetrievalTimeout $verificationId ");
|
|
|
|
_verificationId = verificationId;
|
|
if (codeSentCompleted) {
|
|
completer.complete(fcs.AuthResult(authStatus: AuthStatus.SMS_SENT));
|
|
} else {
|
|
completer.completeError(SigninException("SMS code failed"));
|
|
}
|
|
};
|
|
|
|
_fb.verifyPhoneNumber(
|
|
phoneNumber: phoneNumber,
|
|
timeout: const Duration(seconds: 0),
|
|
verificationCompleted: verificationCompleted,
|
|
verificationFailed: verificationFailed,
|
|
codeSent: codeSent,
|
|
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
|
|
|
|
return completer.future;
|
|
}
|
|
|
|
Future<fcs.AuthResult> signInWithPhoneNumber(String smsCode) async {
|
|
User user;
|
|
try {
|
|
final AuthCredential credential = PhoneAuthProvider.getCredential(
|
|
verificationId: _verificationId,
|
|
smsCode: smsCode,
|
|
);
|
|
AuthResult _authResult = await _fb.signInWithCredential(credential);
|
|
if (_authResult == null) {
|
|
throw SigninException("Sigin error!");
|
|
}
|
|
} on Exception catch (e) {
|
|
return Future.error(SigninException(e.toString()));
|
|
}
|
|
if (user == null) Future.error(SigninException("No current user!"));
|
|
return Future.value(fcs.AuthResult(authStatus: AuthStatus.AUTH_VERIFIED));
|
|
}
|
|
|
|
Future<void> signout() {
|
|
return _fb.signOut();
|
|
}
|
|
|
|
Stream<User> get onAuthStatus async* {
|
|
await for (FirebaseUser firebaseUser in _fb.onAuthStateChanged) {
|
|
if (firebaseUser == null) {
|
|
yield null;
|
|
}
|
|
yield await getUser();
|
|
}
|
|
}
|
|
|
|
Future<User> getUser({bool refreshIdToken = false}) async {
|
|
FirebaseUser firebaseUser = await _fb.currentUser();
|
|
if (firebaseUser == null) return null;
|
|
IdTokenResult idToken =
|
|
await firebaseUser.getIdToken(refresh: refreshIdToken);
|
|
|
|
log.info("Claims:${idToken.claims}");
|
|
|
|
String cid = idToken.claims["cid"];
|
|
User user;
|
|
if (cid != null && cid != "") {
|
|
user = await getUserFromFirestore(cid);
|
|
}
|
|
if (user == null) {
|
|
user = User();
|
|
user.id = cid;
|
|
user.phoneNumber = firebaseUser.phoneNumber;
|
|
user.status = idToken.claims["st"];
|
|
}
|
|
|
|
// add privileges
|
|
String privileges = idToken.claims["pr"];
|
|
if (privileges != null && privileges != "") {
|
|
user.privileges = privileges.split(":").toList();
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
Future<bool> isLogin() async {
|
|
final FirebaseUser firebaseUser = await _fb.currentUser();
|
|
return Future.value(firebaseUser != null);
|
|
}
|
|
|
|
Future<User> signup(String userName) async {
|
|
await requestAPI("/signup", "POST",
|
|
payload: {
|
|
'user_name': userName,
|
|
},
|
|
token: await getToken());
|
|
// refresh token once signup
|
|
return getUser(refreshIdToken: true);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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());
|
|
}
|
|
|
|
Future<String> getToken() async {
|
|
FirebaseUser firebaseUser = await _fb.currentUser();
|
|
IdTokenResult token = await firebaseUser.getIdToken();
|
|
return token.token;
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|