feat: Implement Twitter (X) login using OAuth 2.0 PKCE flow via webview.
This commit is contained in:
@@ -10,7 +10,6 @@ import 'package:real_estate_mobile/features/auth/data/auth_repository.dart';
|
||||
import 'package:real_estate_mobile/features/auth/data/models/register_request.dart';
|
||||
import 'package:real_estate_mobile/features/auth/data/models/user_model.dart';
|
||||
import 'package:real_estate_mobile/features/messaging/data/socket_service.dart';
|
||||
import 'package:twitter_login/twitter_login.dart';
|
||||
|
||||
// Auth state
|
||||
enum AuthStatus { initial, loading, authenticated, error }
|
||||
@@ -291,7 +290,8 @@ class AuthNotifier extends StateNotifier<AuthState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signInWithTwitter() async {
|
||||
/// Complete Twitter/X login after webview returns user data.
|
||||
Future<void> completeTwitterLogin(Map<String, dynamic> twitterUser) async {
|
||||
state = state.copyWith(
|
||||
status: AuthStatus.loading,
|
||||
errorMessage: null,
|
||||
@@ -299,35 +299,12 @@ class AuthNotifier extends StateNotifier<AuthState> {
|
||||
);
|
||||
|
||||
try {
|
||||
final twitterLogin = TwitterLogin(
|
||||
apiKey: 'eWEzaDJ0al9lX1diOGY0ejRYeXM6MTpjaQ',
|
||||
apiSecretKey: 'HadGMSRKKswfXOajbmggrnmLAn9cxJsl8GtFxGHqjX-CJ0A2Tu',
|
||||
redirectURI: 'request://',
|
||||
);
|
||||
|
||||
final authResult = await twitterLogin.login();
|
||||
|
||||
if (authResult.status == TwitterLoginStatus.cancelledByUser) {
|
||||
state = state.copyWith(status: AuthStatus.initial);
|
||||
return;
|
||||
}
|
||||
|
||||
if (authResult.status != TwitterLoginStatus.loggedIn) {
|
||||
state = state.copyWith(
|
||||
status: AuthStatus.error,
|
||||
errorMessage: authResult.errorMessage ?? 'Twitter login failed',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final twitterUser = authResult.user!;
|
||||
|
||||
final user = await _repository.socialAuth(
|
||||
provider: 'twitter',
|
||||
providerId: twitterUser.id.toString(),
|
||||
email: '${twitterUser.screenName}@twitter.placeholder',
|
||||
name: twitterUser.name,
|
||||
avatar: twitterUser.thumbnailImage,
|
||||
providerId: twitterUser['id'] as String,
|
||||
email: '${twitterUser['username']}@x.com',
|
||||
name: twitterUser['name'] as String?,
|
||||
avatar: twitterUser['avatar'] as String?,
|
||||
);
|
||||
|
||||
state = state.copyWith(
|
||||
@@ -345,7 +322,7 @@ class AuthNotifier extends StateNotifier<AuthState> {
|
||||
debugPrint('Twitter sign-in error: $e');
|
||||
state = state.copyWith(
|
||||
status: AuthStatus.error,
|
||||
errorMessage: 'Twitter sign-in failed. Please try again.',
|
||||
errorMessage: 'X/Twitter sign-in failed. Please try again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
144
lib/features/auth/presentation/screens/twitter_login_screen.dart
Normal file
144
lib/features/auth/presentation/screens/twitter_login_screen.dart
Normal file
@@ -0,0 +1,144 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:real_estate_mobile/core/constants/app_colors.dart';
|
||||
import 'package:real_estate_mobile/core/services/twitter_auth_service.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
|
||||
/// Opens a webview for Twitter OAuth 2.0 PKCE login.
|
||||
/// Returns the user data map on success, or null on cancel/failure.
|
||||
class TwitterLoginScreen extends StatefulWidget {
|
||||
const TwitterLoginScreen({super.key});
|
||||
|
||||
@override
|
||||
State<TwitterLoginScreen> createState() => _TwitterLoginScreenState();
|
||||
}
|
||||
|
||||
class _TwitterLoginScreenState extends State<TwitterLoginScreen> {
|
||||
late final TwitterAuthService _authService;
|
||||
late final WebViewController _webViewController;
|
||||
bool _isExchanging = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_authService = TwitterAuthService();
|
||||
_webViewController = WebViewController()
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setUserAgent(
|
||||
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) '
|
||||
'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 '
|
||||
'Mobile/15E148 Safari/604.1',
|
||||
)
|
||||
..setNavigationDelegate(NavigationDelegate(
|
||||
onPageStarted: (url) {
|
||||
final code = _authService.extractCodeFromUrl(url);
|
||||
if (code != null) {
|
||||
_handleCode(code);
|
||||
}
|
||||
},
|
||||
onNavigationRequest: (request) {
|
||||
final code = _authService.extractCodeFromUrl(request.url);
|
||||
if (code != null) {
|
||||
_handleCode(code);
|
||||
return NavigationDecision.prevent;
|
||||
}
|
||||
// User cancelled — Twitter redirects to main page or login
|
||||
final url = request.url;
|
||||
if (url == 'https://twitter.com/' ||
|
||||
url == 'https://x.com/' ||
|
||||
url.startsWith('https://twitter.com/home') ||
|
||||
url.startsWith('https://x.com/home') ||
|
||||
url.startsWith('https://twitter.com/i/flow/login') ||
|
||||
url.startsWith('https://x.com/i/flow/login')) {
|
||||
Navigator.pop(context, null);
|
||||
return NavigationDecision.prevent;
|
||||
}
|
||||
return NavigationDecision.navigate;
|
||||
},
|
||||
))
|
||||
..loadRequest(Uri.parse(_authService.authorizationUrl));
|
||||
}
|
||||
|
||||
Future<void> _handleCode(String code) async {
|
||||
if (_isExchanging) return;
|
||||
setState(() => _isExchanging = true);
|
||||
|
||||
try {
|
||||
final userData = await _authService.exchangeCodeForUser(code);
|
||||
if (mounted) Navigator.pop(context, userData);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('X login failed. Please try again.')),
|
||||
);
|
||||
Navigator.pop(context, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.white,
|
||||
body: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
// Minimal top bar with back button
|
||||
SizedBox(
|
||||
height: 44,
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_back_ios_new_rounded,
|
||||
size: 18, color: AppColors.primaryDark),
|
||||
onPressed: () => Navigator.pop(context, null),
|
||||
),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Sign in with X',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontFamily: 'Fractul',
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.primaryDark,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 48),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Webview
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
WebViewWidget(controller: _webViewController),
|
||||
if (_isExchanging)
|
||||
Container(
|
||||
color: Colors.white.withValues(alpha: 0.8),
|
||||
child: const Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
color: AppColors.accentOrange),
|
||||
SizedBox(height: 16),
|
||||
Text('Signing in...',
|
||||
style: TextStyle(
|
||||
fontFamily: 'Fractul',
|
||||
fontSize: 14,
|
||||
color: AppColors.primaryDark,
|
||||
)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
import 'package:real_estate_mobile/core/constants/app_colors.dart';
|
||||
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';
|
||||
import 'package:real_estate_mobile/features/auth/presentation/screens/twitter_login_screen.dart';
|
||||
|
||||
class SocialLoginButtons extends ConsumerWidget {
|
||||
const SocialLoginButtons({super.key});
|
||||
@@ -17,6 +18,16 @@ class SocialLoginButtons extends ConsumerWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleTwitterLogin(BuildContext context, WidgetRef ref) async {
|
||||
final result = await Navigator.push<Map<String, dynamic>?>(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => const TwitterLoginScreen()),
|
||||
);
|
||||
if (result != null) {
|
||||
ref.read(authProvider.notifier).completeTwitterLogin(result);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final authState = ref.watch(authProvider);
|
||||
@@ -51,7 +62,7 @@ class SocialLoginButtons extends ConsumerWidget {
|
||||
_SocialButton(
|
||||
onTap: isLoading
|
||||
? null
|
||||
: () => ref.read(authProvider.notifier).signInWithTwitter(),
|
||||
: () => _handleTwitterLogin(context, ref),
|
||||
child: SvgPicture.asset(
|
||||
'assets/icons/x.svg',
|
||||
width: 24,
|
||||
|
||||
Reference in New Issue
Block a user