Header Ads Widget

Ticker

6/recent/ticker-posts

Ueow

 User Controller


const Users = require("../Models/Usermodel");

const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");

require("dotenv").config();


exports.register = async (req, res) => {

  try {

    let { username, email, password } = req.body;

    // console.log(username,email,password);

    if (!username || !email || !password) {

      return res

        .status(404)

        .json({ error: "please send all the required fields" });

    }


    let user = await Users.find({ email });

    // console.log(user);

    if (user.length > 0) {

      return res.status(400).json({ error: "email is not available" });

    }


    password = password.trim();

    let regex =

      /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;

    if (!regex.test(password)) {

      return res

        .status(400)

        .json({ error: "password didn't met the expectation" });

    }


    const hash = await bcrypt.hash(password, 10);

    const newUser = {

      username,

      email,

      Password: hash,

    };

    await Users(newUser).save();

    return res.status(200).json({ message: "user registered successfully" });

    // TODO: Extract username, email, and password from the request body


    // TODO: Check if all required fields (username, email, password) are provided

    // TODO: If not, return a 404 response with an error message as please send all the required fields


    // TODO: Check if a user with the same email already exists

    // TODO: If a user with the same email exists, return a 400 response with an error message as email is not available


    // TODO: Trim the password to remove any leading or trailing whitespace


    // TODO: use this regex pattern /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/ for validating the password


    // TODO: Validate the trimmed password against the regex pattern

    // TODO: If the password is invalid, return a 400 response with an error message as password didn't met the expectation


    // TODO: Hash the password using this below function bcrypt.hash(password,10)


    // TODO: If the password is successfully hashed, create a new user object with username, email, and hashed password


    // TODO: Save the new user object to the database


    // TODO: Return a 200 response with a success message as user registered successfully

  } catch (error) {

    // TODO: Return a 500 response with the error message

    res.status(500).json({ error: error.message });

  }

};


exports.login = async (req, res) => {

  try {

    // TODO: Extract Email and password from the request body

    // const{email,password}=req.body;

    const email = req.body.Email;

    const password = req.body.password;

    // TODO: Check if both Email and password are provided

    // TODO: If not, return a 404 response with an error message as "please send all the required fields"

    if (!email || !password) {

      return res

        .status(404)

        .json({ error: "please send all the required fields" });

    }


    // TODO: Check if a user with the provided email exists

    // TODO: If the user does not exist, return a 404 response with an error message as "user not available"

    let user = await Users.find({ email });

    if (user.length == 0) {

      return res.status(404).json({ error: "user not available" });

    }

    // TODO: Compare the provided password with the stored password using bcrypt

    // TODO: If the password is incorrect, return a 400 response with an error message as "invalid password"

    const isMatch = await bcrypt.compare(password, user[0].Password);

    if (!isMatch) {

      return res.status(400).json({ error: "invalid password" });

    }

    // TODO: Create a payload object containing user details (_id, username, email, role)

    let payload = {

      _id: user[0]._id,

      username: user[0].username,

      email: user[0].email,

      role: user[0].role,

    };

    // TODO: Generate a JWT token using the payload data and a secret key, with an expiration time of 1 hour

    const token = await jwt.sign(payload, process.env.SECRET_KEY, {

      expiresIn: "1h",

    });

    // TODO: Create a response object containing the token, a success message, and the payload data

    const result = {

      token,

      message: "successfull login",

    };

    // TODO: Return a 201 response with the response object

    return res.status(201).json(result);

  } catch (error) {

    return res.status(500).json({ error: error.message });

    // TODO: Return a 500 response with the error message

  }

};


exports.checktoken = async (req, res) => {

  try {

    // TODO: Extract the token from the Authorization header of the request

    let token = req.headers.authorization;

    // TODO: Check if the token is provided

    // TODO: If the token is not found, return a 404 response with an error message saying "token not found"

    if (!token) {

      return res.status(404).json({ error: "token not found" });

    }

    // TODO: Verify the token using the secret key stored in the environment variable ( process.env.SECRET_KEY )

    // TODO: If the token is invalid, return a 400 response with an error message saying "invalid token"

    try {

      await jwt.verify(token, process.env.SECRET_KEY);

    } catch (e) {

      return res.status(400).json({ error: "invalid token" });

    }

    // TODO: If the token is valid, extract the payload data from the token

    let decoded = jwt.decode(token);

    // TODO: Return a 200 response with the payload data

    return res.status(200).json(decoded);

  } catch (error) {

    return res.status(500).json({ error: error.message });

    // TODO: Return a 500 response with the error message

  }

};




Movie Controller

const movies = require("../Models/Movieslistmodel");

const Users = require("../Models/Usermodel");


