♻️ Refactored auth system

This commit is contained in:
2024-07-25 01:18:47 +08:00
parent ef58430060
commit 6d92a16a62
38 changed files with 444 additions and 523 deletions

View File

@ -29,93 +29,85 @@ class _AccountScreenState extends State<AccountScreen> {
(const Icon(Icons.info_outline), 'about'.tr, 'about'),
];
final AuthProvider provider = Get.find();
final AuthProvider auth = Get.find();
return Material(
color: Theme.of(context).colorScheme.surface,
child: SafeArea(
child: FutureBuilder(
future: provider.isAuthorized,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasData && snapshot.data == false) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ActionCard(
icon: const Icon(Icons.login, color: Colors.white),
title: 'signin'.tr,
caption: 'signinCaption'.tr,
onTap: () {
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignInPopup(),
).then((val) async {
if (val == true) {
await provider.getProfile(noCache: true);
setState(() {});
}
});
},
),
ActionCard(
icon: const Icon(Icons.add, color: Colors.white),
title: 'signup'.tr,
caption: 'signupCaption'.tr,
onTap: () {
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignUpPopup(),
).then((_) {
setState(() {});
});
},
),
],
),
);
}
return CenteredContainer(
child: ListView(
child: Obx(() {
if (auth.isAuthorized.isFalse) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const AccountHeading().paddingOnly(bottom: 8, top: 8),
...(actionItems.map(
(x) => ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 34),
leading: x.$1,
title: Text(x.$2),
onTap: () {
AppRouter.instance
.pushNamed(x.$3)
.then((_) => setState(() {}));
},
),
)),
ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 34),
leading: const Icon(Icons.logout),
title: Text('signout'.tr),
ActionCard(
icon: const Icon(Icons.login, color: Colors.white),
title: 'signin'.tr,
caption: 'signinCaption'.tr,
onTap: () {
provider.signout();
setState(() {});
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignInPopup(),
).then((val) async {
if (val == true) {
await auth.refreshUserProfile();
}
});
},
),
ActionCard(
icon: const Icon(Icons.add, color: Colors.white),
title: 'signup'.tr,
caption: 'signupCaption'.tr,
onTap: () {
showModalBottomSheet(
useRootNavigator: true,
isDismissible: false,
isScrollControlled: true,
context: context,
builder: (context) => const SignUpPopup(),
).then((_) {
setState(() {});
});
},
),
],
),
);
},
),
}
return CenteredContainer(
child: ListView(
children: [
const AccountHeading().paddingOnly(bottom: 8, top: 8),
...(actionItems.map(
(x) => ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 34),
leading: x.$1,
title: Text(x.$2),
onTap: () {
AppRouter.instance
.pushNamed(x.$3)
.then((_) => setState(() {}));
},
),
)),
ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 34),
leading: const Icon(Icons.logout),
title: Text('signout'.tr),
onTap: () {
auth.signout();
setState(() {});
},
),
],
),
);
}),
),
);
}
@ -139,33 +131,25 @@ class _AccountHeadingState extends State<AccountHeading> {
@override
Widget build(BuildContext context) {
final AuthProvider provider = Get.find();
final AuthProvider auth = Get.find();
return FutureBuilder(
future: provider.getProfile(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const LinearProgressIndicator();
}
final prof = snapshot.data!;
return AccountHeadingWidget(
avatar: prof.body['avatar'],
banner: prof.body['banner'],
name: prof.body['name'],
nick: prof.body['nick'],
desc: prof.body['description'],
status: _status,
badges: prof.body['badges']
?.map((e) => AccountBadge.fromJson(e))
.toList()
.cast<AccountBadge>(),
onEditStatus: () {
setState(() {
_status = Get.find<StatusProvider>().getCurrentStatus();
});
},
);
final prof = auth.userProfile.value!;
return AccountHeadingWidget(
avatar: prof['avatar'],
banner: prof['banner'],
name: prof['name'],
nick: prof['nick'],
desc: prof['description'],
status: _status,
badges: prof['badges']
?.map((e) => AccountBadge.fromJson(e))
.toList()
.cast<AccountBadge>(),
onEditStatus: () {
setState(() {
_status = Get.find<StatusProvider>().getCurrentStatus();
});
},
);
}

View File

@ -18,7 +18,7 @@ class _NotificationScreenState extends State<NotificationScreen> {
Future<void> markAllRead() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
setState(() => _isBusy = true);
@ -42,7 +42,7 @@ class _NotificationScreenState extends State<NotificationScreen> {
Future<void> markOneRead(notify.Notification element, int index) async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
final WebSocketProvider provider = Get.find();

View File

@ -53,17 +53,17 @@ class _PersonalizeScreenState extends State<PersonalizeScreen> {
setState(() => _isBusy = true);
final AuthProvider auth = Get.find();
final prof = await auth.getProfile(noCache: true);
final prof = auth.userProfile.value!;
setState(() {
_usernameController.text = prof.body['name'];
_nicknameController.text = prof.body['nick'];
_descriptionController.text = prof.body['description'];
_firstNameController.text = prof.body['profile']['first_name'];
_lastNameController.text = prof.body['profile']['last_name'];
_avatar = prof.body['avatar'];
_banner = prof.body['banner'];
if (prof.body['profile']['birthday'] != null) {
_birthday = DateTime.parse(prof.body['profile']['birthday']);
_usernameController.text = prof['name'];
_nicknameController.text = prof['nick'];
_descriptionController.text = prof['description'];
_firstNameController.text = prof['profile']['first_name'];
_lastNameController.text = prof['profile']['last_name'];
_avatar = prof['avatar'];
_banner = prof['banner'];
if (prof['profile']['birthday'] != null) {
_birthday = DateTime.parse(prof['profile']['birthday']);
_birthdayController.text =
DateFormat('yyyy-MM-dd').format(_birthday!.toLocal());
}
@ -74,7 +74,7 @@ class _PersonalizeScreenState extends State<PersonalizeScreen> {
Future<void> updateImage(String position) async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
final image = await _imagePicker.pickImage(source: ImageSource.gallery);
if (image == null) return;
@ -120,7 +120,7 @@ class _PersonalizeScreenState extends State<PersonalizeScreen> {
void updatePersonalize() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
setState(() => _isBusy = true);

View File

@ -44,7 +44,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
bool _isBusy = false;
int? _accountId;
String? _overrideAlias;
String? _newAlias;
Channel? _channel;
Call? _ongoingCall;
@ -53,26 +53,20 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
late final ChatEventController _chatController;
getProfile() async {
final AuthProvider auth = Get.find();
final prof = await auth.getProfile();
_accountId = prof.body['id'];
}
getChannel({String? overrideAlias}) async {
getChannel({String? alias}) async {
final ChannelProvider provider = Get.find();
setState(() => _isBusy = true);
if (overrideAlias != null) _overrideAlias = overrideAlias;
if (alias != null) _newAlias = alias;
try {
final resp = await provider.getChannel(
_overrideAlias ?? widget.alias,
_newAlias ?? widget.alias,
realm: widget.realm,
);
final respProfile = await provider.getMyChannelProfile(
_overrideAlias ?? widget.alias,
_newAlias ?? widget.alias,
realm: widget.realm,
);
setState(() {
@ -93,7 +87,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
try {
final resp = await provider.getChannelOngoingCall(
_overrideAlias ?? widget.alias,
_newAlias ?? widget.alias,
realm: widget.realm,
);
if (resp != null) {
@ -150,16 +144,16 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
@override
void initState() {
_accountId = Get.find<AuthProvider>().userProfile.value!['id'];
_chatController = ChatEventController();
_chatController.initialize();
getChannel().then((_) {
_chatController.getEvents(_channel!, widget.realm);
listenMessages();
});
getProfile();
getOngoingCall();
super.initState();
@ -225,7 +219,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
if (value == false) AppRouter.instance.pop();
if (value != null) {
final resp = Channel.fromJson(value as Map<String, dynamic>);
getChannel(overrideAlias: resp.alias);
getChannel(alias: resp.alias);
}
});
},

View File

@ -41,9 +41,9 @@ class _ChannelDetailScreenState extends State<ChannelDetailScreen> {
void checkOwner() async {
final AuthProvider auth = Get.find();
final prof = await auth.getProfile();
setState(() {
_isOwned = prof.body['id'] == widget.channel.account.externalId;
_isOwned =
auth.userProfile.value!['id'] == widget.channel.account.externalId;
});
}
@ -75,14 +75,14 @@ class _ChannelDetailScreenState extends State<ChannelDetailScreen> {
void applyProfileChanges() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
setState(() => _isBusy = true);
final client = auth.configureClient('messaging');
final resp = await client.put(
'/channels/${widget.realm}/${widget.channel.alias}/members/me', {
final resp = await client
.put('/channels/${widget.realm}/${widget.channel.alias}/members/me', {
'nick': null,
'notify_level': _notifyLevel,
});

View File

@ -39,7 +39,7 @@ class _ChannelOrganizeScreenState extends State<ChannelOrganizeScreen> {
void applyChannel() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
if (_aliasController.value.text.isEmpty) randomizeAlias();

View File

@ -97,49 +97,42 @@ class _ChatScreenState extends State<ChatScreen> {
),
],
),
body: FutureBuilder(
future: auth.getProfileWithCheck(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.data == null) {
return SigninRequiredOverlay(
onSignedIn: () => _channels.refreshAvailableChannel(),
);
}
body: Obx(() {
if (auth.isAuthorized.isFalse) {
return SigninRequiredOverlay(
onSignedIn: () => _channels.refreshAvailableChannel(),
);
}
final selfId = snapshot.data!.body['id'];
final selfId = auth.userProfile.value!['id'];
return Column(
children: [
Obx(() {
if (_channels.isLoading.isFalse) {
return const SizedBox();
} else {
return const LinearProgressIndicator();
}
}),
const ChatCallCurrentIndicator(),
Expanded(
child: CenteredContainer(
child: RefreshIndicator(
onRefresh: _channels.refreshAvailableChannel,
child: Obx(
() => ChannelListWidget(
noCategory: true,
channels: _channels.directChannels,
selfId: selfId,
),
return Column(
children: [
Obx(() {
if (_channels.isLoading.isFalse) {
return const SizedBox();
} else {
return const LinearProgressIndicator();
}
}),
const ChatCallCurrentIndicator(),
Expanded(
child: CenteredContainer(
child: RefreshIndicator(
onRefresh: _channels.refreshAvailableChannel,
child: Obx(
() => ChannelListWidget(
noCategory: true,
channels: _channels.directChannels,
selfId: selfId,
),
),
),
),
],
);
},
),
),
],
);
}),
),
);
}

View File

@ -107,42 +107,39 @@ class FeedCreationButton extends StatelessWidget {
Widget build(BuildContext context) {
final AuthProvider auth = Get.find();
return FutureBuilder(
future: auth.isAuthorized,
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data == true) {
return PopupMenuButton(
icon: const Icon(Icons.edit_square),
itemBuilder: (BuildContext context) => [
PopupMenuItem(
child: ListTile(
title: Text('postEditor'.tr),
leading: const Icon(Icons.article),
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
),
onTap: () {
AppRouter.instance.pushNamed('postEditor').then((val) {
if (val != null && onCreated != null) {
onCreated!();
}
});
},
),
if (!hideDraftBox)
PopupMenuItem(
child: ListTile(
title: Text('draftBoxOpen'.tr),
leading: const Icon(Icons.drafts),
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
),
onTap: () {
AppRouter.instance.pushNamed('draftBox');
},
),
],
);
}
return const SizedBox();
});
if (auth.isAuthorized.isFalse) {
return const SizedBox();
}
return PopupMenuButton(
icon: const Icon(Icons.edit_square),
itemBuilder: (BuildContext context) => [
PopupMenuItem(
child: ListTile(
title: Text('postEditor'.tr),
leading: const Icon(Icons.article),
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
),
onTap: () {
AppRouter.instance.pushNamed('postEditor').then((val) {
if (val != null && onCreated != null) {
onCreated!();
}
});
},
),
if (!hideDraftBox)
PopupMenuItem(
child: ListTile(
title: Text('draftBoxOpen'.tr),
leading: const Icon(Icons.drafts),
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
),
onTap: () {
AppRouter.instance.pushNamed('draftBox');
},
),
],
);
}
}

View File

@ -69,7 +69,7 @@ class _PostPublishScreenState extends State<PostPublishScreen> {
void applyPost() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
if (_contentController.value.text.isEmpty) return;
setState(() => _isBusy = true);

View File

@ -28,7 +28,7 @@ class _RealmListScreenState extends State<RealmListScreen> {
getRealms() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
setState(() => _isBusy = true);
@ -81,42 +81,33 @@ class _RealmListScreenState extends State<RealmListScreen> {
),
],
),
body: FutureBuilder(
future: auth.isAuthorized,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.data == false) {
return SigninRequiredOverlay(
onSignedIn: () {
getRealms();
},
);
}
body: Obx(() {
if (auth.isAuthorized.isFalse) {
return SigninRequiredOverlay(
onSignedIn: () => getRealms(),
);
}
return Column(
children: [
if (_isBusy) const LinearProgressIndicator().animate().scaleX(),
Expanded(
child: CenteredContainer(
child: RefreshIndicator(
onRefresh: () => getRealms(),
child: ListView.builder(
itemCount: _realms.length,
itemBuilder: (context, index) {
final element = _realms[index];
return buildRealm(element);
},
),
return Column(
children: [
if (_isBusy) const LinearProgressIndicator().animate().scaleX(),
Expanded(
child: CenteredContainer(
child: RefreshIndicator(
onRefresh: () => getRealms(),
child: ListView.builder(
itemCount: _realms.length,
itemBuilder: (context, index) {
final element = _realms[index];
return buildRealm(element);
},
),
),
),
],
);
},
),
),
],
);
}),
),
);
}

View File

@ -26,9 +26,8 @@ class _RealmDetailScreenState extends State<RealmDetailScreen> {
void checkOwner() async {
final AuthProvider auth = Get.find();
final prof = await auth.getProfile();
setState(() {
_isOwned = prof.body['id'] == widget.realm.accountId;
_isOwned = auth.userProfile.value!['id'] == widget.realm.accountId;
});
}

View File

@ -37,7 +37,7 @@ class _RealmOrganizeScreenState extends State<RealmOrganizeScreen> {
void applyRealm() async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
if (auth.isAuthorized.isFalse) return;
if (_aliasController.value.text.isEmpty) randomizeAlias();

View File

@ -244,44 +244,38 @@ class RealmChannelListWidget extends StatelessWidget {
Widget build(BuildContext context) {
final AuthProvider auth = Get.find();
return FutureBuilder(
future: auth.getProfile(),
builder: (context, snapshot) {
return RefreshIndicator(
onRefresh: onRefresh,
child: Column(
children: [
ListTile(
leading: const Icon(Icons.add_box),
contentPadding: const EdgeInsets.only(left: 32, right: 8),
tileColor: Theme.of(context).colorScheme.surfaceContainer,
title: Text('channelNew'.tr),
subtitle: Text(
'channelNewInRealmHint'
.trParams({'realm': '#${realm.alias}'}),
),
onTap: () {
AppRouter.instance
.pushNamed(
'channelOrganizing',
extra: ChannelOrganizeArguments(realm: realm),
)
.then((value) {
if (value != null) onRefresh();
});
},
),
Expanded(
child: ChannelListWidget(
channels: channels,
selfId: snapshot.data?.body['id'] ?? 0,
noCategory: true,
),
return RefreshIndicator(
onRefresh: onRefresh,
child: Column(
children: [
ListTile(
leading: const Icon(Icons.add_box),
contentPadding: const EdgeInsets.only(left: 32, right: 8),
tileColor: Theme.of(context).colorScheme.surfaceContainer,
title: Text('channelNew'.tr),
subtitle: Text(
'channelNewInRealmHint'.trParams({'realm': '#${realm.alias}'}),
),
onTap: () {
AppRouter.instance
.pushNamed(
'channelOrganizing',
extra: ChannelOrganizeArguments(realm: realm),
)
],
.then((value) {
if (value != null) onRefresh();
});
},
),
);
},
Expanded(
child: ChannelListWidget(
channels: channels,
selfId: auth.userProfile.value!['id'],
noCategory: true,
),
)
],
),
);
}
}