Fix userId (again)

This commit is contained in:
shilangyu 2021-04-11 18:27:22 +02:00
parent e22327b8bc
commit de4b6e674d
16 changed files with 93 additions and 58 deletions

View File

@ -30,7 +30,7 @@ VoidCallback Function(
));
};
}
return () => action(store.defaultToken!);
return () => action(store.defaultUserData!.jwt);
};
}
@ -52,7 +52,7 @@ VoidCallback Function(
));
};
}
final token = store.defaultTokenFor(instanceHost)!;
final token = store.defaultUserDataFor(instanceHost)!.jwt;
return () => action(token);
};
}

View File

@ -53,8 +53,8 @@ class CommunitiesTab extends HookWidget {
sort: SortType.active,
savedOnly: false,
personId:
accountsStore.defaultTokenFor(instanceHost)!.payload.sub,
auth: accountsStore.defaultTokenFor(instanceHost)!.raw,
accountsStore.defaultUserDataFor(instanceHost)!.userId,
auth: accountsStore.defaultUserDataFor(instanceHost)!.jwt.raw,
))
.then((e) => e.follows),
)

View File

@ -55,7 +55,7 @@ class CommunityPage extends HookWidget {
final scrollController = useScrollController();
final fullCommunitySnap = useMemoFuture(() {
final token = accountsStore.defaultTokenFor(instanceHost);
final token = accountsStore.defaultUserDataFor(instanceHost)?.jwt;
if (communityId != null) {
return LemmyApiV3(instanceHost).run(GetCommunity(
@ -196,8 +196,9 @@ class CommunityPage extends HookWidget {
LemmyApiV3(community.instanceHost).run(GetComments(
communityId: community.community.id,
auth: accountsStore
.defaultTokenFor(community.instanceHost)
?.raw,
.defaultUserDataFor(community.instanceHost)
?.jwt
.raw,
type: CommentListingType.community,
sort: sortType,
limit: batchSize,

View File

@ -72,7 +72,7 @@ class CreatePostPage extends HookWidget {
type: PostListingType.all,
sort: SortType.hot,
limit: 9999,
auth: accStore.defaultTokenFor(selectedInstance.value)?.raw,
auth: accStore.defaultUserDataFor(selectedInstance.value)?.jwt.raw,
))
.then(
(value) {

View File

@ -36,7 +36,7 @@ class FullPostPage extends HookWidget {
final fullPostRefreshable =
useRefreshable(() => LemmyApiV3(instanceHost).run(GetPost(
id: id,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth: accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
)));
final loggedInAction = useLoggedInAction(instanceHost);
final newComments = useState(const <CommentView>[]);

View File

@ -293,7 +293,7 @@ class InfiniteHomeList extends HookWidget {
page: page,
limit: limit,
savedOnly: false,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth: accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
))
];
final instancePosts = await Future.wait(futures);
@ -316,7 +316,7 @@ class InfiniteHomeList extends HookWidget {
page: page,
limit: batchSize,
savedOnly: false,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth: accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
));
return InfinitePostList(

View File

@ -109,7 +109,7 @@ class InboxPage extends HookWidget {
defaultSort: SortType.new_,
fetcher: (page, batchSize, sortType) =>
LemmyApiV3(selectedInstance).run(GetReplies(
auth: accStore.defaultTokenFor(selectedInstance)!.raw,
auth: accStore.defaultUserDataFor(selectedInstance)!.jwt.raw,
sort: sortType,
limit: batchSize,
page: page,
@ -127,7 +127,7 @@ class InboxPage extends HookWidget {
defaultSort: SortType.new_,
fetcher: (page, batchSize, sortType) =>
LemmyApiV3(selectedInstance).run(GetPersonMentions(
auth: accStore.defaultTokenFor(selectedInstance)!.raw,
auth: accStore.defaultUserDataFor(selectedInstance)!.jwt.raw,
sort: sortType,
limit: batchSize,
page: page,
@ -146,7 +146,7 @@ class InboxPage extends HookWidget {
controller: isc,
fetcher: (page, batchSize) => LemmyApiV3(selectedInstance).run(
GetPrivateMessages(
auth: accStore.defaultTokenFor(selectedInstance)!.raw,
auth: accStore.defaultUserDataFor(selectedInstance)!.jwt.raw,
limit: batchSize,
page: page,
unreadOnly: unreadOnly.value,
@ -190,7 +190,7 @@ class PrivateMessageTile extends HookWidget {
final toMe = useMemoized(() =>
pmv.value.recipient.originInstanceHost == pmv.value.instanceHost &&
pmv.value.recipient.id ==
accStore.defaultTokenFor(pmv.value.instanceHost)?.payload.sub);
accStore.defaultUserDataFor(pmv.value.instanceHost)?.userId);
final otherSide =
useMemoized(() => toMe ? pmv.value.creator : pmv.value.recipient);
@ -240,7 +240,7 @@ class PrivateMessageTile extends HookWidget {
instanceHost: pmv.value.instanceHost,
query: DeletePrivateMessage(
privateMessageId: pmv.value.privateMessage.id,
auth: accStore.defaultTokenFor(pmv.value.instanceHost)!.raw,
auth: accStore.defaultUserDataFor(pmv.value.instanceHost)!.jwt.raw,
deleted: !deleted.value,
),
onSuccess: (val) => deleted.value = val.privateMessage.deleted,
@ -252,7 +252,7 @@ class PrivateMessageTile extends HookWidget {
instanceHost: pmv.value.instanceHost,
query: MarkPrivateMessageAsRead(
privateMessageId: pmv.value.privateMessage.id,
auth: accStore.defaultTokenFor(pmv.value.instanceHost)!.raw,
auth: accStore.defaultUserDataFor(pmv.value.instanceHost)!.jwt.raw,
read: !read.value,
),
// TODO: add notification for notifying parent list

View File

@ -184,7 +184,8 @@ class InstancePage extends HookWidget {
limit: batchSize,
page: page,
savedOnly: false,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth:
accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
))),
InfiniteCommentList(
fetcher: (page, batchSize, sort) =>
@ -194,7 +195,8 @@ class InstancePage extends HookWidget {
limit: batchSize,
page: page,
savedOnly: false,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth:
accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
))),
_AboutTab(site,
communitiesFuture: communitiesFuture,
@ -244,7 +246,7 @@ class _AboutTab extends HookWidget {
sort: sortType,
limit: batchSize,
page: page,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth: accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
),
),
title: 'Communities of ${site.siteView?.site.name}',

View File

@ -28,8 +28,8 @@ class ManageAccountPage extends HookWidget {
final accountStore = useAccountsStore();
final userFuture = useMemoized(() async {
final site = await LemmyApiV3(instanceHost).run(
GetSite(auth: accountStore.tokenFor(instanceHost, username)!.raw));
final site = await LemmyApiV3(instanceHost).run(GetSite(
auth: accountStore.userDataFor(instanceHost, username)!.jwt.raw));
return site.myUser!;
});
@ -91,7 +91,8 @@ class _ManageAccount extends HookWidget {
final deleteAccountPasswordController = useTextEditingController();
final token = accountsStore.tokenFor(user.instanceHost, user.person.name)!;
final token =
accountsStore.userDataFor(user.instanceHost, user.person.name)!.jwt;
handleSubmit() async {
saveDelayedLoading.start();
@ -398,7 +399,8 @@ class _ImagePicker extends HookWidget {
final upload = await PictrsApi(user.instanceHost).upload(
filePath: pic.path,
auth: accountsStore
.tokenFor(user.instanceHost, user.person.name)!
.userDataFor(user.instanceHost, user.person.name)!
.jwt
.raw,
);
pictrsDeleteToken.value = upload.files[0];

View File

@ -91,7 +91,7 @@ class UserProfileTab extends HookWidget {
actions: actions,
),
body: UserProfile(
userId: accountsStore.defaultToken!.payload.sub,
userId: accountsStore.defaultUserData!.userId,
instanceHost: accountsStore.defaultInstanceHost!,
),
);

View File

@ -45,7 +45,7 @@ class SavedPage extends HookWidget {
savedOnly: true,
page: page,
limit: batchSize,
auth: accountStore.defaultToken!.raw,
auth: accountStore.defaultUserData!.jwt.raw,
),
),
),
@ -58,7 +58,7 @@ class SavedPage extends HookWidget {
savedOnly: true,
page: page,
limit: batchSize,
auth: accountStore.defaultToken!.raw,
auth: accountStore.defaultUserData!.jwt.raw,
),
),
),

View File

@ -81,7 +81,7 @@ class _SearchResultsList extends HookWidget {
q: query,
sort: sort,
type: type,
auth: accStore.defaultTokenFor(instanceHost)?.raw,
auth: accStore.defaultUserDataFor(instanceHost)?.jwt.raw,
page: page,
limit: batchSize,
));

View File

@ -11,16 +11,16 @@ part 'accounts_store.g.dart';
/// Store that manages all accounts
@JsonSerializable()
class AccountsStore extends ChangeNotifier {
static const prefsKey = 'v3:AccountsStore';
static const prefsKey = 'v4:AccountsStore';
static final _prefs = SharedPreferences.getInstance();
/// Map containing JWT tokens of specific users.
/// Map containing user data (jwt token, userId) of specific accounts.
/// If a token is in this map, the user is considered logged in
/// for that account.
/// `tokens['instanceHost']['username']`
/// `accounts['instanceHost']['username']`
@protected
@JsonKey(defaultValue: {'lemmy.ml': {}})
late Map<String, Map<String, Jwt>> tokens;
late Map<String, Map<String, UserData>> accounts;
/// default account for a given instance
/// map where keys are instanceHosts and values are usernames
@ -101,13 +101,13 @@ class AccountsStore extends ChangeNotifier {
String? get defaultInstanceHost => defaultAccount?.split('@')[1];
Jwt? get defaultToken {
UserData? get defaultUserData {
if (defaultAccount == null) {
return null;
}
final userTag = defaultAccount!.split('@');
return tokens[userTag[1]]?[userTag[0]];
return accounts[userTag[1]]?[userTag[0]];
}
String? defaultUsernameFor(String instanceHost) {
@ -118,20 +118,20 @@ class AccountsStore extends ChangeNotifier {
return defaultAccounts[instanceHost];
}
Jwt? defaultTokenFor(String instanceHost) {
UserData? defaultUserDataFor(String instanceHost) {
if (isAnonymousFor(instanceHost)) {
return null;
}
return tokens[instanceHost]?[defaultAccounts[instanceHost]];
return accounts[instanceHost]?[defaultAccounts[instanceHost]];
}
Jwt? tokenFor(String instanceHost, String username) {
UserData? userDataFor(String instanceHost, String username) {
if (!usernamesFor(instanceHost).contains(username)) {
return null;
}
return tokens[instanceHost]?[username];
return accounts[instanceHost]?[username];
}
/// sets globally default account
@ -157,20 +157,20 @@ class AccountsStore extends ChangeNotifier {
return true;
}
return tokens[instanceHost]!.isEmpty;
return accounts[instanceHost]!.isEmpty;
}
/// `true` if no added instance has an account assigned to it
bool get hasNoAccount => loggedInInstances.isEmpty;
Iterable<String> get instances => tokens.keys;
Iterable<String> get instances => accounts.keys;
Iterable<String> get loggedInInstances =>
instances.where((e) => !isAnonymousFor(e));
/// Usernames that are assigned to a given instance
Iterable<String> usernamesFor(String instanceHost) =>
tokens[instanceHost]?.keys ?? const Iterable.empty();
accounts[instanceHost]?.keys ?? const Iterable.empty();
/// adds a new account
/// if it's the first account ever the account is
@ -187,16 +187,16 @@ class AccountsStore extends ChangeNotifier {
}
final lemmy = LemmyApiV3(instanceHost);
final token = await lemmy.run(Login(
final jwt = await lemmy.run(Login(
usernameOrEmail: usernameOrEmail,
password: password,
));
final userData = await lemmy
.run(GetSite(auth: token.raw))
.then((value) => value.myUser!);
final userData =
await lemmy.run(GetSite(auth: jwt.raw)).then((value) => value.myUser!);
tokens[instanceHost]![userData.person.name] = token.copyWith(
payload: token.payload.copyWith(sub: userData.person.id),
accounts[instanceHost]![userData.person.name] = UserData(
jwt: jwt,
userId: userData.person.id,
);
await _assignDefaultAccounts();
@ -224,7 +224,7 @@ class AccountsStore extends ChangeNotifier {
}
}
tokens[instanceHost] = HashMap();
accounts[instanceHost] = HashMap();
await _assignDefaultAccounts();
notifyListeners();
@ -233,7 +233,7 @@ class AccountsStore extends ChangeNotifier {
/// This also removes all accounts assigned to this instance
Future<void> removeInstance(String instanceHost) async {
tokens.remove(instanceHost);
accounts.remove(instanceHost);
await _assignDefaultAccounts();
notifyListeners();
@ -241,14 +241,31 @@ class AccountsStore extends ChangeNotifier {
}
Future<void> removeAccount(String instanceHost, String username) async {
if (!tokens.containsKey(instanceHost)) {
if (!accounts.containsKey(instanceHost)) {
throw Exception("instance doesn't exist");
}
tokens[instanceHost]!.remove(username);
accounts[instanceHost]!.remove(username);
await _assignDefaultAccounts();
notifyListeners();
return save();
}
}
/// Stores data associated with a logged in user
@JsonSerializable()
class UserData {
final Jwt jwt;
final int userId;
const UserData({
required this.jwt,
required this.userId,
});
factory UserData.fromJson(Map<String, dynamic> json) =>
_$UserDataFromJson(json);
Map<String, dynamic> toJson() => _$UserDataToJson(this);
}

View File

@ -8,11 +8,12 @@ part of 'accounts_store.dart';
AccountsStore _$AccountsStoreFromJson(Map<String, dynamic> json) {
return AccountsStore()
..tokens = (json['tokens'] as Map<String, dynamic>?)?.map(
..accounts = (json['accounts'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(
k,
(e as Map<String, dynamic>).map(
(k, e) => MapEntry(k, Jwt.fromJson(e as String)),
(k, e) =>
MapEntry(k, UserData.fromJson(e as Map<String, dynamic>)),
)),
) ??
{'lemmy.ml': {}}
@ -25,7 +26,19 @@ AccountsStore _$AccountsStoreFromJson(Map<String, dynamic> json) {
Map<String, dynamic> _$AccountsStoreToJson(AccountsStore instance) =>
<String, dynamic>{
'tokens': instance.tokens,
'accounts': instance.accounts,
'defaultAccounts': instance.defaultAccounts,
'defaultAccount': instance.defaultAccount,
};
UserData _$UserDataFromJson(Map<String, dynamic> json) {
return UserData(
jwt: Jwt.fromJson(json['jwt'] as String),
userId: json['userId'] as int,
);
}
Map<String, dynamic> _$UserDataToJson(UserData instance) => <String, dynamic>{
'jwt': instance.jwt,
'userId': instance.userId,
};

View File

@ -95,7 +95,7 @@ class CommentWidget extends HookWidget {
final accStore = useAccountsStore();
final isMine = commentTree.comment.comment.creatorId ==
accStore.defaultTokenFor(commentTree.comment.instanceHost)?.payload.sub;
accStore.defaultUserDataFor(commentTree.comment.instanceHost)?.userId;
final selectable = useState(false);
final showRaw = useState(false);
final collapsed = useState(false);

View File

@ -42,7 +42,7 @@ class UserProfile extends HookWidget {
personId: userId,
savedOnly: false,
sort: SortType.active,
auth: accountsStore.defaultTokenFor(instanceHost)?.raw,
auth: accountsStore.defaultUserDataFor(instanceHost)?.jwt.raw,
));
}, [userId, instanceHost]);
@ -100,7 +100,7 @@ class UserProfile extends HookWidget {
sort: SortType.active,
page: page,
limit: batchSize,
auth: accountsStore.defaultTokenFor(instanceHost)?.raw,
auth: accountsStore.defaultUserDataFor(instanceHost)?.jwt.raw,
))
.then((val) => val.posts),
),
@ -112,7 +112,7 @@ class UserProfile extends HookWidget {
sort: SortType.active,
page: page,
limit: batchSize,
auth: accountsStore.defaultTokenFor(instanceHost)?.raw,
auth: accountsStore.defaultUserDataFor(instanceHost)?.jwt.raw,
))
.then((val) => val.comments),
),