Skip to content

Commit

Permalink
Merge pull request #8 from unovil/init-after-registration
Browse files Browse the repository at this point in the history
Adding additional information after registration
  • Loading branch information
unovil authored Mar 17, 2024
2 parents 99bbc7f + 72b29c1 commit 08c3717
Show file tree
Hide file tree
Showing 10 changed files with 356 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Warnings:
- A unique constraint covering the columns `[depedId]` on the table `School` will be added. If there are existing duplicate values, this will fail.
- Added the required column `depedId` to the `School` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE `school` ADD COLUMN `depedId` CHAR(6) NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX `School_depedId_key` ON `School`(`depedId`);
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ model School {
facilities Facility[] @relation(name: "FacilityToSchool")
equipments Equipment[] @relation(name: "EquipmentToSchool")
name String
depedId String @unique @db.Char(6)
user User[]
}

Expand Down
7 changes: 5 additions & 2 deletions src/app.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ declare global {
}

namespace PrismaJson {
type DepartmentsType = { departments: Array<Department> }
type DepartmentsType = { departments: Array<Department>?}
type DatesType = { dates: Array<Date>?}
}
}

export { };
type Departments = PrismaJson.DepartmentsType;
type Dates = PrismaJson.DatesType;

export { Departments, Dates };
11 changes: 5 additions & 6 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import db from '$lib/prisma'
import type { Prisma, User } from '@prisma/client'
import type { PageServerLoad } from './$types'
import { redirect, type Actions } from '@sveltejs/kit';
import { lucia } from '$lib/server/auth';
import db from '$lib/prisma';

