Implemented a simple authentication scheme with Firebase and Iron Session
This commit is contained in:
82
src/pages/login.tsx
Normal file
82
src/pages/login.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import {User} from "@/interfaces/user";
|
||||
import {toast, ToastContainer} from "react-toastify";
|
||||
import axios from "axios";
|
||||
import {FormEvent, useState} from "react";
|
||||
import Head from "next/head";
|
||||
import useUser from "@/hooks/useUser";
|
||||
import {InputText} from "primereact/inputtext";
|
||||
import {Button} from "primereact/button";
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const {mutateUser} = useUser({
|
||||
redirectTo: "/",
|
||||
redirectIfFound: true,
|
||||
});
|
||||
|
||||
const login = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post<User>("/api/login", {email, password})
|
||||
.then((response) => {
|
||||
toast.success("You have been logged in!", {toastId: "login-successful"});
|
||||
mutateUser(response.data);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (e.response.status === 401) {
|
||||
toast.error("Wrong login credentials!", {toastId: "wrong-credentials"});
|
||||
} else {
|
||||
toast.error("Something went wrong!", {toastId: "server-error"});
|
||||
}
|
||||
setIsLoading(false);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Login | IELTS GPT</title>
|
||||
<meta name="description" content="Generated by create next app" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<main className="w-full h-screen flex flex-col items-center justify-center bg-neutral-100">
|
||||
<ToastContainer />
|
||||
<form className="p-4 rounded-xl bg-white drop-shadow-xl flex flex-col gap-4" onSubmit={login}>
|
||||
<div className="p-inputgroup">
|
||||
<span className="p-inputgroup-addon">
|
||||
<i className="pi pi-inbox"></i>
|
||||
</span>
|
||||
<InputText
|
||||
placeholder="E-mail..."
|
||||
type="email"
|
||||
required
|
||||
disabled={isLoading}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-inputgroup">
|
||||
<span className="p-inputgroup-addon">
|
||||
<i className="pi pi-star"></i>
|
||||
</span>
|
||||
<InputText
|
||||
placeholder="Password..."
|
||||
type="password"
|
||||
required
|
||||
disabled={isLoading}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
<Button loading={isLoading} iconPos="right" label="Login" icon="pi pi-check" />
|
||||
</form>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user