Skip to content

Commit

Permalink
Merge branch 'landing' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
xerosanyam committed May 23, 2024
2 parents 2943aeb + 5fa1b24 commit ffba2b4
Show file tree
Hide file tree
Showing 15 changed files with 143 additions and 61 deletions.
9 changes: 5 additions & 4 deletions sample.env.local → .env.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# rename file to .env.local

## Postgres
CONNECTION_STRING=''

## Google Auth
GOOGLE_CLIENT_ID=''
GOOGLE_CLIENT_SECRET=''
REDIRECT_URI=''
REDIRECT_URI=''

## TURSO
TURSO_CONNECTION_URL=''
TURSO_AUTH_TOKEN=''
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ node_modules
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
vite.config.ts.timestamp-*
12 changes: 6 additions & 6 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { lucia } from "$lib/server/auth";
import type { Handle } from "@sveltejs/kit";

let sessionAndUserInfo:any = {}
const sessionAndUserInfo: { [key: string]: App.Locals } = {};

export const handle: Handle = async ({ event, resolve }) => {
console.time('hook.server')
Expand All @@ -15,16 +15,16 @@ export const handle: Handle = async ({ event, resolve }) => {
console.log('session id exists')

console.time('validate')
let {session, user} = sessionAndUserInfo[sessionId]|| {}
if(!session || !user){
({ session, user } = await lucia.validateSession(sessionId))
sessionAndUserInfo[sessionId] = {session,user}
let { session, user } = sessionAndUserInfo[sessionId] || {}
if (!session || !user) {
({ session, user } = await lucia.validateSession(sessionId))
sessionAndUserInfo[sessionId] = { session, user }

}
console.timeEnd('validate')

//session exists in db & has not expired
if (session && session.fresh) {
if (session?.fresh) {
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
Expand Down
6 changes: 6 additions & 0 deletions src/lib/common.util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import type { Session, User } from "lucia";

// for debugging & simulating real-world delays
export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}

export function sessionExists(locals: App.Locals): locals is App.Locals & { session: Session, user: User } {
return !!locals?.session?.id && !!locals?.user?.id
}
13 changes: 12 additions & 1 deletion src/lib/db/tables/card.table.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { db } from '$lib/db/turso.db';
import { cardTable } from '$lib/db/turso.schema';
import { eq } from 'drizzle-orm';
import { and, eq } from 'drizzle-orm';

export const insertCard = async (values: {
id: string;
Expand All @@ -25,5 +25,16 @@ export const getCards = async (userId: string) => {
return data
} catch (err) {
console.error('getCards ~ err:', err)
return []
}
}

export const deleteCard = async ({ cardId, userId }: { cardId: string, userId: string }) => {
try {
console.time('deleteCard')
await db.delete(cardTable).where(and(eq(cardTable.id, cardId), eq(cardTable.userId, userId)))
console.timeEnd('deleteCard')
} catch (err) {
console.error('deleteCard ~ err:', err)
}
}
3 changes: 2 additions & 1 deletion src/routes/(auth)/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { sessionExists } from "$lib/common.util.js";
import { ROUTES } from "$lib/routes.util.js";
import { redirect } from "@sveltejs/kit";

export async function load({ locals }) {
console.log('auth')
if (locals.user) {
if (sessionExists(locals)) {
redirect(302, ROUTES.HOME)
}
}
29 changes: 14 additions & 15 deletions src/routes/(auth)/login/google/callback/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { google, lucia } from "$lib/server/auth";

import type { RequestEvent } from "@sveltejs/kit";
import { getGoogleUserWhereEmail, insertOrUpdateGoogleUser } from "$lib/db/tables/user.table";
import { ROUTES } from "$lib/routes.util";

export async function GET(event: RequestEvent): Promise<Response> {
const code = event.url.searchParams.get("code");
Expand All @@ -27,34 +28,32 @@ export async function GET(event: RequestEvent): Promise<Response> {
const user = await response.json();

const existingUser = await getGoogleUserWhereEmail(user.email);
let userId = null;
if (existingUser) {
await insertOrUpdateGoogleUser({
id: existingUser.id,
...user
});
const session = await lucia.createSession(existingUser.id, {});
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
...sessionCookie.attributes
});
userId = existingUser.id;
} else {
const userId = crypto.randomUUID();
const newUserId = crypto.randomUUID();
await insertOrUpdateGoogleUser({
id: userId,
id: newUserId,
...user
});
const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
...sessionCookie.attributes
});
userId = newUserId;
}

const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
...sessionCookie.attributes
});
return new Response(null, {
status: 302,
headers: {
Location: "/"
Location: ROUTES.HOME
}
});
} catch (e) {
Expand Down
3 changes: 2 additions & 1 deletion src/routes/(protected)/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { sessionExists } from "$lib/common.util.js";
import { ROUTES } from "$lib/routes.util.js";
import { redirect } from "@sveltejs/kit";

export async function load({ locals }) {
console.log('protected')
if (!locals.user) {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN)
}
}
35 changes: 35 additions & 0 deletions src/routes/(protected)/all/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { sessionExists } from '$lib/common.util.js';
import { deleteCard, getCards } from '$lib/db/tables/card.table.js';
import { ROUTES } from '$lib/routes.util.js';
import { redirect } from '@sveltejs/kit';

export async function load({ locals }) {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN)
}
const cards = await getCards(locals.user.id)
return { cards };
}

