Switch to ofetch methods and fix redirection

This commit is contained in:
niko 2025-04-19 20:20:01 -04:00
parent d9b33357f4
commit 25a298c87d
No known key found for this signature in database
GPG Key ID: C3B29CF2BA3406AD
2 changed files with 40 additions and 28 deletions

View File

@ -1,4 +1,6 @@
<script setup lang="ts">
import { FetchError } from 'ofetch';
const route = useRoute();
const redirect = route.query.redirect;
const registerURI = `/account/register${redirect ? `?redirect=${redirect}` : ''}`;
@ -7,24 +9,23 @@ const loginForm = reactive({ username: null, password: null });
const errorMessage = ref<string | null>();
async function loginSubmission() {
const response = await fetch('/api/account/login', {
await $fetch('/api/account/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(loginForm)
});
if (!response.ok) {
errorMessage.value = response.statusText;
body: loginForm
}).catch((error: FetchError) => {
errorMessage.value = error.statusText;
setTimeout(() => { // TODO: this is not the best way to clear this out, but this is temporary! replace all toasts with input alerts in the future
errorMessage.value = null;
}, 5000);
return;
}
});
await navigateTo('/account');
if (typeof redirect === 'string') {
await navigateTo(redirect);
} else {
await navigateTo('/account');
}
}
</script>

View File

@ -1,25 +1,36 @@
import { FetchError } from 'ofetch';
type LoginCCResponse = {
refresh_token: string;
access_token: string;
token_type: string;
expires_in: number;
};
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const apiResponse = await fetch(`${useRuntimeConfig(event).apiBase}/v1/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ...body, grant_type: 'password' })
});
const apiJSON = await apiResponse.json();
if (!apiResponse.ok) {
setResponseStatus(event, apiResponse.status, apiJSON.error);
try {
const apiResponse = await $fetch<LoginCCResponse>(`${useRuntimeConfig(event).apiBase}/v1/login`, {
method: 'POST',
body: { ...body, grant_type: 'password' }
});
setCookie(event, 'refresh_token', apiResponse.refresh_token);
setCookie(event, 'access_token', apiResponse.access_token);
setCookie(event, 'token_type', apiResponse.token_type);
setResponseStatus(event, 200);
event.node.res.end();
} catch (error: unknown) {
if (error instanceof FetchError) {
setResponseStatus(event, error.status, error.data.error);
} else {
setResponseStatus(event, 500);
}
event.node.res.end();
return;
}
setCookie(event, 'refresh_token', apiJSON.refresh_token);
setCookie(event, 'access_token', apiJSON.access_token);
setCookie(event, 'token_type', apiJSON.token_type);
setResponseStatus(event, 200);
event.node.res.end();
});