orgbytes_auth_flutter 0.0.1
orgbytes_auth_flutter: ^0.0.1 copied to clipboard
A stateless Flutter authentication package for OrgBytes. Handles authentication only - you control token storage.
OrgBytesAuth Flutter #
A stateless Flutter authentication package for OrgBytes, designed similar to Google Sign-In. This package handles authentication only - it does NOT store tokens or user data. You have full control over token management and storage.
Features #
- 🔐 Stateless Authentication - No hidden token storage or session management
- 🎯 Simple API - Login, register, and logout with minimal code
- 📱 Native Experience - Card-style modal on iOS, Chrome Custom Tabs on Android
- 🔄 Product-Aware - Optional
productIdparameter for multi-product scenarios - 💾 Full Control - You decide how and where to store tokens
- 🎨 Context Integration - Access user state anywhere in your widget tree
Installation #
Add this to your package's pubspec.yaml file:
dependencies:
orgbytes_auth_flutter: ^1.0.0
Important: Environment Variables #
⚠️ NEVER commit API keys to version control!
Store your credentials in environment variables or use a package like flutter_dotenv:
# pubspec.yaml
dependencies:
flutter_dotenv: ^5.0.0
# .env (add to .gitignore!)
ORGBYTES_API_KEY=your_api_key_here
ORGBYTES_REDIRECT_URI=your-app://auth/callback
ORGBYTES_PRODUCT_ID=your_product_id
Quick Start #
1. Configure (in main.dart) #
import 'package:flutter/material.dart';
import 'package:orgbytes_auth_flutter/orgbytes_auth_flutter.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Load environment variables
await dotenv.load(fileName: ".env");
// Configure OrgBytesAuth
await OrgBytesAuth.configure(
apiKey: dotenv.env['ORGBYTES_API_KEY']!,
baseUrl: 'https://account.orgbyte.org',
redirectUri: dotenv.env['ORGBYTES_REDIRECT_URI']!,
productId: dotenv.env['ORGBYTES_PRODUCT_ID'], // Optional
);
runApp(const MyApp());
}
2. Wrap Your App with OrgBytesAuthScope #
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: OrgBytesAuthScope(
child: HomeScreen(),
),
);
}
}
3. Login and Capture Tokens #
// Login
final result = await OrgBytesAuth.instance.login();
// YOU MUST store the token yourself!
await secureStorage.write(
key: 'auth_token',
value: result.accessToken,
);
// Access user data
print(result.user.email);
print(result.user.name);
4. Access User State in Widgets #
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Widget rebuilds when user changes
final user = OrgBytesAuth.userOf(context);
if (user != null) {
return Text('Welcome, ${user.name}!');
} else {
return Text('Not logged in');
}
}
}
Key Concepts #
🔴 In-Memory Only #
User state is stored in memory ONLY and cleared on app restart.
This package does NOT:
- ❌ Store tokens in secure storage
- ❌ Persist user sessions
- ❌ Automatically restore authentication state
- ❌ Make authenticated API calls for you
✅ What You Need to Do #
- Capture
AuthResultfrom login/register - Store tokens yourself (e.g.,
flutter_secure_storage,shared_preferences) - Handle session restoration on app startup
- Make authenticated API calls with your stored token
Complete Example #
import 'package:flutter/material.dart';
import 'package:orgbytes_auth_flutter/orgbytes_auth_flutter.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class AuthExample extends StatelessWidget {
final storage = const FlutterSecureStorage();
Future<void> handleLogin(BuildContext context) async {
try {
// Login and get result
final result = await OrgBytesAuth.instance.login();
// Store token yourself
await storage.write(
key: 'auth_token',
value: result.accessToken,
);
// Store user data if needed
await storage.write(
key: 'user_email',
value: result.user.email,
);
print('Logged in: ${result.user.email}');
} catch (e) {
print('Login failed: $e');
}
}
Future<void> handleLogout(BuildContext context) async {
// Clear in-memory state
await OrgBytesAuth.instance.logout();
// Clear your stored tokens
await storage.delete(key: 'auth_token');
await storage.delete(key: 'user_email');
}
Future<void> makeAuthenticatedRequest() async {
// Get token from your storage
final token = await storage.read(key: 'auth_token');
if (token == null) {
throw Exception('Not authenticated');
}
// Make API call with token
final response = await http.get(
Uri.parse('https://api.example.com/data'),
headers: {'Authorization': 'Bearer $token'},
);
print('Response: ${response.body}');
}
@override
Widget build(BuildContext context) {
final user = OrgBytesAuth.userOf(context);
return Scaffold(
body: Center(
child: user != null
? Column(
children: [
Text('Welcome, ${user.name}!'),
ElevatedButton(
onPressed: () => handleLogout(context),
child: Text('Logout'),
),
],
)
: ElevatedButton(
onPressed: () => handleLogin(context),
child: Text('Login'),
),
),
);
}
}
API Reference #
Configuration #
await OrgBytesAuth.configure({
required String apiKey, // Your OrgBytes API key
required String baseUrl, // Auth server URL
required String redirectUri, // Your app's redirect URI
String? productId, // Optional: Product identifier
});
Authentication Methods #
// Login
final AuthResult result = await OrgBytesAuth.instance.login();
// Register
final AuthResult result = await OrgBytesAuth.instance.register();
// Logout (clears in-memory state only)
await OrgBytesAuth.instance.logout();
Context Access #
// Get current user (widget rebuilds on change)
final User? user = OrgBytesAuth.userOf(context);
// Get full auth state
final AuthState state = OrgBytesAuth.of(context);
AuthResult #
class AuthResult {
final String accessToken; // JWT access token
final User user; // User profile data
}
User Model #
class User {
final String id;
final String email;
final String? firstName;
final String? lastName;
final String? picture;
final bool emailVerified;
final bool phoneVerified;
final String accountType;
final String organizationId;
String? get name; // Computed: "firstName lastName"
}
Session Restoration Example #
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await OrgBytesAuth.configure(/* ... */);
// Restore session on app startup
final storage = FlutterSecureStorage();
final token = await storage.read(key: 'auth_token');
if (token != null) {
// Validate token and restore user state
try {
final response = await http.get(
Uri.parse('https://account.orgbyte.org/api/v1/auth/me'),
headers: {'Authorization': 'Bearer $token'},
);
if (response.statusCode == 200) {
// Token is valid, you can update UI accordingly
print('Session restored');
} else {
// Token expired, clear it
await storage.delete(key: 'auth_token');
}
} catch (e) {
await storage.delete(key: 'auth_token');
}
}
runApp(const MyApp());
}
Platform Setup #
iOS #
Add to ios/Runner/Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>your-app</string>
</array>
</dict>
</array>
Android #
Add to android/app/src/main/AndroidManifest.xml:
<activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity">
<intent-filter android:label="flutter_web_auth_2">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="your-app" />
</intent-filter>
</activity>
Security Best Practices #
- Use Environment Variables - Never hardcode API keys
- Secure Storage - Use
flutter_secure_storagefor tokens - Token Validation - Validate tokens before using them
- HTTPS Only - Always use HTTPS for API calls
- Token Expiry - Handle token expiration gracefully
Migration from Stateful Packages #
If you're migrating from a package that stores tokens automatically:
- Capture AuthResult - Update login/register to capture the result
- Implement Storage - Add token storage logic
- Session Restoration - Implement session restoration in
main() - Update API Calls - Replace helper methods with manual HTTP calls
Troubleshooting #
"Not authenticated" error #
- Ensure you captured and stored the token from
AuthResult - Check that your token hasn't expired
- Verify you're reading from the correct storage key
User state not persisting #
- This is expected! User state is in-memory only
- Implement session restoration in
main()as shown above
Authentication cancelled #
- User closed the auth modal
- Handle this gracefully in your try-catch block
License #
MIT License - see LICENSE file for details
Support #
For issues and questions:
- GitHub Issues: your-repo/issues
- Documentation: your-docs-url