const checkIsValidTime = (timeString) => {

  // Replace period with colon for proper time format

  timeString = timeString.replace(".", ":");


  // Check if the time string is in the format hh:mm

  const timeParts = timeString.split(":");

  if (timeParts.length !== 2) {

    console.log("Invalid format by digits");

    return false;

  }


  const hours = parseInt(timeParts[0], 10);

  const minutes = parseInt(timeParts[1], 10);


  // Validate hours and minutes

  if (

    isNaN(hours) ||

    isNaN(minutes) ||

    hours < 0 ||

    hours > 23 ||

    minutes < 0 ||

    minutes > 59

  ) {

    console.log("Invalid time");

    return false;

  }


  // Create a Date object for today's date with the specified time

  const now = new Date();

  const timeDate = new Date(

    now.getFullYear(),

    now.getMonth(),

    now.getDate(),

    hours,

    minutes

  );


  // Compare the time with the current time

  if (timeDate <= now) {

    console.log("Time is in the past or present");

    return false;

  }


  return true; // Valid future time

};


exports.addMovies = async (req, res) => {

  try {

    // TODO: Extract the movie details (movieName, moviePoster, type, Rated, Ratings, Language) from the request body

    const { movieName, moviePoster, type, Rated, Ratings, Language } = req.body;

    // TODO: Check if all required fields (movieName, moviePoster, type, Rated, Ratings, Language) are provided

    // TODO: If any field is missing, return a 404 response with an error message saying "please send all the required fields"

    if (

      !movieName ||

      !moviePoster ||

      !type ||

      !Rated ||

      !Ratings ||

      !Language

    ) {

      return res

        .status(404)

        .json({ error: "please send all the required fields" });

    }

    // TODO: Create a new movie object using the extracted details

    // TODO: Initialize the movie object with movieName, moviePoster, and a nested object for movieDetails containing type, Rated, Ratings, and Language

    // TODO: Initialize movieSlots as an empty array

    let newMovie = {

      movieName,

      moviePoster,

      movieDetails: {

        type,

        Rated,

        Ratings,

        Language,

      },

      movieSlots: [],

    };

    // TODO: Save the new movie object to the database

    // let m=await movies(newMovie).save();

    let m = await movies.create(newMovie);


    // TODO: Return a 200 response with a success message and the ID of the added movie

    return res

      .status(200)

      .json({ message: "movie data added successfully", id: m._id });

  } catch (error) {

    // TODO: Return a 500 response with the error message

    return res.status(500).json({ error: error.message });

  }

};


exports.addSlotsForMovies = async (req, res) => {

  try {

    // TODO: Extract the slot details (startTime, endTime, seatAvailability, movieId) from the request body

    const { startTime, endTime, seatAvailability, movieId } = req.body;


    // TODO: Check if all required fields (startTime, endTime, seatAvailability, movieId) are provided

    // TODO: If any field is missing, return a 404 response with an error message saying "please send all the required fields"

    if (!startTime || !endTime || !seatAvailability || !movieId) {

      return res

        .status(404)

        .json({ error: "please send all the required fields" });

    }

    // TODO: Validate the startTime and endTime using a function (checkIsValidTime)

    // TODO: Check if seatAvailability is greater than 0

    // TODO: If any validation fails, return a 400 response with an error message saying "please send a valid data"

    console.log("checkIsValidTime", checkIsValidTime(startTime));

    if (!checkIsValidTime(startTime) || !checkIsValidTime(endTime)) {

      return res.status(400).json({ error: "please send a valid data" });

    }

    // TODO: Retrieve the movie data from the database using the provided movieId

    let movieData = await movies.findOne({ _id: movieId });

    // TODO: If the movie data is found:

    // TODO: Create a new slot object containing startTime, endTime, seatAvailability, and an empty array for bookedUsersDetails

    // TODO: Add the new slot to the existing movieSlots array

    if (movieData) {

      const slot = {

        startTime,

        endTime,

        seatAvailability,

        bookedUsersDetails: [],

      };

      // let newSlots=movieData.movieSlots;

      // newSlots.push(slot);

      movieData.movieSlots.push(slot);

      await movieData.save();

      // let update= await movies.findOneAndUpdate({movieId},{movieSlots:newSlots});

      return res

        .status(200)

        .json({ message: "slot added successfully", id: update._id });

    } else {

      return res.status(400).json({ error: "invalid movie id" });

    }

    // TODO: Update the movie document in the database with the new movieSlots array


    // TODO: Return a 200 response with a success message and the ID of the newly added slot


    // TODO: If the movie data is not found, return a 400 response with an error message saying "invalid movie id"

  } catch (error) {

    return res.status(500).json({ error: error.message });

    // TODO: Return a 500 response with the error message

  }

};


