mirrored_repositories/simple_app/lib
import 'dart:async';

import 'package:flutter_firebase/authentication/authentication.dart';
import 'package:meta/meta.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_firebase/repository/user_repository.dart';
import 'package:flutter_firebase/authentication/authentication_events.dart';

class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> {
  final UserRepository userRepository;

  AuthenticationBloc({@required this.userRepository}) : assert(userRepository != null);

  @override
  AuthenticationState get initialState => AuthenticationUninitialized();

  @override
  Stream<AuthenticationState> mapEventToState(
    AuthenticationEvent event
  ) async* {
      if (event is AppStarted) {
        final bool hasToken = await userRepository.hasToken();

        if (hasToken) {
          yield AuthenticationAuthenticated();
        } else {
          yield AuthenticationUnauthenticated();
        }
      }

      if (event is LoggedIn) {
        yield AuthenticationLoading();
        await userRepository.persistToken(event.token);
        yield AuthenticationAuthenticated();
      }

      if (event is BypassLogin) {
        yield AuthenticationLoading();
        yield AuthenticationAuthenticated();
      }

      if (event is LoggedOut) {
        yield AuthenticationLoading();
        await userRepository.deleteToken();
        yield AuthenticationUnauthenticated();
      }
    }
}