🐛 Bug fixes on bad switching account UX

This commit is contained in:
LittleSheep 2024-05-23 23:54:05 +08:00
parent 3e640768c8
commit 15ed75b04e
12 changed files with 149 additions and 103 deletions

View File

@ -9,13 +9,8 @@ import 'package:solian/services.dart';
import 'package:oauth2/oauth2.dart' as oauth2;
class AuthProvider extends GetConnect {
final deviceEndpoint = Uri.parse(
'${ServiceFinder.services['passport']}/api/notifications/subscribe');
final tokenEndpoint =
Uri.parse('${ServiceFinder.services['passport']}/api/auth/token');
final userinfoEndpoint =
Uri.parse('${ServiceFinder.services['passport']}/api/users/me');
final redirectUrl = Uri.parse('solian://auth');
static const clientId = 'solian';
static const clientSecret = '_F4%q2Eea3';
@ -25,13 +20,12 @@ class AuthProvider extends GetConnect {
@override
void onInit() {
httpClient.baseUrl = ServiceFinder.services['passport'];
applyAuthenticator();
loadCredentials();
}
oauth2.Credentials? credentials;
Future<Request<T?>> reqAuthenticator<T>(Request<T?> request) async {
Future<Request<T?>> requestAuthenticator<T>(Request<T?> request) async {
if (credentials != null && credentials!.isExpired) {
final resp = await post('/api/auth/token', {
'refresh_token': credentials!.refreshToken,
@ -48,7 +42,9 @@ class AuthProvider extends GetConnect {
expiration: DateTime.now().add(const Duration(minutes: 3)),
);
storage.write(
key: 'auth_credentials', value: jsonEncode(credentials!.toJson()));
key: 'auth_credentials',
value: jsonEncode(credentials!.toJson()),
);
}
if (credentials != null) {
@ -58,18 +54,20 @@ class AuthProvider extends GetConnect {
return request;
}
void applyAuthenticator() {
isAuthorized.then((status) async {
if (status) {
final content = await storage.read(key: 'auth_credentials');
credentials = oauth2.Credentials.fromJson(jsonDecode(content!));
httpClient.addAuthenticator(reqAuthenticator);
}
});
Future<void> loadCredentials() async {
if (await isAuthorized) {
final content = await storage.read(key: 'auth_credentials');
credentials = oauth2.Credentials.fromJson(jsonDecode(content!));
}
}
Future<oauth2.Credentials> signin(
BuildContext context, String username, String password) async {
BuildContext context,
String username,
String password,
) async {
_cacheUserProfileResponse = null;
final resp = await oauth2.resourceOwnerPasswordGrant(
tokenEndpoint,
username,
@ -89,13 +87,16 @@ class AuthProvider extends GetConnect {
);
storage.write(
key: 'auth_credentials', value: jsonEncode(credentials!.toJson()));
applyAuthenticator();
key: 'auth_credentials',
value: jsonEncode(credentials!.toJson()),
);
return credentials!;
}
void signout() {
_cacheUserProfileResponse = null;
storage.deleteAll();
}
@ -108,7 +109,11 @@ class AuthProvider extends GetConnect {
return _cacheUserProfileResponse!;
}
final resp = await get('/api/users/me');
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['passport'];
client.httpClient.addAuthenticator(requestAuthenticator);
final resp = await client.get('/api/users/me');
_cacheUserProfileResponse = resp;
return resp;
}

View File

@ -39,7 +39,7 @@ class AttachmentProvider extends GetConnect {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['paperclip'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
final filePayload =
MultipartFile(await file.readAsBytes(), filename: basename(file.path));
@ -78,7 +78,7 @@ class AttachmentProvider extends GetConnect {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['paperclip'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
var resp = await client.put('/api/attachments/$id', {
'metadata': {
@ -102,7 +102,7 @@ class AttachmentProvider extends GetConnect {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['paperclip'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
var resp = await client.delete('/api/attachments/$id');
if (resp.statusCode != 200) {

View File

@ -9,7 +9,7 @@ class FriendProvider extends GetConnect {
final AuthProvider auth = Get.find();
httpClient.baseUrl = ServiceFinder.services['passport'];
httpClient.addAuthenticator(auth.reqAuthenticator);
httpClient.addAuthenticator(auth.requestAuthenticator);
}
Future<Response> listFriendship() => get('/api/users/me/friends');

View File

@ -2,8 +2,6 @@ import 'package:go_router/go_router.dart';
import 'package:solian/screens/account.dart';
import 'package:solian/screens/account/friend.dart';
import 'package:solian/screens/account/personalize.dart';
import 'package:solian/screens/auth/signin.dart';
import 'package:solian/screens/auth/signup.dart';
import 'package:solian/screens/contact.dart';
import 'package:solian/screens/social.dart';
import 'package:solian/screens/posts/publish.dart';
@ -48,16 +46,6 @@ abstract class AppRouter {
name: 'accountPersonalize',
builder: (context, state) => const PersonalizeScreen(),
),
GoRoute(
path: '/auth/sign-in',
name: 'signin',
builder: (context, state) => const SignInScreen(),
),
GoRoute(
path: '/auth/sign-up',
name: 'signup',
builder: (context, state) => const SignUpScreen(),
),
],
),
GoRoute(

View File

@ -2,8 +2,9 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:solian/providers/auth.dart';
import 'package:solian/router.dart';
import 'package:solian/screens/auth/signin.dart';
import 'package:solian/screens/auth/signup.dart';
import 'package:solian/services.dart';
import 'package:solian/theme.dart';
import 'package:solian/widgets/account/account_avatar.dart';
class AccountScreen extends StatefulWidget {
@ -42,7 +43,14 @@ class _AccountScreenState extends State<AccountScreen> {
title: 'signin'.tr,
caption: 'signinCaption'.tr,
onTap: () {
AppRouter.instance.pushNamed('signin').then((_) {
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignInPopup(),
).then((_) async {
await provider.getProfile(noCache: true);
setState(() {});
});
},
@ -52,7 +60,15 @@ class _AccountScreenState extends State<AccountScreen> {
title: 'signup'.tr,
caption: 'signupCaption'.tr,
onTap: () {
AppRouter.instance.pushNamed('signup');
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignUpPopup(),
).then((_) {
setState(() {});
});
},
),
],
@ -69,7 +85,9 @@ class _AccountScreenState extends State<AccountScreen> {
leading: x.$1,
title: Text(x.$2),
onTap: () {
AppRouter.instance.pushNamed(x.$3);
AppRouter.instance
.pushNamed(x.$3)
.then((_) => setState(() {}));
},
),
)),
@ -111,24 +129,27 @@ class AccountNameCard extends StatelessWidget {
children: [
AspectRatio(
aspectRatio: 16 / 7,
child: Stack(
clipBehavior: Clip.none,
fit: StackFit.expand,
children: [
if (prof.body['banner'] != null)
Image.network(
'${ServiceFinder.services['paperclip']}/api/attachments/${prof.body['banner']}',
fit: BoxFit.cover,
child: Container(
color: Theme.of(context).colorScheme.surfaceContainer,
child: Stack(
clipBehavior: Clip.none,
fit: StackFit.expand,
children: [
if (prof.body['banner'] != null)
Image.network(
'${ServiceFinder.services['paperclip']}/api/attachments/${prof.body['banner']}',
fit: BoxFit.cover,
),
Positioned(
bottom: -30,
left: 18,
child: AccountAvatar(
content: prof.body['avatar'],
radius: 48,
),
),
Positioned(
bottom: -30,
left: 18,
child: AccountAvatar(
content: prof.body['avatar'],
radius: 48,
),
),
],
],
),
),
),
Row(
@ -155,9 +176,11 @@ class AccountNameCard extends StatelessWidget {
child: Card(
child: ListTile(
title: Text('description'.tr),
subtitle: Text(prof.body['description']?.isNotEmpty
? prof.body['description']
: 'No description yet.'),
subtitle: Text(
prof.body['description']?.isNotEmpty
? prof.body['description']
: 'No description yet.',
),
),
),
).paddingOnly(left: 24, right: 24, top: 8),

View File

@ -100,7 +100,7 @@ class _PersonalizeScreenState extends State<PersonalizeScreen> {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['passport'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
final resp = await client.put(
'/api/users/me/$position',
@ -124,7 +124,7 @@ class _PersonalizeScreenState extends State<PersonalizeScreen> {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['passport'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
_birthday?.toIso8601String();
final resp = await client.put(

View File

@ -2,18 +2,17 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:solian/exts.dart';
import 'package:solian/providers/auth.dart';
import 'package:solian/router.dart';
import 'package:solian/services.dart';
import 'package:url_launcher/url_launcher_string.dart';
class SignInScreen extends StatefulWidget {
const SignInScreen({super.key});
class SignInPopup extends StatefulWidget {
const SignInPopup({super.key});
@override
State<SignInScreen> createState() => _SignInScreenState();
State<SignInPopup> createState() => _SignInPopupState();
}
class _SignInScreenState extends State<SignInScreen> {
class _SignInPopupState extends State<SignInPopup> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();
@ -23,15 +22,16 @@ class _SignInScreenState extends State<SignInScreen> {
final username = _usernameController.value.text;
final password = _passwordController.value.text;
if (username.isEmpty || password.isEmpty) return;
provider.signin(context, username, password).then((_) {
AppRouter.instance.pop(true);
provider.signin(context, username, password).then((_) async {
Navigator.pop(context, true);
}).catchError((e) {
List<String> messages = e.toString().split('\n');
if (messages.last.contains('risk')) {
final ticketId = RegExp(r'ticketId=(\d+)').firstMatch(messages.last);
if (ticketId == null) {
context.showErrorDialog(
'Requested to multi-factor authenticate, but the ticket id was not found');
'Requested to multi-factor authenticate, but the ticket id was not found',
);
}
showDialog(
context: context,
@ -46,9 +46,7 @@ class _SignInScreenState extends State<SignInScreen> {
launchUrlString(
'${ServiceFinder.services['passport']}/mfa?ticket=${ticketId!.group(1)}',
);
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
Navigator.pop(context);
},
)
],
@ -56,28 +54,32 @@ class _SignInScreenState extends State<SignInScreen> {
},
);
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(messages.last),
));
context.showErrorDialog(messages.last);
}
});
}
@override
Widget build(BuildContext context) {
return Material(
color: Theme.of(context).colorScheme.surface,
return SizedBox(
height: MediaQuery.of(context).size.height * 0.9,
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.6,
constraints: const BoxConstraints(maxWidth: 360),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Image.asset('assets/logo.png', width: 72, height: 72),
),
Image.asset('assets/logo.png', width: 64, height: 64)
.paddingOnly(bottom: 4),
Text(
'signinGreeting'.tr,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.w900,
),
).paddingOnly(left: 4, bottom: 16),
TextField(
autocorrect: false,
enableSuggestions: false,
@ -107,10 +109,19 @@ class _SignInScreenState extends State<SignInScreen> {
FocusManager.instance.primaryFocus?.unfocus(),
onSubmitted: (_) => performAction(context),
),
const SizedBox(height: 16),
ElevatedButton(
child: Text('signin'.tr),
onPressed: () => performAction(context),
const SizedBox(height: 12),
Align(
alignment: Alignment.centerRight,
child: TextButton(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('next'.tr),
const Icon(Icons.chevron_right),
],
),
onPressed: () => performAction(context),
),
)
],
),

View File

@ -4,14 +4,14 @@ import 'package:solian/exts.dart';
import 'package:solian/router.dart';
import 'package:solian/services.dart';
class SignUpScreen extends StatefulWidget {
const SignUpScreen({super.key});
class SignUpPopup extends StatefulWidget {
const SignUpPopup({super.key});
@override
State<SignUpScreen> createState() => _SignUpScreenState();
State<SignUpPopup> createState() => _SignUpPopupState();
}
class _SignUpScreenState extends State<SignUpScreen> {
class _SignUpPopupState extends State<SignUpPopup> {
final _emailController = TextEditingController();
final _usernameController = TextEditingController();
final _nicknameController = TextEditingController();
@ -61,19 +61,25 @@ class _SignUpScreenState extends State<SignUpScreen> {
@override
Widget build(BuildContext context) {
return Material(
color: Theme.of(context).colorScheme.surface,
return SizedBox(
height: MediaQuery.of(context).size.height * 0.9,
child: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.6,
constraints: const BoxConstraints(maxWidth: 360),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Image.asset('assets/logo.png', width: 72, height: 72),
),
Image.asset('assets/logo.png', width: 64, height: 64)
.paddingOnly(bottom: 4),
Text(
'signupGreeting'.tr,
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.w900,
),
).paddingOnly(left: 4, bottom: 16),
TextField(
autocorrect: false,
enableSuggestions: false,
@ -132,9 +138,18 @@ class _SignUpScreenState extends State<SignUpScreen> {
onSubmitted: (_) => performAction(context),
),
const SizedBox(height: 16),
ElevatedButton(
child: Text('signup'.tr),
onPressed: () => performAction(context),
Align(
alignment: Alignment.centerRight,
child: TextButton(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('next'.tr),
const Icon(Icons.chevron_right),
],
),
onPressed: () => performAction(context),
),
)
],
),

View File

@ -65,7 +65,7 @@ class _PostPublishingScreenState extends State<PostPublishingScreen> {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['interactive'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
final payload = {
'content': _contentController.value.text,

View File

@ -43,11 +43,13 @@ class SolianMessages extends Translations {
'aspectRatioPortrait': 'Portrait',
'aspectRatioLandscape': 'Landscape',
'signin': 'Sign in',
'signinGreeting': 'Welcome back\nSolar Network',
'signinCaption':
'Sign in to create post, start a realm, message your friend and more!',
'signinRiskDetected':
'Risk detected, click Next to open a webpage and signin through it to pass security check.',
'signup': 'Sign up',
'signupGreeting': 'Welcome onboard 👋',
'signupCaption':
'Create an account on Solarpass and then get the access of entire Solar Network!',
'signout': 'Sign out',
@ -119,9 +121,11 @@ class SolianMessages extends Translations {
'aspectRatioPortrait': '竖型',
'aspectRatioLandscape': '横型',
'signin': '登录',
'signinGreeting': '欢迎回来\nSolar Network',
'signinCaption': '登录以发表帖子、文章、创建领域、和你的朋友聊天,以及获取更多功能!',
'signinRiskDetected': '检测到风险,点击下一步按钮来打开一个网页,并通过在其上面登录来通过安全检查。',
'signup': '注册',
'signupGreeting': '欢迎加入\nSolar Network',
'signupCaption': '在 Solarpass 注册一个账号以获得整个 Solar Network 的存取权!',
'signout': '登出',
'riskDetection': '检测到风险',

View File

@ -156,7 +156,7 @@ class _PostDeletionDialogState extends State<PostDeletionDialog> {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['interactive'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
setState(() => _isBusy = true);
final resp = await client.delete('/api/posts/${widget.item.id}');

View File

@ -50,7 +50,7 @@ class _PostQuickActionState extends State<PostQuickAction> {
final client = GetConnect();
client.httpClient.baseUrl = ServiceFinder.services['interactive'];
client.httpClient.addAuthenticator(auth.reqAuthenticator);
client.httpClient.addAuthenticator(auth.requestAuthenticator);
setState(() => _isSubmitting = true);