auth_api_rest_mobile

Flutter authentication package providing OAuth2-based authentication with session management, OTP validation, password recovery, and user registration.

pub package License

Features

  • OAuth2-based authentication
  • Session management (list active sessions, close sessions)
  • OTP generation and validation
  • Password recovery (3-step flow)
  • User registration
  • Socket integration for real-time updates
  • BLoC pattern for state management
  • Configurable debug logging

Platforms

  • Android
  • iOS

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  auth_api_rest_mobile: ^1.0.0

Usage

Initialization

import 'package:auth_api_rest_mobile/auth_api_rest.dart';
import 'package:flutter_models_provider/global/environment.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final authApiRest = AuthApiRest(
    clientId: "YOUR_CLIENT_ID",
    clientSecret: "YOUR_CLIENT_SECRET",
    redirectUri: RedirectUri.loginPost,
    gestorData: GestorData.objectBox,
    coleccionFuncionesBackend: 'your_collection',
    // Optional debug flags
    apiRestEnableDebugLogs: false,
    cloudDbEnableDebugLogs: false,
    authApiRestEnableDebugLogs: false,
  );

  await authApiRest.init(
    endpointApi: 'https://your-api-endpoint.com',
    endpointAuth: 'https://your-auth-endpoint.com',
    endpointSocket: 'https://your-socket-endpoint.com',
  );

  runApp(MyApp(authApiRest: authApiRest));
}

Setup BlocProviders

class MyApp extends StatelessWidget {
  final AuthApiRest authApiRest;

  const MyApp({super.key, required this.authApiRest});

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        ...authApiRest.lstBlocsAuth,
      ],
      child: MaterialApp(
        home: MyHomePage(),
      ),
    );
  }
}

Login

import 'package:auth_api_rest_mobile/bloc/auth/auth_bloc.dart';

// Dispatch login event
context.read<AuthBloc>().add(OnLoginAuthV4(
  usuario: 'user@example.com',
  password: 'password123',
));

// Listen to state changes
BlocListener<AuthBloc, AuthState>(
  listener: (context, state) {
    if (state.isLoggedIn) {
      // User logged in successfully
    }
    if (state.error.isNotEmpty) {
      // Handle error
    }
  },
)

Logout

context.read<AuthBloc>().add(const OnLogoutAuth());

Password Recovery

// Step 1: Request reset code
context.read<AuthBloc>().add(OnOlvideMiPasswordPaso1Auth(
  mail: 'user@example.com',
));

// Step 2: Validate code
context.read<AuthBloc>().add(OnOlvideMiPasswordPaso2Auth(
  codigo: '123456',
));

// Step 3: Set new password
context.read<AuthBloc>().add(OnOlvideMiPasswordPaso3Auth(
  password1: 'newPassword123',
  password2: 'newPassword123',
));

OTP

// Generate OTP QR code
context.read<AuthBloc>().add(OnGeneraOTPAuth(
  coleccion: 'collection_name',
  idColeccion: 'collection_id',
));

// Validate OTP
context.read<AuthBloc>().add(OnValidaOTPAuth(
  coleccion: 'collection_name',
  idColeccion: 'collection_id',
  codigoOTP: '123456',
));

Session Management

// Get active sessions
context.read<AuthBloc>().add(OnObtieneSesionesActivasAuth(
  idColeccionAuth: state.idColeccionAuth,
));

// Close a specific session
context.read<AuthBloc>().add(OnCerrarSesionActivaAuth(
  idSesion: 'session_id',
));

AuthState Properties

Property Type Description
isLoggedIn bool Whether user is authenticated
isWorking bool Whether an action is in progress
error String Error message if any
usuarioAuth Map<String, dynamic> Authenticated user data
idColeccionAuth String User collection ID
sesionesActivas List<SesionActivaModel> List of active sessions
qrOTP String Base64 encoded QR code for OTP

Dependencies

This package requires the following RobleSistemas packages:

  • api_rest_flutter
  • flutter_data_mobile_provider
  • flutter_data_cloud_provider
  • flutter_data_shp_provider
  • flutter_http_provider
  • flutter_models_provider
  • flutter_utils_providers
  • flutter_socket_provider
  • flutter_objectbox_provider

License

Copyright 2024 RobleSistemas

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.