Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:atlp-rwanda/e-commerce-ninjas-bn…
Browse files Browse the repository at this point in the history
… into fixes
  • Loading branch information
Aime-Patrick committed Aug 24, 2024
2 parents aa86fd2 + ac63cf4 commit 04e04fb
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 82 deletions.
32 changes: 20 additions & 12 deletions src/databases/migrations/20240704115209-create-termsAndCondition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,28 @@ export default {
up: async (queryInterface: QueryInterface) => {
await queryInterface.createTable("termsAndConditions", {

id: {
type: DataTypes.UUID,
allowNull: false,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
content: {
id: {
type: DataTypes.UUID,
allowNull: false,
type: DataTypes.STRING
},
type: {
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
content: {
allowNull: true,
type: DataTypes.TEXT
},
type: {
type: DataTypes.STRING,
allowNull: true
},
allowNull: false
},
pdfUrl: {
type: DataTypes.STRING,
allowNull: true,
unique: true,
validate: {
isUrl: true
}
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
Expand Down
16 changes: 13 additions & 3 deletions src/databases/models/termsAndCodition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export interface ITermsAndConditions {
id: string;
content:string;
type: string;
pdfUrl: string;
}
class TermsAndConditions extends Model<ITermsAndConditions> implements ITermsAndConditions {
declare id: string;
declare content: string;
declare type: string;
declare pdfUrl: string;

static associate() {

Expand All @@ -29,12 +31,20 @@ TermsAndConditions.init(
defaultValue: DataTypes.UUIDV4
},
content: {
allowNull: false,
type: DataTypes.STRING,
allowNull: true,
type: DataTypes.TEXT,
},
type: {
type: DataTypes.STRING,
allowNull: true
allowNull: false
},
pdfUrl:{
type: DataTypes.STRING,
allowNull: true,
unique: true,
validate:{
isUrl: true
}
}
},
{
Expand Down
21 changes: 4 additions & 17 deletions src/middlewares/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { decodeToken } from "../helpers";
import Session from "../databases/models/sessions";
import { Socket } from "socket.io"
import { ExtendedError } from "socket.io/dist/namespace"
import cookie from "cookie";


interface ExtendedRequest extends Request {
Expand All @@ -19,7 +18,7 @@ interface ExtendedRequest extends Request {
export const userAuthorization = function (roles: string[]) {
return async (req: ExtendedRequest, res: Response, next: NextFunction) => {
try {
const token = req.cookies.token;
const token = req.headers["authorization"]?.split(" ")[1];

if (!token) {
return res
Expand Down Expand Up @@ -71,19 +70,7 @@ export const userAuthorization = function (roles: string[]) {

export const socketAuthMiddleware = async (socket: Socket, next: NextFunction) => {
try {
// Extract the cookie from the socket handshake headers
const cookies = socket.handshake.headers.cookie;

if (!cookies) {
const err = new Error("Authentication error") as ExtendedError;
err.data = { message: "No cookies found" };
return next(err);
}

// Parse the cookies and extract the token
const parsedCookies = cookie.parse(cookies);
const token = parsedCookies.token; // Adjust 'token' to match the cookie name where the token is stored

const token = socket.handshake.auth.token;
if (!token) {
const err = new Error("Authentication error") as ExtendedError;
err.data = { message: "No token provided" };
Expand Down Expand Up @@ -120,7 +107,7 @@ export const socketAuthMiddleware = async (socket: Socket, next: NextFunction) =
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
role: user.role,
role:user.role,
profilePicture: user.profilePicture,
};

Expand All @@ -130,4 +117,4 @@ export const socketAuthMiddleware = async (socket: Socket, next: NextFunction) =
err.data = { message: "Internal server error" };
return next(err);
}
};
};
12 changes: 0 additions & 12 deletions src/modules/auth/controller/authControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,6 @@ const loginUser = async (req: any, res: Response) => {
otp: null
};
await authRepositories.createSession(session);
res.cookie('token', token, {
httpOnly: process.env.NODE_ENV === 'production' ? true : false,
secure: process.env.NODE_ENV === 'production' ? true : false,
sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax',
maxAge: 3600000
});
res
.status(httpStatus.OK)
.json({ message: "Logged in successfully", data: { token } });
Expand All @@ -175,12 +169,6 @@ const logoutUser = async (req: any, res: Response) => {
"token",
req.session.token
);
res.cookie('token', "", {
httpOnly: process.env.NODE_ENV === 'production' ? true : false,
secure: process.env.NODE_ENV === 'production' ? true : false,
sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax',
expires: new Date(0)
});
res.status(httpStatus.OK).json({ status: httpStatus.OK, message: "Successfully logged out" });
} catch (err) {
return res
Expand Down
28 changes: 26 additions & 2 deletions src/modules/user/controller/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,26 @@ const adminSetTermsAndCondition = async (req: Request, res: Response) =>{
}
}

const adminSetTermsAndConditionWithPdf = async (req: Request, res: Response) =>{
try {
if(req.file){
const result= await uploadImages(req.file);
req.body.content = result.secure_url;
}
const termsAndCondition = await userRepositories.createTermsAndConditionWithUrl(req.body.content,req.body.type)
return res.status(httpStatus.CREATED).json({
status: httpStatus.CREATED,
message: "Terms and condition created successfully",
data: { termsAndCondition },
});
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
status: httpStatus.INTERNAL_SERVER_ERROR,
message: error.message,
})
}
}

const adminGetTermsAndCondition = async (req: Request, res: Response) =>{
try {
const termsAndCondition = await userRepositories.getTermsAndCondition()
Expand Down Expand Up @@ -425,8 +445,11 @@ const adminGetSingleTermsAndCondition = async (req: Request, res: Response)=>{
}
const adminUpdateTermsAndCondition = async(req: Request, res: Response) =>{
try {
const {content,type} = req.body
const updatedTermsAndCondition = await userRepositories.UpdateTermsAndCondition({content,type},req.params.id)
if(req.file){
const result= await uploadImages(req.file);
req.body.pdfUrl = result.secure_url;
}
const updatedTermsAndCondition = await userRepositories.UpdateTermsAndCondition(req.body,req.params.id)
return res.status(httpStatus.OK).json({
status: httpStatus.OK,
message: "Terms and condition updated successfully",
Expand Down Expand Up @@ -517,4 +540,5 @@ export default {
adminDeleteTermsAndCondition,
adminUpdateTermsAndCondition,
adminDeleteUser,
adminSetTermsAndConditionWithPdf,
};
7 changes: 6 additions & 1 deletion src/modules/user/repository/userRepositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,15 @@ const createTermsAndCondition = async (content: string, type: string) => {
return await db.TermsAndConditions.create({ content, type });
}

const createTermsAndConditionWithUrl = async(url: string,type:string) => {
return await db.TermsAndConditions.create({ pdfUrl: url, type });
}
const getTermsAndCondition = async () => {
return await db.TermsAndConditions.findAll();
};

const UpdateTermsAndCondition = async (data: any, id: string) => {
console.log(data);
await db.TermsAndConditions.update({ ...data }, { where: { id }, returning: true });
const updateTermsAndCondition = await db.TermsAndConditions.findOne({ where: { id} });
return updateTermsAndCondition;
Expand Down Expand Up @@ -262,5 +266,6 @@ export default {
deleteTermsAndCondition,
getTermsAndConditionById,
findTermByType,
deleteUser
deleteUser,
createTermsAndConditionWithUrl
};
73 changes: 39 additions & 34 deletions src/modules/user/validation/userValidations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,66 +22,71 @@ export const statusSchema = Joi.object({

export const roleSchema = Joi.object({
role: Joi.string().valid("admin", "buyer", "seller").required().messages({
"any.required": "The 'role' parameter is required.",
"string.base": "The 'role' parameter must be a string.",
"any.only": "Only admin, buyer and seller are allowed."
"any.required": "The 'role' parameter is required.",
"string.base": "The 'role' parameter must be a string.",
"any.only": "Only admin, buyer and seller are allowed."
})
});
export const termsSchema = Joi.object({
content : Joi.string().required().messages({
"string.base" : "the content should be a string",
"string.empty" : "the content should not be empty"
content: Joi.string().optional().messages({
"string.base": "the content should be a string",
"string.empty": "the content should not be empty"
}),
type : Joi.string().valid("seller", "buyer").required().messages({
type: Joi.string().valid("seller", "buyer").required().messages({
"any.required": "The 'type' parameter is required.",
"string.base": "The 'type' parameter must be a string.",
"any.only": "Only buyer and seller are allowed.",
"string.empty" : "The 'type' parameter cannot be empty"
"string.empty": "The 'type' parameter cannot be empty"
}),
pdf: Joi.string().uri().optional().messages({
"string.base": "pdf should be a type of text",
"string.uri": "pdf must be a valid URI"
})

})
export const userSchema = Joi.object<User>({
firstName: Joi.string().messages({
"string.base": "firstName should be a type of text",
"string.empty": "firstName cannot be an empty field",
"any.required": "firstName is required"
"string.base": "firstName should be a type of text",
"string.empty": "firstName cannot be an empty field",
"any.required": "firstName is required"
}),
lastName: Joi.string().messages({
"string.base": "lastName should be a type of text",
"string.empty": "lastName cannot be an empty field",
"any.required": "lastName is required"
"string.base": "lastName should be a type of text",
"string.empty": "lastName cannot be an empty field",
"any.required": "lastName is required"
}),
phone: Joi.number().messages({
"number.base": "phone number should be a type of number",
"any.required": "phone number is required"
"number.base": "phone number should be a type of number",
"any.required": "phone number is required"
}),
profilePicture: Joi.string().uri().optional().messages({
"string.base": "profilePicture should be a type of text",
"string.uri": "profilePicture must be a valid URI"
"string.base": "profilePicture should be a type of text",
"string.uri": "profilePicture must be a valid URI"
}),
gender: Joi.string().valid("male", "female", "other").messages({
"string.base": "gender should be a type of text",
"any.only": "gender must be one of [male, female, other]",
"any.required": "gender is required"
"string.base": "gender should be a type of text",
"any.only": "gender must be one of [male, female, other]",
"any.required": "gender is required"
}),
birthDate: Joi.date().iso().messages({
"date.base": "birthDate should be a valid date",
"date.iso": "birthDate must be in ISO format",
"any.required": "birthDate is required"
"date.base": "birthDate should be a valid date",
"date.iso": "birthDate must be in ISO format",
"any.required": "birthDate is required"
}),
language: Joi.string().messages({
"string.base": "language should be a type of text",
"string.empty": "language cannot be an empty field",
"any.required": "language is required"
"string.base": "language should be a type of text",
"string.empty": "language cannot be an empty field",
"any.required": "language is required"
}),
currency: Joi.string().messages({
"string.base": "currency should be a type of text",
"string.empty": "currency cannot be an empty field",
"any.required": "currency is required"
"string.base": "currency should be a type of text",
"string.empty": "currency cannot be an empty field",
"any.required": "currency is required"
}),
role: Joi.string().valid("buyer", "seller", "admin").messages({
"string.base": "role should be a type of text",
"any.only": "role must be one of [buyer, seller, admin]",
"any.required": "role is required"
"string.base": "role should be a type of text",
"any.only": "role must be one of [buyer, seller, admin]",
"any.required": "role is required"
})
});

Expand All @@ -98,7 +103,7 @@ export const changePasswordSchema = Joi.object({
"string.min": "New password should have a minimum length of 8",
"string.pattern.base": "New password must contain both letters and numbers",
"any.required": "New password is required"
}),
}),
confirmPassword: Joi.string().valid(Joi.ref("newPassword")).required().messages({
"any.only": "Confirm password must match new password",
"any.required": "Confirm password is required"
Expand Down
7 changes: 6 additions & 1 deletion src/routes/userRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ import upload from "../helpers/multer";
router.get("/admin-get-user-request/:userId", userAuthorization(["admin"]),isSellerRequestExist,userControllers.adminGetRequestDetails);
router.put("/admin-accept-or-reject-request/:userId", userAuthorization(["admin"]),isSellerRequestExist,isRequestAcceptedOrRejected,userControllers.adminAcceptOrDenyRequest);
router.delete("/admin-delete-user-request/:userId/:id", userAuthorization(["admin"]),isSellerRequestExist,userControllers.adminDeleteSellerRequest);
router.get("/admin-get-users-request", userAuthorization(["admin"]),isSellerRequestExist,userControllers.adminGetAllSellerRequested);
router.get("/admin-get-user-request/:userId", userAuthorization(["admin"]),isSellerRequestExist,userControllers.adminGetRequestDetails);
router.put("/admin-accept-or-reject-request/:userId", userAuthorization(["admin"]),isSellerRequestExist,isRequestAcceptedOrRejected,userControllers.adminAcceptOrDenyRequest);
router.delete("/admin-delete-user-request/:userId/:id", userAuthorization(["admin"]),isSellerRequestExist,userControllers.adminDeleteSellerRequest);
router.put("/admin-update-password-expiration", userAuthorization(["admin"]), validation(passwordExpirationTimeSchema), userControllers.updatePasswordExpirationSetting);
router.get("/admin-get-password-expiration", userAuthorization(["admin"]), userControllers.getPasswordExpiration);
router.post("/admin-set-terms", userAuthorization(["admin"]), validation(termsSchema),isTermsTypeExist,userControllers.adminSetTermsAndCondition);
router.post("/admin-set-terms-with-pdf", userAuthorization(["admin"]), upload.single("pdf"),validation(termsSchema),isTermsTypeExist,userControllers.adminSetTermsAndConditionWithPdf);
router.get("/user-get-terms",userControllers.adminGetTermsAndCondition);
router.get("/admin-get-terms/:id", userAuthorization(["admin"]),isTermsAndConditionsExist,userControllers.adminGetSingleTermsAndCondition);
router.put("/admin-update-terms/:id", userAuthorization(["admin"]),isTermsAndConditionsExist,userControllers.adminUpdateTermsAndCondition);
router.put("/admin-update-terms/:id", userAuthorization(["admin"]),upload.single("pdf"),isTermsAndConditionsExist,userControllers.adminUpdateTermsAndCondition);
router.delete("/admin-delete-terms/:id", userAuthorization(["admin"]),isTermsAndConditionsExist,userControllers.adminDeleteTermsAndCondition);


Expand Down

0 comments on commit 04e04fb

Please sign in to comment.