Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: clean up auth code #28

Merged
merged 5 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified prisma/dev.db
Binary file not shown.
15 changes: 7 additions & 8 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ datasource db {
model User {
id String @id @unique @default(cuid())

email String @unique
email String @unique
firstName String
lastName String
verified Boolean @default(false)
receiveEmail Boolean @default(true)
token String? @unique
// createdAt DateTime @default(now()) @db.Timestamp(6)
// updatedAt DateTime @updatedAt @db.Timestamp(6)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
verified Boolean @default(false)
receiveEmail Boolean @default(true)
token String? @unique

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

auth_session Session[]
key Key[]
Expand Down
10 changes: 4 additions & 6 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@ import { auth } from "$lib/server/lucia";
export const handleError: HandleServerError = async ({ error, event }) => {
const errorId = crypto.randomUUID();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
event.locals.error = error?.toString() || undefined;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
event.locals.errorStackTrace = error?.stack || undefined;
event.locals.error = error?.toString() ?? "";

// @ts-expect-error stack property should exist on error
event.locals.errorStackTrace = error?.stack ?? "";
event.locals.errorId = errorId;

return {
Expand Down
60 changes: 29 additions & 31 deletions src/routes/auth/login/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { fail, redirect } from "@sveltejs/kit";
import { fail, redirect, type RequestEvent } from "@sveltejs/kit";
import { setError, superValidate } from "sveltekit-superforms/server";

import type { RouteParams } from "../$types";

import { userSchema } from "$lib/config/zod-schemas";
import { auth } from "$lib/server/lucia";

Expand All @@ -20,34 +22,30 @@ export const load = async (event) => {
};

export const actions = {
default: async (event) => {
const form = await superValidate(event, loginSchema);
// console.log(form);

if (!form.valid) {
return fail(400, {
form,
});
}

//add user to db
try {
const key = await auth.useKey("email", form.data.email.toLowerCase(), form.data.password);

const session = await auth.createSession({
userId: key.userId,
attributes: {},
});

event.locals.auth.setSession(session);
} catch (e) {
//TODO: need to return error message to client
console.error(e);
// email already in use
//const { fieldErrors: errors } = e.flatten();
return setError(form, "", "The email or password is incorrect.");
}

return { form };
},
default: login,
};

async function login(event: RequestEvent<RouteParams, "/auth/login">) {
const form = await superValidate(event, loginSchema);

if (!form.valid) {
return fail(400, { form });
}

try {
const key = await auth.useKey("email", form.data.email.toLowerCase(), form.data.password);

const session = await auth.createSession({
userId: key.userId,
attributes: {},
});

event.locals.auth.setSession(session);
} catch (e) {
console.error(e);
// Handle the error, assume it's an incorrect email or password for simplicity
return setError(form, "", "The email or password is incorrect.");
}

return { form };
}
24 changes: 15 additions & 9 deletions src/routes/auth/logout/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@ import { redirect } from "@sveltejs/kit";
import { auth } from "$lib/server/lucia";

export const actions = {
default: async ({ locals }) => {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, "/auth");
}
await auth.invalidateSession(session.sessionId); // invalidate session
locals.auth.setSession(null); // remove cookie
throw redirect(302, "/auth");
},
default: logout,
};

interface LogoutInterface {
locals: App.Locals;
}

async function logout({ locals }: LogoutInterface) {
const session = await locals.auth.validate();
if (!session) {
throw redirect(302, "/auth");
}
await auth.invalidateSession(session.sessionId); // Invalidate session
locals.auth.setSession(null); // Remove cookie
throw redirect(302, "/auth"); // Redirect to auth page
}
83 changes: 42 additions & 41 deletions src/routes/auth/register/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { fail, redirect } from "@sveltejs/kit";
import { fail, redirect, type RequestEvent } from "@sveltejs/kit";
import { setError, superValidate } from "sveltekit-superforms/server";

// import { sendVerificationEmail } from "$lib/config/email-messages";

import type { RouteParams } from "../$types";

import { userSchema } from "$lib/config/zod-schemas";
import { auth } from "$lib/server/lucia";

Expand All @@ -24,49 +26,48 @@ export const load = async (event) => {
};

export const actions = {
default: async (event) => {
const form = await superValidate(event, signUpSchema);
//console.log(form);
default: register,
};

if (!form.valid) {
return fail(400, {
form,
});
}
async function register(event: RequestEvent<RouteParams, "/auth/register">) {
const form = await superValidate(event, signUpSchema);

//add user to db
try {
console.log("creating user");
const token = crypto.randomUUID();
if (!form.valid) {
return fail(400, {
form,
});
}

const user = await auth.createUser({
key: {
providerId: "email",
providerUserId: form.data.email.toLowerCase(),
password: form.data.password,
},
attributes: {
email: form.data.email.toLowerCase(),
firstName: form.data.firstName,
lastName: form.data.lastName,
// role: "USER",
verified: false,
receiveEmail: true,
token: token,
},
});
try {
const token = crypto.randomUUID();

// await sendVerificationEmail(form.data.email, token);
const user = await auth.createUser({
key: {
providerId: "email",
providerUserId: form.data.email.toLowerCase(),
password: form.data.password,
},
attributes: {
email: form.data.email.toLowerCase(),
firstName: form.data.firstName,
lastName: form.data.lastName,
// role: "USER",
verified: false,
receiveEmail: true,
token: token,
},
});

const session = await auth.createSession({ userId: user.userId, attributes: {} });
event.locals.auth.setSession(session);
} catch (e) {
console.error(e);
// email already in use
//might be other type of error but this is most common and this is how lucia docs sets the error to duplicate user
return setError(form, "email", "A user with that email already exists.");
}
// await sendVerificationEmail(form.data.email, token);

return { form };
},
};
const session = await auth.createSession({ userId: user.userId, attributes: {} });
event.locals.auth.setSession(session);
} catch (e) {
console.error(e);
// email already in use
// might be other type of error but this is most common and this is how lucia docs sets the error to duplicate user
return setError(form, "email", "A user with that email already exists.");
}

return { form };
}
Loading