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.',
|
||||
|
||||
Reference in New Issue
Block a user