From 94f2f95bcf6221c50ffed746484f072daffb301a Mon Sep 17 00:00:00 2001 From: Shinigami Date: Sat, 26 Nov 2022 20:33:36 +0100 Subject: [PATCH] fix: auto logout on stale token (#144) --- composables/statusDrafts.ts | 14 ++++++++++++++ composables/users.ts | 19 +++++++++++++++---- plugins/masto.ts | 7 ++++++- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/composables/statusDrafts.ts b/composables/statusDrafts.ts index d332b66a..f9238988 100644 --- a/composables/statusDrafts.ts +++ b/composables/statusDrafts.ts @@ -78,3 +78,17 @@ export function directMessageUser(account: Account) { visibility: 'direct', })) } + +export function clearUserDrafts(account?: Account) { + if (!account) + account = currentUser.value?.account + + if (!account) + return + + const id = `${account.acct}@${currentUser.value?.server}` + if (!allDrafts.value[id]) + return + + delete allDrafts.value[id] +} diff --git a/composables/users.ts b/composables/users.ts index a9941940..7fb8c842 100644 --- a/composables/users.ts +++ b/composables/users.ts @@ -1,5 +1,6 @@ import { login as loginMasto } from 'masto' import type { AccountCredentials, Instance } from 'masto' +import { clearUserDrafts } from './statusDrafts' import type { UserLogin } from '~/types' import { DEFAULT_POST_CHARS_LIMIT, DEFAULT_SERVER, STORAGE_KEY_CURRENT_USER, STORAGE_KEY_SERVERS, STORAGE_KEY_USERS } from '~/constants' @@ -55,12 +56,22 @@ export async function signout() { if (!currentUser.value) return - const index = users.value.findIndex(u => u.account?.id === currentUser.value?.account.id) - if (index === -1) - return + const _currentUserId = currentUser.value.account.id - users.value.splice(index, 1) + const index = users.value.findIndex(u => u.account?.id === _currentUserId) + + if (index !== -1) { + // Clear stale data + delete servers.value[_currentUserId] + clearUserDrafts() + + // Remove the current user from the users + users.value.splice(index, 1) + } + + // Set currentUserId to next user if available currentUserId.value = users.value[0]?.account?.id + await reloadPage() } diff --git a/plugins/masto.ts b/plugins/masto.ts index 16043571..55f3be0f 100644 --- a/plugins/masto.ts +++ b/plugins/masto.ts @@ -4,12 +4,17 @@ import { DEFAULT_SERVER } from '~/constants' export default defineNuxtPlugin(async () => { try { + const accessToken = currentUser.value?.token + // TODO: improve upstream to make this synchronous (delayed auth) const masto = await login({ url: `https://${currentUser.value?.server || DEFAULT_SERVER}`, - accessToken: currentUser.value?.token || undefined, + accessToken, }) + if (accessToken) + masto.accounts.verifyCredentials().catch(() => signout()) + return { provide: { masto,