Changeset 8ca35dc
- Timestamp:
- 01/19/25 23:18:37 (4 months ago)
- Branches:
- main
- Children:
- f5b256e
- Parents:
- db39d9e
- Files:
-
- 4 added
- 49 edited
Legend:
- Unmodified
- Added
- Removed
-
my-react-app/package-lock.json
rdb39d9e r8ca35dc 14 14 "axios": "^1.6.7", 15 15 "bootstrap": "^5.3.2", 16 "jwt-decode": "^4.0.0", 16 17 "react": "^18.2.0", 17 18 "react-dom": "^18.2.0", … … 12268 12269 } 12269 12270 }, 12271 "node_modules/jwt-decode": { 12272 "version": "4.0.0", 12273 "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz", 12274 "integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==", 12275 "engines": { 12276 "node": ">=18" 12277 } 12278 }, 12270 12279 "node_modules/keyv": { 12271 12280 "version": "4.5.4", -
my-react-app/package.json
rdb39d9e r8ca35dc 9 9 "axios": "^1.6.7", 10 10 "bootstrap": "^5.3.2", 11 "jwt-decode": "^4.0.0", 11 12 "react": "^18.2.0", 12 13 "react-dom": "^18.2.0", -
my-react-app/src/App.js
rdb39d9e r8ca35dc 1 import {BrowserRouter as Router, Route, Routes, useNavigate} from 'react-router-dom';1 import {BrowserRouter as Router, Navigate, Route, Routes, useNavigate} from 'react-router-dom'; 2 2 import Customers from './components/Customers'; 3 3 import Layout from "./components/Layout"; … … 14 14 import { CuisineContext } from './components/CuisineContext'; 15 15 import RestaurantInfo from "./components/RestaurantInfo"; 16 import LoginForm from "./components/Login";16 import AuthForm from "./components/AuthForm"; 17 17 import AppContent from "./components/AppContent"; 18 import ReservationHistory from "./components/ReservationHistory"; 19 20 const ProtectedRoute = ({ element, isAuthenticated }) => { 21 return isAuthenticated ? element : <Navigate to="/login" />; 22 }; 18 23 19 24 const App = () => { 25 const [isAuthenticated, setIsAuthenticated] = React.useState(false); 26 27 React.useEffect(() => { 28 const token = localStorage.getItem('token'); 29 if (token) { 30 setIsAuthenticated(true); 31 } 32 }, []); 33 20 34 return ( 21 35 <Router> … … 23 37 <Routes> 24 38 <Route path="/" element={<Home />} /> 25 <Route path="/customers" element={<Customers />} /> 26 <Route path="/customers/add" element={<CustomerFormContainer/>} /> 27 <Route path="/customers/:id" element={<CustomerDetails />} /> 28 <Route path="/customers/edit/:id" element={<CustomerFormContainer/>} /> 29 <Route path="/restaurants" element={<Restaurants />} /> 30 <Route path="/restaurants/:id" element={<RestaurantDetails />} /> 31 <Route path="/reservations" element={<Reservations />} /> 32 <Route path="/reservationConfirmation/:tableNumber/:timeSlot/:restaurantId" element={<ReservationConfirmation />} /> 33 <Route path="/reservations/reservationEdit/:reservationId" element={<ReservationEdit />} /> 34 <Route path="/login" element={<LoginForm/>}/> 35 <Route path="/error" element={<ErrorPage/>}/> 39 <Route path="/customers" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Customers />} />} /> 40 <Route path="/customers/add" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerFormContainer />} />} /> 41 <Route path="/customers/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerDetails />} />} /> 42 <Route path="/customers/edit/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<CustomerFormContainer />} />} /> 43 <Route path="/restaurants" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Restaurants />} />} /> 44 <Route path="/restaurants/:id" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<RestaurantDetails />} />} /> 45 <Route path="/reservations" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<Reservations />} />} /> 46 <Route path="/reservationConfirmation/:tableNumber/:timeSlot/:restaurantId" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationConfirmation />} />} /> 47 <Route path="/reservations/reservationEdit/:reservationId" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationEdit />} />} /> 48 <Route path="/reservations-past" element={<ProtectedRoute isAuthenticated={isAuthenticated} element={<ReservationHistory />} />} /> 49 <Route path="/login" element={<AuthForm setIsAuthenticated={setIsAuthenticated} />} /> 50 51 <Route path="/error" element={<ErrorPage />} /> 36 52 </Routes> 37 <AppContent/>38 53 </Layout> 39 54 </Router> 40 55 ); 41 } 56 }; 42 57 43 58 … … 149 164 150 165 try { 151 const response = await axios.post('http://localhost:808 0/api/search', data);166 const response = await axios.post('http://localhost:8081/api/search', data); 152 167 const filteredRestaurants = response.data; 153 168 setFilteredRestaurants(filteredRestaurants); … … 163 178 const cuisineName = cuisine.replace('Searching by cuisine: ', ''); 164 179 try { 165 const response = await axios.post(`http://localhost:808 0/api/search/shortcut/${cuisineName}`, cuisineName);180 const response = await axios.post(`http://localhost:8081/api/search/shortcut/${cuisineName}`, cuisineName); 166 181 console.log(response.data); 167 182 setFilteredRestaurants(response.data) -
my-react-app/src/axios_helper.js
rdb39d9e r8ca35dc 1 1 import axios from "axios"; 2 2 import data from "bootstrap/js/src/dom/data"; 3 axios.defaults.baseURL = 'http://localhost:808 0'3 axios.defaults.baseURL = 'http://localhost:8081' 4 4 axios.defaults.headers.post["Content-Type"] = 'application/json' 5 5 6 6 export const getAuthToken = () => { 7 7 return window.localStorage.getItem("auth_token"); 8 }9 10 export const setAuthToken = (token) => {11 window.localStorage.setItem("auth_token", token);12 8 } 13 9 … … 24 20 }) 25 21 } 22 23 export const setAuthToken = (token) => { 24 if (token) { 25 axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; 26 localStorage.setItem('token', token); 27 } else { 28 delete axios.defaults.headers.common['Authorization']; 29 localStorage.removeItem('token'); 30 } 31 }; -
my-react-app/src/components/AppContent.js
rdb39d9e r8ca35dc 1 import * as React from "react"; 1 import React from "react"; 2 import axios from "axios"; 2 3 import WelcomeContent from "./WelcomeContent"; 3 4 import AuthContent from "./AuthContent"; 4 5 import LoginForm from "./LoginForm"; 5 import { request, setAuthToken } from "../axios_helper"; 6 import Buttons from './Buttons' 6 import AuthForm from "./AuthForm"; 7 import Buttons from './Buttons'; 8 import restaurants from "./Restaurants"; 7 9 8 export defaultclass AppContent extends React.Component {10 class AppContent extends React.Component { 9 11 constructor(props) { 10 12 super(props); 11 13 this.state = { 12 componentToShow: "welcome" 14 componentToShow: "welcome", 15 isAuthenticated: false, 16 user: null, 17 loading: false // Add loading state 13 18 }; 19 } 20 21 componentDidMount() { 22 const token = localStorage.getItem('token'); 23 console.log(token); 24 if (token) { 25 this.setAuthToken(token); 26 this.setState({ componentToShow: "restaurants", isAuthenticated: true }); 27 } 28 } 29 30 fetchUserDetails = (token) => { 31 console.log("Fetch"); 32 axios.get("/api/user") 33 .then((response) => { 34 this.setState({ user: response.data, componentToShow: "restaurants", isAuthenticated: true }); 35 }) 36 .catch((error) => { 37 console.error("Failed to fetch user details:", error); 38 this.logout(); 39 }); 14 40 }; 15 41 16 42 login = () => { 17 this.setState({ componentToShow: "login"})43 this.setState({ componentToShow: "login" }); 18 44 } 19 45 20 46 logout = () => { 21 this.setState({componentToShow: "welcome"}) 47 localStorage.removeItem('token'); 48 this.setAuthToken(null); 49 this.setState({ componentToShow: "welcome", isAuthenticated: false }); 22 50 } 23 51 24 52 onLogin = (e, email, password) => { 25 53 e.preventDefault(); 26 request( 27 "POST", 28 "/api/login", 29 {email: email, password: password} 30 ).then((response) => { 31 this.setState({componentToShow: "restaurants"}) 32 setAuthToken(response.data.token); 33 }).catch((error) => { 34 this.setState({componentToShow: "welcome"}) 35 }); 54 // After successful login, save the token 55 axios.post("/api/login", { email, password }) 56 .then((response) => { 57 const token = response.data.token; 58 localStorage.setItem('token', token); // Save the token 59 console.log(token); 60 this.setAuthToken(token); // Set the token for future requests 61 this.setState({ componentToShow: "restaurants", isAuthenticated: true }); 62 }) 63 .catch((error) => { 64 console.error("Login failed:", error); 65 this.setState({ componentToShow: "welcome" }); 66 }); 67 36 68 }; 37 69 38 70 onRegister = (e, firstName, lastName, email, password) => { 39 71 e.preventDefault(); 40 request( 41 "POST", 42 "/api/register", 43 { 44 firstName: firstName, 45 lastName: lastName, 46 email: email, 47 password: password 48 } 49 ).then((response) => { 50 this.setState({componentToShow: "restaurants"}) 51 setAuthToken(response.data.token); 52 }).catch((error) => { 53 this.setState({componentToShow: "welcome"}) 54 }); 72 axios.post("/api/register", { firstName, lastName, email, password }) 73 .then((response) => { 74 const token = response.data.token; 75 localStorage.setItem('token', token); 76 console.log(token); 77 this.setAuthToken(token); 78 this.fetchUserDetails(token); 79 }) 80 .catch((error) => { 81 this.setState({ componentToShow: "welcome" }); 82 console.error(error); 83 }); 84 }; 85 86 setAuthToken = (token) => { 87 if (token) { 88 axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; 89 } else { 90 delete axios.defaults.headers.common["Authorization"]; 91 } 55 92 }; 56 93 … … 58 95 return ( 59 96 <div> 60 <Buttons login={this.login} logout={this.logout}></Buttons> 61 {this.state.componentToShow === "welcome" && <WelcomeContent/>} 62 {this.state.componentToShow === "restaurants" && <AuthContent/>} 63 {this.state.componentToShow === "login" && <LoginForm onLogin={this.onLogin} onRegister={this.onRegister}/>} 97 <Buttons login={this.login} logout={this.logout} /> 98 {this.state.componentToShow === "welcome" && <WelcomeContent />} 99 {this.state.componentToShow === "restaurants" && <AuthContent />} 100 {this.state.componentToShow === "login" && <LoginForm onLogin={this.onLogin} onRegister={this.onRegister} />} 101 {this.state.loading && <div>Loading...</div>} {/* Show loading state */} 64 102 </div> 65 ) 103 ); 66 104 } 67 105 } 106 107 108 export default AppContent; -
my-react-app/src/components/AuthContent.js
rdb39d9e r8ca35dc 28 28 <p>Cuisine Type: {restaurant.cuisineType}</p> 29 29 <p>Address: {restaurant.address}</p> 30 30 <p>User: {}</p> 31 31 </div> 32 32 ))} -
my-react-app/src/components/CuisineContext.js
rdb39d9e r8ca35dc 10 10 const fetchCuisineTypes = async () => { 11 11 try { 12 const response = await axios.get('http://localhost:808 0/api/cuisineTypes');12 const response = await axios.get('http://localhost:8081/api/cuisineTypes'); 13 13 setCuisineTypes(response.data); 14 14 } catch (error) { -
my-react-app/src/components/CustomerContext.js
rdb39d9e r8ca35dc 10 10 const fetchCustomers = async () => { 11 11 try { 12 const response = await axios.get("http://localhost:808 0/api/customers");12 const response = await axios.get("http://localhost:8081/api/customers"); 13 13 setCustomers(response.data) 14 14 } catch (error) { -
my-react-app/src/components/CustomerDetails.js
rdb39d9e r8ca35dc 10 10 const fetchCustomer = async () => { 11 11 try { 12 const response = await axios.get(`http://localhost:808 0/api/customers/${id}`);12 const response = await axios.get(`http://localhost:8081/api/customers/${id}`); 13 13 setCustomer(response.data); 14 14 } catch (error) { -
my-react-app/src/components/CustomerFormContainer.js
rdb39d9e r8ca35dc 26 26 const fetchCustomer = async () => { 27 27 try { 28 const response = await axios.get(`http://localhost:808 0/api/customers/${id}`);28 const response = await axios.get(`http://localhost:8081/api/customers/${id}`); 29 29 const customerData = response.data; 30 30 setFormData({ … … 54 54 try { 55 55 if (customer) { 56 await axios.put(`http://localhost:808 0/api/customers/edit/${customer.id}`, formData);56 await axios.put(`http://localhost:8081/api/customers/edit/${customer.id}`, formData); 57 57 } else { 58 await axios.post("http://localhost:808 0/api/customers", formData);58 await axios.post("http://localhost:8081/api/customers", formData); 59 59 } 60 60 navigate("/customers"); -
my-react-app/src/components/Customers.js
rdb39d9e r8ca35dc 26 26 const handleDeleteClick = async (customerId) => { 27 27 try { 28 await axios.delete(`http://localhost:808 0/api/customers/delete/${customerId}`);28 await axios.delete(`http://localhost:8081/api/customers/delete/${customerId}`); 29 29 setCustomers(customers.filter(customer => customer.customerID !== customerId)); 30 30 window.location.reload(); … … 48 48 <p className="card-text"><strong>Phone:</strong> {customer.phone}</p> 49 49 <p className="card-text"><strong>Address:</strong> {customer.address}</p> 50 <p className="card-text"><strong>Membership 51 Level:</strong> {customer.membershipLevel}</p> 50 <p className="card-text"><strong>Membership Level:</strong> {customer.membershipLevel}</p> 52 51 {/*<p className="card-text"><strong>Registration*/} 53 52 {/* Date:</strong> {new Date(customer.registrationDate).toLocaleString()}</p>*/} -
my-react-app/src/components/Header.js
rdb39d9e r8ca35dc 1 1 import React from 'react'; 2 import { Link } from 'react-router-dom';2 import { Link, useNavigate } from 'react-router-dom'; 3 3 4 4 const Header = () => { 5 const navigate = useNavigate(); 6 7 // Check if the user is logged in by looking for a token in localStorage 8 const isLoggedIn = localStorage.getItem('token'); 9 10 const handleLogout = () => { 11 // Clear the token from localStorage 12 localStorage.removeItem('token'); 13 // Redirect to the home page or login page after logging out 14 navigate('/login'); 15 }; 16 5 17 return ( 6 18 <header className="header navbar navbar-expand-lg navbar-light bg-light"> … … 15 27 </li> 16 28 <li className="nav-item"> 17 <Link className="nav-link" to="/customers">Customers</Link>18 </li>19 <li className="nav-item">20 <Link className="nav-link" to="/customers/add">Add Customer</Link>21 </li>22 <li className="nav-item">23 29 <Link className="nav-link" to="/restaurants">Restaurants</Link> 24 30 </li> … … 26 32 <Link className="nav-link" to="/reservations">Reservations</Link> 27 33 </li> 34 <li className="nav-item"> 35 <Link className="nav-link" to="/reservations-past">Reservation history</Link> 36 </li> 28 37 <form className="form-inline mt-2 mt-md-0 ml-3"> 29 <Link className="btn btn-outline-info my-2 my-sm-0" to={"/login"}>Login</Link> 38 {isLoggedIn ? ( 39 <button className="btn btn-outline-danger my-2 my-sm-0" onClick={handleLogout}>Logout</button> 40 ) : ( 41 <Link className="btn btn-outline-info my-2 my-sm-0" to="/login">Login</Link> 42 )} 30 43 </form> 31 44 </ul> -
my-react-app/src/components/Login.js
rdb39d9e r8ca35dc 6 6 const navigate = useNavigate(); 7 7 const [credentials, setCredentials] = useState({ username: '', password: '' }); 8 const [error, setError] = useState(''); 8 9 9 10 const handleChange = (e) => { … … 15 16 e.preventDefault(); 16 17 try { 17 const response = await axios.post('http://localhost:808 0/api/login', {18 const response = await axios.post('http://localhost:8081/api/login', { 18 19 email: credentials.username, 19 20 password: credentials.password 20 21 }); 21 22 const { token } = response.data; 22 // Store token securely (e.g., using HTTP cookies) 23 24 // Store token securely (consider httpOnly cookies) 23 25 localStorage.setItem('token', token); 24 26 … … 27 29 // Handle login failure 28 30 console.error('Login failed:', error); 31 setError('Login failed. Please check your credentials and try again.'); 29 32 } 30 33 }; 31 32 34 33 35 return ( … … 53 55 /> 54 56 </div> 57 {error && <div style={{ color: 'red' }}>{error}</div>} 55 58 <button type="submit">Login</button> 56 59 </form> -
my-react-app/src/components/LoginForm.js
rdb39d9e r8ca35dc 55 55 <div className="tab-content"> 56 56 <div 57 className={classNames("tab-pane", "fade", this.state.active === "login" ? "show active" : "")} id="pills-login"> 57 className={classNames("tab-pane", "fade", this.state.active === "login" ? "show active" : "")} 58 id="pills-login"> 58 59 <form onSubmit={this.onSubmitLogin}> 59 60 <div className="form-outline mb-4"> 60 <input type="email" id="email" name="email" className="form-control" onChange={this.onChangeHandler}/> 61 <input type="email" id="email" name="email" className="form-control" 62 onChange={this.onChangeHandler}/> 61 63 <label className="form-label" htmlFor="email">Email</label> 62 64 </div> 63 65 <div className="form-outline mb-4"> 64 <input type="password" id="loginPassword" name="password" className="form-control" onChange={this.onChangeHandler}/> 66 <input type="password" id="loginPassword" name="password" className="form-control" 67 onChange={this.onChangeHandler}/> 65 68 <label className="form-label" htmlFor="loginPassword">Password</label> 66 69 </div> … … 71 74 72 75 <div 73 className={classNames("tab-pane", "fade", this.state.active === "register" ? "show active" : "")} id="pills-register"> 76 className={classNames("tab-pane", "fade", this.state.active === "register" ? "show active" : "")} 77 id="pills-register"> 74 78 <form onSubmit={this.onSubmitRegister}> 75 79 <div className="form-outline mb-4"> 76 <input type="text" id="firstName" name="firstName" className="form-control" onChange={this.onChangeHandler}/> 80 <input type="text" id="firstName" name="firstName" className="form-control" 81 onChange={this.onChangeHandler}/> 77 82 <label className="form-label" htmlFor="firstName">First Name</label> 78 83 </div> 79 84 <div className="form-outline mb-4"> 80 <input type="text" id="lastName" name="lastName" className="form-control" onChange={this.onChangeHandler}/> 85 <input type="text" id="lastName" name="lastName" className="form-control" 86 onChange={this.onChangeHandler}/> 81 87 <label className="form-label" htmlFor="lastName">Last Name</label> 82 88 </div> 83 89 <div className="form-outline mb-4"> 84 <input type="text" id="email" name="email" className="form-control" onChange={this.onChangeHandler}/> 90 <input type="email" id="email" name="email" className="form-control" 91 onChange={this.onChangeHandler}/> 85 92 <label className="form-label" htmlFor="email">Email</label> 86 93 </div> 87 94 <div className="form-outline mb-4"> 88 <input type="password" id="loginPassword" name="password" className="form-control" onChange={this.onChangeHandler}/> 95 <input type="password" id="loginPassword" name="password" className="form-control" 96 onChange={this.onChangeHandler}/> 89 97 <label className="form-label" htmlFor="loginPassword">Password</label> 90 98 </div> 91 99 92 <button type="submit" className="btn btn-primary btn-block mb-4"> Sign In</button>100 <button type="submit" className="btn btn-primary btn-block mb-4">Register</button> 93 101 </form> 94 102 </div> … … 96 104 </div> 97 105 </div> 98 ) 106 ); 107 99 108 } 100 109 } -
my-react-app/src/components/MembershipsEnum.js
rdb39d9e r8ca35dc 3 3 4 4 const MembershipsEnum = () => { 5 const [memberships, setMemberships] = useState([]); 6 7 useEffect(() => { 8 const fetchMemberships = async () => { 9 try { 10 const response = await axios.get('http://localhost:8080/api/memberships'); 11 // Assuming the response.data is an array of enum values 12 setMemberships(response.data); 13 } catch (error) { 14 console.error('Error fetching enum data:', error); 15 } 16 }; 17 18 fetchMemberships(); 19 }, []); 20 21 return memberships; 5 return ['GOLD', 'PLATINUM', 'STANDARD']; 22 6 }; 23 7 -
my-react-app/src/components/ReservationConfirmation.js
rdb39d9e r8ca35dc 3 3 import axios from 'axios'; 4 4 import { useNavigate } from 'react-router-dom'; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 const ReservationConfirmation = () => { … … 17 18 const fetchTableDetails = async () => { 18 19 try { 19 const tableResponse = await axios.get(`http://localhost:808 0/api/tables/${tableNumber}`);20 const tableResponse = await axios.get(`http://localhost:8081/api/tables/${tableNumber}`); 20 21 setTable(tableResponse.data); 21 22 22 const restaurantResponse = await axios.get(`http://localhost:808 0/api/restaurants/${restaurantId}`);23 const restaurantResponse = await axios.get(`http://localhost:8081/api/restaurants/${restaurantId}`); 23 24 setRestaurant(restaurantResponse.data); 24 25 } catch (error) { … … 31 32 const handleSubmit = async (e) => { 32 33 e.preventDefault(); 33 // Handle form submission here 34 35 if (!restaurant || !table) { 36 console.error("Restaurant or table is missing."); 37 return; 38 } 39 34 40 try { 35 // Check if restaurant and table are valid36 if (! restaurant || !table) {37 console.error(" Restaurant or table is missing.");41 const token = localStorage.getItem("token"); 42 if (!token) { 43 console.error("No token found"); 38 44 return; 39 45 } 40 46 41 const response = await axios.post(`http://localhost:8080/api/reservations`, { 42 restaurant: restaurant, // Assuming restaurant has an 'id' property 43 table: table, // Assuming table has an 'id' property 44 checkInTime: timeSlot, // Fill in as needed 45 partySize: partySize, 46 specialRequests: specialRequests 47 }); 48 // Handle successful reservation creation 49 // console.log("Reservation created:", response.data); 50 navigate("/reservations") 47 // Decode the token to get the user email 48 const decodedToken = jwtDecode(token); 49 console.log(decodedToken) 50 const userId = decodedToken.iss;// Assuming the email is part of the decoded JWT token 51 52 const response = await axios.post( 53 `http://localhost:8081/api/reservations/${userId}`, 54 { 55 restaurant: restaurant, 56 table: table, 57 checkInTime: timeSlot, 58 partySize: partySize, 59 specialRequests: specialRequests 60 }, 61 { 62 headers: { 63 Authorization: `Bearer ${token}` // Include the token here 64 } 65 } 66 ); 67 68 navigate("/reservations"); 51 69 } catch (error) { 52 70 console.error("Error creating reservation:", error); -
my-react-app/src/components/ReservationEdit.js
rdb39d9e r8ca35dc 3 3 import {useNavigate, useParams} from 'react-router-dom'; 4 4 import StarRating from "./StarRating"; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 const ReservationEdit = () => { … … 14 15 const [timeSlots, setTimeSlots] = useState([]); 15 16 const [filteredTimeSlots, setFilteredTimeSlots] = useState([]); 17 const [checkInTime, setCheckInTime] = useState([]); 16 18 17 19 useEffect(() => { … … 19 21 try { 20 22 setIsLoading(true); 21 const response = await axios.get(`http://localhost:8080/api/reservations/${reservationId}`); 22 setFormData(response.data); // Set form data with reservation data 23 const response = await axios.get(`http://localhost:8081/api/reservations/${reservationId}`); 24 setCheckInTime(response.data.checkInTime) 25 setFormData(response.data); 23 26 setTable(response.data.table); 24 27 setRestaurant(response.data.restaurant); … … 56 59 const handleSubmit = async (e) => { 57 60 e.preventDefault(); 61 58 62 try { 59 // Send updated reservation data to the server 60 await axios.post(`http://localhost:8080/api/reservations/${reservationId}`, formData); 61 // Redirect or show success message 63 const token = localStorage.getItem("token"); 64 if (!token) { 65 console.error("No token found"); 66 return; 67 } 68 69 const decodedToken = jwtDecode(token); 70 console.log(decodedToken) 71 const userId = decodedToken.iss; 72 73 await axios.post(`http://localhost:8081/api/reservations/${reservationId}/${userId}`, formData); 74 62 75 navigate(`/reservations`) 63 76 } catch (error) { … … 71 84 const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); 72 85 return `${formattedDate} - ${formattedTime}`; 86 }; 87 88 const formatCurrentTimeSlot = (timeSlot) => { 89 const date = new Date(timeSlot); 90 const formattedDate = date.toLocaleDateString('en-GB'); // Format date as YYYY-MM-DD 91 const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); // Format time as HH:MM 92 return `${formattedDate} ${formattedTime}`; 73 93 }; 74 94 … … 100 120 ))} 101 121 </select> 122 <label className=".text-danger">Current check in time: {formatTimeSlot(checkInTime)}</label> 102 123 </div> 103 124 <div className="mb-3"> -
my-react-app/src/components/Reservations.js
rdb39d9e r8ca35dc 3 3 import 'bootstrap/dist/css/bootstrap.min.css'; 4 4 import {useNavigate} from "react-router-dom"; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 … … 13 14 const fetchReservations = async () => { 14 15 try { 15 const response = await axios.get('http://localhost:8080/api/reservations'); // Adjust URL as needed 16 const token = localStorage.getItem("token"); 17 if (!token) { 18 console.error("No token found"); 19 return; 20 } 21 const decodedToken = jwtDecode(token); 22 console.log(decodedToken) 23 const userId = decodedToken.iss; 24 25 const response = await axios.get(`http://localhost:8081/api/reservations/by/${userId}`); 16 26 setReservations(response.data); 17 27 } catch (error) { … … 31 41 const handleCancelReservation = async (reservationID) => { 32 42 try { 33 await axios.delete(`http://localhost:808 0/api/reservations/delete/${reservationID}`);43 await axios.delete(`http://localhost:8081/api/reservations/delete/${reservationID}`); 34 44 setReservations(reservations.filter(reservation => reservation.reservationID !== reservationID)); 35 45 alert('Reservation canceled successfully!'); -
my-react-app/src/components/RestaurantContext.js
rdb39d9e r8ca35dc 10 10 const fetchRestaurants = async () => { 11 11 try { 12 const response = await axios.get('http://localhost:808 0/api/restaurants');12 const response = await axios.get('http://localhost:8081/api/restaurants'); 13 13 setRestaurants(response.data); 14 14 } catch (error) { … … 17 17 }; 18 18 19 fetchRestaurants() ;19 fetchRestaurants().then(r => console.log(fetchRestaurants())); 20 20 }, []); 21 21 -
my-react-app/src/components/RestaurantDetails.js
rdb39d9e r8ca35dc 21 21 try { 22 22 if (!id) return; 23 const response = await axios.get(`http://localhost:808 0/api/restaurants/${id}`);23 const response = await axios.get(`http://localhost:8081/api/restaurants/${id}`); 24 24 setRestaurant(response.data); 25 25 } catch (error) { … … 36 36 const fetchTableDetails = async () => { 37 37 try { 38 const response = await axios.get(`http://localhost:808 0/api/tables/${selectedTableId}`);38 const response = await axios.get(`http://localhost:8081/api/tables/${selectedTableId}`); 39 39 setSelectedTable(response.data); 40 40 } catch (error) { -
package-lock.json
rdb39d9e r8ca35dc 6 6 "": { 7 7 "dependencies": { 8 "classnames": "^2.5.1", 8 9 "react-router-dom": "^6.22.1", 9 10 "swagger-ui-express": "^5.0.0", -
package.json
rdb39d9e r8ca35dc 1 1 { 2 2 "dependencies": { 3 "classnames": "^2.5.1", 3 4 "react-router-dom": "^6.22.1", 4 5 "swagger-ui-express": "^5.0.0", -
pom.xml
rdb39d9e r8ca35dc 108 108 <version>4.3.0</version> 109 109 </dependency> 110 111 <dependency> 112 <groupId>javax.xml.bind</groupId> 113 <artifactId>jaxb-api</artifactId> 114 <version>2.3.1</version> 115 </dependency> 116 110 117 </dependencies> 111 118 -
src/main/java/com/example/rezevirajmasa/demo/bootstrap/ReservationInitializer.java
rdb39d9e r8ca35dc 1 package com.example.rezevirajmasa.demo.bootstrap;2 3 import com.example.rezevirajmasa.demo.model.Reservation;4 import com.example.rezevirajmasa.demo.model.Restaurant;5 import com.example.rezevirajmasa.demo.service.ReservationHistoryService;6 import com.example.rezevirajmasa.demo.service.ReservationService;7 import org.springframework.stereotype.Component;8 9 import jakarta.annotation.PostConstruct;10 import java.time.LocalDateTime;11 import java.util.List;12 import java.util.stream.Collectors;13 14 @Component15 public class ReservationInitializer {16 private final ReservationHistoryService reservationHistoryService;17 private final ReservationService reservationService;18 19 public ReservationInitializer(ReservationHistoryService reservationHistoryService, ReservationService reservationService) {20 this.reservationHistoryService = reservationHistoryService;21 this.reservationService = reservationService;22 }23 24 @PostConstruct25 public void initializePastReservations() {26 LocalDateTime currentTime = LocalDateTime.now();27 List<Reservation> reservationsToMove = reservationService.findReservationsToMove(currentTime);28 29 List<Restaurant.ReservationHistory> reservationHistories = reservationsToMove.stream()30 .map(reservation -> new Restaurant.ReservationHistory(31 reservation.getCustomer(),32 reservation.getTable(),33 reservation.getRestaurant(),34 reservation.getReservationDateTime(),35 reservation.getPartySize(),36 reservation.getSpecialRequests(),37 "Done",38 null, // You can set cancellation reason if needed, it's not clear from the code provided 39 reservation.getCheckInTime() // Use currentTime for check-in date 40 ))41 .collect(Collectors.toList());42 43 reservationHistoryService.moveReservationsToPast(reservationHistories);44 45 reservationsToMove.forEach(reservation -> reservationService.deleteReservation(reservation.getReservationID()));46 }47 48 }1 //package com.example.rezevirajmasa.demo.bootstrap; 2 // 3 //import com.example.rezevirajmasa.demo.model.Reservation; 4 //import com.example.rezevirajmasa.demo.model.Restaurant; 5 //import com.example.rezevirajmasa.demo.service.ReservationHistoryService; 6 //import com.example.rezevirajmasa.demo.service.ReservationService; 7 //import org.springframework.stereotype.Component; 8 // 9 //import jakarta.annotation.PostConstruct; 10 //import java.time.LocalDateTime; 11 //import java.util.List; 12 //import java.util.stream.Collectors; 13 // 14 //@Component 15 //public class ReservationInitializer { 16 // private final ReservationHistoryService reservationHistoryService; 17 // private final ReservationService reservationService; 18 // 19 // public ReservationInitializer(ReservationHistoryService reservationHistoryService, ReservationService reservationService) { 20 // this.reservationHistoryService = reservationHistoryService; 21 // this.reservationService = reservationService; 22 // } 23 // 24 // @PostConstruct 25 // public void initializePastReservations() { 26 // LocalDateTime currentTime = LocalDateTime.now(); 27 // List<Reservation> reservationsToMove = reservationService.findReservationsToMove(currentTime); 28 // 29 // List<Restaurant.ReservationHistory> reservationHistories = reservationsToMove.stream() 30 // .map(reservation -> new Restaurant.ReservationHistory( 31 // reservation.getUser(), 32 // reservation.getTable(), 33 // reservation.getRestaurant(), 34 // reservation.getReservationDateTime(), 35 // reservation.getPartySize(), 36 // reservation.getSpecialRequests(), 37 // "Done", 38 // null, 39 // reservation.getCheckInTime() 40 // )) 41 // .collect(Collectors.toList()); 42 // 43 // reservationHistoryService.moveReservationsToPast(reservationHistories); 44 // 45 // reservationsToMove.forEach(reservation -> reservationService.deleteReservation(reservation.getReservationID())); 46 // } 47 // 48 //} -
src/main/java/com/example/rezevirajmasa/demo/config/SecurityConfig.java
rdb39d9e r8ca35dc 7 7 import org.springframework.http.HttpMethod; 8 8 import org.springframework.security.authentication.AuthenticationManager; 9 import org.springframework.security.config.Customizer; 9 10 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 11 import org.springframework.security.config.annotation.web.builders.HttpSecurity; … … 15 16 import org.springframework.security.core.userdetails.UserDetailsService; 16 17 import org.springframework.security.web.SecurityFilterChain; 18 import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 17 19 import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 20 import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 18 21 import org.springframework.web.servlet.config.annotation.CorsRegistry; 22 import org.springframework.context.annotation.Bean; 23 import org.springframework.context.annotation.Configuration; 24 import org.springframework.security.config.annotation.web.builders.HttpSecurity; 25 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 26 import org.springframework.security.web.SecurityFilterChain; 19 27 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 20 28 … … 40 48 public void addCorsMappings(CorsRegistry registry) { 41 49 registry.addMapping("/**") 50 .allowedOrigins("http://localhost:3000") 51 .allowedMethods("GET", "POST", "PUT", "DELETE") 52 .allowedHeaders("*") 42 53 .allowCredentials(true) 43 .allowedOrigins("http://localhost:3000") // Allow requests from this origin 44 .allowedMethods("GET", "POST", "PUT", "DELETE") // Allow these HTTP methods 45 .allowedHeaders("*") 46 .maxAge(3600L); // Allow all headers 54 .maxAge(3600L); 47 55 } 48 56 49 57 // @Bean 50 // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 51 // 58 // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 52 59 // http 60 // .exceptionHandling(exception -> exception.authenticationEntryPoint(customerAuthenticationEntryPoint)) 61 // .addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class) 53 62 // .csrf(AbstractHttpConfigurer::disable) 54 // . authorizeHttpRequests( (requests) -> requests55 // .requestMatchers(AntPathRequestMatcher.antMatcher("/"), AntPathRequestMatcher.antMatcher("/restaurants"))56 // . permitAll()57 // . anyRequest()58 // . hasAnyRole("ADMIN", "USER")63 // .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 64 // .authorizeHttpRequests(requests -> requests 65 // .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll() 66 // .requestMatchers("/", "/home").authenticated() // Restrict `/` to authenticated users 67 // .anyRequest().authenticated() 59 68 // ) 60 // .formLogin((form) -> form 61 // .permitAll() 62 // .failureUrl("/login?error=BadCredentials") 63 // .defaultSuccessUrl("/restaurants", true) 64 // ) 65 // .logout((logout) -> logout 69 // .logout(logout -> logout 66 70 // .logoutUrl("/logout") 67 71 // .clearAuthentication(true) 68 72 // .invalidateHttpSession(true) 69 73 // .deleteCookies("JSESSIONID") 70 // .logoutSuccessUrl("/ ")74 // .logoutSuccessUrl("/api/login") // Redirect to login page after logout 71 75 // ); 72 76 // … … 83 87 .authorizeHttpRequests((requests) -> requests 84 88 .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll() 85 .anyRequest().authenticated() 86 ); 89 .anyRequest().authenticated()); 87 90 return http.build(); 88 91 } 92 89 93 @Bean 90 94 public AuthenticationManager authManager(HttpSecurity http) throws Exception { … … 95 99 } 96 100 } 101 // 102 //import com.example.rezevirajmasa.demo.web.filters.JwtAuthFilter; 103 //import org.springframework.context.annotation.Bean; 104 //import org.springframework.context.annotation.Configuration; 105 //import org.springframework.security.authentication.AuthenticationManager; 106 //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 107 //import org.springframework.security.config.annotation.web.builders.HttpSecurity; 108 //import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 109 //import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 110 //import org.springframework.security.config.http.SessionCreationPolicy; 111 //import org.springframework.security.core.userdetails.UserDetailsService; 112 //import org.springframework.security.web.SecurityFilterChain; 113 //import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 114 // 115 //@Configuration 116 //@EnableWebSecurity 117 //public class SecurityConfig { 118 // 119 // private final UserDetailsService userDetailsService; 120 //// private final UserAuthProvider userAuthProvider; 121 // private final JwtAuthFilter jwtAuthFilter; 122 // 123 // public SecurityConfig(UserDetailsService userDetailsService) { 124 // this.userDetailsService = userDetailsService; 125 //// this.userAuthProvider = userAuthProvider; 126 // this.jwtAuthFilter = new JwtAuthFilter(userAuthProvider); 127 // } 128 // 129 // @Bean 130 // public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 131 // http 132 // .csrf(AbstractHttpConfigurer::disable) 133 // .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 134 // .authorizeHttpRequests((requests) -> requests 135 // .requestMatchers("/api/login", "/api/register").permitAll() 136 // .anyRequest().authenticated()) 137 // .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); 138 // 139 // return http.build(); 140 // } 141 // 142 // @Bean 143 // public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { 144 // AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); 145 // authenticationManagerBuilder.userDetailsService(userDetailsService); 146 // return authenticationManagerBuilder.build(); 147 // } 148 //} -
src/main/java/com/example/rezevirajmasa/demo/config/UserAuthProvider.java
rdb39d9e r8ca35dc 7 7 import com.example.rezevirajmasa.demo.dto.UserDto; 8 8 import com.example.rezevirajmasa.demo.service.UserService; 9 import io.jsonwebtoken.Claims; 10 import io.jsonwebtoken.Jwts; 9 11 import jakarta.annotation.PostConstruct; 10 12 import lombok.RequiredArgsConstructor; … … 12 14 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 13 15 import org.springframework.security.core.Authentication; 16 import org.springframework.security.core.userdetails.UserDetails; 14 17 import org.springframework.stereotype.Component; 15 18 16 import java.util.Base64; 17 import java.util.Collections; 18 import java.util.Date; 19 import java.util.*; 20 import java.util.function.Function; 19 21 20 22 @RequiredArgsConstructor … … 29 31 protected void init() { 30 32 secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); 33 } 34 35 public String generateToken(UserDetails userDetails){ 36 Map<String, Object> claims = new HashMap<>(); 37 return createToken(userDetails.getUsername()); 31 38 } 32 39 … … 50 57 return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()); 51 58 } 59 60 public String extractUsername(String token) { 61 return extractClaim(token, Claims::getSubject); 62 } 63 64 public Date extractExpiration(String token) { 65 return extractClaim(token, Claims::getExpiration); 66 } 67 68 public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { 69 final Claims claims = extractAllClaims(token); 70 return claimsResolver.apply(claims); 71 } 72 73 private Claims extractAllClaims(String token) { 74 return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); 75 } 76 77 private Boolean isTokenExpired(String token) { 78 return extractExpiration(token).before(new Date()); 79 } 52 80 } -
src/main/java/com/example/rezevirajmasa/demo/dto/CredentialsDto.java
rdb39d9e r8ca35dc 11 11 @Data 12 12 public class CredentialsDto { 13 private String login;13 private String email; 14 14 private char[] password; 15 15 } -
src/main/java/com/example/rezevirajmasa/demo/dto/SignUpDto.java
rdb39d9e r8ca35dc 15 15 private String email; 16 16 private char[] password; 17 private String phone; 18 private String address; 19 private String membershipLevel; 17 20 } -
src/main/java/com/example/rezevirajmasa/demo/dto/UserDto.java
rdb39d9e r8ca35dc 16 16 private String email; 17 17 private String token; 18 private String phone; 19 private String address; 20 private String membershipLevel; 18 21 } -
src/main/java/com/example/rezevirajmasa/demo/mappers/UserMapper.java
rdb39d9e r8ca35dc 14 14 @Mapping(target = "password", ignore = true) 15 15 User signUpToUser(SignUpDto userDto); 16 17 SignUpDto toSignUpDto(UserDto userDto); 18 User toUser(UserDto userDto); 16 19 } -
src/main/java/com/example/rezevirajmasa/demo/mappers/UserMapperImpl.java
rdb39d9e r8ca35dc 3 3 import com.example.rezevirajmasa.demo.dto.SignUpDto; 4 4 import com.example.rezevirajmasa.demo.dto.UserDto; 5 import com.example.rezevirajmasa.demo.model.MembershipLevel; 5 6 import com.example.rezevirajmasa.demo.model.User; 6 7 import org.springframework.stereotype.Component; … … 36 37 user.setFirstName(userDto.getFirstName()); 37 38 user.setLastName(userDto.getLastName()); 38 user.setPassword(Arrays.toString(userDto.getPassword())); 39 user.setPassword(Arrays.toString(userDto.getPassword())); // Assuming password is a char[] or string array. 40 41 return user; 42 } 43 44 @Override 45 public SignUpDto toSignUpDto(UserDto userDto) { 46 if (userDto == null) { 47 return null; 48 } 49 50 SignUpDto signUpDto = new SignUpDto(); 51 signUpDto.setEmail(userDto.getEmail()); 52 signUpDto.setFirstName(userDto.getFirstName()); 53 signUpDto.setLastName(userDto.getLastName()); 54 55 // Since SignUpDto has password field, you may set it if needed. 56 // Assuming a default value or handling empty password as required. 57 signUpDto.setPassword(new char[0]); // Empty password for now or assign actual value if required. 58 59 return signUpDto; 60 } 61 62 @Override 63 public User toUser(UserDto userDto) { 64 if(userDto == null) { 65 return null; 66 } 67 68 User user = new User(); 69 user.setLastName(userDto.getLastName()); 70 user.setFirstName(userDto.getFirstName()); 71 user.setPhone(userDto.getPhone()); 72 user.setMembershipLevel(MembershipLevel.valueOf(userDto.getMembershipLevel())); 73 user.setAddress(userDto.getAddress()); 74 user.setEmail(userDto.getEmail()); 75 user.setId(userDto.getId()); 39 76 40 77 return user; -
src/main/java/com/example/rezevirajmasa/demo/model/Reservation.java
rdb39d9e r8ca35dc 16 16 17 17 @ManyToOne 18 @JoinColumn(name = " CustomerID")19 private Customer customer;18 @JoinColumn(name = "UserID") 19 private User user; 20 20 21 21 @ManyToOne … … 68 68 } 69 69 70 public Reservation( Customer customer, TableEntity table, Restaurant restaurant, LocalDateTime reservationDateTime, int partySize, String specialRequests, String status, LocalDateTime checkInTime, LocalDateTime checkOutTime, String paymentStatus) {70 public Reservation(User user, TableEntity table, Restaurant restaurant, LocalDateTime reservationDateTime, int partySize, String specialRequests, String status, LocalDateTime checkInTime, LocalDateTime checkOutTime, String paymentStatus) { 71 71 // this.customer = customer; 72 72 this.table = table; 73 this.user = user; 73 74 this.restaurant = restaurant; 74 75 this.reservationDateTime = reservationDateTime; … … 81 82 } 82 83 84 public User getUser() { 85 return user; 86 } 87 88 public void setUser(User user) { 89 this.user = user; 90 } 91 83 92 public Long getReservationID() { 84 93 return reservationID; … … 89 98 } 90 99 91 public Customer getCustomer() {92 return customer;93 }94 95 public void setCustomer(Customer customer) {96 this.customer = customer;97 }98 100 99 101 public TableEntity getTable() { … … 173 175 return "Reservation{" + 174 176 "reservationID=" + reservationID + 175 ", customer=" + customer +177 ", customer=" + user + 176 178 ", table=" + table + 177 179 ", restaurant=" + restaurant + -
src/main/java/com/example/rezevirajmasa/demo/model/Restaurant.java
rdb39d9e r8ca35dc 151 151 @ManyToOne 152 152 @JoinColumn(name = "customer_id") 153 private Customer customer;153 private User user; 154 154 155 155 @ManyToOne … … 179 179 private LocalDateTime checkInDate; 180 180 181 public ReservationHistory( Customer customer, TableEntity table, Restaurant restaurant, LocalDateTime reservationDateTime, int partySize, String specialRequests, String status, String cancellationReason, LocalDateTime checkInDate) {182 this. customer = customer;181 public ReservationHistory(User user, TableEntity table, Restaurant restaurant, LocalDateTime reservationDateTime, int partySize, String specialRequests, String status, String cancellationReason, LocalDateTime checkInDate) { 182 this.user = user; 183 183 this.table = table; 184 184 this.restaurant = restaurant; … … 202 202 } 203 203 204 public Customer getCustomer() {205 return customer;206 } 207 208 public void set Customer(Customer customer) {209 this. customer = customer;204 public User getUser() { 205 return user; 206 } 207 208 public void setUser(User user) { 209 this.user = user; 210 210 } 211 211 … … 278 278 return "ReservationHistory{" + 279 279 "id=" + id + 280 ", customer=" + customer +280 ", user=" + user + 281 281 ", table=" + table + 282 282 ", restaurant=" + restaurant + -
src/main/java/com/example/rezevirajmasa/demo/model/User.java
rdb39d9e r8ca35dc 7 7 import lombok.NoArgsConstructor; 8 8 import org.springframework.web.bind.annotation.GetMapping; 9 10 import java.util.Date; 9 11 10 12 @AllArgsConstructor … … 31 33 @Column(nullable = false) 32 34 private String password; 35 36 @Enumerated(EnumType.STRING) 37 private Role role; 38 39 @Column(name = "Phone", length = 20) 40 private String phone; 41 42 @Column(name = "Address", columnDefinition = "TEXT") 43 private String address; 44 45 @Enumerated(EnumType.STRING) 46 @Column(name = "MembershipLevel", length = 20) 47 private MembershipLevel membershipLevel; 48 49 @Column(name = "RegistrationDate", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") 50 @Temporal(TemporalType.TIMESTAMP) 51 private Date registrationDate; 33 52 } -
src/main/java/com/example/rezevirajmasa/demo/repository/ReservationHistoryRepository.java
rdb39d9e r8ca35dc 4 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.User; 6 7 import org.springframework.cglib.core.Local; 7 8 import org.springframework.data.jpa.repository.JpaRepository; … … 11 12 12 13 public interface ReservationHistoryRepository extends JpaRepository<Restaurant.ReservationHistory, Long> { 13 List<Restaurant.ReservationHistory> findA llByCustomer(Customer customer);14 List<Restaurant.ReservationHistory> findALlByUser(User user); 14 15 List<Restaurant.ReservationHistory> findByCheckInDateBeforeAndStatus(LocalDateTime currentTime, String scheduled); 15 16 List<Restaurant.ReservationHistory> findAllByCheckInDateBefore(LocalDateTime currentTime); -
src/main/java/com/example/rezevirajmasa/demo/repository/ReservationRepository.java
rdb39d9e r8ca35dc 1 1 package com.example.rezevirajmasa.demo.repository; 2 2 3 import com.example.rezevirajmasa.demo.model.Customer; 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.TableEntity; 3 import com.example.rezevirajmasa.demo.model.*; 7 4 import org.springframework.data.jpa.repository.JpaRepository; 8 5 … … 11 8 12 9 public interface ReservationRepository extends JpaRepository<Reservation, Long> { 13 List<Reservation> findA llByCustomer(Customer customer);10 List<Reservation> findALlByUserAndCheckInTimeAfter(User user, LocalDateTime now); 14 11 List<Reservation> findByTableAndCheckInTimeBetween(TableEntity table, LocalDateTime startTime, LocalDateTime endTime); 15 12 … … 17 14 List<Reservation> findAllByCheckInTimeBefore(LocalDateTime currentTime); 18 15 List<Reservation> findByCheckInTimeAfterAndCheckInTimeBefore(LocalDateTime startTime, LocalDateTime endTime); 16 List<Reservation> findALlByUserAndCheckInTimeBefore(User user, LocalDateTime now); 19 17 } -
src/main/java/com/example/rezevirajmasa/demo/service/ReservationHistoryService.java
rdb39d9e r8ca35dc 4 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.User; 6 7 7 8 import java.time.LocalDateTime; … … 11 12 public void moveReservationToHistory(Reservation reservation, String status, String cancellationReason); 12 13 public void moveReservationsToPast(List<Restaurant.ReservationHistory> reservationsToMove); 13 List<Restaurant.ReservationHistory> findBy Customer(Customer customer);14 List<Restaurant.ReservationHistory> findByUser(User user); 14 15 List<Restaurant.ReservationHistory> findAll(); 15 16 List<Restaurant.ReservationHistory> findReservationsToMove(LocalDateTime currentTime); -
src/main/java/com/example/rezevirajmasa/demo/service/ReservationService.java
rdb39d9e r8ca35dc 1 1 package com.example.rezevirajmasa.demo.service; 2 2 3 import com.example.rezevirajmasa.demo.model.Customer; 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.TableEntity; 3 import com.example.rezevirajmasa.demo.model.*; 4 import org.springframework.security.core.userdetails.UserDetails; 7 5 8 6 import java.time.LocalDateTime; … … 10 8 11 9 public interface ReservationService { 12 public void makeReservation( Customer customer, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests);13 public Reservation makeReservationRest(Reservation reservation );10 public void makeReservation(User user, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests); 11 public Reservation makeReservationRest(Reservation reservation, User user); 14 12 public List<Reservation> listAll(); 15 13 public Reservation findById(Long id); 16 14 public Reservation getReservationById(Long reservationId); 17 15 public boolean cancelReservation(Long reservationId); 18 public List<Reservation> findReservationByCustomer(Customer customer); 16 public List<Reservation> findReservationByUser(User user); 17 public List<Reservation> findReservationsByUserPast(User user); 19 18 public List<Reservation> findReservationsByTableAndDateRange(TableEntity table, LocalDateTime startDateTime, LocalDateTime endDateTime); 20 19 List<Reservation> findReservationsToMove(LocalDateTime currentTime); -
src/main/java/com/example/rezevirajmasa/demo/service/UserService.java
rdb39d9e r8ca35dc 4 4 import com.example.rezevirajmasa.demo.dto.SignUpDto; 5 5 import com.example.rezevirajmasa.demo.dto.UserDto; 6 import com.example.rezevirajmasa.demo.model.User; 6 7 import lombok.RequiredArgsConstructor; 7 8 … … 9 10 public interface UserService { 10 11 public UserDto findByEmail(String email); 12 public User findByMail(String email); 11 13 public UserDto login(CredentialsDto credentialsDto); 12 14 public UserDto register(SignUpDto userDto); 15 public User findUserById(Long userId); 13 16 } -
src/main/java/com/example/rezevirajmasa/demo/service/impl/ReservationHistoryServiceImpl.java
rdb39d9e r8ca35dc 4 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.User; 6 7 import com.example.rezevirajmasa.demo.repository.ReservationHistoryRepository; 7 8 import com.example.rezevirajmasa.demo.service.ReservationHistoryService; … … 22 23 public void moveReservationToHistory(Reservation reservation, String status, String cancellationReason) { 23 24 Restaurant.ReservationHistory history = new Restaurant.ReservationHistory(); 24 history.set Customer(reservation.getCustomer());25 history.setUser(reservation.getUser()); 25 26 history.setTable(reservation.getTable()); 26 27 history.setReservationDateTime(reservation.getReservationDateTime()); … … 42 43 43 44 @Override 44 public List<Restaurant.ReservationHistory> findBy Customer(Customer customer) {45 return reservationHistoryRepository.findA llByCustomer(customer);45 public List<Restaurant.ReservationHistory> findByUser(User user) { 46 return reservationHistoryRepository.findALlByUser(user); 46 47 } 47 48 48 49 @Override 49 50 public void moveReservationsToPast(List<Restaurant.ReservationHistory> reservationsToMove) { 50 // Update the status of reservations to "Past"51 51 for (Restaurant.ReservationHistory reservation : reservationsToMove) { 52 52 reservation.setStatus("Past"); 53 53 } 54 54 55 // Save the updated reservations56 55 reservationHistoryRepository.saveAll(reservationsToMove); 57 56 } -
src/main/java/com/example/rezevirajmasa/demo/service/impl/ReservationImpl.java
rdb39d9e r8ca35dc 1 1 package com.example.rezevirajmasa.demo.service.impl; 2 2 3 import com.example.rezevirajmasa.demo.model.Customer; 4 import com.example.rezevirajmasa.demo.model.Reservation; 5 import com.example.rezevirajmasa.demo.model.Restaurant; 6 import com.example.rezevirajmasa.demo.model.TableEntity; 3 import com.example.rezevirajmasa.demo.dto.UserDto; 4 import com.example.rezevirajmasa.demo.mappers.UserMapper; 5 import com.example.rezevirajmasa.demo.model.*; 7 6 import com.example.rezevirajmasa.demo.model.exceptions.InvalidReservationException; 8 7 import com.example.rezevirajmasa.demo.model.exceptions.InvalidReservationIdException; … … 11 10 import com.example.rezevirajmasa.demo.repository.RestaurantRepository; 12 11 import com.example.rezevirajmasa.demo.repository.TableRepository; 12 import com.example.rezevirajmasa.demo.service.ReservationHistoryService; 13 13 import com.example.rezevirajmasa.demo.service.ReservationService; 14 import com.example.rezevirajmasa.demo.service.UserService; 14 15 import org.springframework.beans.factory.annotation.Autowired; 16 import org.springframework.cglib.core.Local; 17 import org.springframework.security.core.Authentication; 18 import org.springframework.security.core.annotation.AuthenticationPrincipal; 19 import org.springframework.security.core.context.SecurityContextHolder; 20 import org.springframework.security.core.userdetails.UserDetails; 15 21 import org.springframework.stereotype.Service; 22 import org.springframework.web.bind.annotation.RequestBody; 16 23 17 24 import javax.swing.text.html.Option; … … 27 34 private TableRepository tableRepository; 28 35 @Autowired 29 private RestaurantRepository restaurantRepository; 36 private ReservationHistoryService reservationHistoryService; 37 private final UserMapper userMapper; 30 38 @Autowired 31 private CustomerRepository customerRepository;39 private UserService userService; 32 40 @Autowired 33 41 private ReservationRepository reservationRepository; 42 43 public ReservationImpl(UserMapper userMapper) { 44 this.userMapper = userMapper; 45 } 34 46 35 47 @Override … … 39 51 40 52 @Override 41 public void makeReservation( Customer customer, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests) {53 public void makeReservation(User user, TableEntity table, Restaurant restaurant, LocalDateTime localDateTime, LocalDateTime checkInTime, int partySize, String specialRequests) { 42 54 if (!table.isAvailable(checkInTime)) { 43 55 // Handle unavailability (throw an exception, return a specific response, etc.) … … 46 58 47 59 Reservation reservation = 48 new Reservation( customer, table, restaurant, LocalDateTime.now(), partySize, specialRequests, "Reserved", checkInTime, checkInTime.plusHours(2), null);60 new Reservation(user, table, restaurant, LocalDateTime.now(), partySize, specialRequests, "Reserved", checkInTime, checkInTime.plusHours(2), null); 49 61 50 62 // // Update table status or perform additional logic if needed … … 56 68 57 69 @Override 58 public Reservation makeReservationRest(Reservation reservation ) {70 public Reservation makeReservationRest(Reservation reservation, User user) { 59 71 Optional<TableEntity> optionalTable = tableRepository.findById(reservation.getTable().getId()); 60 if (optionalTable.isPresent()) {72 if (optionalTable.isPresent()) { 61 73 TableEntity table = optionalTable.get(); 74 75 reservation.setUser(user); 62 76 63 77 LocalDateTime startTime = reservation.getCheckInTime().minusHours(2); … … 67 81 x -> x.isAfter(startTime) && x.isBefore(endTime) 68 82 ); 69 83 reservation.setReservationDateTime(LocalDateTime.now()); 70 84 return reservationRepository.save(reservation); 71 85 } else { 72 throw new InvalidReservationException("Unsuccessful reservation -> time slot not ava laible");86 throw new InvalidReservationException("Unsuccessful reservation -> time slot not available"); 73 87 } 74 88 } 89 75 90 76 91 @Override … … 109 124 from = from.plusMinutes(15); 110 125 } 126 reservationHistoryService.moveReservationToHistory(reservation, "Canceled", "Canceled by user"); 111 127 reservationRepository.delete(reservation); 112 return true; // Return true indicating successful cancellation128 return true; 113 129 } else { 114 return false; // Return false indicating reservation with the given ID not found130 return false; 115 131 } 116 132 } … … 118 134 119 135 @Override 120 public List<Reservation> findReservationByCustomer(Customer customer) { 121 return reservationRepository.findAllByCustomer(customer); 136 public List<Reservation> findReservationByUser(User user) { 137 LocalDateTime now = LocalDateTime.now(); 138 return reservationRepository.findALlByUserAndCheckInTimeAfter(user, now); 139 } 140 141 @Override 142 public List<Reservation> findReservationsByUserPast(User user) { 143 LocalDateTime now = LocalDateTime.now(); 144 return reservationRepository.findALlByUserAndCheckInTimeBefore(user, now); 122 145 } 123 146 -
src/main/java/com/example/rezevirajmasa/demo/service/impl/RestaurantServiceImpl.java
rdb39d9e r8ca35dc 175 175 .collect(Collectors.toList()); 176 176 } else { 177 List<Restaurant> restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(search); 177 String searchTerm = "%" + search + "%"; 178 List<Restaurant> restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(searchTerm); 178 179 if (restaurantList.isEmpty()) { 179 180 restaurantList = restaurantRepository.findAllByCuisineTypeContaining(search); -
src/main/java/com/example/rezevirajmasa/demo/service/impl/UserServiceImpl.java
rdb39d9e r8ca35dc 6 6 import com.example.rezevirajmasa.demo.mappers.UserMapper; 7 7 import com.example.rezevirajmasa.demo.mappers.UserMapperImpl; 8 import com.example.rezevirajmasa.demo.model.MembershipLevel; 9 import com.example.rezevirajmasa.demo.model.Role; 8 10 import com.example.rezevirajmasa.demo.model.User; 9 11 import com.example.rezevirajmasa.demo.model.exceptions.AppException; … … 12 14 import lombok.RequiredArgsConstructor; 13 15 import org.mapstruct.control.MappingControl; 16 import org.openqa.selenium.InvalidArgumentException; 14 17 import org.springframework.http.HttpStatus; 15 18 import org.springframework.security.crypto.password.PasswordEncoder; 16 19 import org.springframework.stereotype.Service; 17 20 import java.nio.CharBuffer; 21 import java.sql.Date; 22 import java.time.LocalDate; 18 23 import java.util.Optional; 19 24 … … 30 35 } 31 36 37 @Override 38 public User findByMail(String email) { 39 return userRepository.findByEmail(email).orElseThrow(() -> new AppException(("Unknown user"), HttpStatus.NOT_FOUND)); 40 } 41 32 42 public UserDto login(CredentialsDto credentialsDto) { 33 User user = userRepository.findByEmail(credentialsDto.get Login())43 User user = userRepository.findByEmail(credentialsDto.getEmail()) 34 44 .orElseThrow(() -> new AppException("Unknown user", HttpStatus.NOT_FOUND)); 35 45 … … 51 61 user.setPassword(passwordEncoder.encode(CharBuffer.wrap(userDto.getPassword()))); 52 62 63 user.setFirstName(userDto.getFirstName()); 64 user.setLastName(userDto.getLastName()); 65 user.setAddress(userDto.getAddress()); 66 user.setPhone(userDto.getPhone()); 67 user.setMembershipLevel(MembershipLevel.valueOf(userDto.getMembershipLevel())); 68 user.setRegistrationDate(Date.valueOf(LocalDate.now())); 69 user.setRole(Role.ROLE_USER); 70 53 71 User savedUser = userRepository.save(user); 54 72 55 return userMapper.toUserDto(user); 73 return userMapper.toUserDto(savedUser); 74 } 75 76 @Override 77 public User findUserById(Long userId) { 78 return userRepository.findById(userId).orElseThrow(()->new InvalidArgumentException("Invalid user Id")); 56 79 } 57 80 } -
src/main/java/com/example/rezevirajmasa/demo/web/controller/ReservationController.java
rdb39d9e r8ca35dc 1 1 package com.example.rezevirajmasa.demo.web.controller; 2 2 3 import com.example.rezevirajmasa.demo.dto.SignUpDto; 4 import com.example.rezevirajmasa.demo.dto.UserDto; 5 import com.example.rezevirajmasa.demo.mappers.UserMapper; 3 6 import com.example.rezevirajmasa.demo.model.*; 4 7 import com.example.rezevirajmasa.demo.model.exceptions.ExpiredReservationException; … … 19 22 public class ReservationController { 20 23 private final ReservationService reservationService; 21 private final CustomerService customerService;24 private final UserService userService; 22 25 private final TableService tableService; 23 26 private final ReservationHistoryService reservationHistoryService; 24 27 25 public ReservationController(ReservationService reservationService, CustomerService customerService, TableService tableService, ReservationHistoryService reservationHistoryService) { 28 private final UserMapper userMapper; 29 30 public ReservationController(ReservationService reservationService, UserService userService, TableService tableService, ReservationHistoryService reservationHistoryService, UserMapper userMapper) { 26 31 this.reservationService = reservationService; 27 this. customerService = customerService;32 this.userService = userService; 28 33 this.tableService = tableService; 29 34 this.reservationHistoryService = reservationHistoryService; 35 this.userMapper = userMapper; 30 36 } 31 37 32 38 @GetMapping("/reservations") 33 39 public String showReservations(Model model, Authentication authentication) { 34 Customer customer = customerService.findByEmail(authentication.getName()); 35 List<Reservation> reservationList; 36 if(customer.getRole().equals(Role.ROLE_ADMIN)) { 37 reservationList = reservationService.listAll(); 38 } else { 39 reservationList = reservationService.findReservationByCustomer(customer); 40 } 40 UserDto userDto = userService.findByEmail(authentication.getName()); 41 42 SignUpDto signUpDto = userMapper.toSignUpDto(userDto); 43 44 User user = userMapper.signUpToUser(signUpDto); 45 46 List<Reservation> reservationList = reservationService.findReservationByUser(user); 47 41 48 model.addAttribute("bodyContent", "reservationList"); 42 49 model.addAttribute("reservations", reservationList); 43 50 return "index"; 44 51 } 52 45 53 46 54 @GetMapping("/reservations/edit/{reservationId}") … … 62 70 Restaurant restaurant = table.getRestaurant(); 63 71 64 Customer customer = customerService.findByEmail(authentication.getName()); 72 UserDto userDto = userService.findByEmail(authentication.getName()); 73 74 SignUpDto signUpDto = userMapper.toSignUpDto(userDto); 75 76 User user = userMapper.signUpToUser(signUpDto); 65 77 66 78 if(!table.isAvailable(reservationDateTime)) { … … 68 80 } 69 81 tableService.deleteTimeSlotsForReservation(tableNumber, reservationDateTime); 70 reservationService.makeReservation( customer, table, restaurant, LocalDateTime.now(), reservationDateTime, partySize, specialRequests);82 reservationService.makeReservation(user, table, restaurant, LocalDateTime.now(), reservationDateTime, partySize, specialRequests); 71 83 return "redirect:/reservations"; 72 84 } -
src/main/java/com/example/rezevirajmasa/demo/web/controller/ReservationHistoryController.java
rdb39d9e r8ca35dc 1 1 package com.example.rezevirajmasa.demo.web.controller; 2 2 3 import com.example.rezevirajmasa.demo.dto.SignUpDto; 4 import com.example.rezevirajmasa.demo.dto.UserDto; 5 import com.example.rezevirajmasa.demo.mappers.UserMapper; 3 6 import com.example.rezevirajmasa.demo.model.Customer; 4 7 import com.example.rezevirajmasa.demo.model.Restaurant; 5 8 import com.example.rezevirajmasa.demo.model.Role; 9 import com.example.rezevirajmasa.demo.model.User; 6 10 import com.example.rezevirajmasa.demo.service.CustomerService; 7 11 import com.example.rezevirajmasa.demo.service.ReservationHistoryService; 12 import com.example.rezevirajmasa.demo.service.UserService; 8 13 import org.springframework.security.core.Authentication; 9 14 import org.springframework.stereotype.Controller; … … 18 23 public class ReservationHistoryController { 19 24 private final ReservationHistoryService reservationHistoryService; 20 private final CustomerService customerService; 25 private final UserService userService; 26 private final UserMapper userMapper; 21 27 22 public ReservationHistoryController(ReservationHistoryService reservationHistoryService, CustomerService customerService) {28 public ReservationHistoryController(ReservationHistoryService reservationHistoryService, UserService userService, UserMapper userMapper) { 23 29 this.reservationHistoryService = reservationHistoryService; 24 this.customerService = customerService; 30 this.userService = userService; 31 this.userMapper = userMapper; 25 32 } 26 33 … … 28 35 public String showPastReservations(Authentication authentication, Model model) { 29 36 List<Restaurant.ReservationHistory> reservationHistoryList; 30 Customer customer = customerService.findByEmail(authentication.getName()); 31 if(customer.getRole().equals(Role.ROLE_ADMIN)) { 32 reservationHistoryList = reservationHistoryService.findAll(); 33 } else { 34 reservationHistoryList = reservationHistoryService.findByCustomer(customer); 35 } 37 UserDto userDto = userService.findByEmail(authentication.getName()); 38 39 SignUpDto signUpDto = userMapper.toSignUpDto(userDto); 40 41 User user = userMapper.signUpToUser(signUpDto); 42 43 reservationHistoryList = reservationHistoryService.findByUser(user); 44 // if(customer.getRole().equals(Role.ROLE_ADMIN)) { 45 // reservationHistoryList = reservationHistoryService.findAll(); 46 // } else { 47 // reservationHistoryList = reservationHistoryService.findByUser(User user); 48 // } 36 49 model.addAttribute("historyReservations", reservationHistoryList); 37 50 model.addAttribute("bodyContent", "pastReservations"); -
src/main/java/com/example/rezevirajmasa/demo/web/filters/JwtAuthFilter.java
rdb39d9e r8ca35dc 2 2 3 3 import com.example.rezevirajmasa.demo.config.UserAuthProvider; 4 import io.jsonwebtoken.ExpiredJwtException; 4 5 import jakarta.servlet.FilterChain; 5 6 import jakarta.servlet.ServletException; … … 7 8 import jakarta.servlet.http.HttpServletResponse; 8 9 import lombok.RequiredArgsConstructor; 10 import org.springframework.beans.factory.annotation.Autowired; 9 11 import org.springframework.http.HttpHeaders; 12 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 10 13 import org.springframework.security.core.context.SecurityContextHolder; 11 14 import org.springframework.web.filter.OncePerRequestFilter; … … 17 20 18 21 private final UserAuthProvider userAuthProvider; 22 19 23 @Override 20 24 protected void doFilterInternal( … … 24 28 String header = request.getHeader(HttpHeaders.AUTHORIZATION); 25 29 30 String username = null; 31 String jwt = null; 32 26 33 if(header != null) { 34 jwt = header.substring(7); 27 35 String[] elements = header.split(" "); 28 36 29 37 if(elements.length == 2 && "Bearer".equals(elements[0])) { 30 38 try { 39 username = userAuthProvider.extractUsername(jwt); // logikata vidi ja 31 40 SecurityContextHolder.getContext().setAuthentication( 32 41 userAuthProvider.validateToken(elements[1]) 33 42 ); 43 if (username != null) { 44 System.out.println("Authenticated user: " + username); // Debug log 45 SecurityContextHolder.getContext().setAuthentication( 46 userAuthProvider.validateToken(jwt) // Ensure token validation works properly 47 ); 48 } 49 } catch (ExpiredJwtException e) { 50 String isRefreshToken = request.getHeader("isRefreshToken"); 51 String requestURL = request.getRequestURL().toString(); 52 if (isRefreshToken != null && isRefreshToken.equals("true") && requestURL.contains("refresh-token")) { 53 allowForRefreshToken(e, request); 54 } else 55 request.setAttribute("exception", e); 56 34 57 } catch (RuntimeException e) { 35 58 SecurityContextHolder.clearContext(); … … 40 63 filterChain.doFilter(request, response); 41 64 } 65 66 private void allowForRefreshToken(ExpiredJwtException ex, HttpServletRequest request) { 67 UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( 68 null, null, null); 69 SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); 70 request.setAttribute("claims", ex.getClaims()); 71 } 42 72 } -
src/main/java/com/example/rezevirajmasa/demo/web/rest/AuthController.java
rdb39d9e r8ca35dc 14 14 import org.springframework.http.ResponseEntity; 15 15 import org.springframework.security.authentication.AuthenticationManager; 16 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 import org.springframework.security.core.Authentication; 16 18 import org.springframework.security.crypto.password.PasswordEncoder; 17 19 import org.springframework.web.bind.annotation.CrossOrigin; … … 30 32 public ResponseEntity<UserDto> login(@RequestBody CredentialsDto credentialsDto) { 31 33 UserDto user = userService.login(credentialsDto); 32 user.setToken(userAuthProvider.createToken(user.getEmail())); 34 String token = userAuthProvider.createToken(user.getEmail()); 35 user.setToken(token); 36 33 37 return ResponseEntity.ok(user); 34 38 } … … 38 42 UserDto user = userService.register(signUpDto); 39 43 user.setToken(userAuthProvider.createToken(user.getEmail())); 40 return ResponseEntity.created(URI.create("/users/" + user.getId())) 41 .body(user); 44 return ResponseEntity.created(URI.create("/users/" + user.getId())).body(user); 42 45 } 43 46 } -
src/main/java/com/example/rezevirajmasa/demo/web/rest/testController.java
rdb39d9e r8ca35dc 2 2 3 3 import com.example.rezevirajmasa.demo.dto.CustomerDTO; 4 import com.example.rezevirajmasa.demo.dto.UserDto; 5 import com.example.rezevirajmasa.demo.mappers.UserMapper; 4 6 import com.example.rezevirajmasa.demo.model.*; 5 import com.example.rezevirajmasa.demo.service.CustomerService; 6 import com.example.rezevirajmasa.demo.service.ReservationService; 7 import com.example.rezevirajmasa.demo.service.RestaurantService; 8 import com.example.rezevirajmasa.demo.service.TableService; 7 import com.example.rezevirajmasa.demo.service.*; 8 import com.example.rezevirajmasa.demo.service.impl.TokenService; 9 import jakarta.servlet.http.HttpServletRequest; 9 10 import jdk.jfr.consumer.RecordingStream; 10 11 import org.apache.coyote.Response; 12 import org.apache.http.protocol.HTTP; 11 13 import org.springframework.format.annotation.DateTimeFormat; 12 14 import org.springframework.http.HttpStatus; 13 15 import org.springframework.http.ResponseEntity; 16 import org.springframework.security.core.Authentication; 17 import org.springframework.security.core.annotation.AuthenticationPrincipal; 18 import org.springframework.security.core.context.SecurityContextHolder; 19 import org.springframework.security.core.parameters.P; 20 import org.springframework.security.core.userdetails.UserDetails; 14 21 import org.springframework.web.bind.annotation.*; 15 22 23 import java.nio.file.attribute.UserPrincipal; 24 import java.security.Principal; 16 25 import java.time.LocalDateTime; 17 26 import java.time.format.DateTimeFormatter; … … 26 35 private final RestaurantService restaurantService; 27 36 private final CustomerService customerService; 37 private final UserService userService; 28 38 private final ReservationService reservationService; 39 private final ReservationHistoryService reservationHistoryService; 29 40 private final TableService tableService; 30 31 public testController(RestaurantService restaurantService, CustomerService customerService, ReservationService reservationService, TableService tableService) { 41 private final UserMapper userMapper; 42 private final TokenService tokenService; 43 public testController(RestaurantService restaurantService, CustomerService customerService, UserService userService, ReservationService reservationService, ReservationHistoryService reservationHistoryService, TableService tableService, UserMapper userMapper, TokenService tokenService) { 32 44 this.restaurantService = restaurantService; 33 45 this.customerService = customerService; 46 this.userService = userService; 34 47 this.reservationService = reservationService; 48 this.reservationHistoryService = reservationHistoryService; 35 49 this.tableService = tableService; 50 this.userMapper = userMapper; 51 this.tokenService = tokenService; 36 52 } 37 53 … … 114 130 ); 115 131 } 132 @GetMapping("/api/user") 133 public ResponseEntity<?> getCurrentUser() { 134 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 135 136 if (authentication == null || !authentication.isAuthenticated() || authentication.getPrincipal().equals("anonymousUser")) { 137 return new ResponseEntity<>("User is not authenticated", HttpStatus.UNAUTHORIZED); 138 } 139 140 Customer customer = (Customer) authentication.getPrincipal(); 141 return new ResponseEntity<>(customer, HttpStatus.OK); 142 } 143 116 144 117 145 @PostMapping("/api/customers") … … 137 165 // Reservation Calls 138 166 139 @GetMapping("/api/reservations") 140 public ResponseEntity<List<Reservation>> getReservations() { 141 return new ResponseEntity<List<Reservation>>(reservationService.listAll(), HttpStatus.OK); 142 } 143 144 @PostMapping("/api/reservations") 145 public ResponseEntity<Reservation> createReservation(@RequestBody Reservation reservation) { 146 reservation.setReservationDateTime(LocalDateTime.now()); 147 Reservation savedReservation = reservationService.makeReservationRest(reservation); 167 @GetMapping("/api/reservations/by/{email}") 168 public ResponseEntity<List<Reservation>> getReservations(@PathVariable String email) { 169 User user = userService.findByMail(email); 170 return new ResponseEntity<List<Reservation>>(reservationService.findReservationByUser(user), HttpStatus.OK); 171 } 172 173 @PostMapping("/api/reservations/{email}") 174 public ResponseEntity<Reservation> createReservation(@RequestBody Reservation reservation, @PathVariable String email) { 175 User user = userService.findByMail(email); 176 Reservation savedReservation = reservationService.makeReservationRest(reservation, user); 177 148 178 return new ResponseEntity<>(savedReservation, HttpStatus.CREATED); 149 179 } 180 150 181 151 182 @GetMapping("/api/reservations/{reservationId}") … … 159 190 } 160 191 161 @PostMapping("/api/reservations/{reservationId} ")192 @PostMapping("/api/reservations/{reservationId}/{email}") 162 193 public ResponseEntity<Reservation> editReservation(@PathVariable Long reservationId, 163 @RequestBody Reservation reservation) { 194 @RequestBody Reservation reservation, 195 @PathVariable String email) { 196 User user = userService.findByMail(email); 197 164 198 if (!reservation.getReservationID().equals(reservationId)) { 165 199 return ResponseEntity.badRequest().build(); 166 200 } 167 201 168 Reservation savedReservation = reservationService.findById(reservationId); 169 if(!reservation.getCheckInTime().equals(savedReservation.getCheckInTime())) { 170 tableService.canceledTimeSlots(savedReservation.getTable().getId(), savedReservation.getCheckInTime()); 171 } 172 173 savedReservation.setReservationDateTime(LocalDateTime.now()); 174 savedReservation.setCheckInTime(reservation.getCheckInTime()); 175 savedReservation.setCheckOutTime(reservation.getCheckInTime().plusHours(2)); 176 savedReservation.setPartySize(reservation.getPartySize()); 177 savedReservation.setSpecialRequests(reservation.getSpecialRequests()); 178 tableService.deleteTimeSlotsForReservation(reservation.getTable().getId(), reservation.getCheckInTime()); 179 180 //moze da se vovede sistem za ako od 4ca doagjaat samo 2ca da se najde pomala masa po moznost ako ima u toj moment 181 //listaj samo slotovi za taa masa vo toj moment ili da ima da odbere od novo ama taka bolje nova rezevacij 182 183 Reservation updatedReservation = reservationService.makeReservationRest(savedReservation); 184 System.out.println("Saved reservation time: " + savedReservation.getCheckInTime()); 202 // Fetch existing reservation 203 Reservation existingReservation = reservationService.findById(reservationId); 204 if (existingReservation == null) { 205 return ResponseEntity.notFound().build(); 206 } 207 208 if (!reservation.getCheckInTime().equals(existingReservation.getCheckInTime())) { 209 tableService.canceledTimeSlots(existingReservation.getTable().getId(), existingReservation.getCheckInTime()); 210 211 tableService.deleteTimeSlotsForReservation(reservation.getTable().getId(), reservation.getCheckInTime()); 212 } 213 214 existingReservation.setReservationDateTime(LocalDateTime.now()); 215 existingReservation.setCheckInTime(reservation.getCheckInTime()); 216 existingReservation.setCheckOutTime(reservation.getCheckInTime().plusHours(2)); 217 existingReservation.setPartySize(reservation.getPartySize()); 218 existingReservation.setSpecialRequests(reservation.getSpecialRequests()); 219 220 Reservation updatedReservation = reservationService.makeReservationRest(existingReservation, user); 221 222 System.out.println("Updated reservation time: " + updatedReservation.getCheckInTime()); 185 223 return ResponseEntity.ok(updatedReservation); 186 224 } 225 187 226 188 227 @DeleteMapping("/api/reservations/delete/{reservationId}") … … 196 235 } 197 236 237 @GetMapping("/api/reservations/past/{email}") 238 public ResponseEntity<List<Restaurant.ReservationHistory>> pastReservations(@PathVariable String email) { 239 User user = userService.findByMail(email); 240 return null; 241 } 242 198 243 // TableEntity Calls 199 244 … … 203 248 } 204 249 250 // past reservation calls 251 @GetMapping("/api/past-reservations/{email}") 252 public ResponseEntity<List<Restaurant.ReservationHistory>> findPastReservationsByUser(@PathVariable String email) { 253 User user = userService.findByMail(email); 254 List<Restaurant.ReservationHistory> reservations = reservationHistoryService.findByUser(user); 255 return new ResponseEntity<>(reservations, HttpStatus.OK); 256 } 257 205 258 } -
src/main/resources/application.properties
rdb39d9e r8ca35dc 9 9 spring.jpa.show-sql=true 10 10 spring.main.allow-bean-definition-overriding=true 11 12 server.port=8081
Note:
See TracChangeset
for help on using the changeset viewer.