Update Lucia to V2, add APIs for user interactions, and fix anything to get the build working.

This commit is contained in:
Bradley Shellnut 2023-07-29 22:00:51 -07:00
parent 4905ee152c
commit 1f1d9d7838
20 changed files with 814 additions and 630 deletions

View file

@ -22,37 +22,38 @@
"seed": "ts-node --esm prisma/seed.ts" "seed": "ts-node --esm prisma/seed.ts"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.36.1", "@playwright/test": "^1.36.2",
"@sveltejs/adapter-auto": "^1.0.3", "@sveltejs/adapter-auto": "^1.0.3",
"@sveltejs/adapter-vercel": "^1.0.6", "@sveltejs/adapter-vercel": "^1.0.6",
"@sveltejs/kit": "^1.22.3", "@sveltejs/kit": "^1.22.3",
"@types/cookie": "^0.5.1", "@types/cookie": "^0.5.1",
"@types/node": "^18.16.19", "@types/node": "^18.17.1",
"@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0", "@typescript-eslint/parser": "^5.62.0",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"eslint": "^8.45.0", "eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-svelte": "^2.32.2", "eslint-plugin-svelte": "^2.32.4",
"just-clone": "^6.2.0", "just-clone": "^6.2.0",
"just-debounce-it": "^3.2.0", "just-debounce-it": "^3.2.0",
"postcss": "^8.4.26", "postcss": "^8.4.27",
"postcss-import": "^15.1.0", "postcss-import": "^15.1.0",
"postcss-load-config": "^4.0.1", "postcss-load-config": "^4.0.1",
"postcss-preset-env": "^8.5.1", "postcss-preset-env": "^8.5.1",
"prettier": "^2.8.8", "prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1", "prettier-plugin-svelte": "^2.10.1",
"prisma": "^4.16.2", "prisma": "^4.16.2",
"sass": "^1.63.6", "sass": "^1.64.1",
"svelte": "^4.0.0", "svelte": "^4.1.1",
"svelte-check": "^3.4.3", "svelte-check": "^3.4.6",
"svelte-preprocess": "^5.0.4", "svelte-preprocess": "^5.0.4",
"sveltekit-superforms": "^1.3.0", "sveltekit-flash-message": "^2.1.0",
"sveltekit-superforms": "^1.5.0",
"tailwindcss": "^3.3.3", "tailwindcss": "^3.3.3",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tslib": "^2.6.0", "tslib": "^2.6.1",
"typescript": "^5.0.0", "typescript": "^5.1.6",
"vite": "^4.4.4", "vite": "^4.4.7",
"vitest": "^0.25.3", "vitest": "^0.25.3",
"zod": "^3.21.4" "zod": "^3.21.4"
}, },
@ -69,9 +70,9 @@
"@leveluptuts/svelte-side-menu": "^1.0.5", "@leveluptuts/svelte-side-menu": "^1.0.5",
"@leveluptuts/svelte-toy": "^2.0.3", "@leveluptuts/svelte-toy": "^2.0.3",
"@lucia-auth/adapter-mysql": "^1.1.1", "@lucia-auth/adapter-mysql": "^1.1.1",
"@lucia-auth/adapter-prisma": "^2.0.0", "@lucia-auth/adapter-prisma": "^3.0.0",
"@lukeed/uuid": "^2.0.1", "@lukeed/uuid": "^2.0.1",
"@prisma/client": "4.16.1", "@prisma/client": "4.16.2",
"@types/feather-icons": "^4.29.1", "@types/feather-icons": "^4.29.1",
"class-variance-authority": "^0.6.1", "class-variance-authority": "^0.6.1",
"clsx": "^1.2.1", "clsx": "^1.2.1",
@ -80,16 +81,15 @@
"iconify-icon": "^1.0.8", "iconify-icon": "^1.0.8",
"just-kebab-case": "^4.2.0", "just-kebab-case": "^4.2.0",
"loader": "^2.1.1", "loader": "^2.1.1",
"lucia-auth": "^1.8.0", "lucia": "^2.0.0",
"lucide-svelte": "^0.256.1", "lucide-svelte": "^0.256.1",
"open-props": "^1.5.10", "open-props": "^1.5.10",
"radix-svelte": "^0.8.0", "radix-svelte": "^0.8.0",
"svelte-lazy": "^1.2.1", "svelte-lazy": "^1.2.1",
"svelte-lazy-loader": "^1.0.0", "svelte-lazy-loader": "^1.0.0",
"svelte-legos": "^0.2.1", "svelte-legos": "^0.2.1",
"sveltekit-flash-message": "^0.11.3",
"tailwind-merge": "^1.14.0", "tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.6", "tailwindcss-animate": "^1.0.6",
"zod-to-json-schema": "^3.21.4" "zod-to-json-schema": "^3.21.4"
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -22,10 +22,10 @@ model Role {
model UserRole { model UserRole {
id String @id @default(cuid()) id String @id @default(cuid())
user AuthUser @relation(fields: [user_id], references: [id]) user User @relation(fields: [user_id], references: [id])
user_id String user_id String
role Role @relation(fields: [role_id], references: [id]) role Role @relation(fields: [role_id], references: [id])
role_id String role_id String
created_at DateTime @default(now()) @db.Timestamp(6) created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6) updated_at DateTime @updatedAt @db.Timestamp(6)
@ -35,7 +35,7 @@ model UserRole {
@@map("user_roles") @@map("user_roles")
} }
model AuthUser { model User {
id String @id @default(cuid()) id String @id @default(cuid())
username String @unique username String @unique
email String? @unique email String? @unique
@ -50,39 +50,37 @@ model AuthUser {
theme String @default("system") theme String @default("system")
created_at DateTime @default(now()) @db.Timestamp(6) created_at DateTime @default(now()) @db.Timestamp(6)
updated_at DateTime @updatedAt @db.Timestamp(6) updated_at DateTime @updatedAt @db.Timestamp(6)
auth_session AuthSession[] auth_session Session[]
auth_key AuthKey[] auth_key Key[]
@@map("auth_user") @@map("users")
} }
model AuthSession { model Session {
id String @id @unique id String @id @unique
user_id String user_id String
active_expires BigInt active_expires BigInt
idle_expires BigInt idle_expires BigInt
auth_user AuthUser @relation(references: [id], fields: [user_id], onDelete: Cascade) user User @relation(references: [id], fields: [user_id], onDelete: Cascade)
@@index([user_id]) @@index([user_id])
@@map("auth_session") @@map("sessions")
} }
model AuthKey { model Key {
id String @id @unique id String @id @unique
hashed_password String? hashed_password String?
user_id String user_id String
primary_key Boolean user User @relation(references: [id], fields: [user_id], onDelete: Cascade)
expires BigInt?
auth_user AuthUser @relation(references: [id], fields: [user_id], onDelete: Cascade)
@@index([user_id]) @@index([user_id])
@@map("auth_key") @@map("keys")
} }
model Collection { model Collection {
id String @id @default(cuid()) id String @id @default(cuid())
user_id String @unique user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id]) user User @relation(references: [id], fields: [user_id])
items CollectionItem[] items CollectionItem[]
@@index([user_id]) @@index([user_id])
@ -105,7 +103,7 @@ model Wishlist {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
user_id String @unique user_id String @unique
auth_user AuthUser @relation(references: [id], fields: [user_id]) user User @relation(references: [id], fields: [user_id])
items WishlistItem[] items WishlistItem[]
@@index([user_id]) @@index([user_id])

13
src/app.d.ts vendored
View file

@ -2,9 +2,9 @@
// for information about these interfaces // for information about these interfaces
// and what to do when importing types // and what to do when importing types
import type { AuthUser } from '@prisma/client'; import type { User } from '@prisma/client';
type User = Omit<AuthUser, 'created_at' | 'updated_at'>; type User = Omit<User, 'created_at' | 'updated_at'>;
// src/app.d.ts // src/app.d.ts
declare global { declare global {
@ -13,7 +13,7 @@ declare global {
flash?: { type: 'success' | 'error'; message: string }; flash?: { type: 'success' | 'error'; message: string };
} }
interface Locals { interface Locals {
auth: import('lucia-auth').AuthRequest; auth: import('lucia').AuthRequest;
prisma: PrismaClient; prisma: PrismaClient;
user: Lucia.UserAttributes; user: Lucia.UserAttributes;
startTimer: number; startTimer: number;
@ -34,11 +34,12 @@ declare global {
// interface Error {} // interface Error {}
// interface Platform {} // interface Platform {}
/// <reference types="lucia-auth" /> /// <reference types="lucia" />
declare global { declare global {
namespace Lucia { namespace Lucia {
type Auth = import('$lib/lucia').Auth; type Auth = import('$lib/server/lucia').Auth;
type UserAttributes = User; type DatabaseUserAttributes = User;
type DatabaseSessionAttributes = {};
} }
} }

View file

@ -1,18 +1,18 @@
import { auth } from '$lib/server/lucia'; import { auth } from '$lib/server/lucia';
import prisma from '$lib/prisma'; import prisma from '$lib/prisma';
import type { AuthUser } from '@prisma/client'; import type { User } from '@prisma/client';
import { add_user_to_role } from './roles'; import { add_user_to_role } from './roles';
export function create_user(user: AuthUser) { export function create_user(user: User) {
return prisma.authUser.create({ return prisma.user.create({
data: { data: {
username: user.username username: user.username
} }
}); });
} }
export async function find_or_create_user(user: AuthUser) { export async function find_or_create_user(user: User) {
const existing_user = await prisma.authUser.findUnique({ const existing_user = await prisma.user.findUnique({
where: { where: {
username: user.username username: user.username
} }
@ -27,7 +27,7 @@ export async function find_or_create_user(user: AuthUser) {
} }
export async function find_user_with_roles(user_id: string) { export async function find_user_with_roles(user_id: string) {
const user_with_roles = await prisma.authUser.findUnique({ const user_with_roles = await prisma.user.findUnique({
where: { where: {
id: user_id id: user_id
}, },

View file

@ -1,9 +1,8 @@
import { sequence } from '@sveltejs/kit/hooks'; import { sequence } from '@sveltejs/kit/hooks';
import { redirect, type HandleServerError, type Handle } from '@sveltejs/kit'; import { type HandleServerError, type Handle } from '@sveltejs/kit';
import { dev } from '$app/environment'; import { dev } from '$app/environment';
import { auth } from '$lib/server/lucia'; import { auth } from '$lib/server/lucia';
import log from '$lib/server/log'; import log from '$lib/server/log';
import prisma from '$lib/config/prisma';
export const handleError: HandleServerError = async ({ error, event }) => { export const handleError: HandleServerError = async ({ error, event }) => {
const errorId = crypto.randomUUID(); const errorId = crypto.randomUUID();
@ -36,13 +35,21 @@ export const authentication: Handle = async function ({ event, resolve }) {
event.locals.startTimer = startTimer; event.locals.startTimer = startTimer;
event.locals.auth = auth.handleRequest(event); event.locals.auth = auth.handleRequest(event);
if (event.locals?.auth) { if (event?.locals?.auth) {
const { user } = await event.locals.auth.validateUser(); console.log('auth not empty');
event.locals.user = user; try {
// if (event.route.id?.startsWith('/(protected)')) { const session = await event.locals.auth.validate();
// if (!user) throw redirect(302, '/auth/sign-in'); console.log('user', session?.user);
// if (!user.verified) throw redirect(302, '/auth/verify/email'); event.locals.user = session?.user;
// } // if (event.route.id?.startsWith('/(protected)')) {
// if (!user) throw redirect(302, '/auth/sign-in');
// if (!user.verified) throw redirect(302, '/auth/verify/email');
// }
} catch (error) {
console.error('Error validating user', error);
}
} else {
console.log('auth empty');
} }
const response = await resolve(event); const response = await resolve(event);

View file

@ -20,21 +20,22 @@
import type { ListGameSchema } from '$lib/zodValidation'; import type { ListGameSchema } from '$lib/zodValidation';
import type { CollectionItem } from '@prisma/client'; import type { CollectionItem } from '@prisma/client';
export let data: SuperValidated<ListGameSchema>; // export let data: SuperValidated<ListGameSchema>;
export let game: GameType | CollectionItem; export let game: GameType | CollectionItem;
export let detailed: boolean = false; export let detailed: boolean = false;
const { form, errors, enhance, delayed } = superForm(data); // const { form, errors, enhance, delayed } = superForm(data);
// data={modifyListForm}
const dispatch = createEventDispatcher(); // const dispatch = createEventDispatcher();
function removeGameFromWishlist() { // function removeGameFromWishlist() {
dispatch('handleRemoveWishlist', game); // dispatch('handleRemoveWishlist', game);
} // }
function removeGameFromCollection() { // function removeGameFromCollection() {
dispatch('handleRemoveCollection', game); // dispatch('handleRemoveCollection', game);
} // }
function onCollectionClick() { function onCollectionClick() {
if (existsInCollection) { if (existsInCollection) {
@ -88,16 +89,16 @@
<article class="grid grid-template-cols-2 gap-4" transition:fade|global> <article class="grid grid-template-cols-2 gap-4" transition:fade|global>
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>{game.game_name}</CardTitle> <CardTitle>{game.name}</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<a <a
class="thumbnail" class="thumbnail"
href={`/game/${game.game_id}`} href={`/game/${game.id}`}
title={`View ${game.game_name}`} title={`View ${game.game_name}`}
data-sveltekit-preload-data data-sveltekit-preload-data
> >
<img src={game.thumb_url} alt={`Image of ${game.game_name}`} loading="lazy" decoding="async" /> <img src={game.thumb_url} alt={`Image of ${game.name}`} loading="lazy" decoding="async" />
<div class="game-details"> <div class="game-details">
{#if game?.players} {#if game?.players}
<p>Players: {game.players}</p> <p>Players: {game.players}</p>
@ -114,7 +115,7 @@
</CardContent> </CardContent>
<CardFooter> <CardFooter>
<div class="grid gap-2 place-items-center"> <div class="grid gap-2 place-items-center">
<form method="POST" use:enhance action={`/collection?/${existsInCollection ? 'remove' : 'add'}`}> <form method="POST" action={`/collection?/${existsInCollection ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} /> <input type="hidden" name="id" value={game.id} />
<Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onCollectionClick}> <Button variant={existsInCollection ? 'destructive' : 'default'} on:click={onCollectionClick}>
{collectionText} {collectionText}
@ -125,7 +126,7 @@
{/if} {/if}
</Button> </Button>
</form> </form>
<form method="POST" use:enhance action={`/wishlist?/${existsInWishlist ? 'remove' : 'add'}`}> <form method="POST" action={`/wishlist?/${existsInWishlist ? 'remove' : 'add'}`}>
<input type="hidden" name="id" value={game.id} /> <input type="hidden" name="id" value={game.id} />
<Button variant={existsInWishlist ? 'destructive' : 'default'} on:click={onWishlistClick}> <Button variant={existsInWishlist ? 'destructive' : 'default'} on:click={onWishlistClick}>
{wishlistText} {wishlistText}

View file

@ -29,8 +29,9 @@
export let showButton: boolean = false; export let showButton: boolean = false;
export let advancedSearch: boolean = false; export let advancedSearch: boolean = false;
const { games, totalCount } = data?.searchData;
const { form, errors, enhance, constraints, message }: SuperValidated<SearchSchema> = superForm(data.form); const { form, errors, enhance, constraints, message }: SuperValidated<SearchSchema> = superForm(data.form);
const { form: modifyListForm, errors: listErrors, constraints: listConstraints, enhance: listEnhance, message: listMessage } : SuperValidated<ListGameSchema> = superForm(data.modifyListForm); // const { form: modifyListForm, errors: listErrors, constraints: listConstraints, enhance: listEnhance, message: listMessage } : SuperValidated<ListGameSchema> = superForm(data.modifyListForm);
let gameToRemove: GameType | SavedGameType; let gameToRemove: GameType | SavedGameType;
let numberOfGameSkeleton = 1; let numberOfGameSkeleton = 1;
@ -43,8 +44,8 @@
let name = form?.name || ''; let name = form?.name || '';
let disclosureOpen = $errors.length > 0 || false; let disclosureOpen = $errors.length > 0 || false;
$: skip = (page - 1) * pageSize; // $: skip = (page - 1) * pageSize;
$: showPagination = $gameStore?.length > 1; // $: showPagination = $gameStore?.length > 1;
if ($xl) { if ($xl) {
numberOfGameSkeleton = 8; numberOfGameSkeleton = 8;
@ -222,9 +223,9 @@
<div class="games"> <div class="games">
<h1>Games Found:</h1> <h1>Games Found:</h1>
<div class="games-list"> <div class="games-list">
{#if $gameStore?.length > 0} {#if totalCount > 0}
{#each $gameStore as game (game.id)} {#each games as game (game.id)}
<Game {game} data={modifyListForm} /> <Game {game} />
{/each} {/each}
{:else} {:else}
<h2>Sorry no games found!</h2> <h2>Sorry no games found!</h2>

View file

@ -1,25 +1,26 @@
// lib/server/lucia.ts // lib/server/lucia.ts
import lucia from 'lucia-auth'; import { lucia } from 'lucia';
import { sveltekit } from 'lucia-auth/middleware'; import { sveltekit } from 'lucia/middleware';
import prisma from '@lucia-auth/adapter-prisma'; import { prisma } from '@lucia-auth/adapter-prisma';
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
import { dev } from '$app/environment'; import { dev } from '$app/environment';
const client = new PrismaClient();
export const auth = lucia({ export const auth = lucia({
adapter: prisma(new PrismaClient()), adapter: prisma(client),
env: dev ? 'DEV' : 'PROD', env: dev ? 'DEV' : 'PROD',
middleware: sveltekit(), middleware: sveltekit(),
transformDatabaseUser: (userData) => { getUserAttributes: (databaseUser) => {
return { return {
id: userData.id, username: databaseUser.username,
username: userData.username, email: databaseUser.email,
email: userData.email, firstName: databaseUser.firstName,
firstName: userData.firstName, lastName: databaseUser.lastName,
lastName: userData.lastName, verified: databaseUser.verified,
verified: userData.verified, receiveEmail: databaseUser.receiveEmail,
receiveEmail: userData.receiveEmail, token: databaseUser.token,
token: userData.token, theme: databaseUser.theme
theme: userData.theme
}; };
}, },
experimental: { experimental: {

View file

@ -60,7 +60,7 @@ export const search_schema = z
exactMinPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()), exactMinPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
exactMaxPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()), exactMaxPlayers: z.preprocess((a) => Boolean(a), z.boolean().optional()),
sort: z.enum(['asc', 'desc']).optional(), sort: z.enum(['asc', 'desc']).optional(),
sortBy: z.enum(['name', 'min_players', 'max_players', 'min_age', 'times_played']).optional(), order: z.enum(['name', 'min_players', 'max_players', 'min_age', 'times_played']).optional(),
limit: z.number().min(10).max(100).default(10), limit: z.number().min(10).max(100).default(10),
skip: z.number().min(0).default(0) skip: z.number().min(0).default(0)
}) })

View file

@ -1,6 +1,11 @@
export const load = async ({ url, locals }) => { import { loadFlash } from 'sveltekit-flash-message/server';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ url, locals }) => {
return { return {
url: url.pathname, url: url.pathname,
user: locals.user user: locals.user
}; };
}; };
// loadFlash(

View file

@ -1,9 +1,11 @@
<script lang="ts"> <script lang="ts">
import "../app.postcss"; import "../app.postcss";
import { onMount } from "svelte";
// import { getFlash } from 'sveltekit-flash-message/client';
import { navigating, page } from '$app/stores';
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { navigating } from '$app/stores';
import debounce from 'just-debounce-it'; import debounce from 'just-debounce-it';
import { Toy } from '@leveluptuts/svelte-toy'; // import { Toy } from '@leveluptuts/svelte-toy';
import 'iconify-icon'; import 'iconify-icon';
import Analytics from '$lib/components/analytics.svelte'; import Analytics from '$lib/components/analytics.svelte';
import Header from '$lib/components/header/index.svelte'; import Header from '$lib/components/header/index.svelte';
@ -14,13 +16,10 @@
import { boredState } from '$lib/stores/boredState'; import { boredState } from '$lib/stores/boredState';
import { collectionStore } from '$lib/stores/collectionStore'; import { collectionStore } from '$lib/stores/collectionStore';
import { wishlistStore } from '$lib/stores/wishlistStore'; import { wishlistStore } from '$lib/stores/wishlistStore';
import { gameStore } from '$lib/stores/gameSearchStore';
import { toast } from '$lib/components/toast/toast';
import Toast from '$lib/components/toast/Toast.svelte'; import Toast from '$lib/components/toast/Toast.svelte';
import { theme } from '$state/theme'; import { theme } from '$state/theme';
// import '$styles/styles.pcss'; // import '$styles/styles.pcss';
import type { SavedGameType } from '$lib/types'; import type { SavedGameType } from '$lib/types';
import { onMount } from "svelte";
$: { $: {
if ($navigating) { if ($navigating) {
@ -34,6 +33,7 @@
} }
$: isOpen = $boredState?.dialog?.isOpen; $: isOpen = $boredState?.dialog?.isOpen;
// const flash = getFlash(page);
if (browser) { if (browser) {
const collator = new Intl.Collator('en'); const collator = new Intl.Collator('en');
@ -121,6 +121,10 @@
</div> </div>
{/if} {/if}
<Toast></Toast> <Toast></Toast>
<!-- {#if $flash}
{@const bg = $flash.type == 'success' ? '#3D9970' : '#FF4136'}
<div style:background-color={bg} class="flash">{$flash.message}</div>
{/if} -->
<style lang="postcss"> <style lang="postcss">
.loading { .loading {

View file

@ -10,9 +10,9 @@ export const load = async ({ fetch, url }) => {
return { form }; return { form };
}; };
export const actions = { // export const actions = {
default: async ({ request, locals }): Promise<any> => { // default: async ({ request, locals }): Promise<any> => {
// Do things in here // // Do things in here
return {}; // return {};
} // }
}; // };

View file

@ -24,7 +24,7 @@
<Random /> <Random />
</div> </div>
</section> </section>
<TextSearch showButton advancedSearch data={data.form} /> <!-- <TextSearch showButton advancedSearch data={data.form} /> -->
</div> </div>
<style lang="scss"> <style lang="scss">

View file

@ -0,0 +1,29 @@
import { error } from '@sveltejs/kit';
// Fetch collection for user
export function GET({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
return new Response();
}
// Create a new collection for user
export function POST({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
}
// Update or Create a collection
export function PUT({ url }) {
const searchParams = Object.fromEntries(url.searchParams);
const q = searchParams?.q;
const limit = parseInt(searchParams?.limit) || 10;
const skip = parseInt(searchParams?.skip) || 0;
}
//

View file

@ -21,7 +21,7 @@ export async function GET({ url, locals, params }) {
let collection = await prisma.collection.findUnique({ let collection = await prisma.collection.findUnique({
where: { where: {
user_id: locals.user.id user_id: locals.user.userId
} }
}); });
console.log('collection', collection); console.log('collection', collection);

View file

@ -10,6 +10,7 @@ const signInSchema = userSchema.pick({
}); });
export const load = async (event) => { export const load = async (event) => {
console.log('sign in load event', event);
const session = await event.locals.auth.validate(); const session = await event.locals.auth.validate();
if (session) { if (session) {
throw redirect(302, '/'); throw redirect(302, '/');
@ -33,7 +34,10 @@ export const actions = {
try { try {
const key = await auth.useKey('username', form.data.username, form.data.password); const key = await auth.useKey('username', form.data.username, form.data.password);
const session = await auth.createSession(key.userId); const session = await auth.createSession({
userId: key.userId,
attributes: {}
});
event.locals.auth.setSession(session); event.locals.auth.setSession(session);
const user = await prisma.authUser.findUnique({ const user = await prisma.authUser.findUnique({

View file

@ -1,5 +1,7 @@
import { fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import { setError, superValidate } from 'sveltekit-superforms/server'; import { setError, superValidate } from 'sveltekit-superforms/server';
import { redirect as flashRedirect } from 'sveltekit-flash-message/server';
import { LuciaError } from 'lucia';
import { auth } from '$lib/server/lucia'; import { auth } from '$lib/server/lucia';
import { userSchema } from '$lib/config/zod-schemas'; import { userSchema } from '$lib/config/zod-schemas';
import { add_user_to_role } from '$db/roles'; import { add_user_to_role } from '$db/roles';
@ -31,6 +33,7 @@ const signUpSchema = userSchema
}); });
export const load = async (event) => { export const load = async (event) => {
console.log('sign up load event', event);
const session = await event.locals.auth.validate(); const session = await event.locals.auth.validate();
if (session) { if (session) {
throw redirect(302, '/'); throw redirect(302, '/');
@ -57,7 +60,7 @@ export const actions = {
const token = crypto.randomUUID(); const token = crypto.randomUUID();
const user = await auth.createUser({ const user = await auth.createUser({
primaryKey: { key: {
providerId: 'username', providerId: 'username',
providerUserId: form.data.username, providerUserId: form.data.username,
password: form.data.password password: form.data.password
@ -73,28 +76,36 @@ export const actions = {
token token
} }
}); });
add_user_to_role(user.id, 'user'); console.log('signup user', user);
add_user_to_role(user.userId, 'user');
await prisma.collection.create({ await prisma.collection.create({
data: { data: {
user_id: user.id user_id: user.userId
} }
}); });
await prisma.wishlist.create({ await prisma.wishlist.create({
data: { data: {
user_id: user.id, user_id: user.userId,
name: 'My Wishlist' name: 'My Wishlist'
} }
}); });
console.log('User', user); console.log('User', user);
const session = await auth.createSession(user.id); const session = await auth.createSession({
userId: user.userId,
attributes: {}
});
event.locals.auth.setSession(session); event.locals.auth.setSession(session);
// const message = { type: 'success', message: 'Signed Up!' } as const;
// throw flashRedirect(message, event);
} catch (error) { } catch (error) {
if (error instanceof LuciaError && error.message === `DUPLICATE_KEY_ID`) {
// key already exists
console.error(error);
}
console.log(error); console.log(error);
return setError(form, '', 'Unable to create your account. Please try again.'); return setError(form, '', 'Unable to create your account. Please try again.');
} }
return { form };
} }
}; };

View file

@ -3,18 +3,9 @@
import { Image } from 'svelte-lazy-loader'; import { Image } from 'svelte-lazy-loader';
import minusCircle from '@iconify-icons/line-md/minus-circle'; import minusCircle from '@iconify-icons/line-md/minus-circle';
import plusCircle from '@iconify-icons/line-md/plus-circle'; import plusCircle from '@iconify-icons/line-md/plus-circle';
// import {
// ChevronRightIcon,
// ExternalLinkIcon,
// MinusCircleIcon,
// MinusIcon,
// PlusCircleIcon,
// PlusIcon
// } from '@rgossiaux/svelte-heroicons/outline';
import type { GameType, SavedGameType } from '$lib/types'; import type { GameType, SavedGameType } from '$lib/types';
import { collectionStore } from '$lib/stores/collectionStore'; import { collectionStore } from '$lib/stores/collectionStore';
import { wishlistStore } from '$lib/stores/wishlistStore'; import { wishlistStore } from '$lib/stores/wishlistStore';
import Button from '$lib/components/button/index.svelte';
import RemoveCollectionDialog from '$lib/components/dialog/RemoveCollectionDialog.svelte'; import RemoveCollectionDialog from '$lib/components/dialog/RemoveCollectionDialog.svelte';
import { addToCollection } from '$lib/util/manipulateCollection'; import { addToCollection } from '$lib/util/manipulateCollection';
import type { PageData } from './$types'; import type { PageData } from './$types';
@ -25,6 +16,7 @@
import RemoveWishlistDialog from '$lib/components/dialog/RemoveWishlistDialog.svelte'; import RemoveWishlistDialog from '$lib/components/dialog/RemoveWishlistDialog.svelte';
import { binarySearchOnStore } from '$lib/util/binarySearchOnStore'; import { binarySearchOnStore } from '$lib/util/binarySearchOnStore';
import { convertToSavedGame } from '$lib/util/gameMapper'; import { convertToSavedGame } from '$lib/util/gameMapper';
import { Button } from '$components/ui/button';
$: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id); $: existsInCollection = $collectionStore.find((item: SavedGameType) => item.id === game.id);
$: existsInWishlist = $wishlistStore.find((item: SavedGameType) => item.id === game.id); $: existsInWishlist = $wishlistStore.find((item: SavedGameType) => item.id === game.id);
@ -127,7 +119,7 @@
<iconify-icon icon={plusCircle} width="24" height="24" /> <iconify-icon icon={plusCircle} width="24" height="24" />
{/if} {/if}
</Button> </Button>
<Button size="md" kind={existsInWishlist ? 'danger' : 'primary'} icon on:click={onWishlistClick}> <Button kind={existsInWishlist ? 'danger' : 'primary'} icon on:click={onWishlistClick}>
{wishlistText} {wishlistText}
{#if existsInWishlist} {#if existsInWishlist}
<iconify-icon icon={minusCircle} width="24" height="24" /> <iconify-icon icon={minusCircle} width="24" height="24" />
@ -138,7 +130,7 @@
</div> </div>
{:else} {:else}
<span> <span>
<a href="/auth/signup">Sign Up</a> or <a href="/auth/signin">Sign In</a> to collect this game <Button href="/auth/signup">Sign Up</Button> or <Button href="/auth/signin">Sign In</Button> to add to a list.
</span> </span>
{/if} {/if}
</div> </div>

View file

@ -6,37 +6,75 @@ import prisma from '$lib/prisma.js';
import type { GameType, SearchQuery } from '$lib/types'; import type { GameType, SearchQuery } from '$lib/types';
import { mapAPIGameToBoredGame } from '$lib/util/gameMapper'; import { mapAPIGameToBoredGame } from '$lib/util/gameMapper';
import { search_schema } from '$lib/zodValidation'; import { search_schema } from '$lib/zodValidation';
import { listGameSchema } from '$lib/config/zod-schemas.js'; import type { PageServerLoad } from '../$types.js';
// import { listGameSchema } from '$lib/config/zod-schemas.js';
async function searchForGames(urlQueryParams: SearchQuery, locals) { /**
* Asynchronous function searchForGames to fetch games from a local and remote repository based on the given parameters.
* @async
* @function searchForGames
* @param {SearchQuery} urlQueryParams - An object that represents the search parameters. It includes properties like name, min_players,
* max_players, min_playtime, max_playtime, min_age, skip, limit which are used to define the search condition for games.
* @param {any} locals - An object that contains data related to the local server environment like user information.
* @param {Function} eventFetch - A function that fetches games from the local API.
* @returns {Object} returns an object with totalCount property which is the total number of games fetched and games property which is
* an array of all the games fetched. If any error occurred during the operation, it returns an object with totalCount as 0 and games as empty array.
* @throws will throw an error if the response received from fetching games operation is not OK (200).
*/
async function searchForGames(urlQueryParams: SearchQuery, locals, eventFetch) {
try { try {
let games = await prisma.game.findMany({ console.log('urlQueryParams search games', urlQueryParams);
where: { // let games = await prisma.game.findMany({
name: { // where: {
search: urlQueryParams?.name // name: {
}, // search: urlQueryParams?.name
min_players: { // },
gte: urlQueryParams?.min_players || 0 // min_players: {
}, // gte: urlQueryParams?.min_players || 0
max_players: { // },
lte: urlQueryParams?.max_players || 100 // max_players: {
}, // lte: urlQueryParams?.max_players || 100
min_playtime: { // },
gte: urlQueryParams?.min_playtime || 0 // min_playtime: {
}, // gte: urlQueryParams?.min_playtime || 0
max_playtime: { // },
lte: urlQueryParams?.max_playtime || 5000 // max_playtime: {
}, // lte: urlQueryParams?.max_playtime || 5000
min_age: { // },
gte: urlQueryParams?.min_age || 0 // min_age: {
} // gte: urlQueryParams?.min_age || 0
}, // }
skip: urlQueryParams?.skip, // },
take: urlQueryParams?.limit, // skip: urlQueryParams?.skip,
orderBy: { // take: urlQueryParams?.limit,
name: 'asc' // orderBy: {
} // name: 'asc'
}); // }
// });
const headers: HeadersInit = new Headers();
headers.set('Content-Type', 'application/json');
const requestInit: RequestInit = {
method: 'GET',
headers
};
const response = await eventFetch(
`/api/game/search${urlQueryParams ? `?${urlQueryParams}` : ''}`,
requestInit
);
console.log('response from internal api', response);
if (!response.ok) {
console.log('Status not 200', response.status);
throw error(response.status);
}
// const games: GameType[] = [];
// let totalCount = 0;
let games = [];
if (response.ok) {
games = await response.json();
}
console.log('games from DB', games); console.log('games from DB', games);
let totalCount = games?.length || 0; let totalCount = games?.length || 0;
@ -134,6 +172,17 @@ async function searchForGames(urlQueryParams: SearchQuery, locals) {
}; };
} }
/**
* Asynchronous function createOrUpdateGame is used to create or update a game using the given game information.
*
* @async
* @function createOrUpdateGame
* @param {GameType} game - An object that holds the details about a game. It should contain required information like name, description,
* id (both internal and external), thumbnail URL, minimum age, minimum and maximum number of players, minimum and maximum play time,
* year of publication and primary publisher information including the publisher's name and ID, categories and mechanics related to the game.
*
* @returns {Promise<Object>} The return is a Promise that resolves with the data of the game that was created or updated.
*/
async function createOrUpdateGame(game: GameType) { async function createOrUpdateGame(game: GameType) {
const categoryIds = game.categories.map((category) => ({ const categoryIds = game.categories.map((category) => ({
external_id: category.id external_id: category.id
@ -214,19 +263,21 @@ async function createOrUpdateGame(game: GameType) {
}); });
} }
export const load = async (event) => { export const load: PageServerLoad = async ({ params, locals, request, fetch, url }) => {
const { params, locals, request, fetch, url } = event;
const defaults = { const defaults = {
limit: 10, limit: 10,
skip: 0 skip: 0,
order: 'asc',
sort: 'name'
}; };
const searchParams = Object.fromEntries(url?.searchParams); const searchParams = Object.fromEntries(url?.searchParams);
console.log('searchParams', searchParams); console.log('searchParams', searchParams);
searchParams.limit = searchParams.limit || `${defaults.limit}`; searchParams.limit = searchParams.limit || `${defaults.limit}`;
searchParams.skip = searchParams.skip || `${defaults.skip}`; searchParams.skip = searchParams.skip || `${defaults.skip}`;
searchParams.order = searchParams.order || 'asc'; searchParams.order = searchParams.order || 'asc';
searchParams.sort = searchParams.sort || 'name';
const form = await superValidate(searchParams, search_schema); const form = await superValidate(searchParams, search_schema);
const modifyListForm = await superValidate(listGameSchema); // const modifyListForm = await superValidate(listGameSchema);
const queryParams: SearchQuery = { const queryParams: SearchQuery = {
order_by: 'rank', order_by: 'rank',
@ -269,11 +320,11 @@ export const load = async (event) => {
} }
const urlQueryParams = new URLSearchParams(newQueryParams); const urlQueryParams = new URLSearchParams(newQueryParams);
const searchData = await searchForGames(urlQueryParams, locals); const searchData = await searchForGames(urlQueryParams, locals, fetch);
return { return {
form, form,
modifyListForm, // modifyListForm,
searchData searchData
}; };
}; };