feat: Implement Twitter (X) login using OAuth 2.0 PKCE flow via webview.
This commit is contained in:
107
lib/core/services/twitter_auth_service.dart
Normal file
107
lib/core/services/twitter_auth_service.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
/// Twitter OAuth 2.0 PKCE flow for mobile.
|
||||
class TwitterAuthService {
|
||||
static const _clientId = 'eWEzaDJ0al9lX1diOGY0ejRYeXM6MTpjaQ';
|
||||
// Must match the callback URL configured in Twitter Developer Portal
|
||||
static const _redirectUri = 'https://dev.re-quest.com/auth/callback/twitter';
|
||||
static const _scope = 'tweet.read users.read offline.access';
|
||||
|
||||
late final String _codeVerifier;
|
||||
late final String _codeChallenge;
|
||||
late final String _stateParam;
|
||||
|
||||
TwitterAuthService() {
|
||||
_codeVerifier = _generateCodeVerifier();
|
||||
_codeChallenge = _generateCodeChallenge(_codeVerifier);
|
||||
_stateParam = _generateRandomString(32);
|
||||
}
|
||||
|
||||
/// Build the Twitter authorization URL to open in a webview.
|
||||
String get authorizationUrl {
|
||||
final params = {
|
||||
'response_type': 'code',
|
||||
'client_id': _clientId,
|
||||
'redirect_uri': _redirectUri,
|
||||
'scope': _scope,
|
||||
'state': _stateParam,
|
||||
'code_challenge': _codeChallenge,
|
||||
'code_challenge_method': 'S256',
|
||||
};
|
||||
final query = params.entries
|
||||
.map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
|
||||
.join('&');
|
||||
return 'https://twitter.com/i/oauth2/authorize?$query';
|
||||
}
|
||||
|
||||
/// Check if a URL is the redirect callback and extract the auth code.
|
||||
String? extractCodeFromUrl(String url) {
|
||||
if (!url.startsWith(_redirectUri)) return null;
|
||||
final uri = Uri.parse(url);
|
||||
final state = uri.queryParameters['state'];
|
||||
if (state != _stateParam) return null;
|
||||
return uri.queryParameters['code'];
|
||||
}
|
||||
|
||||
/// Exchange the auth code for tokens and fetch user info.
|
||||
Future<Map<String, dynamic>?> exchangeCodeForUser(String code) async {
|
||||
final dio = Dio();
|
||||
|
||||
// Exchange code for access token
|
||||
final tokenResponse = await dio.post(
|
||||
'https://api.twitter.com/2/oauth2/token',
|
||||
options: Options(
|
||||
contentType: 'application/x-www-form-urlencoded',
|
||||
headers: {
|
||||
'Authorization': 'Basic ${base64Encode(utf8.encode('$_clientId:'))}',
|
||||
},
|
||||
),
|
||||
data: {
|
||||
'code': code,
|
||||
'grant_type': 'authorization_code',
|
||||
'redirect_uri': _redirectUri,
|
||||
'code_verifier': _codeVerifier,
|
||||
},
|
||||
);
|
||||
|
||||
final accessToken = tokenResponse.data['access_token'] as String?;
|
||||
if (accessToken == null) return null;
|
||||
|
||||
// Fetch user info
|
||||
final userResponse = await dio.get(
|
||||
'https://api.twitter.com/2/users/me',
|
||||
queryParameters: {'user.fields': 'id,name,username,profile_image_url'},
|
||||
options: Options(
|
||||
headers: {'Authorization': 'Bearer $accessToken'},
|
||||
),
|
||||
);
|
||||
|
||||
final userData = userResponse.data['data'] as Map<String, dynamic>?;
|
||||
if (userData == null) return null;
|
||||
|
||||
return {
|
||||
'id': userData['id'],
|
||||
'name': userData['name'],
|
||||
'username': userData['username'],
|
||||
'avatar': userData['profile_image_url'],
|
||||
};
|
||||
}
|
||||
|
||||
String _generateRandomString(int length) {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
|
||||
final random = Random.secure();
|
||||
return List.generate(length, (_) => chars[random.nextInt(chars.length)]).join();
|
||||
}
|
||||
|
||||
String _generateCodeVerifier() => _generateRandomString(64);
|
||||
|
||||
String _generateCodeChallenge(String verifier) {
|
||||
final bytes = utf8.encode(verifier);
|
||||
final digest = sha256.convert(bytes);
|
||||
return base64Url.encode(digest.bytes).replaceAll('=', '');
|
||||
}
|
||||
}
|
||||
@@ -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