mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-02-16 10:42:08 +00:00
Implement authentication using Passport.js
This commit is contained in:
@@ -1,57 +1,37 @@
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import createNewBeerComment from '@/services/BeerComment/createNewBeerComment';
|
||||
import { BeerCommentQueryResultT } from '@/services/BeerComment/schema/BeerCommentQueryResult';
|
||||
import BeerCommentValidationSchema from '@/services/BeerComment/schema/CreateBeerCommentValidationSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiHandler } from 'next';
|
||||
import nextConnect from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
const handler: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
|
||||
const createComment: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
|
||||
req,
|
||||
res,
|
||||
) => {
|
||||
try {
|
||||
const { method } = req;
|
||||
|
||||
if (method !== 'POST') {
|
||||
throw new ServerError('Method not allowed', 405);
|
||||
}
|
||||
|
||||
const cleanedReqBody = BeerCommentValidationSchema.safeParse(req.body);
|
||||
if (!cleanedReqBody.success) {
|
||||
throw new ServerError('Invalid request body', 400);
|
||||
}
|
||||
const { content, rating, beerPostId } = cleanedReqBody.data;
|
||||
|
||||
const newBeerComment: BeerCommentQueryResultT = await createNewBeerComment({
|
||||
content,
|
||||
rating,
|
||||
beerPostId,
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Beer comment created successfully',
|
||||
statusCode: 201,
|
||||
payload: newBeerComment,
|
||||
success: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ServerError) {
|
||||
res.status(error.statusCode).json({
|
||||
message: error.message,
|
||||
statusCode: error.statusCode,
|
||||
payload: null,
|
||||
success: false,
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
message: 'Internal server error',
|
||||
statusCode: 500,
|
||||
payload: null,
|
||||
success: false,
|
||||
});
|
||||
}
|
||||
const cleanedReqBody = BeerCommentValidationSchema.safeParse(req.body);
|
||||
if (!cleanedReqBody.success) {
|
||||
throw new ServerError('Invalid request body', 400);
|
||||
}
|
||||
const { content, rating, beerPostId } = cleanedReqBody.data;
|
||||
|
||||
const newBeerComment: BeerCommentQueryResultT = await createNewBeerComment({
|
||||
content,
|
||||
rating,
|
||||
beerPostId,
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Beer comment created successfully',
|
||||
statusCode: 201,
|
||||
payload: newBeerComment,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handler = nextConnect(NextConnectConfig).post(createComment);
|
||||
|
||||
export default handler;
|
||||
|
||||
@@ -1,59 +1,38 @@
|
||||
import nextConnect from 'next-connect';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
import createNewBeerPost from '@/services/BeerPost/createNewBeerPost';
|
||||
import BeerPostValidationSchema from '@/services/BeerPost/schema/CreateBeerPostValidationSchema';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiHandler } from 'next';
|
||||
import { z } from 'zod';
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
|
||||
const handler: NextApiHandler<z.infer<typeof APIResponseValidationSchema>> = async (
|
||||
req,
|
||||
res,
|
||||
) => {
|
||||
try {
|
||||
const { method } = req;
|
||||
|
||||
if (method !== 'POST') {
|
||||
throw new ServerError('Method not allowed', 405);
|
||||
}
|
||||
|
||||
const cleanedReqBody = BeerPostValidationSchema.safeParse(req.body);
|
||||
if (!cleanedReqBody.success) {
|
||||
throw new ServerError('Invalid request body', 400);
|
||||
}
|
||||
|
||||
const { name, description, typeId, abv, ibu, breweryId } = cleanedReqBody.data;
|
||||
const newBeerPost = await createNewBeerPost({
|
||||
name,
|
||||
description,
|
||||
abv,
|
||||
ibu,
|
||||
typeId,
|
||||
breweryId,
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Beer post created successfully',
|
||||
statusCode: 201,
|
||||
payload: newBeerPost,
|
||||
success: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ServerError) {
|
||||
res.status(error.statusCode).json({
|
||||
message: error.message,
|
||||
statusCode: error.statusCode,
|
||||
payload: null,
|
||||
success: false,
|
||||
});
|
||||
} else {
|
||||
res.status(500).json({
|
||||
message: 'Internal server error',
|
||||
statusCode: 500,
|
||||
payload: null,
|
||||
success: false,
|
||||
});
|
||||
}
|
||||
const createBeerPost: NextApiHandler<
|
||||
z.infer<typeof APIResponseValidationSchema>
|
||||
> = async (req, res) => {
|
||||
const cleanedReqBody = BeerPostValidationSchema.safeParse(req.body);
|
||||
if (!cleanedReqBody.success) {
|
||||
throw new ServerError('Invalid request body', 400);
|
||||
}
|
||||
|
||||
const { name, description, typeId, abv, ibu, breweryId } = cleanedReqBody.data;
|
||||
const newBeerPost = await createNewBeerPost({
|
||||
name,
|
||||
description,
|
||||
abv,
|
||||
ibu,
|
||||
typeId,
|
||||
breweryId,
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Beer post created successfully',
|
||||
statusCode: 201,
|
||||
payload: newBeerPost,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handler = nextConnect(NextConnectConfig).post(createBeerPost);
|
||||
|
||||
export default handler;
|
||||
|
||||
24
pages/api/users/current.ts
Normal file
24
pages/api/users/current.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
import { ExtendedNextApiRequest } from '@/config/auth/types';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiResponse } from 'next';
|
||||
import getCurrentUser from '@/config/auth/middleware/getCurrentUser';
|
||||
import nextConnect from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
|
||||
const sendCurrentUser = async (req: ExtendedNextApiRequest, res: NextApiResponse) => {
|
||||
const { user } = req;
|
||||
res.status(200).json({
|
||||
message: `Currently logged in as ${user!.username}`,
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
payload: user,
|
||||
});
|
||||
};
|
||||
|
||||
const handler = nextConnect<
|
||||
ExtendedNextApiRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>(NextConnectConfig).get(getCurrentUser, sendCurrentUser);
|
||||
|
||||
export default handler;
|
||||
47
pages/api/users/login.ts
Normal file
47
pages/api/users/login.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
import passport from 'passport';
|
||||
import nextConnect from 'next-connect';
|
||||
import localStrat from '@/config/auth/localStrat';
|
||||
import { setLoginSession } from '@/config/auth/session';
|
||||
import { NextApiResponse } from 'next';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
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>>
|
||||
>(NextConnectConfig)
|
||||
.use(passport.initialize())
|
||||
.use(async (req, res, next) => {
|
||||
passport.use(localStrat);
|
||||
const parsed = LoginSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
throw new ServerError('Username and password are required.', 400);
|
||||
}
|
||||
|
||||
passport.authenticate('local', { session: false }, (error, token) => {
|
||||
if (error) {
|
||||
next(error);
|
||||
} else {
|
||||
req.user = token;
|
||||
next();
|
||||
}
|
||||
})(req, res, next);
|
||||
})
|
||||
.post(async (req, res) => {
|
||||
const user = req.user!;
|
||||
await setLoginSession(res, user);
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Login successful.',
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
});
|
||||
});
|
||||
27
pages/api/users/logout.ts
Normal file
27
pages/api/users/logout.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { getLoginSession } from '@/config/auth/session';
|
||||
import { removeTokenCookie } from '@/config/auth/cookie';
|
||||
import NextConnectConfig from '@/config/nextConnect/NextConnectConfig';
|
||||
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
|
||||
import { NextApiRequest, NextApiResponse } from 'next';
|
||||
import nextConnect from 'next-connect';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
|
||||
const handler = nextConnect<
|
||||
NextApiRequest,
|
||||
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
|
||||
>(NextConnectConfig).all(async (req, res) => {
|
||||
const session = await getLoginSession(req);
|
||||
|
||||
if (!session) {
|
||||
throw new ServerError('You are not logged in.', 400);
|
||||
}
|
||||
|
||||
removeTokenCookie(res);
|
||||
res.status(200).json({
|
||||
message: 'Logged out.',
|
||||
statusCode: 200,
|
||||
success: true,
|
||||
});
|
||||
});
|
||||
export default handler;
|
||||
55
pages/api/users/register.ts
Normal file
55
pages/api/users/register.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { z } from 'zod';
|
||||
import ServerError from '@/config/util/ServerError';
|
||||
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';
|
||||
|
||||
interface RegisterUserRequest extends NextApiRequest {
|
||||
body: z.infer<typeof CreateUserValidationSchema>;
|
||||
}
|
||||
|
||||
const validateRequest =
|
||||
({
|
||||
bodySchema,
|
||||
querySchema,
|
||||
}: {
|
||||
bodySchema?: z.ZodSchema<any>;
|
||||
querySchema?: z.ZodSchema<any>;
|
||||
}) =>
|
||||
async (req: NextApiRequest, res: NextApiResponse, next: NextHandler) => {
|
||||
if (bodySchema) {
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
throw new ServerError('Invalid request body.', 400);
|
||||
}
|
||||
}
|
||||
|
||||
if (querySchema) {
|
||||
const parsed = querySchema.safeParse(req.query);
|
||||
if (!parsed.success) {
|
||||
throw new ServerError(parsed.error.message, 400);
|
||||
}
|
||||
req.query = parsed.data;
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
const registerUser = async (req: RegisterUserRequest, res: NextApiResponse) => {
|
||||
const user = await createNewUser(req.body);
|
||||
res.status(201).json({
|
||||
message: 'User created successfully.',
|
||||
payload: user,
|
||||
statusCode: 201,
|
||||
success: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handler = nc(NextConnectConfig).post(
|
||||
validateRequest({ bodySchema: CreateUserValidationSchema }),
|
||||
registerUser,
|
||||
);
|
||||
|
||||
export default handler;
|
||||
@@ -1,5 +1,6 @@
|
||||
import BeerForm from '@/components/BeerForm';
|
||||
import Layout from '@/components/ui/Layout';
|
||||
|
||||
import DBClient from '@/prisma/DBClient';
|
||||
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
|
||||
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
|
||||
|
||||
16
pages/protected.tsx
Normal file
16
pages/protected.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user