mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 20:13:49 +00:00
Implement login, add useUser hook
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user