From 5acb15621ff0fad6cfb6cec06a4715bf3f541f1c Mon Sep 17 00:00:00 2001 From: Jai A Date: Fri, 14 Jul 2023 18:47:26 -0700 Subject: [PATCH] more --- composables/auth.js | 41 ++++++++++++++++++++++++++++++++++++++++- composables/user.js | 15 +++++++++++++++ layouts/default.vue | 28 ++++++++-------------------- middleware/auth.js | 2 +- 4 files changed, 64 insertions(+), 22 deletions(-) diff --git a/composables/auth.js b/composables/auth.js index 1058e74d3c..8d9c0971b0 100644 --- a/composables/auth.js +++ b/composables/auth.js @@ -16,8 +16,12 @@ export const initAuth = async (oldToken = null) => { const auth = { user: null, token: '', - headers: {}, } + + if (oldToken === 'none') { + return auth + } + const route = useRoute() const authCookie = useCookie('auth-token', { maxAge: 60 * 60 * 24 * 365 * 10, @@ -37,6 +41,11 @@ export const initAuth = async (oldToken = null) => { if (authCookie.value) { auth.token = authCookie.value + + if (!auth.token || !auth.token.startsWith('mra_')) { + return auth + } + try { auth.user = await useBaseFetch( 'user', @@ -50,6 +59,36 @@ export const initAuth = async (oldToken = null) => { } catch {} } + if (!auth.user) { + try { + const session = await useBaseFetch( + 'session/refresh', + { + method: 'POST', + headers: { + Authorization: auth.token, + }, + }, + true + ) + + auth.token = session.session + authCookie.value = auth.token + + auth.user = await useBaseFetch( + 'user', + { + headers: { + Authorization: auth.token, + }, + }, + true + ) + } catch { + authCookie.value = null + } + } + return auth } diff --git a/composables/user.js b/composables/user.js index 2738d7a71b..fc32f7730f 100644 --- a/composables/user.js +++ b/composables/user.js @@ -149,3 +149,18 @@ export const resendVerifyEmail = async () => { } stopLoading() } + +export const logout = async () => { + startLoading() + const auth = await useAuth() + try { + await useBaseFetch(`session/${auth.value.token}`, { + method: 'DELETE', + }) + } catch {} + + await useAuth('none') + useCookie('auth-token').value = null + await navigateTo('/') + stopLoading() +} diff --git a/layouts/default.vue b/layouts/default.vue index fdcb3e2451..534d7111ad 100644 --- a/layouts/default.vue +++ b/layouts/default.vue @@ -103,14 +103,14 @@ Moderation
-
- + Sign in
@@ -160,13 +160,13 @@
Visit your profile
- + Sign in