Skip to content

Commit

Permalink
fix(validation): implement validation for sign up
Browse files Browse the repository at this point in the history
-Ensure user has valid email before create account
-Not allow extra field to the existing field

[Finished #187431242]
  • Loading branch information
yvanddniyo committed Apr 23, 2024
1 parent b9bd13e commit 5a994ca
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 8 deletions.
4 changes: 2 additions & 2 deletions __test__/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ test('should return 409 when registering with an existing email', async () => {
.send(userData);
expect(response.status).toBe(409); }, 20000);

test('should return 500 when registering with an invalid credential', async () => {
test('should return 400 when registering with an invalid credential', async () => {
const userData = {
email: '[email protected]', name: "", username: 'existinguser', };
const response = await request(app)
.post('/api/v1/users/register')
.send(userData);

expect(response.status).toBe(500); }, 20000); });
expect(response.status).toBe(400); }, 20000); });

test("should return all users in db --> given '/api/v1/users'", async () => {
const spy = jest.spyOn(User, "findAll");
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@
"cross-env": "^7.0.3",
"cryptr": "^6.3.0",
"dotenv": "^16.4.5",
"email-validator": "^2.0.4",
"express": "^4.19.2",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"path": "^0.12.7",
"pg": "^8.11.5",
Expand Down
7 changes: 5 additions & 2 deletions src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,17 @@ export const userLogin = async(req:Request,res:Response) =>{


export const createUserController = async (req: Request, res: Response) => {
try {
try {
const { name, email, username, password } = req.body;
const user = await createUserService(name, email, username, password);

if (!user) {
return res.status(409).json({
status: 409,
message: 'User already exists' });
message: 'Username or email already exists'
});
}

res.status(201).json({
status: 201,
message: "User successfully created."
Expand Down
35 changes: 35 additions & 0 deletions src/middleware/validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Request, Response, NextFunction } from 'express';
import validator from 'email-validator';
import { Schema } from 'joi';

export const emailValidation = (req: Request, res: Response, next: NextFunction) => {
const { email } = req.body;

if (!email) {
return res.status(400).json({
status: 400,
message: "Email is required"
});
}

const isValid = validator.validate(email);
if (isValid) {
next();
} else {
return res.status(400).json({
status: 400,
message: "Email is not valid."
});
}
};


export const validateSchema = (schema: Schema) => {
return (req: Request, res: Response, next: NextFunction) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ message: error.details[0].message });
}
next();
};
};
13 changes: 11 additions & 2 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,21 @@ import {
createUserController,
userLogin }
from "../controllers/userControllers";
import {
emailValidation,
validateSchema,
} from "../middleware/validator";
import signUpSchema from "../schemas/signUpSchema";

const userRoutes = Router();

userRoutes.get("/", fetchAllUsers);
userRoutes.post('/login',userLogin);
userRoutes.post("/register", createUserController)
userRoutes.post("/register",
emailValidation,
validateSchema(signUpSchema),
createUserController
)


export default userRoutes;
export default userRoutes;
21 changes: 21 additions & 0 deletions src/schemas/signUpSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Joi from "joi";

export const signUpSchema = Joi.object({
name: Joi.string()
.min(5)
.max(40)
.required(),
username: Joi.string()
.min(4)
.required(),
email: Joi.string()
.min(6)
.required()
.email(),
password: Joi.string()
.min(6)
.max(20)
.required()
}).options({ allowUnknown: false });

export default signUpSchema
9 changes: 7 additions & 2 deletions src/services/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { errors } from "undici-types";
import User from "../sequelize/models/users";
import { hashedPassword } from "../helpers/hashPassword";
import { hashedPassword } from "../utils/hashPassword";
import { Op } from "sequelize";

export const getAllUsers = async () => {
try {
Expand Down Expand Up @@ -30,7 +31,11 @@ export const loggedInUser = async(email:string) => {
};
};
export const createUserService = async (name: string, email: string, username: string, password: string): Promise<User | null> => {
const existingUser = await User.findOne({ where: { email } });
const existingUser = await User.findOne({
where: {
[Op.or]: [{ email }, { username }]
}
});
if (existingUser) {
return null;
}
Expand Down
File renamed without changes.

0 comments on commit 5a994ca

Please sign in to comment.