fix: auto logout on stale token (#144)

This commit is contained in:
Shinigami 2022-11-26 20:33:36 +01:00 committed by GitHub
parent 2d16c4868e
commit 94f2f95bcf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 5 deletions

View file

@ -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]
}

View file

@ -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
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()
}

View file

@ -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,