migration to new backend
This commit is contained in:
12
frontend/src/routes/+layout.server.ts
Normal file
12
frontend/src/routes/+layout.server.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = async (event) => {
|
||||
if (event.locals.user) {
|
||||
return {
|
||||
user: event.locals.user
|
||||
};
|
||||
}
|
||||
return {
|
||||
user: null
|
||||
};
|
||||
};
|
||||
11
frontend/src/routes/+layout.svelte
Normal file
11
frontend/src/routes/+layout.svelte
Normal file
@@ -0,0 +1,11 @@
|
||||
<script>
|
||||
import Navbar from '$lib/components/Navbar.svelte';
|
||||
import Toast from '$lib/components/Toast.svelte';
|
||||
import 'tailwindcss/tailwind.css';
|
||||
export let data;
|
||||
</script>
|
||||
|
||||
<Navbar {data} />
|
||||
<Toast />
|
||||
|
||||
<slot></slot>
|
||||
44
frontend/src/routes/+page.server.ts
Normal file
44
frontend/src/routes/+page.server.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import { redirect, type Actions } from '@sveltejs/kit';
|
||||
|
||||
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const actions: Actions = {
|
||||
setTheme: async ({ url, cookies }) => {
|
||||
const theme = url.searchParams.get('theme');
|
||||
// change the theme only if it is one of the allowed themes
|
||||
if (
|
||||
theme &&
|
||||
['light', 'dark', 'night', 'retro', 'forest', 'aqua', 'forest', 'garden', 'emerald'].includes(
|
||||
theme
|
||||
)
|
||||
) {
|
||||
cookies.set('colortheme', theme, {
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 365
|
||||
});
|
||||
}
|
||||
},
|
||||
logout: async ({ cookies }: { cookies: any }) => {
|
||||
const cookie = cookies.get('auth') || null;
|
||||
|
||||
if (!cookie) {
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch(`${serverEndpoint}/auth/logout/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: cookies.get('auth')
|
||||
}
|
||||
});
|
||||
if (res.ok) {
|
||||
cookies.delete('auth', { path: '/' });
|
||||
cookies.delete('refresh', { path: '/' });
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
}
|
||||
};
|
||||
126
frontend/src/routes/+page.svelte
Normal file
126
frontend/src/routes/+page.svelte
Normal file
@@ -0,0 +1,126 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
import AdventureOverlook from '$lib/assets/AdventureOverlook.webp';
|
||||
import MapWithPins from '$lib/assets/MapWithPins.webp';
|
||||
|
||||
export let data;
|
||||
</script>
|
||||
|
||||
<section class="flex items-center justify-center w-full py-12 md:py-24 lg:py-32">
|
||||
<div class="container px-4 md:px-6">
|
||||
<div class="grid gap-6 lg:grid-cols-[1fr_550px] lg:gap-12 xl:grid-cols-[1fr_650px]">
|
||||
<div class="flex flex-col justify-center space-y-4">
|
||||
<div class="space-y-2">
|
||||
{#if data.user}
|
||||
{#if data.user.first_name && data.user.first_name !== null}
|
||||
<h1
|
||||
class="text-3xl font-bold tracking-tighter sm:text-5xl xl:text-6xl/none bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent pb-4"
|
||||
>
|
||||
{data.user.first_name.charAt(0).toUpperCase() + data.user.first_name.slice(1)},
|
||||
Discover the World's Most Thrilling Adventures
|
||||
</h1>
|
||||
{:else}
|
||||
<h1
|
||||
class="text-3xl font-bold tracking-tighter sm:text-5xl xl:text-6xl/none bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent pb-4"
|
||||
>
|
||||
Discover the World's Most Thrilling Adventures
|
||||
</h1>
|
||||
{/if}
|
||||
{:else}
|
||||
<h1
|
||||
class="text-3xl font-bold tracking-tighter sm:text-5xl xl:text-6xl/none bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent pb-4"
|
||||
>
|
||||
Discover the World's Most Thrilling Adventures
|
||||
</h1>
|
||||
{/if}
|
||||
<p class="max-w-[600px] text-gray-500 md:text-xl dark:text-gray-400">
|
||||
Discover and plan your next epic adventure with our cutting-edge travel app. Explore
|
||||
breathtaking destinations, create custom itineraries, and stay connected on the go.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 min-[400px]:flex-row">
|
||||
<button on:click={() => goto('/visited')} class="btn btn-primary">
|
||||
Go To AdventureLog
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<img
|
||||
src={AdventureOverlook}
|
||||
width="550"
|
||||
height="550"
|
||||
alt="Hero"
|
||||
class="mx-auto aspect-video overflow-hidden rounded-xl object-cover sm:w-full lg:order-last"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section
|
||||
class="flex items-center justify-center w-full py-12 md:py-24 lg:py-32 bg-gray-100 dark:bg-gray-800"
|
||||
>
|
||||
<div class="container px-4 md:px-6">
|
||||
<div class="flex flex-col items-center justify-center space-y-4 text-center">
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
class="inline-block rounded-lg bg-gray-100 px-3 py-1 text-md dark:bg-gray-800 dark:text-gray-400"
|
||||
>
|
||||
Key Features
|
||||
</div>
|
||||
<h2
|
||||
class="text-3xl font-bold tracking-tighter sm:text-5xl bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent"
|
||||
>
|
||||
Discover, Plan, and Explore with Ease
|
||||
</h2>
|
||||
<p
|
||||
class="max-w-[900px] text-gray-500 md:text-xl/relaxed lg:text-base/relaxed xl:text-xl/relaxed dark:text-gray-400"
|
||||
>
|
||||
Our adventure travel app is designed to simplify your journey, providing you with the
|
||||
tools and resources to plan, pack, and navigate your next epic adventure.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mx-auto grid max-w-5xl items-center gap-6 py-12 lg:grid-cols-2 lg:gap-12">
|
||||
<!-- svelte-ignore a11y-img-redundant-alt -->
|
||||
<img
|
||||
src={MapWithPins}
|
||||
width="550"
|
||||
height="310"
|
||||
alt="Image"
|
||||
class="mx-auto aspect-video overflow-hidden rounded-xl object-cover object-center sm:w-full lg:order-last"
|
||||
/>
|
||||
<div class="flex flex-col justify-center space-y-4">
|
||||
<ul class="grid gap-6">
|
||||
<li>
|
||||
<div class="grid gap-1">
|
||||
<h3 class="text-xl font-bold dark:text-gray-400">Trip Planning</h3>
|
||||
<p class="text-gray-500 dark:text-gray-400">
|
||||
Easily create custom itineraries and get real-time updates on your trip.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div class="grid gap-1">
|
||||
<h3 class="text-xl font-bold dark:text-gray-400">Packing Lists</h3>
|
||||
<p class="text-gray-500 dark:text-gray-400">
|
||||
Never forget a thing with our comprehensive packing lists.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div class="grid gap-1">
|
||||
<h3 class="text-xl font-bold dark:text-gray-400">Destination Guides</h3>
|
||||
<p class="text-gray-500 dark:text-gray-400">
|
||||
Discover the best attractions, activities, and hidden gems in your destination.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<svelte:head>
|
||||
<title>Home | AdventureLog</title>
|
||||
<meta name="description" content="AdventureLog is a platform to log your adventures." />
|
||||
</svelte:head>
|
||||
26
frontend/src/routes/add/+page.svelte
Normal file
26
frontend/src/routes/add/+page.svelte
Normal file
@@ -0,0 +1,26 @@
|
||||
<script lang="ts">
|
||||
// @ts-nocheck
|
||||
|
||||
import { DefaultMarker, MapEvents, MapLibre, Popup } from 'svelte-maplibre';
|
||||
function addMarker(e: CustomEvent<MapMouseEvent>) {
|
||||
markers = [];
|
||||
markers = [...markers, { lngLat: e.detail.lngLat }];
|
||||
console.log(markers);
|
||||
}
|
||||
let markers = [];
|
||||
</script>
|
||||
|
||||
<MapLibre
|
||||
style="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
|
||||
class="relative aspect-[9/16] max-h-[70vh] w-full sm:aspect-video sm:max-h-full"
|
||||
standardControls
|
||||
>
|
||||
<!-- MapEvents gives you access to map events even from other components inside the map,
|
||||
where you might not have access to the top-level `MapLibre` component. In this case
|
||||
it would also work to just use on:click on the MapLibre component itself. -->
|
||||
<MapEvents on:click={addMarker} />
|
||||
|
||||
{#each markers as marker}
|
||||
<DefaultMarker lngLat={marker.lngLat} />
|
||||
{/each}
|
||||
</MapLibre>
|
||||
312
frontend/src/routes/adventures/+page.server.ts
Normal file
312
frontend/src/routes/adventures/+page.server.ts
Normal file
@@ -0,0 +1,312 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
import type { Actions } from '@sveltejs/kit';
|
||||
import { fetchCSRFToken, tryRefreshToken } from '$lib/index.server';
|
||||
import { checkLink } from '$lib';
|
||||
|
||||
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async (event) => {
|
||||
const formData = await event.request.formData();
|
||||
|
||||
const type = formData.get('type') as string;
|
||||
const name = formData.get('name') as string;
|
||||
const location = formData.get('location') as string | null;
|
||||
let date = (formData.get('date') as string | null) ?? null;
|
||||
const description = formData.get('description') as string | null;
|
||||
const activity_types = formData.get('activity_types')
|
||||
? (formData.get('activity_types') as string).split(',')
|
||||
: null;
|
||||
const rating = formData.get('rating') ? Number(formData.get('rating')) : null;
|
||||
let link = formData.get('link') as string | null;
|
||||
let latitude = formData.get('latitude') as string | null;
|
||||
let longitude = formData.get('longitude') as string | null;
|
||||
|
||||
// check if latitude and longitude are valid
|
||||
if (latitude && longitude) {
|
||||
if (isNaN(Number(latitude)) || isNaN(Number(longitude))) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: 'Invalid latitude or longitude' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// round latitude and longitude to 6 decimal places
|
||||
if (latitude) {
|
||||
latitude = Number(latitude).toFixed(6);
|
||||
}
|
||||
if (longitude) {
|
||||
longitude = Number(longitude).toFixed(6);
|
||||
}
|
||||
|
||||
const image = formData.get('image') as File;
|
||||
|
||||
if (!type || !name) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: 'Missing required fields' }
|
||||
};
|
||||
}
|
||||
|
||||
if (date == null || date == '') {
|
||||
date = null;
|
||||
}
|
||||
|
||||
if (link) {
|
||||
link = checkLink(link);
|
||||
}
|
||||
|
||||
const formDataToSend = new FormData();
|
||||
formDataToSend.append('type', type);
|
||||
formDataToSend.append('name', name);
|
||||
formDataToSend.append('location', location || '');
|
||||
formDataToSend.append('date', date || '');
|
||||
formDataToSend.append('description', description || '');
|
||||
formDataToSend.append('latitude', latitude || '');
|
||||
formDataToSend.append('longitude', longitude || '');
|
||||
if (activity_types) {
|
||||
// Filter out empty and duplicate activity types, then trim each activity type
|
||||
const cleanedActivityTypes = Array.from(
|
||||
new Set(
|
||||
activity_types
|
||||
.map((activity_type) => activity_type.trim())
|
||||
.filter((activity_type) => activity_type !== '' && activity_type !== ',')
|
||||
)
|
||||
);
|
||||
|
||||
// Append each cleaned activity type to formDataToSend
|
||||
cleanedActivityTypes.forEach((activity_type) => {
|
||||
formDataToSend.append('activity_types', activity_type);
|
||||
});
|
||||
}
|
||||
formDataToSend.append('rating', rating ? rating.toString() : '');
|
||||
formDataToSend.append('link', link || '');
|
||||
formDataToSend.append('image', image);
|
||||
|
||||
let auth = event.cookies.get('auth');
|
||||
|
||||
if (!auth) {
|
||||
const refresh = event.cookies.get('refresh');
|
||||
if (!refresh) {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
let res = await tryRefreshToken(refresh);
|
||||
if (res) {
|
||||
auth = res;
|
||||
event.cookies.set('auth', auth, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
|
||||
path: '/'
|
||||
});
|
||||
} else {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!auth) {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
|
||||
const csrfToken = await fetchCSRFToken();
|
||||
|
||||
if (!csrfToken) {
|
||||
return {
|
||||
status: 500,
|
||||
body: { message: 'Failed to fetch CSRF token' }
|
||||
};
|
||||
}
|
||||
|
||||
const res = await fetch(`${serverEndpoint}/api/adventures/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken,
|
||||
Cookie: auth
|
||||
},
|
||||
body: formDataToSend
|
||||
});
|
||||
|
||||
let new_id = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
const errorBody = await res.json();
|
||||
return {
|
||||
status: res.status,
|
||||
body: { error: errorBody }
|
||||
};
|
||||
}
|
||||
|
||||
let id = new_id.id;
|
||||
let user_id = new_id.user_id;
|
||||
let image_url = new_id.image;
|
||||
let link_url = new_id.link;
|
||||
|
||||
return { id, user_id, image_url, link };
|
||||
},
|
||||
edit: async (event) => {
|
||||
const formData = await event.request.formData();
|
||||
|
||||
const adventureId = formData.get('adventureId') as string;
|
||||
const type = formData.get('type') as string;
|
||||
const name = formData.get('name') as string;
|
||||
const location = formData.get('location') as string | null;
|
||||
let date = (formData.get('date') as string | null) ?? null;
|
||||
const description = formData.get('description') as string | null;
|
||||
let activity_types = formData.get('activity_types')
|
||||
? (formData.get('activity_types') as string).split(',')
|
||||
: null;
|
||||
const rating = formData.get('rating') ? Number(formData.get('rating')) : null;
|
||||
let link = formData.get('link') as string | null;
|
||||
let latitude = formData.get('latitude') as string | null;
|
||||
let longitude = formData.get('longitude') as string | null;
|
||||
|
||||
// check if latitude and longitude are valid
|
||||
if (latitude && longitude) {
|
||||
if (isNaN(Number(latitude)) || isNaN(Number(longitude))) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: 'Invalid latitude or longitude' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// round latitude and longitude to 6 decimal places
|
||||
if (latitude) {
|
||||
latitude = Number(latitude).toFixed(6);
|
||||
}
|
||||
if (longitude) {
|
||||
longitude = Number(longitude).toFixed(6);
|
||||
}
|
||||
|
||||
const image = formData.get('image') as File;
|
||||
|
||||
console.log(activity_types);
|
||||
|
||||
if (!type || !name) {
|
||||
return {
|
||||
status: 400,
|
||||
body: { error: 'Missing required fields' }
|
||||
};
|
||||
}
|
||||
|
||||
if (date == null || date == '') {
|
||||
date = null;
|
||||
}
|
||||
|
||||
if (link) {
|
||||
link = checkLink(link);
|
||||
}
|
||||
|
||||
const formDataToSend = new FormData();
|
||||
formDataToSend.append('type', type);
|
||||
formDataToSend.append('name', name);
|
||||
formDataToSend.append('location', location || '');
|
||||
formDataToSend.append('date', date || '');
|
||||
formDataToSend.append('description', description || '');
|
||||
formDataToSend.append('latitude', latitude || '');
|
||||
formDataToSend.append('longitude', longitude || '');
|
||||
if (activity_types) {
|
||||
// Filter out empty and duplicate activity types, then trim each activity type
|
||||
const cleanedActivityTypes = Array.from(
|
||||
new Set(
|
||||
activity_types
|
||||
.map((activity_type) => activity_type.trim())
|
||||
.filter((activity_type) => activity_type !== '' && activity_type !== ',')
|
||||
)
|
||||
);
|
||||
|
||||
// Append each cleaned activity type to formDataToSend
|
||||
cleanedActivityTypes.forEach((activity_type) => {
|
||||
formDataToSend.append('activity_types', activity_type);
|
||||
});
|
||||
}
|
||||
formDataToSend.append('rating', rating ? rating.toString() : '');
|
||||
formDataToSend.append('link', link || '');
|
||||
|
||||
if (image && image.size > 0) {
|
||||
formDataToSend.append('image', image);
|
||||
}
|
||||
|
||||
let auth = event.cookies.get('auth');
|
||||
|
||||
if (!auth) {
|
||||
const refresh = event.cookies.get('refresh');
|
||||
if (!refresh) {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
let res = await tryRefreshToken(refresh);
|
||||
if (res) {
|
||||
auth = res;
|
||||
event.cookies.set('auth', auth, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
|
||||
path: '/'
|
||||
});
|
||||
} else {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!auth) {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
|
||||
const csrfToken = await fetchCSRFToken();
|
||||
|
||||
if (!csrfToken) {
|
||||
return {
|
||||
status: 500,
|
||||
body: { message: 'Failed to fetch CSRF token' }
|
||||
};
|
||||
}
|
||||
|
||||
const res = await fetch(`${serverEndpoint}/api/adventures/${adventureId}/`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken,
|
||||
Cookie: auth
|
||||
},
|
||||
body: formDataToSend
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorBody = await res.json();
|
||||
return {
|
||||
status: res.status,
|
||||
body: { error: errorBody }
|
||||
};
|
||||
}
|
||||
|
||||
let adventure = await res.json();
|
||||
|
||||
let image_url = adventure.image;
|
||||
let link_url = adventure.link;
|
||||
return { image_url, link_url };
|
||||
}
|
||||
};
|
||||
99
frontend/src/routes/adventures/[id]/+page.server.ts
Normal file
99
frontend/src/routes/adventures/[id]/+page.server.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
const id = event.params as { id: string };
|
||||
let request = await fetch(`${endpoint}/api/adventures/${id.id}/`, {
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!request.ok) {
|
||||
console.error('Failed to fetch adventure ' + id.id);
|
||||
return {
|
||||
props: {
|
||||
adventure: null
|
||||
}
|
||||
};
|
||||
} else {
|
||||
let adventure = (await request.json()) as Adventure;
|
||||
if (!adventure.is_public && adventure.user_id !== event.locals.user.pk) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
return {
|
||||
props: {
|
||||
adventure
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}) satisfies PageServerLoad;
|
||||
|
||||
import type { Actions } from '@sveltejs/kit';
|
||||
import { tryRefreshToken } from '$lib/index.server';
|
||||
|
||||
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const actions: Actions = {
|
||||
delete: async (event) => {
|
||||
const id = event.params as { id: string };
|
||||
const adventureId = id.id;
|
||||
|
||||
if (!event.locals.user) {
|
||||
const refresh = event.cookies.get('refresh');
|
||||
let auth = event.cookies.get('auth');
|
||||
if (!refresh) {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
let res = await tryRefreshToken(refresh);
|
||||
if (res) {
|
||||
auth = res;
|
||||
event.cookies.set('auth', auth, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
|
||||
path: '/'
|
||||
});
|
||||
} else {
|
||||
return {
|
||||
status: 401,
|
||||
body: { message: 'Unauthorized' }
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!adventureId) {
|
||||
return {
|
||||
status: 400,
|
||||
error: new Error('Bad request')
|
||||
};
|
||||
}
|
||||
|
||||
let res = await fetch(`${serverEndpoint}/api/adventures/${event.params.id}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
console.log(res);
|
||||
if (!res.ok) {
|
||||
return {
|
||||
status: res.status,
|
||||
error: new Error('Failed to delete adventure')
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: 204
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
100
frontend/src/routes/adventures/[id]/+page.svelte
Normal file
100
frontend/src/routes/adventures/[id]/+page.svelte
Normal file
@@ -0,0 +1,100 @@
|
||||
<!-- <script lang="ts">
|
||||
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
||||
import type { Adventure } from '$lib/types';
|
||||
|
||||
export let data;
|
||||
console.log(data);
|
||||
let adventure: Adventure | null = data.props.adventure;
|
||||
</script>
|
||||
|
||||
{#if !adventure}
|
||||
<p>Adventure not found</p>
|
||||
{:else}
|
||||
<AdventureCard {adventure} type={adventure.type} />
|
||||
{/if} -->
|
||||
|
||||
<script lang="ts">
|
||||
import type { Adventure } from '$lib/types';
|
||||
import { onMount } from 'svelte';
|
||||
import type { PageData } from './$types';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
export let data: PageData;
|
||||
|
||||
let adventure: Adventure;
|
||||
|
||||
onMount(() => {
|
||||
if (data.props.adventure) {
|
||||
adventure = data.props.adventure;
|
||||
} else {
|
||||
goto('/404');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if !adventure}
|
||||
<div class="flex justify-center items-center w-full mt-16">
|
||||
<span class="loading loading-spinner w-24 h-24"></span>
|
||||
</div>
|
||||
{:else}
|
||||
{#if adventure.name}
|
||||
<h1 class="text-center font-extrabold text-4xl mb-2">{adventure.name}</h1>
|
||||
{/if}
|
||||
{#if adventure.location}
|
||||
<p class="text-center text-2xl">
|
||||
<iconify-icon icon="mdi:map-marker" class="text-xl -mb-0.5"
|
||||
></iconify-icon>{adventure.location}
|
||||
</p>
|
||||
{/if}
|
||||
{#if adventure.date}
|
||||
<p class="text-center text-lg mt-4 pl-16 pr-16">
|
||||
Visited on: {adventure.date}
|
||||
</p>
|
||||
{/if}
|
||||
{#if adventure.rating !== undefined && adventure.rating !== null}
|
||||
<div class="flex justify-center items-center">
|
||||
<div class="rating" aria-readonly="true">
|
||||
{#each Array.from({ length: 5 }, (_, i) => i + 1) as star}
|
||||
<input
|
||||
type="radio"
|
||||
name="rating-1"
|
||||
class="mask mask-star"
|
||||
checked={star <= adventure.rating}
|
||||
disabled
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if adventure.description}
|
||||
<p class="text-center text-lg mt-4 pl-16 pr-16">{adventure.description}</p>
|
||||
{/if}
|
||||
{#if adventure.link}
|
||||
<div class="flex justify-center items-center mt-4">
|
||||
<a href={adventure.link} target="_blank" rel="noopener noreferrer" class="btn btn-primary">
|
||||
Visit Website
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
{#if adventure.activity_types && adventure.activity_types.length > 0}
|
||||
<div class="flex justify-center items-center mt-4">
|
||||
<p class="text-center text-lg">Activities: </p>
|
||||
<ul class="flex flex-wrap">
|
||||
{#each adventure.activity_types as activity}
|
||||
<div class="badge badge-primary mr-1 text-md font-semibold pb-2 pt-1 mb-1">
|
||||
{activity}
|
||||
</div>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
{#if adventure.image}
|
||||
<div class="flex content-center justify-center">
|
||||
<img
|
||||
src={adventure.image}
|
||||
alt={adventure.name}
|
||||
class="w-1/2 mt-4 align-middle rounded-lg shadow-lg"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
28
frontend/src/routes/featured/+page.server.ts
Normal file
28
frontend/src/routes/featured/+page.server.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let visitedFetch = await fetch(`${endpoint}/api/adventures/featured/`, {
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!visitedFetch.ok) {
|
||||
console.error('Failed to fetch featured adventures');
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let featured = (await visitedFetch.json()) as Adventure[];
|
||||
return {
|
||||
props: {
|
||||
featured
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}) satisfies PageServerLoad;
|
||||
23
frontend/src/routes/featured/+page.svelte
Normal file
23
frontend/src/routes/featured/+page.svelte
Normal file
@@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
||||
import type { Adventure } from '$lib/types';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
export let data: PageData;
|
||||
console.log(data);
|
||||
|
||||
let adventures: Adventure[] = data.props.featured;
|
||||
</script>
|
||||
|
||||
<h1 class="text-center font-bold text-4xl mb-4">Featured Adventures</h1>
|
||||
<div class="flex flex-wrap gap-4 mr-4 ml-4 justify-center content-center">
|
||||
{#each adventures as adventure}
|
||||
<AdventureCard type="featured" {adventure} />
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if adventures.length === 0}
|
||||
<div class="flex justify-center items-center h-96">
|
||||
<p class="text-2xl text-primary-content">No visited adventures yet!</p>
|
||||
</div>
|
||||
{/if}
|
||||
75
frontend/src/routes/login/+page.server.ts
Normal file
75
frontend/src/routes/login/+page.server.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
if (event.locals.user) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
default: async (event) => {
|
||||
const formData = await event.request.formData();
|
||||
const formUsername = formData.get('username');
|
||||
const formPassword = formData.get('password');
|
||||
|
||||
let username = formUsername?.toString().toLocaleLowerCase();
|
||||
|
||||
const password = formData.get('password');
|
||||
|
||||
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
const csrfTokenFetch = await event.fetch(`${serverEndpoint}/csrf/`);
|
||||
|
||||
if (!csrfTokenFetch.ok) {
|
||||
console.error('Failed to fetch CSRF token');
|
||||
event.locals.user = null;
|
||||
return fail(500, {
|
||||
message: 'Failed to fetch CSRF token'
|
||||
});
|
||||
}
|
||||
|
||||
const tokenPromise = await csrfTokenFetch.json();
|
||||
const csrfToken = tokenPromise.csrfToken;
|
||||
|
||||
const loginFetch = await event.fetch(`${serverEndpoint}/auth/login/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password
|
||||
})
|
||||
});
|
||||
const loginResponse = await loginFetch.json();
|
||||
if (!loginFetch.ok) {
|
||||
// get the value of the first key in the object
|
||||
const firstKey = Object.keys(loginResponse)[0] || 'error';
|
||||
const error = loginResponse[firstKey][0] || 'Invalid username or password';
|
||||
return fail(400, {
|
||||
message: error
|
||||
});
|
||||
} else {
|
||||
const token = loginResponse.access;
|
||||
const tokenFormatted = `auth=${token}`;
|
||||
const refreshToken = `${loginResponse.refresh}`;
|
||||
event.cookies.set('auth', tokenFormatted, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
|
||||
path: '/'
|
||||
});
|
||||
event.cookies.set('refresh', refreshToken, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year
|
||||
path: '/'
|
||||
});
|
||||
|
||||
return redirect(302, '/');
|
||||
}
|
||||
}
|
||||
};
|
||||
78
frontend/src/routes/login/+page.svelte
Normal file
78
frontend/src/routes/login/+page.svelte
Normal file
@@ -0,0 +1,78 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { goto } from '$app/navigation';
|
||||
import { getRandomQuote } from '$lib';
|
||||
import { redirect, type SubmitFunction } from '@sveltejs/kit';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
export let data;
|
||||
console.log(data);
|
||||
|
||||
import { page } from '$app/stores';
|
||||
|
||||
let quote: string = '';
|
||||
let backgroundImageUrl =
|
||||
'https://images.unsplash.com/photo-1465056836041-7f43ac27dcb5?q=80&w=2942&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D';
|
||||
|
||||
onMount(async () => {
|
||||
quote = getRandomQuote();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="min-h-screen bg-no-repeat bg-cover flex items-center justify-center"
|
||||
style="background-image: url('{backgroundImageUrl}')"
|
||||
>
|
||||
<div class="card card-compact w-96 bg-base-100 shadow-xl p-6">
|
||||
<article class="text-center text-4xl font-extrabold">
|
||||
<h1>Sign in</h1>
|
||||
</article>
|
||||
|
||||
<div class="flex justify-center">
|
||||
<form method="post" use:enhance class="w-full max-w-xs">
|
||||
<label for="username">Username</label>
|
||||
<input
|
||||
name="username"
|
||||
id="username"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="password">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
name="password"
|
||||
id="password"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<button class="py-2 px-4 btn btn-primary mr-2">Login</button>
|
||||
<button
|
||||
class="py-2 px-4 btn btn-neutral"
|
||||
type="button"
|
||||
on:click={() => goto('/settings/forgot-password')}>Forgot Password</button
|
||||
>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if ($page.form?.message && $page.form?.message.length > 1) || $page.form?.type === 'error'}
|
||||
<div class="text-center text-error mt-4">
|
||||
{$page.form.message || 'Unable to login with the provided credentials.'}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-center mt-12 mr-25 ml-25">
|
||||
<blockquote class="w-80 text-center text-lg break-words">
|
||||
{#if quote != ''}
|
||||
{quote}
|
||||
{/if}
|
||||
<!-- <footer class="text-sm">- Steve Jobs</footer> -->
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<svelte:head>
|
||||
<title>Login | AdventureLog</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Login to your AdventureLog account to start logging your adventures!"
|
||||
/>
|
||||
</svelte:head>
|
||||
38
frontend/src/routes/map/+page.server.ts
Normal file
38
frontend/src/routes/map/+page.server.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let visitedFetch = await fetch(`${endpoint}/api/adventures/`, {
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!visitedFetch.ok) {
|
||||
console.error('Failed to fetch visited adventures');
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let visited = (await visitedFetch.json()) as Adventure[];
|
||||
console.log('VISITEDL ' + visited);
|
||||
// make a long lat array like this { lngLat: [-20, 0], name: 'Adventure 1' },
|
||||
let markers = visited
|
||||
.filter((adventure) => adventure.latitude !== null && adventure.longitude !== null)
|
||||
.map((adventure) => {
|
||||
return {
|
||||
lngLat: [adventure.longitude, adventure.latitude] as [number, number],
|
||||
name: adventure.name
|
||||
};
|
||||
});
|
||||
return {
|
||||
props: {
|
||||
markers
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}) satisfies PageServerLoad;
|
||||
31
frontend/src/routes/map/+page.svelte
Normal file
31
frontend/src/routes/map/+page.svelte
Normal file
@@ -0,0 +1,31 @@
|
||||
<script>
|
||||
// @ts-nocheck
|
||||
|
||||
import { DefaultMarker, MapEvents, MapLibre, Popup } from 'svelte-maplibre';
|
||||
export let data;
|
||||
|
||||
let markers = data.props.markers;
|
||||
console.log(markers);
|
||||
</script>
|
||||
|
||||
<MapLibre
|
||||
style="https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json"
|
||||
class="relative aspect-[9/16] max-h-[70vh] w-full sm:aspect-video sm:max-h-full"
|
||||
standardControls
|
||||
>
|
||||
{#each data.props.markers as { lngLat, name }}
|
||||
<!-- Unlike the custom marker example, default markers do not have mouse events,
|
||||
and popups only support the default openOn="click" behavior -->
|
||||
<DefaultMarker {lngLat}>
|
||||
<Popup offset={[0, -10]}>
|
||||
<div class="text-lg font-bold">{name}</div>
|
||||
</Popup>
|
||||
</DefaultMarker>
|
||||
{/each}
|
||||
</MapLibre>
|
||||
|
||||
<style>
|
||||
:global(.map) {
|
||||
height: 500px;
|
||||
}
|
||||
</style>
|
||||
28
frontend/src/routes/planner/+page.server.ts
Normal file
28
frontend/src/routes/planner/+page.server.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let plannedFetch = await fetch(`${endpoint}/api/adventures/planned/`, {
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!plannedFetch.ok) {
|
||||
console.error('Failed to fetch planned adventures');
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let planned = (await plannedFetch.json()) as Adventure[];
|
||||
return {
|
||||
props: {
|
||||
planned
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}) satisfies PageServerLoad;
|
||||
94
frontend/src/routes/planner/+page.svelte
Normal file
94
frontend/src/routes/planner/+page.svelte
Normal file
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
||||
import NewAdventure from '$lib/components/NewAdventure.svelte';
|
||||
import type { Adventure } from '$lib/types';
|
||||
import Plus from '~icons/mdi/plus';
|
||||
import type { PageData } from './$types';
|
||||
import EditAdventure from '$lib/components/EditAdventure.svelte';
|
||||
|
||||
export let data: PageData;
|
||||
console.log(data);
|
||||
|
||||
let adventures: Adventure[] = data.props.planned;
|
||||
let isShowingCreateModal: boolean = false;
|
||||
|
||||
let adventureToEdit: Adventure;
|
||||
let isEditModalOpen: boolean = false;
|
||||
|
||||
function deleteAdventure(event: CustomEvent<number>) {
|
||||
adventures = adventures.filter((adventure) => adventure.id !== event.detail);
|
||||
}
|
||||
|
||||
function createAdventure(event: CustomEvent<Adventure>) {
|
||||
adventures = [event.detail, ...adventures];
|
||||
isShowingCreateModal = false;
|
||||
}
|
||||
|
||||
function editAdventure(event: CustomEvent<Adventure>) {
|
||||
adventureToEdit = event.detail;
|
||||
isEditModalOpen = true;
|
||||
}
|
||||
|
||||
function saveEdit(event: CustomEvent<Adventure>) {
|
||||
adventures = adventures.map((adventure) => {
|
||||
if (adventure.id === event.detail.id) {
|
||||
return event.detail;
|
||||
}
|
||||
return adventure;
|
||||
});
|
||||
isEditModalOpen = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isShowingCreateModal}
|
||||
<NewAdventure
|
||||
type="planned"
|
||||
on:create={createAdventure}
|
||||
on:close={() => (isShowingCreateModal = false)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if isEditModalOpen}
|
||||
<EditAdventure
|
||||
{adventureToEdit}
|
||||
on:close={() => (isEditModalOpen = false)}
|
||||
on:saveEdit={saveEdit}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<div class="fixed bottom-4 right-4 z-[999]">
|
||||
<div class="flex flex-row items-center justify-center gap-4">
|
||||
<div class="dropdown dropdown-top dropdown-end">
|
||||
<div tabindex="0" role="button" class="btn m-1 size-16 btn-primary">
|
||||
<Plus class="w-8 h-8" />
|
||||
</div>
|
||||
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
|
||||
<ul
|
||||
tabindex="0"
|
||||
class="dropdown-content z-[1] menu p-4 shadow bg-base-300 text-base-content rounded-box w-52 gap-4"
|
||||
>
|
||||
<p class="text-center font-bold text-lg">Create new...</p>
|
||||
<button class="btn btn-primary" on:click={() => (isShowingCreateModal = true)}
|
||||
>Planned Adventure</button
|
||||
>
|
||||
<!-- <button
|
||||
class="btn btn-primary"
|
||||
on:click={() => (isShowingNewTrip = true)}>Trip Planner</button
|
||||
> -->
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 class="text-center font-bold text-4xl mb-4">Visited Adventures</h1>
|
||||
<div class="flex flex-wrap gap-4 mr-4 ml-4 justify-center content-center">
|
||||
{#each adventures as adventure}
|
||||
<AdventureCard type="planned" {adventure} on:delete={deleteAdventure} on:edit={editAdventure} />
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if adventures.length === 0}
|
||||
<div class="flex justify-center items-center h-96">
|
||||
<p class="text-2xl text-primary-content">No planned adventures yet!</p>
|
||||
</div>
|
||||
{/if}
|
||||
145
frontend/src/routes/settings/+page.server.ts
Normal file
145
frontend/src/routes/settings/+page.server.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { fail, redirect, type Actions } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from '../$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { User } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
if (!event.cookies.get('auth')) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
let res = await fetch(`${endpoint}/auth/user/`, {
|
||||
headers: {
|
||||
Cookie: event.cookies.get('auth') || ''
|
||||
}
|
||||
});
|
||||
let user = (await res.json()) as User;
|
||||
|
||||
if (!res.ok) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
user
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
changeDetails: async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
if (!event.cookies.get('auth')) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
|
||||
try {
|
||||
const formData = await event.request.formData();
|
||||
|
||||
let username = formData.get('username') as string | null | undefined;
|
||||
let first_name = formData.get('first_name') as string | null | undefined;
|
||||
let last_name = formData.get('last_name') as string | null | undefined;
|
||||
let profile_pic = formData.get('profile_pic') as File | null | undefined;
|
||||
|
||||
const resCurrent = await fetch(`${endpoint}/auth/user/`, {
|
||||
headers: {
|
||||
Cookie: event.cookies.get('auth') || ''
|
||||
}
|
||||
});
|
||||
|
||||
if (!resCurrent.ok) {
|
||||
return fail(resCurrent.status, await resCurrent.json());
|
||||
}
|
||||
|
||||
let currentUser = (await resCurrent.json()) as User;
|
||||
|
||||
if (username === currentUser.username) {
|
||||
username = undefined;
|
||||
}
|
||||
if (first_name === currentUser.first_name) {
|
||||
first_name = undefined;
|
||||
}
|
||||
if (last_name === currentUser.last_name) {
|
||||
last_name = undefined;
|
||||
}
|
||||
if (currentUser.profile_pic && !profile_pic) {
|
||||
profile_pic = undefined;
|
||||
}
|
||||
|
||||
let formDataToSend = new FormData();
|
||||
if (username) {
|
||||
formDataToSend.append('username', username);
|
||||
}
|
||||
if (first_name) {
|
||||
formDataToSend.append('first_name', first_name);
|
||||
}
|
||||
if (last_name) {
|
||||
formDataToSend.append('last_name', last_name);
|
||||
}
|
||||
if (profile_pic) {
|
||||
formDataToSend.append('profile_pic', profile_pic);
|
||||
}
|
||||
|
||||
let res = await fetch(`${endpoint}/auth/user/`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Cookie: event.cookies.get('auth') || ''
|
||||
},
|
||||
body: formDataToSend
|
||||
});
|
||||
|
||||
let response = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
// change the first key in the response to 'message' for the fail function
|
||||
response = { message: Object.values(response)[0] };
|
||||
return fail(res.status, response);
|
||||
}
|
||||
|
||||
let user = response as User;
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
return { error: 'An error occurred while processing your request.' };
|
||||
}
|
||||
},
|
||||
changePassword: async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
if (!event.cookies.get('auth')) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
console.log('changePassword');
|
||||
const formData = await event.request.formData();
|
||||
|
||||
const password1 = formData.get('password1') as string | null | undefined;
|
||||
const password2 = formData.get('password2') as string | null | undefined;
|
||||
|
||||
if (password1 !== password2) {
|
||||
return fail(400, { message: 'Passwords do not match' });
|
||||
}
|
||||
|
||||
let res = await fetch(`${endpoint}/auth/password/change/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: event.cookies.get('auth') || '',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
new_password1: password1,
|
||||
new_password2: password2
|
||||
})
|
||||
});
|
||||
if (!res.ok) {
|
||||
return fail(res.status, await res.json());
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
};
|
||||
133
frontend/src/routes/settings/+page.svelte
Normal file
133
frontend/src/routes/settings/+page.svelte
Normal file
@@ -0,0 +1,133 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { goto, invalidateAll } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
import { addToast } from '$lib/toasts';
|
||||
import type { User } from '$lib/types.js';
|
||||
import { onMount } from 'svelte';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
export let data;
|
||||
let user: User;
|
||||
if (data.user) {
|
||||
user = data.user;
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
if (browser) {
|
||||
const queryParams = new URLSearchParams($page.url.search);
|
||||
const pageParam = queryParams.get('page');
|
||||
|
||||
if (pageParam === 'success') {
|
||||
addToast('success', 'Settings updated successfully!');
|
||||
console.log('Settings updated successfully!');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$: {
|
||||
if (browser && $page.form?.success) {
|
||||
window.location.href = '/settings?page=success';
|
||||
}
|
||||
if (browser && $page.form?.error) {
|
||||
addToast('error', 'Error updating settings');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1 class="text-center font-extrabold text-4xl mb-6">Settings Page</h1>
|
||||
|
||||
<h1 class="text-center font-extrabold text-xl">User Account Settings</h1>
|
||||
<div class="flex justify-center">
|
||||
<form
|
||||
method="post"
|
||||
action="?/changeDetails"
|
||||
use:enhance
|
||||
class="w-full max-w-xs"
|
||||
enctype="multipart/form-data"
|
||||
>
|
||||
<label for="username">Username</label>
|
||||
<input
|
||||
bind:value={user.username}
|
||||
name="username"
|
||||
id="username"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="first_name">First Name</label>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={user.first_name}
|
||||
name="first_name"
|
||||
id="first_name"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
|
||||
<label for="last_name">Last Name</label>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={user.last_name}
|
||||
name="last_name"
|
||||
id="last_name"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<!-- <label for="first_name">Email</label>
|
||||
<input
|
||||
type="email"
|
||||
bind:value={user.email}
|
||||
name="email"
|
||||
id="email"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br /> -->
|
||||
<label for="profilePicture">Profile Picture</label>
|
||||
<input
|
||||
type="file"
|
||||
name="profile_pic"
|
||||
id="profile_pic"
|
||||
class="file-input file-input-bordered w-full max-w-xs mb-2"
|
||||
/><br />
|
||||
<button class="py-2 mt-2 px-4 btn btn-primary">Update</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if $page.form?.message}
|
||||
<div class="text-center text-error mt-4">
|
||||
{$page.form?.message}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<h1 class="text-center font-extrabold text-xl mt-4 mb-2">Password Change</h1>
|
||||
<div class="flex justify-center">
|
||||
<form action="?/changePassword" method="post" class="w-full max-w-xs">
|
||||
<input
|
||||
type="password"
|
||||
name="password1"
|
||||
placeholder="New Password"
|
||||
id="password1"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/>
|
||||
<br />
|
||||
<input
|
||||
type="password"
|
||||
name="password2"
|
||||
id="password2"
|
||||
placeholder="Confirm New Password"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/>
|
||||
<button class="py-2 px-4 btn btn-primary mt-2">Change Password</button>
|
||||
<br />
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<small class="text-center"
|
||||
><b>For Debug Use:</b> Server PK={user.pk} | Date Joined: {user.date_joined
|
||||
? new Date(user.date_joined).toDateString()
|
||||
: ''} | Staff user: {user.is_staff}</small
|
||||
>
|
||||
|
||||
<svelte:head>
|
||||
<title>User Settings | AdventureLog</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Update your user account settings here. Change your username, first name, last name, and profile icon."
|
||||
/>
|
||||
</svelte:head>
|
||||
30
frontend/src/routes/settings/forgot-password/+page.server.ts
Normal file
30
frontend/src/routes/settings/forgot-password/+page.server.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { fail, type Actions } from '@sveltejs/kit';
|
||||
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const actions: Actions = {
|
||||
forgotPassword: async (event) => {
|
||||
const formData = await event.request.formData();
|
||||
|
||||
const email = formData.get('email') as string | null | undefined;
|
||||
|
||||
if (!email) {
|
||||
return fail(400, { message: 'Email is required' });
|
||||
}
|
||||
|
||||
let res = await fetch(`${endpoint}/auth/password/reset/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email
|
||||
})
|
||||
});
|
||||
if (!res.ok) {
|
||||
return fail(res.status, { message: await res.json() });
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
};
|
||||
30
frontend/src/routes/settings/forgot-password/+page.svelte
Normal file
30
frontend/src/routes/settings/forgot-password/+page.svelte
Normal file
@@ -0,0 +1,30 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { page } from '$app/stores';
|
||||
</script>
|
||||
|
||||
<h1 class="text-center font-extrabold text-4xl mb-6">Reset Password</h1>
|
||||
|
||||
<div class="flex justify-center">
|
||||
<form method="post" action="?/forgotPassword" class="w-full max-w-xs">
|
||||
<label for="email">Email</label>
|
||||
<input
|
||||
name="email"
|
||||
type="email"
|
||||
id="email"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<button class="py-2 px-4 btn btn-primary mr-2">Reset Password</button>
|
||||
{#if $page.form?.message}
|
||||
<div class="text-center text-error mt-4">
|
||||
{$page.form?.message}
|
||||
</div>
|
||||
{/if}
|
||||
{#if $page.form?.success}
|
||||
<div class="text-center text-success mt-4">
|
||||
If the email address you provided is associated with an account, you will receive an email
|
||||
with instructions to reset your password!
|
||||
</div>
|
||||
{/if}
|
||||
</form>
|
||||
</div>
|
||||
80
frontend/src/routes/signup/+page.server.ts
Normal file
80
frontend/src/routes/signup/+page.server.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { error, fail, redirect } from '@sveltejs/kit';
|
||||
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
|
||||
export const load: PageServerLoad = async (event) => {
|
||||
if (event.locals.user) {
|
||||
return redirect(302, '/');
|
||||
}
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
default: async (event) => {
|
||||
const formData = await event.request.formData();
|
||||
const formUsername = formData.get('username');
|
||||
const password1 = formData.get('password1');
|
||||
const password2 = formData.get('password2');
|
||||
const email = formData.get('email');
|
||||
const first_name = formData.get('first_name');
|
||||
const last_name = formData.get('last_name');
|
||||
|
||||
let username = formUsername?.toString().toLocaleLowerCase();
|
||||
|
||||
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
const csrfTokenFetch = await event.fetch(`${serverEndpoint}/csrf/`);
|
||||
|
||||
if (!csrfTokenFetch.ok) {
|
||||
event.locals.user = null;
|
||||
return fail(500, { message: 'Failed to fetch CSRF token' });
|
||||
}
|
||||
|
||||
const tokenPromise = await csrfTokenFetch.json();
|
||||
const csrfToken = tokenPromise.csrfToken;
|
||||
|
||||
const loginFetch = await event.fetch(`${serverEndpoint}/auth/registration/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrfToken,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: username,
|
||||
password1: password1,
|
||||
password2: password2,
|
||||
email: email,
|
||||
first_name,
|
||||
last_name
|
||||
})
|
||||
});
|
||||
const loginResponse = await loginFetch.json();
|
||||
|
||||
if (!loginFetch.ok) {
|
||||
// get the value of the first key in the object
|
||||
const firstKey = Object.keys(loginResponse)[0] || 'error';
|
||||
const error =
|
||||
loginResponse[firstKey][0] || 'Failed to register user. Check your inputs and try again.';
|
||||
return fail(400, {
|
||||
message: error
|
||||
});
|
||||
} else {
|
||||
const token = loginResponse.access;
|
||||
const tokenFormatted = `auth=${token}`;
|
||||
const refreshToken = `${loginResponse.refresh}`;
|
||||
event.cookies.set('auth', tokenFormatted, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
|
||||
path: '/'
|
||||
});
|
||||
event.cookies.set('refresh', refreshToken, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year
|
||||
path: '/'
|
||||
});
|
||||
|
||||
return redirect(302, '/');
|
||||
}
|
||||
}
|
||||
};
|
||||
104
frontend/src/routes/signup/+page.svelte
Normal file
104
frontend/src/routes/signup/+page.svelte
Normal file
@@ -0,0 +1,104 @@
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import { goto } from '$app/navigation';
|
||||
import { getRandomQuote } from '$lib';
|
||||
import { redirect, type SubmitFunction } from '@sveltejs/kit';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
export let data;
|
||||
console.log(data);
|
||||
|
||||
import { page } from '$app/stores';
|
||||
|
||||
let quote: string = '';
|
||||
let errors: { message?: string } = {};
|
||||
let backgroundImageUrl =
|
||||
'https://images.unsplash.com/photo-1465056836041-7f43ac27dcb5?q=80&w=2942&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D';
|
||||
|
||||
onMount(async () => {
|
||||
quote = getRandomQuote();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="min-h-screen bg-no-repeat bg-cover flex items-center justify-center"
|
||||
style="background-image: url('{backgroundImageUrl}')"
|
||||
>
|
||||
<div class="card card-compact w-96 bg-base-100 shadow-xl p-6 mt-4 mb-4">
|
||||
<article class="text-center text-4xl font-extrabold">
|
||||
<h1>Signup</h1>
|
||||
</article>
|
||||
|
||||
<div class="flex justify-center">
|
||||
<form method="post" use:enhance class="w-full max-w-xs">
|
||||
<label for="username">Username</label>
|
||||
<input
|
||||
name="username"
|
||||
id="username"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="first_name">Email</label>
|
||||
<input
|
||||
name="email"
|
||||
id="email"
|
||||
type="email"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="first_name">First Name</label>
|
||||
<input
|
||||
name="first_name"
|
||||
id="first_name"
|
||||
type="text"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="first_name">Last Name</label>
|
||||
<input
|
||||
name="last_name"
|
||||
id="last_name"
|
||||
type="text"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<label for="password">Password</label>
|
||||
<input
|
||||
type="password"
|
||||
name="password1"
|
||||
id="password1"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br /><label for="password">Confirm Password</label>
|
||||
<input
|
||||
type="password"
|
||||
name="password2"
|
||||
id="password2"
|
||||
class="block mb-2 input input-bordered w-full max-w-xs"
|
||||
/><br />
|
||||
<button class="py-2 px-4 btn btn-primary">Signup</button>
|
||||
{#if $page.form?.message}
|
||||
<div class="text-center text-error mt-4">{$page.form?.message}</div>
|
||||
{/if}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{#if errors.message}
|
||||
<div class="text-center text-error mt-4">
|
||||
{errors.message}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-center mt-12 mr-25 ml-25">
|
||||
<blockquote class="w-80 text-center text-lg break-words">
|
||||
{#if quote != ''}
|
||||
{quote}
|
||||
{/if}
|
||||
<!-- <footer class="text-sm">- Steve Jobs</footer> -->
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<svelte:head>
|
||||
<title>Login | AdventureLog</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Login to your AdventureLog account to start logging your adventures!"
|
||||
/>
|
||||
</svelte:head>
|
||||
12
frontend/src/routes/toast/+page.svelte
Normal file
12
frontend/src/routes/toast/+page.svelte
Normal file
@@ -0,0 +1,12 @@
|
||||
<script>
|
||||
import { addToast } from '$lib/toasts';
|
||||
|
||||
const showToast = () => {
|
||||
addToast('success', 'This is a success message!');
|
||||
addToast('error', 'This is an error message!');
|
||||
addToast('info', 'This is an info message!');
|
||||
addToast('warning', 'This is a warning message!');
|
||||
};
|
||||
</script>
|
||||
|
||||
<button on:click={showToast}>Show Toast</button>
|
||||
28
frontend/src/routes/visited/+page.server.ts
Normal file
28
frontend/src/routes/visited/+page.server.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Adventure } from '$lib/types';
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let visitedFetch = await fetch(`${endpoint}/api/adventures/visited/`, {
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!visitedFetch.ok) {
|
||||
console.error('Failed to fetch visited adventures');
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
let visited = (await visitedFetch.json()) as Adventure[];
|
||||
return {
|
||||
props: {
|
||||
visited
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}) satisfies PageServerLoad;
|
||||
94
frontend/src/routes/visited/+page.svelte
Normal file
94
frontend/src/routes/visited/+page.svelte
Normal file
@@ -0,0 +1,94 @@
|
||||
<script lang="ts">
|
||||
import AdventureCard from '$lib/components/AdventureCard.svelte';
|
||||
import NewAdventure from '$lib/components/NewAdventure.svelte';
|
||||
import type { Adventure } from '$lib/types';
|
||||
import Plus from '~icons/mdi/plus';
|
||||
import type { PageData } from './$types';
|
||||
import EditAdventure from '$lib/components/EditAdventure.svelte';
|
||||
|
||||
export let data: PageData;
|
||||
console.log(data);
|
||||
|
||||
let adventures: Adventure[] = data.props.visited;
|
||||
let isShowingCreateModal: boolean = false;
|
||||
|
||||
let adventureToEdit: Adventure;
|
||||
let isEditModalOpen: boolean = false;
|
||||
|
||||
function deleteAdventure(event: CustomEvent<number>) {
|
||||
adventures = adventures.filter((adventure) => adventure.id !== event.detail);
|
||||
}
|
||||
|
||||
function createAdventure(event: CustomEvent<Adventure>) {
|
||||
adventures = [event.detail, ...adventures];
|
||||
isShowingCreateModal = false;
|
||||
}
|
||||
|
||||
function editAdventure(event: CustomEvent<Adventure>) {
|
||||
adventureToEdit = event.detail;
|
||||
isEditModalOpen = true;
|
||||
}
|
||||
|
||||
function saveEdit(event: CustomEvent<Adventure>) {
|
||||
adventures = adventures.map((adventure) => {
|
||||
if (adventure.id === event.detail.id) {
|
||||
return event.detail;
|
||||
}
|
||||
return adventure;
|
||||
});
|
||||
isEditModalOpen = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if isShowingCreateModal}
|
||||
<NewAdventure
|
||||
type="visited"
|
||||
on:create={createAdventure}
|
||||
on:close={() => (isShowingCreateModal = false)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if isEditModalOpen}
|
||||
<EditAdventure
|
||||
{adventureToEdit}
|
||||
on:close={() => (isEditModalOpen = false)}
|
||||
on:saveEdit={saveEdit}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<div class="fixed bottom-4 right-4 z-[999]">
|
||||
<div class="flex flex-row items-center justify-center gap-4">
|
||||
<div class="dropdown dropdown-top dropdown-end">
|
||||
<div tabindex="0" role="button" class="btn m-1 size-16 btn-primary">
|
||||
<Plus class="w-8 h-8" />
|
||||
</div>
|
||||
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
|
||||
<ul
|
||||
tabindex="0"
|
||||
class="dropdown-content z-[1] menu p-4 shadow bg-base-300 text-base-content rounded-box w-52 gap-4"
|
||||
>
|
||||
<p class="text-center font-bold text-lg">Create new...</p>
|
||||
<button class="btn btn-primary" on:click={() => (isShowingCreateModal = true)}
|
||||
>Visited Adventure</button
|
||||
>
|
||||
<!-- <button
|
||||
class="btn btn-primary"
|
||||
on:click={() => (isShowingNewTrip = true)}>Trip Planner</button
|
||||
> -->
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 class="text-center font-bold text-4xl mb-4">Visited Adventures</h1>
|
||||
<div class="flex flex-wrap gap-4 mr-4 ml-4 justify-center content-center">
|
||||
{#each adventures as adventure}
|
||||
<AdventureCard type="visited" {adventure} on:delete={deleteAdventure} on:edit={editAdventure} />
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if adventures.length === 0}
|
||||
<div class="flex justify-center items-center h-96">
|
||||
<p class="text-2xl text-primary-content">No visited adventures yet!</p>
|
||||
</div>
|
||||
{/if}
|
||||
101
frontend/src/routes/worldtravel/+page.server.ts
Normal file
101
frontend/src/routes/worldtravel/+page.server.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Country } from '$lib/types';
|
||||
import { redirect, type Actions } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
if (!event.locals.user) {
|
||||
return redirect(302, '/login');
|
||||
} else {
|
||||
const res = await fetch(`${endpoint}/api/countries/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error('Failed to fetch countries');
|
||||
return { status: 500 };
|
||||
} else {
|
||||
const countries = (await res.json()) as Country[];
|
||||
return {
|
||||
props: {
|
||||
countries
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}) satisfies PageServerLoad;
|
||||
|
||||
export const actions: Actions = {
|
||||
markVisited: async (event) => {
|
||||
const body = await event.request.json();
|
||||
|
||||
if (!body || !body.regionId) {
|
||||
return {
|
||||
status: 400
|
||||
};
|
||||
}
|
||||
|
||||
if (!event.locals.user || !event.cookies.get('auth')) {
|
||||
return redirect(302, '/login');
|
||||
}
|
||||
|
||||
const res = await fetch(`${endpoint}/api/visitedregion/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ region: body.regionId })
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
console.error('Failed to mark country as visited');
|
||||
return { status: 500 };
|
||||
} else {
|
||||
return {
|
||||
status: 200,
|
||||
data: await res.json()
|
||||
};
|
||||
}
|
||||
},
|
||||
removeVisited: async (event) => {
|
||||
const body = await event.request.json();
|
||||
|
||||
console.log(body);
|
||||
|
||||
if (!body || !body.visitId) {
|
||||
return {
|
||||
status: 400
|
||||
};
|
||||
}
|
||||
|
||||
const visitId = body.visitId as number;
|
||||
|
||||
if (!event.locals.user || !event.cookies.get('auth')) {
|
||||
return redirect(302, '/login');
|
||||
}
|
||||
|
||||
const res = await fetch(`${endpoint}/api/visitedregion/${visitId}/`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (res.status !== 204) {
|
||||
console.error('Failed to remove country from visited');
|
||||
return { status: 500 };
|
||||
} else {
|
||||
return {
|
||||
status: 200
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
24
frontend/src/routes/worldtravel/+page.svelte
Normal file
24
frontend/src/routes/worldtravel/+page.svelte
Normal file
@@ -0,0 +1,24 @@
|
||||
<script lang="ts">
|
||||
import CountryCard from '$lib/components/CountryCard.svelte';
|
||||
import type { Country } from '$lib/types';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
export let data: PageData;
|
||||
console.log(data);
|
||||
|
||||
const countries: Country[] = data.props?.countries || [];
|
||||
</script>
|
||||
|
||||
<h1 class="text-center font-bold text-4xl mb-4">Country List</h1>
|
||||
|
||||
<div class="flex flex-wrap gap-4 mr-4 ml-4 justify-center content-center">
|
||||
{#each countries as country}
|
||||
<CountryCard countryCode={country.country_code} countryName={country.name} />
|
||||
<!-- <p>Name: {item.name}, Continent: {item.continent}</p> -->
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<svelte:head>
|
||||
<title>WorldTravel | AdventureLog</title>
|
||||
<meta name="description" content="Explore the world and add countries to your visited list!" />
|
||||
</svelte:head>
|
||||
45
frontend/src/routes/worldtravel/[id]/+page.server.ts
Normal file
45
frontend/src/routes/worldtravel/[id]/+page.server.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
import type { Region, VisitedRegion } from '$lib/types';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
|
||||
export const load = (async (event) => {
|
||||
const id = event.params.id;
|
||||
|
||||
let regions: Region[] = [];
|
||||
let visitedRegions: VisitedRegion[] = [];
|
||||
|
||||
let res = await fetch(`${endpoint}/api/${id}/regions/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error('Failed to fetch regions');
|
||||
return { status: 500 };
|
||||
} else {
|
||||
regions = (await res.json()) as Region[];
|
||||
}
|
||||
|
||||
res = await fetch(`${endpoint}/api/${id}/visits/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Cookie: `${event.cookies.get('auth')}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error('Failed to fetch visited regions');
|
||||
return { status: 500 };
|
||||
} else {
|
||||
visitedRegions = (await res.json()) as VisitedRegion[];
|
||||
}
|
||||
|
||||
return {
|
||||
props: {
|
||||
regions,
|
||||
visitedRegions
|
||||
}
|
||||
};
|
||||
}) satisfies PageServerLoad;
|
||||
25
frontend/src/routes/worldtravel/[id]/+page.svelte
Normal file
25
frontend/src/routes/worldtravel/[id]/+page.svelte
Normal file
@@ -0,0 +1,25 @@
|
||||
<script lang="ts">
|
||||
import RegionCard from '$lib/components/RegionCard.svelte';
|
||||
import type { Region, VisitedRegion } from '$lib/types';
|
||||
import type { PageData } from './$types';
|
||||
export let data: PageData;
|
||||
let regions: Region[] = data.props?.regions || [];
|
||||
let visitedRegions: VisitedRegion[] = data.props?.visitedRegions || [];
|
||||
|
||||
console.log(data);
|
||||
</script>
|
||||
|
||||
<h1 class="text-center font-bold text-4xl mb-4">Regions</h1>
|
||||
|
||||
<div class="flex flex-wrap gap-4 mr-4 ml-4 justify-center content-center">
|
||||
{#each regions as region}
|
||||
<RegionCard
|
||||
{region}
|
||||
visited={visitedRegions.some((visitedRegion) => visitedRegion.region === region.id)}
|
||||
on:visit={(e) => {
|
||||
visitedRegions = [...visitedRegions, e.detail];
|
||||
}}
|
||||
visit_id={visitedRegions.find((visitedRegion) => visitedRegion.region === region.id)?.id}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
Reference in New Issue
Block a user