Skip to main content

Authentication & Authorization

Sistem autentikasi dengan JWT, Google Sign-In, dan Apple Sign-In

๐ŸŽฏ Overview

Authentication adalah salah satu fitur utama dalam MStore Mobile yang menyediakan fungsionalitas untuk sistem autentikasi dengan jwt, google sign-in, dan apple sign-in.

๐Ÿ“‹ Features

  • โœ… Email/Password login
  • โœ… Google Sign-In
  • โœ… Apple Sign-In
  • โœ… JWT token management
  • โœ… Auto token refresh
  • โœ… Biometric authentication
  • โœ… Role-based access control (RBAC)

๐Ÿ—๏ธ Architecture

BLoC Implementation

BLoC: AuthBloc
// Events
abstract class AuthenticationEvent extends Equatable {}

class LoadAuthentication extends AuthenticationEvent {}
class CreateAuthentication extends AuthenticationEvent {}
class UpdateAuthentication extends AuthenticationEvent {}
class DeleteAuthentication extends AuthenticationEvent {}

// States
abstract class AuthenticationState extends Equatable {}

class AuthenticationInitial extends AuthenticationState {}
class AuthenticationLoading extends AuthenticationState {}
class AuthenticationLoaded extends AuthenticationState {}
class AuthenticationError extends AuthenticationState {}

// BLoC
class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> {
  final AuthenticationRepository _repository;
  
  AuthenticationBloc({required AuthenticationRepository repository})
      : _repository = repository,
        super(AuthenticationInitial()) {
    on<LoadAuthentication>(_onLoad);
    on<CreateAuthentication>(_onCreate);
    on<UpdateAuthentication>(_onUpdate);
    on<DeleteAuthentication>(_onDelete);
  }
  
  Future<void> _onLoad(
    LoadAuthentication event,
    Emitter<AuthenticationState> emit,
  ) async {
    emit(AuthenticationLoading());
    
    final result = await _repository.getAuthentications();
    
    result.fold(
      (failure) => emit(AuthenticationError(failure.message)),
      (data) => emit(AuthenticationLoaded(data)),
    );
  }
}

Repository Pattern

abstract class AuthenticationRepository {
  Future<Either<Failure, List<Authentication>>> getAuthentications();
  Future<Either<Failure, Authentication>> getAuthenticationById(String id);
  Future<Either<Failure, Authentication>> createAuthentication(Authentication data);
  Future<Either<Failure, Authentication>> updateAuthentication(String id, Authentication data);
  Future<Either<Failure, void>> deleteAuthentication(String id);
}

class AuthenticationRepositoryImpl implements AuthenticationRepository {
  final AuthenticationApi _api;
  final AuthenticationLocalRepository _localRepo;
  
  @override
  Future<Either<Failure, List<Authentication>>> getAuthentications() async {
    try {
      // Try local first (offline-first)
      final local = await _localRepo.getAuthentications();
      
      // Sync with API in background
      final result = await _api.getAuthentications();
      result.fold(
        (failure) => null,
        (data) => _localRepo.saveAuthentications(data),
      );
      
      return Right(local.isNotEmpty ? local : result.getOrElse(() => []));
    } catch (e) {
      return Left(UnexpectedFailure(e.toString()));
    }
  }
}

๐Ÿ“ก API Integration

Endpoints

  • /api/v1/auth/login
  • /api/v1/auth/refresh-token
  • /api/v1/auth/register-device

Request/Response Examples

Get List

GET /api/v1/auth/login
Authorization: Bearer {access_token}
Response:
{
  "success": true,
  "data": [
    {
      "id": "123",
      "name": "Example",
      "created_at": "2024-10-14T10:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}

๐Ÿ’พ Local Database (Isar)

Schema

  • ConfigLocal (tokens)
@collection
class AuthenticationLocal {
  Id id = Isar.autoIncrement;
  
  @Index()
  String? authenticationId;
  
  String? name;
  DateTime? createdAt;
  DateTime? updatedAt;
  DateTime? syncedAt;
  
  bool? isSynced;
  bool? isDeleted;
}

Queries

// Get all
final items = await isar.authenticationLocals.where().findAll();

// Get by ID
final item = await isar.authenticationLocals
    .filter()
    .authenticationIdEqualTo(id)
    .findFirst();

// Search
final results = await isar.authenticationLocals
    .filter()
    .nameContains(query, caseSensitive: false)
    .findAll();

// Get unsynced
final unsynced = await isar.authenticationLocals
    .filter()
    .isSyncedEqualTo(false)
    .findAll();

๐Ÿ”„ Offline-First Strategy

Write Operations

  1. Save to local Isar immediately
  2. Show success to user
  3. Add to sync queue
  4. Background sync when online
  5. Update with server response

Read Operations

  1. Read from local Isar (fast)
  2. Show to user immediately
  3. Background fetch from API
  4. Update local cache if changed
  5. Notify UI if data updated

Conflict Resolution

  • Strategy: Last-write-wins
  • Timestamp: Server timestamp as source of truth
  • Logging: All conflicts logged for audit

๐ŸŽจ UI Components

Main Screen

class AuthenticationPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<AuthenticationBloc>()..add(LoadAuthentication()),
      child: Scaffold(
        appBar: AppBar(title: Text('Authentication & Authorization')),
        body: BlocBuilder<AuthenticationBloc, AuthenticationState>(
          builder: (context, state) {
            if (state is AuthenticationLoading) {
              return Center(child: CircularProgressIndicator());
            }
            
            if (state is AuthenticationError) {
              return ErrorWidget(message: state.message);
            }
            
            if (state is AuthenticationLoaded) {
              return AuthenticationListView(items: state.items);
            }
            
            return SizedBox.shrink();
          },
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => _navigateToCreate(context),
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

๐Ÿงช Testing

Unit Tests

void main() {
  group('AuthenticationBloc', () {
    late AuthenticationBloc bloc;
    late MockAuthenticationRepository mockRepository;

    setUp(() {
      mockRepository = MockAuthenticationRepository();
      bloc = AuthenticationBloc(repository: mockRepository);
    });

    tearDown(() {
      bloc.close();
    });

    test('initial state is AuthenticationInitial', () {
      expect(bloc.state, equals(AuthenticationInitial()));
    });

    blocTest<AuthenticationBloc, AuthenticationState>(
      'emits [Loading, Loaded] when Load succeeds',
      build: () {
        when(() => mockRepository.getAuthentications()).thenAnswer(
          (_) async => Right([Authentication(id: '1', name: 'Test')]),
        );
        return bloc;
      },
      act: (bloc) => bloc.add(LoadAuthentication()),
      expect: () => [
        AuthenticationLoading(),
        isA<AuthenticationLoaded>(),
      ],
    );
  });
}

๐Ÿ“Š Performance Considerations

  • Lazy Loading: Load data on demand
  • Pagination: Implement pagination for large datasets
  • Caching: Cache frequently accessed data
  • Indexing: Use Isar indexes for fast queries
  • Background Sync: Sync in background to avoid blocking UI

๐Ÿ” Security

  • Authorization: Check user permissions before operations
  • Data Encryption: Sensitive data encrypted in Isar
  • Input Validation: Validate all user inputs
  • Audit Trail: Log all operations for audit

๐Ÿ“ฑ Platform-Specific

iOS

  • Use Cupertino widgets
  • Follow iOS HIG
  • Handle safe area insets

Android

  • Use Material widgets
  • Follow Material Design
  • Handle back button

Last Updated: October 14, 2024
Status: โœ… Production Ready