1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-08-05 05:05:17 +02:00

Merge pull request #71 from seanmorley15/TripAdventure

Trip adventure
This commit is contained in:
Sean Morley 2024-05-24 15:26:47 -04:00 committed by GitHub
commit b406802058
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 208 additions and 86 deletions

View file

@ -18,7 +18,15 @@ export const load: PageServerLoad = async (event) => {
export const actions: Actions = {
default: async (event) => {
const formData = await event.request.formData();
const username = formData.get("username");
const formUsername = formData.get("username");
let username = formUsername?.toString().toLocaleLowerCase();
if (typeof formUsername !== "string") {
return error(400, {
message: "Invalid username",
});
}
const password = formData.get("password");
if (!username || !password) {
@ -31,7 +39,7 @@ export const actions: Actions = {
typeof username !== "string" ||
username.length < 3 ||
username.length > 31 ||
!/^[a-z0-9_-]+$/.test(username)
!/^[a-zA-Z0-9_-]+$/.test(username)
) {
return error(400, {
message: "Invalid username",
@ -86,6 +94,5 @@ export const actions: Actions = {
});
return redirect(302, "/");
},
};

View file

@ -1,4 +1,10 @@
import { error, redirect, type Actions, type Handle } from "@sveltejs/kit";
import {
error,
fail,
redirect,
type Actions,
type Handle,
} from "@sveltejs/kit";
import type { PageServerLoad } from "./$types";
import { db } from "$lib/db/db.server";
import {
@ -8,8 +14,10 @@ import {
userTable,
userVisitedWorldTravel,
} from "$lib/db/schema";
import type { DatabaseUser } from "$lib/server/auth";
import { lucia, type DatabaseUser } from "$lib/server/auth";
import { count, eq } from "drizzle-orm";
import { generateId } from "lucia";
import { Argon2id } from "oslo/password";
export const load: PageServerLoad = async (event) => {
let users: DatabaseUser[] = [];
@ -86,4 +94,111 @@ export const actions: Actions = {
};
}
},
adduser: async (event) => {
const formData = await event.request.formData();
const formUsername = formData.get("username");
let username = formUsername?.toString().toLocaleLowerCase();
if (typeof formUsername !== "string") {
return fail(400, { message: "Invalid username" });
}
const password = formData.get("password");
const firstName = formData.get("first_name");
const lastName = formData.get("last_name");
// username must be between 4 ~ 31 characters, and only consists of lowercase letters, 0-9, -, and _
// keep in mind some database (e.g. mysql) are case insensitive
if (!event.locals.user) {
return redirect(302, "/");
}
// check all to make sure all fields are provided
if (!username || !password || !firstName || !lastName) {
return fail(400, { message: "All fields are required" });
}
if (!event.locals.user || event.locals.user.role !== "admin") {
return fail(403, {
message: "You are not authorized to perform this action",
});
}
if (
typeof username !== "string" ||
username.length < 3 ||
username.length > 31 ||
!/^[a-zA-Z0-9_-]+$/.test(username)
) {
return fail(400, {
message: "Invalid username",
});
}
if (
typeof password !== "string" ||
password.length < 6 ||
password.length > 255
) {
return fail(400, {
message: "Invalid password",
});
}
if (
typeof firstName !== "string" ||
firstName.length < 1 ||
firstName.length > 255
) {
return fail(400, {
message: "Invalid first name",
});
}
if (
typeof lastName !== "string" ||
lastName.length < 1 ||
lastName.length > 255
) {
return fail(400, {
message: "Invalid last name",
});
}
const usernameTaken = await db
.select()
.from(userTable)
.where(eq(userTable.username, username))
.limit(1)
.then((results) => results[0] as unknown as DatabaseUser | undefined);
if (usernameTaken) {
return fail(400, {
message: "Username already taken",
});
}
const userId = generateId(15);
const hashedPassword = await new Argon2id().hash(password);
await db
.insert(userTable)
.values({
id: userId,
username: username,
first_name: firstName,
last_name: lastName,
hashed_password: hashedPassword,
signup_date: new Date(),
role: "admin",
last_login: new Date(),
} as DatabaseUser)
.execute();
const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".",
...sessionCookie.attributes,
});
return { success: true };
},
};

View file

@ -6,14 +6,15 @@
import { type SubmitFunction } from "@sveltejs/kit";
import type { DatabaseUser } from "lucia";
import UserCard from "$lib/components/UserCard.svelte";
let errors: { message?: string } = {};
let message: { message?: string } = {};
let username: string = "";
let first_name: string = "";
let last_name: string = "";
let password: string = "";
import ConfirmModal from "$lib/components/ConfirmModal.svelte";
let errors: { addUser?: string } = {};
let sucess: { addUser?: string } = {};
let isModalOpen = false;
async function clearAllSessions() {
@ -34,30 +35,7 @@
isModalOpen = false;
}
const addUser: SubmitFunction = async ({ formData, action, cancel }) => {
const response = await fetch(action, {
method: "POST",
body: formData,
});
if (response.ok) {
console.log("User Added Successfully!");
errors = {};
username = "";
first_name = "";
last_name = "";
password = "";
cancel();
return;
}
const { type, error } = await response.json();
if (type === "error") {
errors = { message: error.message };
}
console.log(errors);
cancel();
};
let form = $page.form;
let visitCount = $page.data.visitCount[0].count;
let userCount = $page.data.userCount[0].count;
@ -71,12 +49,7 @@
<h2 class="text-center font-extrabold text-2xl">Add User</h2>
<div class="flex justify-center mb-4">
<form
method="POST"
action="/signup"
use:enhance={addUser}
class="w-full max-w-xs"
>
<form method="POST" class="w-full max-w-xs" use:enhance action="?/adduser">
<label for="username">Username</label>
<input
name="username"
@ -114,14 +87,16 @@
class="block mb-2 checkbox-primary checkbox"
/><br />
<button class="py-2 px-4 btn btn-primary">Signup</button>
</form>
</div>
{#if errors.message}
{#if $page.form?.message}
<div class="text-center text-error mt-4">
{errors.message}
{$page.form?.message}
</div>
{/if}
{#if $page.form?.success}
<div class="text-center text-success mt-4">User added successfully!</div>
{/if}
</form>
</div>
<h2 class="text-center font-extrabold text-2xl mb-2">Session Managment</h2>
<div class="flex justify-center items-center">

View file

@ -14,7 +14,15 @@ import { insertData } from "$lib/db/insertData";
export const actions: Actions = {
default: async (event) => {
const formData = await event.request.formData();
const username = formData.get("username");
const formUsername = formData.get("username");
let username = formUsername?.toString().toLocaleLowerCase();
if (typeof formUsername !== "string") {
return fail(400, {
message: "Invalid username",
});
}
const password = formData.get("password");
const firstName = formData.get("first_name");
const lastName = formData.get("last_name");

View file

@ -6,21 +6,37 @@ import { Argon2id } from "oslo/password";
import { db } from "$lib/db/db.server";
import type { DatabaseUser } from "$lib/server/auth";
import type { Actions } from "./$types";
import type { Actions, PageServerLoad } from "./$types";
import { userTable } from "$lib/db/schema";
import { eq } from "drizzle-orm";
export const load: PageServerLoad = async (event) => {
if (event.locals.user) {
return redirect(302, "/");
}
return {};
};
export const actions: Actions = {
default: async (event) => {
const formData = await event.request.formData();
const username = formData.get("username");
const formUsername = formData.get("username");
let username = formUsername?.toString().toLocaleLowerCase();
if (typeof formUsername !== "string") {
return error(400, {
message: "Invalid username",
});
}
const password = formData.get("password");
const firstName = formData.get("first_name");
const lastName = formData.get("last_name");
let role: string = "";
// username must be between 4 ~ 31 characters, and only consists of lowercase letters, 0-9, -, and _
// keep in mind some database (e.g. mysql) are case insensitive
if (event.locals.user) {
return redirect(302, "/");
}
// check all to make sure all fields are provided
if (!username || !password || !firstName || !lastName) {
return error(400, {
@ -28,20 +44,11 @@ export const actions: Actions = {
});
}
if (!event.locals.user) {
role = "user";
}
if (event.locals.user && event.locals.user.role === "admin") {
const isAdmin = formData.get("role") === "on";
role = isAdmin ? "admin" : "user";
}
if (
typeof username !== "string" ||
username.length < 3 ||
username.length > 31 ||
!/^[a-z0-9_-]+$/.test(username)
!/^[a-zA-Z0-9_-]+$/.test(username)
) {
return error(400, {
message: "Invalid username",
@ -102,12 +109,11 @@ export const actions: Actions = {
last_name: lastName,
hashed_password: hashedPassword,
signup_date: new Date(),
role: role,
role: "user",
last_login: new Date(),
} as DatabaseUser)
.execute();
if (!event.locals.user) {
const session = await lucia.createSession(userId, {});
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookies.set(sessionCookie.name, sessionCookie.value, {
@ -115,23 +121,6 @@ export const actions: Actions = {
...sessionCookie.attributes,
});
redirect(302, "/");
} else {
if (event.locals.user && event.locals.user.role !== "admin") {
return error(403, {
message: "You are not authorized to add users",
});
}
return {
status: 200,
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
message: "User date",
}),
};
}
return redirect(302, "/");
},
};

View file

@ -1,15 +1,38 @@
<!-- routes/signup/+page.svelte -->
<script lang="ts">
import { enhance } from "$app/forms";
import { goto } from "$app/navigation";
import { getRandomQuote } from "$lib";
import type { SubmitFunction } from "@sveltejs/kit";
import { onMount } from "svelte";
let errors: { message?: string } = {};
let backgroundImageUrl = "https://source.unsplash.com/random/?mountains";
let quote: string = "";
onMount(async () => {
quote = getRandomQuote();
});
const handleSubmit: SubmitFunction = async ({ formData, action, cancel }) => {
const response = await fetch(action, {
method: "POST",
body: formData,
});
if (response.ok) {
errors = {};
goto("/signup");
return;
}
const { type, error } = await response.json();
if (type === "error") {
errors = { message: error.message };
}
console.log(errors);
cancel();
};
</script>
<div
@ -22,7 +45,7 @@
</article>
<div class="flex justify-center">
<form method="post" use:enhance class="w-full max-w-xs">
<form method="post" use:enhance={handleSubmit} class="w-full max-w-xs">
<label for="username">Username</label>
<input
name="username"
@ -52,6 +75,12 @@
</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 != ""}
@ -62,7 +91,6 @@
</div>
</div>
</div>
<!-- username first last pass -->
<svelte:head>