mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Implement login, add useUser hook
This commit is contained in:
23
components/ui/Spinner.tsx
Normal file
23
components/ui/Spinner.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
const Spinner = () => (
|
||||
<div role="status" className="flex flex-col items-center justify-center rounded-3xl">
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="w-[100px] animate-spin fill-success text-gray-500"
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
<span className="sr-only">Loading...</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Spinner;
|
||||
@@ -1,6 +1,4 @@
|
||||
import { FunctionComponent } from 'react';
|
||||
// import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
// import { faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
/**
|
||||
* @example
|
||||
|
||||
@@ -2,7 +2,7 @@ import { FunctionComponent } from 'react';
|
||||
import { UseFormRegisterReturn } from 'react-hook-form';
|
||||
|
||||
interface FormSelectProps {
|
||||
options: ReadonlyArray<{ value: string; text: string }>;
|
||||
options: readonly { value: string; text: string }[];
|
||||
id: string;
|
||||
formRegister: UseFormRegisterReturn<string>;
|
||||
error: boolean;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { NextApiResponse } from 'next';
|
||||
import { NextHandler } from 'next-connect';
|
||||
import findUserById from '@/services/user/findUserById';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import { getLoginSession } from '../session';
|
||||
import { ExtendedNextApiRequest } from '../types';
|
||||
|
||||
@@ -10,7 +12,12 @@ const getCurrentUser = async (
|
||||
next: NextHandler,
|
||||
) => {
|
||||
const session = await getLoginSession(req);
|
||||
const user = { id: session.id, username: session.username };
|
||||
const user = await findUserById(session?.id);
|
||||
|
||||
if (!user) {
|
||||
throw new ServerError('Could not get user.', 401);
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { NextApiResponse } from 'next';
|
||||
import Iron from '@hapi/iron';
|
||||
import { SessionRequest, UserInfoSchema, UserSessionSchema } from '@/config/auth/types';
|
||||
import {
|
||||
SessionRequest,
|
||||
BasicUserInfoSchema,
|
||||
UserSessionSchema,
|
||||
} from '@/config/auth/types';
|
||||
import { z } from 'zod';
|
||||
import { MAX_AGE, setTokenCookie, getTokenCookie } from './cookie';
|
||||
import ServerError from '../util/ServerError';
|
||||
@@ -9,7 +13,7 @@ const { TOKEN_SECRET } = process.env;
|
||||
|
||||
export async function setLoginSession(
|
||||
res: NextApiResponse,
|
||||
session: z.infer<typeof UserInfoSchema>,
|
||||
session: z.infer<typeof BasicUserInfoSchema>,
|
||||
) {
|
||||
if (!TOKEN_SECRET) {
|
||||
throw new ServerError('Authentication is not configured.', 500);
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import GetUserSchema from '@/services/user/schema/GetUserSchema';
|
||||
import { IncomingMessage } from 'http';
|
||||
import { NextApiRequest } from 'next';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const UserInfoSchema = z.object({
|
||||
export const BasicUserInfoSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
username: z.string(),
|
||||
});
|
||||
|
||||
export const UserSessionSchema = UserInfoSchema.merge(
|
||||
export const UserSessionSchema = BasicUserInfoSchema.merge(
|
||||
z.object({
|
||||
createdAt: z.number(),
|
||||
maxAge: z.number(),
|
||||
@@ -15,7 +16,7 @@ export const UserSessionSchema = UserInfoSchema.merge(
|
||||
);
|
||||
|
||||
export interface ExtendedNextApiRequest extends NextApiRequest {
|
||||
user?: z.infer<typeof UserInfoSchema>;
|
||||
user?: z.infer<typeof GetUserSchema>;
|
||||
}
|
||||
|
||||
export type SessionRequest = IncomingMessage & {
|
||||
|
||||
35
hooks/useUser.ts
Normal file
35
hooks/useUser.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import GetUserSchema from '@/services/user/schema/GetUserSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const useUser = () => {
|
||||
const {
|
||||
data: user,
|
||||
error,
|
||||
isLoading,
|
||||
} = useSWR('/api/users/current', async (url) => {
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.error.message);
|
||||
}
|
||||
|
||||
const parsedPayload = GetUserSchema.safeParse(parsed.data.payload);
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error(parsedPayload.error.message);
|
||||
}
|
||||
|
||||
return parsedPayload.data;
|
||||
});
|
||||
|
||||
return { user, isLoading, error: error as unknown };
|
||||
};
|
||||
|
||||
export default useUser;
|
||||
@@ -7,13 +7,9 @@ import { setLoginSession } from '@/config/auth/session';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import LoginValidationSchema from '@/services/user/schema/LoginValidationSchema';
|
||||
import { ExtendedNextApiRequest } from '../../../config/auth/types';
|
||||
|
||||
const LoginSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
export default nextConnect<
|
||||
ExtendedNextApiRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
@@ -21,7 +17,7 @@ export default nextConnect<
|
||||
.use(passport.initialize())
|
||||
.use(async (req, res, next) => {
|
||||
passport.use(localStrat);
|
||||
const parsed = LoginSchema.safeParse(req.body);
|
||||
const parsed = LoginValidationSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
throw new ServerError('Username and password are required.', 400);
|
||||
}
|
||||
@@ -41,6 +37,7 @@ export default nextConnect<
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Login successful.',
|
||||
payload: user,
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
});
|
||||
|
||||
@@ -5,6 +5,8 @@ import nc, { NextHandler } from 'next-connect';
|
||||
import createNewUser from '@/services/user/createNewUser';
|
||||
import CreateUserValidationSchema from '@/services/user/schema/CreateUserValidationSchema';
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
import findUserByUsername from '@/services/user/findUserByUsername';
|
||||
import findUserByEmail from '@/services/user/findUserByEmail';
|
||||
|
||||
interface RegisterUserRequest extends NextApiRequest {
|
||||
body: z.infer<typeof CreateUserValidationSchema>;
|
||||
@@ -38,6 +40,25 @@ const validateRequest =
|
||||
};
|
||||
|
||||
const registerUser = async (req: RegisterUserRequest, res: NextApiResponse) => {
|
||||
const [usernameTaken, emailTaken] = await Promise.all([
|
||||
findUserByUsername(req.body.username),
|
||||
findUserByEmail(req.body.email),
|
||||
]);
|
||||
|
||||
if (usernameTaken) {
|
||||
throw new ServerError(
|
||||
'Could not register a user with that username as it is already taken.',
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
if (emailTaken) {
|
||||
throw new ServerError(
|
||||
'Could not register a user with that email as it is already taken.',
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const user = await createNewUser(req.body);
|
||||
res.status(201).json({
|
||||
message: 'User created successfully.',
|
||||
|
||||
107
pages/login/index.tsx
Normal file
107
pages/login/index.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import { NextPage } from 'next';
|
||||
import { SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { useEffect } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import FormError from '@/components/ui/forms/FormError';
|
||||
import FormInfo from '@/components/ui/forms/FormInfo';
|
||||
import FormLabel from '@/components/ui/forms/FormLabel';
|
||||
import FormSegment from '@/components/ui/forms/FormSegment';
|
||||
import FormTextInput from '@/components/ui/forms/FormTextInput';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import LoginValidationSchema from '@/services/user/schema/LoginValidationSchema';
|
||||
import sendLoginUserRequest from '@/requests/sendLoginUserRequest';
|
||||
import useUser from '@/hooks/useUser';
|
||||
|
||||
type LoginT = z.infer<typeof LoginValidationSchema>;
|
||||
const LoginForm = () => {
|
||||
const router = useRouter();
|
||||
const { register, handleSubmit, formState } = useForm<LoginT>({
|
||||
resolver: zodResolver(LoginValidationSchema),
|
||||
defaultValues: {
|
||||
username: '',
|
||||
password: '',
|
||||
},
|
||||
});
|
||||
|
||||
const { errors } = formState;
|
||||
|
||||
const onSubmit: SubmitHandler<LoginT> = async (data) => {
|
||||
try {
|
||||
const response = await sendLoginUserRequest(data);
|
||||
|
||||
router.push(`/users/${response.id}`);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="form-control w-9/12 space-y-5" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div>
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="username">username</FormLabel>
|
||||
<FormError>{errors.username?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="username"
|
||||
type="text"
|
||||
formValidationSchema={register('username')}
|
||||
error={!!errors.username}
|
||||
placeholder="username"
|
||||
/>
|
||||
</FormSegment>
|
||||
|
||||
<FormInfo>
|
||||
<FormLabel htmlFor="password">password</FormLabel>
|
||||
<FormError>{errors.password?.message}</FormError>
|
||||
</FormInfo>
|
||||
<FormSegment>
|
||||
<FormTextInput
|
||||
id="password"
|
||||
type="password"
|
||||
formValidationSchema={register('password')}
|
||||
error={!!errors.password}
|
||||
placeholder="password"
|
||||
/>
|
||||
</FormSegment>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<button type="submit" className="btn-primary btn w-full">
|
||||
Login
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
const LoginPage: NextPage = () => {
|
||||
const { user } = useUser();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
router.push(`/user/current`);
|
||||
}, [user]);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex h-full flex-row">
|
||||
<div className="flex h-full w-[40%] flex-col items-center justify-center bg-base-100">
|
||||
<h1>Login</h1>
|
||||
</div>
|
||||
<div className="flex h-full w-[60%] flex-col items-center justify-center bg-base-300">
|
||||
<LoginForm />
|
||||
</div>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
@@ -1,16 +0,0 @@
|
||||
import withPageAuthRequired from '@/config/auth/withPageAuthRequired';
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
|
||||
const protectedPage: NextPage<{
|
||||
username: string;
|
||||
}> = ({ username }) => {
|
||||
return (
|
||||
<div>
|
||||
<h1> Hello, {username}! </h1>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();
|
||||
|
||||
export default protectedPage;
|
||||
30
pages/user/current.tsx
Normal file
30
pages/user/current.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import Layout from '@/components/ui/Layout';
|
||||
import Spinner from '@/components/ui/Spinner';
|
||||
import withPageAuthRequired from '@/config/auth/withPageAuthRequired';
|
||||
import useUser from '@/hooks/useUser';
|
||||
import { GetServerSideProps, NextPage } from 'next';
|
||||
|
||||
const ProtectedPage: NextPage = () => {
|
||||
const { user, isLoading, error } = useUser();
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="flex h-full flex-col items-center justify-center">
|
||||
<h1 className="text-7xl font-bold text-white">Hello!</h1>
|
||||
<>
|
||||
{isLoading && <Spinner />}
|
||||
{error && <p>Something went wrong.</p>}
|
||||
{user && (
|
||||
<div>
|
||||
<p>{user.username}</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = withPageAuthRequired();
|
||||
|
||||
export default ProtectedPage;
|
||||
28
requests/sendLoginUserRequest.tsx
Normal file
28
requests/sendLoginUserRequest.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { BasicUserInfoSchema } from '@/config/auth/types';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
|
||||
const sendLoginUserRequest = async (data: { username: string; password: string }) => {
|
||||
const response = await fetch('/api/users/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
const json: unknown = await response.json();
|
||||
|
||||
const parsed = APIResponseValidationSchema.safeParse(json);
|
||||
if (!parsed.success) {
|
||||
throw new Error('API response validation failed');
|
||||
}
|
||||
|
||||
const parsedPayload = BasicUserInfoSchema.safeParse(parsed.data.payload);
|
||||
if (!parsedPayload.success) {
|
||||
throw new Error('API response payload validation failed');
|
||||
}
|
||||
|
||||
return parsedPayload.data;
|
||||
};
|
||||
|
||||
export default sendLoginUserRequest;
|
||||
@@ -1,9 +1,8 @@
|
||||
import findUserByUsername from '@/services/user/findUserByUsername';
|
||||
import { hashPassword } from '@/config/auth/passwordFns';
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import CreateUserValidationSchema from './schema/CreateUserValidationSchema';
|
||||
import GetUserSchema from './schema/GetUserSchema';
|
||||
|
||||
const createNewUser = async ({
|
||||
email,
|
||||
@@ -13,17 +12,8 @@ const createNewUser = async ({
|
||||
dateOfBirth,
|
||||
username,
|
||||
}: z.infer<typeof CreateUserValidationSchema>) => {
|
||||
const userExists = await findUserByUsername(username);
|
||||
|
||||
if (userExists) {
|
||||
throw new ServerError(
|
||||
"Could not register a user with that username as it's already taken.",
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
const hash = await hashPassword(password);
|
||||
const user = DBClient.instance.user.create({
|
||||
const user: z.infer<typeof GetUserSchema> = await DBClient.instance.user.create({
|
||||
data: {
|
||||
username,
|
||||
email,
|
||||
|
||||
13
services/user/findUserByEmail.ts
Normal file
13
services/user/findUserByEmail.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
|
||||
const findUserByEmail = async (email: string) =>
|
||||
DBClient.instance.user.findFirst({
|
||||
where: { email },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
hash: true,
|
||||
},
|
||||
});
|
||||
|
||||
export default findUserByEmail;
|
||||
23
services/user/findUserById.ts
Normal file
23
services/user/findUserById.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import { z } from 'zod';
|
||||
import GetUserSchema from './schema/GetUserSchema';
|
||||
|
||||
const findUserById = async (id: string) => {
|
||||
const user: z.infer<typeof GetUserSchema> | null =
|
||||
await DBClient.instance.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
dateOfBirth: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
export default findUserById;
|
||||
14
services/user/schema/GetUserSchema.ts
Normal file
14
services/user/schema/GetUserSchema.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const GetUserSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
username: z.string(),
|
||||
createdAt: z.date().or(z.string()),
|
||||
updatedAt: z.date().or(z.string()).optional(),
|
||||
email: z.string().email(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
dateOfBirth: z.date().or(z.string()),
|
||||
});
|
||||
|
||||
export default GetUserSchema;
|
||||
18
services/user/schema/LoginValidationSchema.ts
Normal file
18
services/user/schema/LoginValidationSchema.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const LoginValidationSchema = z.object({
|
||||
username: z
|
||||
.string({
|
||||
required_error: 'Username is required.',
|
||||
invalid_type_error: 'Username must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Username is required.' }),
|
||||
password: z
|
||||
.string({
|
||||
required_error: 'Password is required.',
|
||||
invalid_type_error: 'Password must be a string.',
|
||||
})
|
||||
.min(1, { message: 'Password is required.' }),
|
||||
});
|
||||
|
||||
export default LoginValidationSchema;
|
||||
Reference in New Issue
Block a user