import 'package:api_sdk/models/user.dart';
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
String errorMessage;
//Create User Object from Firebase User
User _userFromFirebaseUser(FirebaseUser user, token) {
return user != null
? User(uid: user.uid, email: user.email, token: token)
: null;
}
//Signin With email and password
Future signInWithEmailAndPassword(String email, String password) async {
try {
AuthResult userCredential = await _auth.signInWithEmailAndPassword(
email: email, password: password);
final res = await userCredential.user.getIdToken();
return _userFromFirebaseUser(userCredential.user, res.token);
} catch (err) {
//getMessageFromErrorCode is a custom function which returns error message for a particular error code.
errorMessage = getMessageFromErrorCode(err.code);
return Future.error(errorMessage);
}
}
//Register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult userCredential = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
final res = await userCredential.user.getIdToken();
return _userFromFirebaseUser(userCredential.user, res.token);
} catch (err) {
//getMessageFromErrorCode is a custom function which returns error message for a particular error code.
errorMessage = getMessageFromErrorCode(err.code);
return Future.error(errorMessage);
}
}
//Get Current User
Future getCurrentUser() async {
try {
final FirebaseUser user = await _auth.currentUser();
final res = await user.getIdToken();
return _userFromFirebaseUser(user, res.token);
} catch (err) {
return null;
}
}
//Signout
Future<void> signOut() async {
return await _auth.signOut();
}
}