Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
5.7 kB
1
Indexable
Never
import 'dart:async';
import 'dart:convert';
import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:one_on_us/src/interface/base_bloc.dart';
import 'package:one_on_us/src/network/modals/request/LoginRequest.dart';
import 'package:one_on_us/src/network/modals/response/LoginResponse.dart';
import 'package:one_on_us/src/network/utils/RestApiCalls.dart';
import 'package:one_on_us/src/utils/app_utils.dart';
import 'package:apple_sign_in/apple_sign_in.dart' as apple;

class LoginBloc with BaseBloc {
  BuildContext context;

  /// Controllers
  final _loginStreamController = StreamController<LoginResponse>.broadcast();

  LoginBloc(this.context);

  /// Stream
  Stream<LoginResponse> get loginStream => _loginStreamController.stream;

  /// Sink
  StreamSink<LoginResponse> get loginSink => _loginStreamController.sink;

  /// Subscription

  StreamSubscription<LoginResponse> get loginSubscription =>
      loginStream.listen((event) {});



  /// calling login method and adding data to the stream
  /// on success response

  login(LoginRequest request) {
    RestApiCalls apiCalls = RestApiCalls();
    CommonUtils.fullScreenProgress(context);
    apiCalls.login(context, jsonEncode(request)).then((value) {
      CommonUtils.dismissProgressDialog(context);
      loginSink.add(value);
    }).catchError((error) {
      print(error.toString());
      CommonUtils.dismissProgressDialog(context);
      loginSink.addError(error.toString());
    });
  }

  /// google login integration

  Future<User> googleLogin() async {
    GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'https://www.googleapis.com/auth/userinfo.email'
      ],
    );
    GoogleSignInAccount signInAccount = await googleSignIn.signIn();
    if (signInAccount != null) {
      GoogleSignInAuthentication auth = await signInAccount.authentication;
      AuthCredential credentials = GoogleAuthProvider.credential(
          idToken: auth.idToken, accessToken: auth.accessToken);

      UserCredential authResult =
          await FirebaseAuth.instance.signInWithCredential(credentials);

      if (authResult.user != null) {
        return authResult.user;
      } else {
        // Auth Failed
        return null;
      }
    }
    return null;
  }

  /// FaceBook login integration

  Future<User> facebookSignIn() async {
    FacebookLogin facebookLogin = FacebookLogin();
    final result =
        await facebookLogin.logIn(permissions: [FacebookPermission.email]);

    switch (result.status) {
      case FacebookLoginStatus.success:
        print("@Success");

        AuthCredential credentials =
            FacebookAuthProvider.credential(result.accessToken.token);

        UserCredential authResult =
            await FirebaseAuth.instance.signInWithCredential(credentials);
        if (authResult.user != null) {
          print("Tarun");
          return authResult.user;
        } else {
          /// Auth Failed
          print("auth failed");
          return null;
        }
        break;
      case FacebookLoginStatus.error:
        CommonUtils.errorMessage(msg: result.error.developerMessage);
        return null;
        break;
      case FacebookLoginStatus.cancel:
        CommonUtils.errorMessage(msg: result.error.developerMessage);
        return null;
        break;
    }
    return null;
  }

  /// Apple  login integration

  Future<User> appleLogin() async {
    // TODO Apple Login
    if (await AppleSignIn.isAvailable()) {

      List<apple.Scope> scopes = [
        apple.Scope.email,
        apple.Scope.fullName,
      ];
      final _firebaseAuth = FirebaseAuth.instance;
      final result = await apple.AppleSignIn.performRequests(
          [apple.AppleIdRequest(requestedScopes: scopes)]);

      switch (result.status) {
        case apple.AuthorizationStatus.authorized:
          final appleIdCredential = result.credential;
          final oAuthProvider = OAuthProvider('apple.com');
          final credential = oAuthProvider.credential(
            idToken: String.fromCharCodes(appleIdCredential.identityToken),
            accessToken:
                String.fromCharCodes(appleIdCredential.authorizationCode),
          );
          final authResult =
              await _firebaseAuth.signInWithCredential(credential);
          final firebaseUser = authResult.user;
          if (scopes.contains(apple.Scope.fullName)) {
            await FirebaseAuth.instance.currentUser.updateProfile(
              displayName:
                  '${appleIdCredential.fullName.givenName} ${appleIdCredential.fullName.familyName}',
            );

          }
          return firebaseUser;
        case apple.AuthorizationStatus.error:
          print(result.error.toString());
          throw PlatformException(
            code: 'ERROR_AUTHORIZATION_DENIED',
            message: result.error.toString(),
          );

        case apple.AuthorizationStatus.cancelled:
          throw PlatformException(
            code: 'ERROR_ABORTED_BY_USER',
            message: 'Sign in aborted by user',
          );
      }
    } else {
      print('Apple SignIn is not available for your device');
      return null;
    }

    return null;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _loginStreamController?.close();
  }
}