Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/controllers/media.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
import { RequestHandler } from 'express';
import { MediaService } from '../services/media.service';
import { cloudinaryService } from '../lib/cloudinary';
import Media from '../models/media';
import EventTicket from '../models/event-ticket';

async function verifyMediaOwnership(req: any, publicId: string): Promise<boolean> {
const userId = req.user?._id || req.user?.id;
if (!userId) return false;

const isAdmin = (req.user as any)?.role === 'admin';
if (isAdmin) return true;

const mediaRecord = await Media.findOne({ publicId });
if (mediaRecord && mediaRecord.userId.toString() === userId.toString()) {
return true;
}

const eventTicket = await EventTicket.findOne({ cloudinary_public_id: publicId });
if (eventTicket && eventTicket.organizedBy.toString() === userId.toString()) {
return true;
}

return false;
}

export const uploadMedia: RequestHandler = async (req, res) => {
try {
Expand All @@ -15,6 +37,19 @@ export const uploadMedia: RequestHandler = async (req, res) => {

const result = await MediaService.upload(req.file.buffer, { folder });

const userId = req.user?._id || req.user?.id;
if (userId) {
try {
await Media.findOneAndUpdate(
{ publicId: result.publicId },
{ userId: userId, publicId: result.publicId },
{ upsert: true, new: true },
);
} catch (e) {
if ((e as any)?.code !== 11000) throw e;
}
}

res.status(201).json({
message: 'File uploaded successfully',
data: result,
Expand All @@ -39,6 +74,14 @@ export const invalidateMedia: RequestHandler = async (req, res) => {
});
}

const authorized = await verifyMediaOwnership(req, publicId);
if (!authorized) {
return res.status(403).json({
error: 'Forbidden',
message: 'You are not authorized to invalidate this media',
});
}

const result = await MediaService.invalidate(publicId);

res.status(200).json({
Expand Down Expand Up @@ -68,6 +111,14 @@ export const destroyMedia: RequestHandler = async (req, res) => {
});
}

const authorized = await verifyMediaOwnership(req, publicId);
if (!authorized) {
return res.status(403).json({
error: 'Forbidden',
message: 'You are not authorized to delete this media',
});
}

const result = await MediaService.destroy(publicId);

res.status(200).json({
Expand Down
17 changes: 17 additions & 0 deletions src/models/media.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import mongoose, { Schema, Document } from 'mongoose';

export interface IMedia extends Document {
publicId: string;
userId: mongoose.Types.ObjectId;
}

const mediaSchema = new Schema<IMedia>(
{
publicId: { type: String, required: true, unique: true },
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
},
{ timestamps: true },
);

const Media = mongoose.model<IMedia>('Media', mediaSchema);
export default Media;
64 changes: 45 additions & 19 deletions src/services/event-ticket.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mongoose from 'mongoose';
import EventTicket, { IEventTicket } from '../models/event-ticket';
import TicketOrder, { ITicketOrder } from '../models/ticket-order';
import User from '../models/user';
import Media from '../models/media';
import zkEmailNotificationService from './zk-email-notification.service';

import { CreateEventStepTwoInput } from '../validators/event.validator';
Expand Down Expand Up @@ -270,6 +271,9 @@ export class EventTicketService {
tags: string[];
},
): Promise<IEventTicket> {
const session = await mongoose.startSession();
session.startTransaction();

try {
const {
privacyLevel,
Expand Down Expand Up @@ -299,28 +303,50 @@ export class EventTicketService {
attendanceMode || this.mapPrivacyLevelToAttendanceMode(privacyLevel);

// Create the event with all privacy settings
const event = await EventTicket.create({
...baseEventData,
privacyLevel,
attendanceMode: mappedAttendanceMode,
eventType,
locationType,
location,
paymentPrivacy,
offerReceipts,
hasZkEmailUpdates,
hasEventReminders,
ticketType: ticketTypes,
totalTickets,
availableTickets: totalTickets,
soldTickets: 0,
isPublished,
allowAnonymous,
requiresVerification,
});
const event = await EventTicket.create(
[
{
...baseEventData,
privacyLevel,
attendanceMode: mappedAttendanceMode,
eventType,
locationType,
location,
paymentPrivacy,
offerReceipts,
hasZkEmailUpdates,
hasEventReminders,
ticketType: ticketTypes,
totalTickets,
availableTickets: totalTickets,
soldTickets: 0,
isPublished,
allowAnonymous,
requiresVerification,
},
],
{ session },
).then((docs) => docs[0]);

if (event.cloudinary_public_id && baseEventData.organizedBy) {
const existingMedia = await Media.findOne({
publicId: event.cloudinary_public_id,
userId: baseEventData.organizedBy,
}).session(session);
if (!existingMedia) {
throw new Error(
`Media with publicId ${event.cloudinary_public_id} does not exist or is not owned by organizer`,
);
}
}

await session.commitTransaction();
session.endSession();

return event;
} catch (error) {
await session.abortTransaction();
session.endSession();
throw new Error(
`Failed to create event with privacy settings: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
Expand Down
Loading
Loading