Skip to content

Commit

Permalink
v0.3.0 (#28)
Browse files Browse the repository at this point in the history
# Release Notes - TPET v0.3.0

## New Features

- Users need to log in first to navigate to send email page
- Users are forced to log in first if they try to directly navigate to the send email page
- Sign out is also available now.
  • Loading branch information
chungchihhan authored Jul 26, 2024
1 parent 1998e26 commit 2ac330e
Show file tree
Hide file tree
Showing 11 changed files with 131 additions and 121 deletions.
2 changes: 0 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 22 additions & 27 deletions src/app/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,21 @@ import { FormEvent, useRef, useState, useEffect } from "react";
import { submitLogin, submitChangePassword } from "@/lib/actions";
import { useRouter } from "next/navigation";
import { ScanEye } from "lucide-react";
import Cookies from "js-cookie";

interface SubmitResponse {
cookie?: string;
message: string;
challengeName: string;
session: string;
challengeParameters: {
USER_ID_FOR_SRP: string;
requiredAttributes: string;
userAttributes: string;
};
}

// interface LoginResponse {
// message: string;
// accessToken: string;
// }
// interface FirstTimeLoginResponse {
// message: string;
// challengeName: string;
// session: string;
// challengeParameters: {
// USER_ID_FOR_SRP: string;
// requiredAttributes: string;
// userAttributes: string;
// };
// }

export default function Page() {
const router = useRouter();
Expand Down Expand Up @@ -50,27 +52,20 @@ export default function Page() {
};

try {
const response = (await submitLogin(JSON.stringify(formData))) as
| SubmitResponse
| undefined;

if (response === undefined) {
console.error("Login failed: No response");
return;
}
console.log("response", response);

if (response.cookie) {
Cookies.set("accessToken", response.cookie, { path: "/" }); // Set the cookie in the client using js-cookie
}
const response = await submitLogin(JSON.stringify(formData));

alert(response.message);

if (response.message == "Login successful") {
localStorage.setItem("access_token", response.access_token);

const tokenExpiryTime = new Date().getTime() + 24 * 60 * 60 * 10000;
localStorage.setItem("token_expiry_time", tokenExpiryTime.toString());

router.push("/sendEmail");
}

if (response.challengeName == "NEW_PASSWORD_REQUIRED") {
console.log(response);
setSession(response.session);
}
} catch (error: any) {
Expand Down
4 changes: 2 additions & 2 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ export default function Page() {
</span>
</p>
<Link
href="/login"
href="sendEmail"
className="flex items-center gap-5 self-start rounded-lg bg-sky-950 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-sky-900 md:text-base"
>
Log in to my account.
Start Sending Emails
</Link>
</div>
<div className="flex items-center justify-center p-6 md:w-3/5 md:px-12 md:py-4">
Expand Down
29 changes: 16 additions & 13 deletions src/app/ui/Tiptap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { useState } from "react";
import NextStepLink from "next/link";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { checkLoginStatus } from "@/lib/actions";

const htmltemplateContent = `
<p>親愛的{{Name}},</p>
Expand All @@ -37,20 +36,21 @@ const Tiptap = ({ onChange, content }: any) => {
const [showNextStep, setShowNextStep] = useState(false);

const router = useRouter();
const [isLoggedIn, setIsLoggedIn] = useState(false);

useEffect(() => {
const verifyLoginStatus = async () => {
const loggedIn = await checkLoginStatus();
if (!loggedIn) {
router.push("/login");
} else {
setIsLoggedIn(true);
}
};
const isTokenExpired = () => {
const expiryTime = localStorage.getItem("token_expiry_time");
if (!expiryTime) return true;
return new Date().getTime() > parseInt(expiryTime);
};

verifyLoginStatus();
}, [router]);
useEffect(() => {
console.log("checkLoginStatus function called");
const access_token = localStorage.getItem("access_token");
if (!access_token || isTokenExpired()) {
// alert("Session expired. Please login again.");
router.push("/login");
}
}, []);

const handleUpload = async () => {
const html = `
Expand All @@ -74,6 +74,9 @@ const Tiptap = ({ onChange, content }: any) => {
setIsUploading(true);
const response = await fetch(url.toString(), {
method: "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
body: formData,
});
const result = await response.json();
Expand Down
3 changes: 3 additions & 0 deletions src/app/ui/Toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ const Toolbar = ({ editor, content }: Props) => {

const response = await fetch(url.toString(), {
method: "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
body: formData,
});

Expand Down
3 changes: 3 additions & 0 deletions src/app/ui/attach-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ export default function AttachDropdown({ onSelect }: AttachDropdownProps) {

const response = await fetch(url.toString(), {
method: "GET",
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
});

if (!response.ok) {
Expand Down
3 changes: 3 additions & 0 deletions src/app/ui/file-upload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ export default function FileUpload({
const url = new URL(`${base_url}/upload-multiple-file`);
const response = await fetch(url.toString(), {
method: "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
body: formData,
});

Expand Down
12 changes: 8 additions & 4 deletions src/app/ui/select-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,13 @@ export default function SelectDropdown({
url.searchParams.append("file_extension", file_extension);
url.searchParams.append("limit", limit.toString());

const token = localStorage.getItem("access_token");
const response = await fetch(url.toString(), {
method: "GET",
credentials: "include",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});

if (!response.ok) {
Expand Down Expand Up @@ -137,15 +141,15 @@ export default function SelectDropdown({

{isOpen && (
<div
className="z-50 p-3 pb-6 origin-top-right absolute w-full mt-2 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5"
className="z-50 p-3 pb-6 origin-top-right absolute w-full mt-2 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 min-w-96"
role="menu"
aria-orientation="vertical"
aria-labelledby="options-menu"
>
<div className="flex justify-between items-center mb-2 pl-4">
<div className="flex justify-between items-center mb-2 pl-4 ">
<p className="font-medium">SELECT A FILE</p>
<input
className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
className="rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 w-full max-w-52"
placeholder="Search a file name..."
type="text"
value={searchTerm}
Expand Down
55 changes: 21 additions & 34 deletions src/app/ui/send-email-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import FileUpload from "@/app/ui/file-upload";
import IframePreview from "@/app/ui/iframe-preview";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { checkLoginStatus } from "@/lib/actions";
import { access } from "fs";

interface SubmitResponse {
status: string;
Expand All @@ -18,17 +18,6 @@ interface SubmitResponse {
errors?: { path: string; message: string }[];
}

interface fileDataType {
file_id: string;
created_at: string;
updated_at: string;
file_url: string;
file_name: string;
file_extension: string;
file_size: number;
uploader_id: string;
}

export default function SendEmailForm() {
const ref = useRef<HTMLFormElement>(null);
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
Expand All @@ -48,22 +37,21 @@ export default function SendEmailForm() {
useState<boolean>(false);

const router = useRouter();
const [isLoggedIn, setIsLoggedIn] = useState(false);

const isTokenExpired = () => {
const expiryTime = localStorage.getItem("token_expiry_time");
if (!expiryTime) return true;
return new Date().getTime() > parseInt(expiryTime);
};

useEffect(() => {
console.log("checkLoginStatus function called");
const verifyLoginStatus = async () => {
const loggedIn = await checkLoginStatus();
if (!loggedIn) {
// router.push("/login");
console.log("not logged in");
} else {
console.log("logged in");
setIsLoggedIn(true);
}
};
verifyLoginStatus();
}, [router]);
const access_token = localStorage.getItem("access_token");
if (!access_token || isTokenExpired()) {
// alert("Session expired. Please login again.");
router.push("/login");
}
}, []);

const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
Expand All @@ -81,12 +69,12 @@ export default function SendEmailForm() {
is_generate_certificate: isGenerateCertificate,
};

console.log(formData.attachment_file_ids);
setIsSubmitting(true);
try {
const response: SubmitResponse = (await submitForm(
JSON.stringify(formData)
)) as SubmitResponse;
const response: SubmitResponse = await submitForm(
JSON.stringify(formData),
localStorage.getItem("access_token") ?? ""
);

if (response.status === "error" && response.errors) {
const newErrors: { [key: string]: string } = {};
Expand Down Expand Up @@ -389,8 +377,10 @@ export default function SendEmailForm() {
</div>
)}
</div>
{errors.template_file_id && (
<p className="text-red-500 text-sm">{errors.template_file_id}</p>
{errors.spreadsheet_file_id && (
<p className="text-red-500 text-sm">
{errors.spreadsheet_file_id}
</p>
)}
</div>
<div className="m-3">
Expand Down Expand Up @@ -430,9 +420,6 @@ export default function SendEmailForm() {
</div>
)}
</div>
{errors.template_file_id && (
<p className="text-red-500 text-sm">{errors.template_file_id}</p>
)}
</div>
<div className="my-5 mx-3">
<label className="mb-2 block text-sm font-medium">
Expand Down
17 changes: 17 additions & 0 deletions src/app/ui/side-nav.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
"use client";
import Link from "next/link";
import Image from "next/image";
// import { HomeIcon } from "@heroicons/react/24/outline";
import { useRouter } from "next/navigation";

export default function SideNav() {
const router = useRouter();
const signout = () => {
localStorage.removeItem("access_token");
localStorage.removeItem("token_expiry_time");
router.push("/");
};
return (
<div className="flex h-full flex-col px-5 py-4 md:px-3 bg-gray-200 gap-2 min-w-60">
<Link
Expand Down Expand Up @@ -32,6 +40,15 @@ export default function SideNav() {
<p className="px-3 text-white">Send Email</p>
</Link>
</div>
<div>
<button
className="flex flex-grow min-w-48 max-h-10 items-center justify-center rounded-md bg-sky-950 p-4 hover:bg-sky-800 w-full"
type="button"
onClick={signout}
>
<p className="px-3 text-white">Sign Out</p>
</button>
</div>
</div>
);
}
Loading

0 comments on commit 2ac330e

Please sign in to comment.