export const actions = {
delete: async function ({ locals, request }) {
const data = await request.formData();
const id = data.get('id') as string

try {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN);
}
if (!id) {
return { status: 400, body: { message: 'No id provided' } };
}
await deleteCard({
cardId: id,
userId: locals.user.id,
});
redirect(302, ROUTES.HOME);
} catch (err) {
console.error('delete ~ err:', err);
}
}
}
15 changes: 15 additions & 0 deletions src/routes/(protected)/all/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script lang="ts">
export let data;
</script>

{#each data.cards as card}
<div class="border">
<div>{card.front}</div>
<div>{card.back}</div>
<form method="post" action="?/delete">
<input type="hidden" name="id" value={card.id} />
<button type="submit">Delete</button>
</form>
<hr />
</div>
{/each}
11 changes: 7 additions & 4 deletions src/routes/(protected)/home/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import { ROUTES } from "$lib/routes.util.js";
import type { RequestEvent } from "./$types.js";
import { getCards, insertCard } from "$lib/db/tables/card.table.js";
import { cardAddSchema, cardReviewSchema } from "$lib/schemas.js";
import { sessionExists } from "$lib/common.util.js";


export async function load({ locals }) {
if (!locals?.user?.id) {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN)
}

Expand All @@ -30,8 +31,9 @@ export const actions = {
}

async function add(event: RequestEvent) {
const { locals } = event
try {
if (!event.locals.user) {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN);
}

Expand All @@ -44,7 +46,7 @@ async function add(event: RequestEvent) {
id: crypto.randomUUID(),
front: form.data.front,
back: form.data.back,
userId: event.locals.user.id
userId: locals.user.id
});

redirect(302, ROUTES.HOME);
Expand All @@ -54,8 +56,9 @@ async function add(event: RequestEvent) {
}

async function review(event: RequestEvent) {
const { locals } = event
try {
if (!event.locals.user) {
if (!sessionExists(locals)) {
redirect(302, ROUTES.LOGIN);
}

Expand Down
10 changes: 9 additions & 1 deletion src/routes/(protected)/home/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,28 @@
export let data;
</script>

<img src={data.user?.picture} alt="User's display" />
<h1>Hey {data.user?.name},</h1>

<ol type="A">
<li>
<CardAddTable data={data.addForm} />
<hr />
</li>
<li>
<CardReviewTable data={data.reviewForm} />
{#if data.cards.length > 0}
<CardReviewTable data={data.reviewForm} card={data.cards[0]} />
{/if}
Total cards: {data.cards?.length}
<hr />
</li>
<li>
<h2>Others</h2>
<nav>
<ol>
<li>
<a href="/all">All Cards</a>
</li>
<li>
<Logout />
</li>
Expand Down
52 changes: 27 additions & 25 deletions src/routes/(protected)/home/CardReviewTable.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,30 @@
export let data: SuperValidated<Infer<CardReviewSchema>>;
const { errors } = superForm(data);
export let card;
</script>

<h2>Try to recall the answer</h2>
<form method="post" action="?/review">
<table>
<tbody>
<tr>
<th>Question: </th>
<td> What is wealth? </td>
</tr>
<tr>
<th>Answer:</th>
<td>
<details>
<summary>Show Answer</summary>
<p>Assets that earn while you sleep</p>
</details>
</td>
</tr>
<tr>
<th>Action(s):</th>
<td>
<table>
<tbody>
<tr>
<th>Question: </th>
<td>{card.front}</td>
</tr>
<tr>
<th>Answer:</th>
<td>
<details>
<summary>Show Answer</summary>
<p>{card.back}</p>
</details>
</td>
</tr>
<tr>
<th>Action(s):</th>
<td>
<form method="post" action="?/review">
<fieldset>
<legend>How difficult was it to remember ?</legend>
<ol>
Expand All @@ -36,9 +38,9 @@
{/each}
</ol>
</fieldset>
</td>
{#if $errors.difficulty}<td>{$errors.difficulty}</td>{/if}
</tr>
</tbody>
</table>
</form>
</form>
</td>
{#if $errors.difficulty}<td>{$errors.difficulty}</td>{/if}
</tr>
</tbody>
</table>
3 changes: 2 additions & 1 deletion src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { sessionExists } from "$lib/common.util.js";
import { ROUTES } from "$lib/routes.util.js";
import { redirect } from "@sveltejs/kit";

export async function load({ locals }) {
if (locals.user) {
if (sessionExists(locals)) {
redirect(302, ROUTES.HOME)
}
}
1 change: 0 additions & 1 deletion src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<script>
export const prerender = true;
import Google from '$lib/components/Google.svelte';
import { ROUTES } from '$lib/routes.util';
</script>
Expand Down

0 comments on commit ffba2b4

Please sign in to comment.