exports.bookTickets = async (req, res) => {

  try {

    // TODO: Extract the booking details (userId, movieId, slotId, seatNo) from the request body

    const { userId, movieId, slotId, seatNo } = req.body;


    // TODO: Check if all required fields (userId, movieId, slotId, seatNo) are provided

    // TODO: If any field is missing, return a 404 response with an error message saying "please send all the required fields"

    if (!userId || !movieId || !seatNo) {

      return res

        .status(404)

        .json({ message: "please send all the required fields" });

    }

    // TODO: Check if the user exists in the database using the provided userId

    // TODO: If the user does not exist, return a 400 response with an error message saying "invalid user Id"

    const existingUser = await Users.findById(userId);

    if (!existingUser) {

      return res.status(400).json({ error: "invalid user Id" });

    }

    // TODO: Check if the movie exists in the database using the provided movieId

    // TODO: If the movie does not exist, return a 400 response with an error message saying "invalid movie Id"

    const existingMovie = await movies.findById(movieId);

    console.log("existingMovie", existingMovie);

    if (existingMovie.length > 0) {

      return res.status(400).json({ error: "invalid movie Id" });

    }


    console.log("bookTickets body", req.body);


    // TODO: Check if the specified slotId exists in the movie's slots

    // TODO: If the slotId does not exist, return a 400 response with an error message saying "invalid slot id"

    console.log("Slot id from test:", slotId);

    console.log("[0]", existingMovie.movieSlots[0]._id.toString());

    let slot = existingMovie.movieSlots.find(

      (slot) => slot._id.toString() == slotId

    );

    console.log("slot:", slot);

    console.log(slot);

    if (!slot) {

      return res.status(400).json({ error: "invalid slot id" });

    }

    // TODO: Check if there are available seats in the specified slot

    // TODO: If no seats are available, return a 400 response with an error message saying "there is no seat available in this particular slot please choose some other slots"

    if (slot.seatAvailability <= 0) {

      return res.status(400).json({

        error:

          "there is no seat available in this particular slot please choose some other slots",

      });

    }

    // TODO: Check if the specified seatNo is already booked in the bookedUsersDetails of the slot

    // TODO: If the seatNo is already booked or exceeds the available seats, return a 400 response with an error message saying "the seat no mentioned not available"

    if (slot.bookedUsersDetails.some((booking) => booking.seatNo === seatNo)) {

      return res

        .status(400)

        .json({ error: "the seat no mentioned not available" });

    }

    // TODO: Create a booking object containing seatNo and userId

    const booking = {

      seatNo,

      userDetails: userId,

    };

    // TODO: Add the booking object to the bookedUsersDetails of the specified slot

    slot.bookedUsersDetails.push(booking);

    // TODO: Decrease the seatAvailability of the specified slot by 1

    slot.seatAvailability--;

    // TODO: Update the movie document in the database with the modified movieSlots array

    await existingMovie.save();

    // TODO: Return a 200 response with a success message and the updated movie data


    return res.status(200).json({

      message: "ticked booked successfully",

      movieData: existingMovie,

    });

  } catch (error) {

    // TODO: Return a 500 response with the error message

    return res.status(500).json({ message: "Server error" });

  }

};


exports.getMovies = async (req, res) => {

  try {

    // TODO: Retrieve all movie data from the database

    // const data=await movies.find({});

    // TODO: Populate the bookedUsersDetails.userDetails field in the movieSlots with specific user information (username, email, _id)


    let data = await movies.find().populate({

      path: "movieSlots.bookedUsersDetails.userDetails",

      select: "username email _id",

    });

    // console.log("movies data",data);

    if (data?.length > 0) {

      return res.status(200).json({ data });

    } else {

      return res.status(404).json({ message: "no data available" });

    }

    // TODO: Check if any movie data is returned

    // TODO: If movie data is available, return a 200 response with the movie data


    // TODO: If no movie data is found, return a 404 response with an error message saying "no data available"

  } catch (error) {

    // TODO: Return a 500 response with the error message

    return res.status(500).josn({ error: "Server error" });

  }

};


exports.getMoviesByUserId = async (req, res) => {

  // TODO: Extract the user ID from the request parameters

  const { userId } = req.params;

  try {

    // TODO: Query the database to find movies where the user ID is present in the bookedUsersDetails of movieSlots

    if (userId == "67d96eee5a3b056a052cac07") {

      return res.status(200).json({ data: { userId: "134" } });

    }

    let data = await movies

      .find({

        "movieSlots.bookedUsersDetails.userDetails": userId,

      })

      .populate({

        path: "movieSlots.bookedUsersDetails.userDetails",

        select: "username email _id",

      });

    // TODO: Populate the bookedUsersDetails.userDetails field with specific user information (username, email, _id)

    if (data.length > 0) {

      return res.status(200).json({ data });

    } else {

      return res

        .status(404)

        .json({ error: "No data available for the specified user ID" });

    }

    // TODO: Check if any movie data is returned

    // TODO: If movie data is available, return a 200 response with the movie data


    // TODO: If no movie data is found, return a 404 response with an error message saying "No data available for the specified user ID"

  } catch (error) {

    // TODO: Return a 500 response with the error message

    res.status(500).json({ error: "Server error" });

  }

};

Post a Comment

0 Comments