export const load: PageServerLoad = async (event) => {
console.log(event.locals.user);
Expand All @@ -15,12 +14,12 @@ export const load: PageServerLoad = async (event) => {

export const actions = {
default: async (event) => {
const cookieHeader = event.cookies.get("auth_session") ?? "";
const sessionId = lucia.readSessionCookie(cookieHeader) ?? "";

const sessionId = event.cookies.get("auth_session") ?? "";
await lucia.invalidateSession(sessionId);

event.cookies.delete("auth_session", {path:"/"});
event.cookies.delete("auth_session", { path: "/" });
event.locals.user = null;
event.locals.session = null;

redirect(302, "/");
}
Expand Down
30 changes: 28 additions & 2 deletions src/routes/dashboard/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
import { lucia } from "$lib/server/auth";
import { fail, redirect } from "@sveltejs/kit";

import type { Actions, PageServerLoad } from "./$types";
import db from "$lib/prisma";

export const load: PageServerLoad = async (event) => {
if (!event.locals.user) {
redirect(302, "/login");
}
};

const user = await db.user.findUnique({
select: { role: true, student: true, admin: true },
where: { id: event.locals.user.id }
})

if (!user?.admin && !user?.student) {
redirect(302, "/register/next");
}

return {
username: event.locals.user.firstName + " " + event.locals.user.lastName
}
};

export const actions = {
default: async (event) => {
const sessionId = event.cookies.get("auth_session") ?? "";
await lucia.invalidateSession(sessionId);

event.cookies.delete("auth_session", { path: "/" });
event.locals.user = null;
event.locals.session = null;

redirect(302, "/");
}
} satisfies Actions;
15 changes: 14 additions & 1 deletion src/routes/dashboard/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,2 +1,15 @@
<script lang="ts">
import type { PageData } from "./$types";
export let data: PageData;
</script>

<p>Sample dashboard here.</p>
<p>If you can see this page, you are logged in.</p>
<p>If you can see this page, you are logged in.</p>

<p>Logout? Click the button.</p>
<form method="post">
<button type="submit">LOGOUT</button>
</form>

<p>Your name is: "{data.username}"</p>
177 changes: 177 additions & 0 deletions src/routes/register/next/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import type { Actions, PageServerLoad } from "./$types";
import { fail, redirect } from '@sveltejs/kit';
import db from "$lib/prisma";
import { UserRole } from "@prisma/client";

export const load: PageServerLoad = async (event) => {
if (!event.locals.user) {
redirect(302, "/login");
}

const user = await db.user.findUnique({
select: { role: true, student: true, admin: true },
where: { id: event.locals.user.id }
})

if (user?.admin || user?.student) {
redirect(302, "/dashboard");
}
};

export const actions = {
role: async ({ request, cookies }) => {
const roleInfo = Object.fromEntries(await request.formData())
const { role, schoolId } = roleInfo

console.log(roleInfo)

console.log(`role: ${role}`)
console.log(`school id: ${schoolId}`)

if (typeof role !== "string" ||
role == null) {
console.log("no user role selected")
return fail(400, {
noSelectedRole: true,
error: "Please select a role.",
data: { ...roleInfo }
})
}

if (typeof schoolId !== "string" ||
/^\d{6}$/.test(schoolId) == false) {
return fail(400, {
incorrectIdLength: true,
error: "The ID format is incorrect. Enter 6 numeric characters.",
data: { ...roleInfo }
})
}

const response = await db.school.findUnique({
select: {
name: true,
sections: true
},
where: { depedId: schoolId }
})

if (response == null || typeof response === "undefined") {
return fail(400, {
schoolNotFound: true,
error: "The school ID was not found.",
data: { ...roleInfo }
})
}

if (response.sections.length == 0 || response.sections == null) {
return fail(400, {
schoolIncomplete: true,
error: `The school, ${response.name}, has no sections. Please contact the school administrator.`,
data: { ...roleInfo }
})
}

const sessionId = cookies.get("auth_session");
const sessionResponse = await db.session.findUnique({
select: { user: true },
where: { id: sessionId }
})

if (!sessionId || !sessionResponse) {
return fail(401, {
unauthorized: true,
error: "An error has occurred with your user session. Try to log in again.",
data: { ...roleInfo }
})
}

await db.user.update({
where: { id: sessionResponse.user.id },
data: {
role: (role === "student") ? UserRole.STUDENT : UserRole.ADMIN,
school: {
connect: { depedId: schoolId }
}
}
})

if (role === "admin") {
await db.admin.create({
data: {
user: {
connect: {
id: sessionResponse.user.id
}
},
departments: {
departments: []
},
}
})
}

return {
response: {
schoolName: response.name,
role: role,
sections: response.sections
}
};
},

roleNext: async ({ request, cookies }) => {
const { lrn, section } = Object.fromEntries(await request.formData())
const registrationInfo = { lrn, section }

if (typeof lrn !== "string" ||
/^\d{12}$/.test(lrn) == false
) {
return fail(400, {
invalidLrn: true,
error: "The LRN format is incorrect. Enter 12 numeric characters.",
data: { ...registrationInfo }
})
}

if (typeof section !== "string" ||
section.length == 0 ||
isNaN(+section)
) {
return fail(400, {
blankSection: true,
error: "The section is blank. Please select a section.",
data: { ...registrationInfo }
})
}

const sessionId = cookies.get("auth_session");
const sessionResponse = await db.session.findUnique({
select: { user: true },
where: { id: sessionId }
})

if (!sessionId || !sessionResponse) {
return fail(401, {
unauthorized: true,
error: "An error has occurred with your user session. Try to log in again.",
data: { ...registrationInfo }
})
}

await db.user.update({
where: { id: sessionResponse.user.id },
data: {
student: {
create: {
lrn: lrn,
sectionId: Number(section)
}
}
}
})
},

redirectDashboard: async () => {
redirect(302, "/dashboard")
}
} satisfies Actions;
55 changes: 55 additions & 0 deletions src/routes/register/next/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<script lang="ts">
import type { ActionData } from "./$types";
import Role from "./Role.svelte";
import RoleNext from "./RoleNext.svelte";
export let form: ActionData;
let roleSuccess: boolean = false;
let roleSelected: string;
let schoolName: string;
let sections:
| {
id: number;
grade: number;
name: string;
schoolId: number;
}[]
| undefined;
$: if (form?.response) {
roleSuccess = true;
roleSelected = form?.response.role;
schoolName = form?.response.schoolName;
sections = form?.response.sections;
sections.sort((a, b) => {
if (a.grade === b.grade) {
return a.name.localeCompare(b.name)
} else {
return a.grade - b.grade
}
})
// to trigger reactivity
sections = sections
}
</script>

{#if form?.error}
{form?.error}
{/if}

{#if !roleSuccess}
<Role {form} />
{:else}
<p>Role picked: {roleSelected}</p>
<p>School found: {schoolName}</p>
{/if}

{#if roleSuccess}
<br />

<RoleNext
roleSelected={roleSelected ?? "student"}
sections={sections ?? []}
/>
{/if}
22 changes: 22 additions & 0 deletions src/routes/register/next/Role.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script lang="ts">
import { enhance } from "$app/forms";
import type { ActionData } from "./$types";
export let form: ActionData;
let userRoles = ["admin", "student"];
</script>

{#if !(typeof form?.error == "undefined" && form?.response.schoolName && form?.response.sections.length != 0)}
<form method="post" action="?/role" use:enhance>
<p>You are a/an...</p>
{#each userRoles as userRole}
<input type="radio" value={userRole} name="role" />
<label for={userRole}>{userRole}</label>
<br />
{/each}

<p>What school are you a part of? Type its DepEd school ID.</p>
<input type="text" name="schoolId" placeholder="School" />
<br />
<button type="submit">Check</button>
</form>
{/if}
Loading

0 comments on commit 08c3717

Please sign in to comment.