Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bookingpage img #95

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
Expand Down
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"editor.tabSize": 2,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.insertSpaces": true
}
7 changes: 6 additions & 1 deletion back-end/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ export const userLogin = async (req, res) => {
if (!token) {
return res.status(500).json({ error: "Failed to generate token" });
}
res.cookie("token", token, { httpOnly: true });
res.cookie("token", token, {
httpOnly: true, // Prevents JavaScript access
secure: false, // Set to true in production (over HTTPS)
sameSite: 'Lax', // CSRF protection
maxAge: 60 * 60 * 1000 // 1 hour
});
const { password: _, ...userWithoutPassword } = user.toObject();
res.status(200).json({ message: "User logged in successfully", user: userWithoutPassword });
} catch (error) {
Expand Down
32 changes: 17 additions & 15 deletions back-end/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,22 +179,24 @@ export const removeTicket = async (req, res) => {
}
}

export const getUserInfo = async (req, res) => {
try {
const user = await User.findById(req.user._id).populate("bookings").exec();
if (!user) {
return res.status(404).json({ error: 'User not found' });
export const getUserInfo = async (req, res) => {
try {
const user = await User.findById(req.user._id).populate("bookings").exec();
console.log("User info endpoint hit");
if (!user) {
return res.status(404).json({ error: 'User not found' });
}

// Remove the password field from the user object
const { password, ...userWithoutPassword } = user.toObject();

res.status(200).json({user:userWithoutPassword});
console.log("User info sent");
} catch (error) {
console.error('Error fetching user info:', error); // Log the error for debugging
res.status(500).json({ error: 'Server error' });
}

// Remove the password field from the user object
const { password, ...userWithoutPassword } = user.toObject();

res.status(200).json(userWithoutPassword);
} catch (error) {
console.error('Error fetching user info:', error); // Log the error for debugging
res.status(500).json({ error: 'Server error' });
}
};
};

export const updateProfile = async (req, res) => {
try {
Expand Down
70 changes: 68 additions & 2 deletions back-end/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import movierouter from "./routes/movie.js";
import userRouter from "./routes/user.js";
import showtimeRouter from "./routes/showtime.js";
import ticketRouter from "./routes/ticket.js";
import { Server } from "socket.io";
import http from "http";
import Showtime from "./models/Showtime.js";

dotenv.config();

const app = express();

app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.json());
Expand All @@ -22,10 +27,71 @@ app.use("/api/movie", movierouter);
app.use("/api/user", userRouter);
app.use("/api/showtime", showtimeRouter);
app.use("/api/ticket", ticketRouter);
app.listen(process.env.PORT || 5001, () => {

// Skapa HTTP-server och Socket.io-server
const server = http.createServer(app);
const io = new Server(server);

// Socket.io-anslutningar
io.on("connection", (socket) => {
console.log("A user connected");

socket.on("book-seat", async (seatId, showtimeId) => {
try {
// Uppdatera databasen och signalera till alla anslutna klienter
await updateSeatStatus(seatId, showtimeId);
io.emit("seat-booked", seatId);
} catch (error) {
console.error("Error booking seat:", error);
socket.emit("booking-error", { message: "Failed to book seat" });
}
});

socket.on("disconnect", () => {
console.log("A user disconnected");
});
});

async function updateSeatStatus(seatId, showtimeId) {
try {
// Uppdatera platsens status i Showtime-dokumentet
const updatedShowtime = await Showtime.findOneAndUpdate(
{
_id: showtimeId,
"seats.seat": seatId,
},
{
$set: {
"seats.$.isBooked": true,
},
},
{ new: true }
);

if (!updatedShowtime) {
throw new Error("Showtime or seat not found");
}

// Find the updated seat object
const updatedSeat = updatedShowtime.seats.find(
(seat) => seat.seat.toString() === seatId
);

// Emit a 'seat-status-updated' event with the updated seat object
io.emit("seat-status-updated", updatedSeat);

return updatedSeat;
} catch (error) {
console.error("Error updating seat status:", error);
throw error;
}
}

// Starta servern
server.listen(process.env.PORT, () => {
try {
connectDB();
console.log("Server started at", process.env.PORT || 5001);
console.log("Server started at", process.env.PORT);
} catch (error) {
console.error("Server failed to start");
process.exit(1);
Expand Down
22 changes: 11 additions & 11 deletions front-end/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { useRef, useState } from 'react'
import { BrowserRouter as Router } from 'react-router-dom'
import './App.css'
import Footer from './layout/Footer/Footer'
import Header from './layout/Header/Header'
import Main from './layout/Main/Main'
import React, { useRef, useState } from "react";
import { BrowserRouter as Router } from "react-router-dom";
import "./App.css";
import Footer from "./layout/Footer/Footer";
import Header from "./layout/Header/Header";
import Main from "./layout/Main/Main";

const App: React.FC = () => {
const scheduleRef = useRef<HTMLElement | null>(null);
Expand All @@ -13,26 +13,26 @@ const App: React.FC = () => {
const newDate = new Date();
newDate.setDate(newDate.getDate() + daysAhead);
setSelectedDate(newDate);
scheduleRef.current?.scrollIntoView({ behavior: 'smooth' });
scheduleRef.current?.scrollIntoView({ behavior: "smooth" });
};

return (
<div className="app container g-0 p-0">
<div className="row w-100 g-0">
<Router>
<div className="col-12 sticky-top">
<Header onSelectDate={handleSelectDate}/>
<Header onSelectDate={handleSelectDate} />
</div>
<div className="col-12 g-0">
<Main scheduleRef={scheduleRef} selectedDate={selectedDate}/>
<Main scheduleRef={scheduleRef} selectedDate={selectedDate} />
</div>
<div className="col-12">
<Footer />
</div>
</Router>
</Router>
</div>
</div>
);
};

export default App
export default App;
55 changes: 39 additions & 16 deletions front-end/src/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,52 @@
import { createContext, useState, Dispatch, SetStateAction, ReactNode } from 'react';

import {
createContext,
useState,
Dispatch,
SetStateAction,
ReactNode,
useEffect,
} from "react";
import { useCookies } from "react-cookie";
interface User {
name: string;
email: string;
// Add other user properties here
name: string;
email: string;
// Add other user properties here
}

interface UserContextType {
user: User | null;
setUser: Dispatch<SetStateAction<User | null>>;
user: User | null;
setUser: Dispatch<SetStateAction<User | null>>;
}


export const UserContext = createContext<UserContextType>({
user: null,
setUser: () => null // No-op function with the correct type
user: null,
setUser: () => null, // No-op function with the correct type
});

const UserProvider = ({children}: {children: ReactNode}) => {
const [user, setUser] = useState<User | null>(null);
const UserProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User | null>(null);
const [cookies] = useCookies(["token"]);
useEffect(() => {
if (cookies.token) {
fetch("/api/user/info", {
method: "GET",
credentials: "include",
})
.then((res) => res.json())
.then((data) => {
if (data.user) {
setUser(data.user);
} else if (data.error) {
console.log(data.error);
}
});
}
}, [cookies.token]);
return (
<UserContext.Provider value={{user, setUser}}>
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
)
}
);
};

export default UserProvider
export default UserProvider;
Loading