Changeset 8ca35dc


Ignore:
Timestamp:
01/19/25 23:18:37 (4 months ago)
Author:
Aleksandar Panovski <apano77@…>
Branches:
main
Children:
f5b256e
Parents:
db39d9e
Message:

Done with stupid timeslots

Files:
4 added
49 edited

Legend:

Unmodified
Added
Removed
  • my-react-app/package-lock.json

    rdb39d9e r8ca35dc  
    1414        "axios": "^1.6.7",
    1515        "bootstrap": "^5.3.2",
     16        "jwt-decode": "^4.0.0",
    1617        "react": "^18.2.0",
    1718        "react-dom": "^18.2.0",
     
    1226812269      }
    1226912270    },
     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    },
    1227012279    "node_modules/keyv": {
    1227112280      "version": "4.5.4",
  • my-react-app/package.json

    rdb39d9e r8ca35dc  
    99    "axios": "^1.6.7",
    1010    "bootstrap": "^5.3.2",
     11    "jwt-decode": "^4.0.0",
    1112    "react": "^18.2.0",
    1213    "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';
     1import {BrowserRouter as Router, Navigate, Route, Routes, useNavigate} from 'react-router-dom';
    22import Customers from './components/Customers';
    33import Layout from "./components/Layout";
     
    1414import { CuisineContext } from './components/CuisineContext';
    1515import RestaurantInfo from "./components/RestaurantInfo";
    16 import LoginForm from "./components/Login";
     16import AuthForm from "./components/AuthForm";
    1717import AppContent from "./components/AppContent";
     18import ReservationHistory from "./components/ReservationHistory";
     19
     20const ProtectedRoute = ({ element, isAuthenticated }) => {
     21    return isAuthenticated ? element : <Navigate to="/login" />;
     22};
    1823
    1924const 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
    2034    return (
    2135        <Router>
     
    2337                <Routes>
    2438                    <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 />} />
    3652                </Routes>
    37                 <AppContent/>
    3853            </Layout>
    3954        </Router>
    4055    );
    41 }
     56};
    4257
    4358
     
    149164
    150165        try {
    151             const response = await axios.post('http://localhost:8080/api/search', data);
     166            const response = await axios.post('http://localhost:8081/api/search', data);
    152167            const filteredRestaurants = response.data;
    153168            setFilteredRestaurants(filteredRestaurants);
     
    163178        const cuisineName = cuisine.replace('Searching by cuisine: ', '');
    164179        try {
    165             const response = await axios.post(`http://localhost:8080/api/search/shortcut/${cuisineName}`, cuisineName);
     180            const response = await axios.post(`http://localhost:8081/api/search/shortcut/${cuisineName}`, cuisineName);
    166181            console.log(response.data);
    167182            setFilteredRestaurants(response.data)
  • my-react-app/src/axios_helper.js

    rdb39d9e r8ca35dc  
    11import axios from "axios";
    22import data from "bootstrap/js/src/dom/data";
    3 axios.defaults.baseURL = 'http://localhost:8080'
     3axios.defaults.baseURL = 'http://localhost:8081'
    44axios.defaults.headers.post["Content-Type"] = 'application/json'
    55
    66export const getAuthToken = () => {
    77    return window.localStorage.getItem("auth_token");
    8 }
    9 
    10 export const setAuthToken = (token) => {
    11     window.localStorage.setItem("auth_token", token);
    128}
    139
     
    2420    })
    2521}
     22
     23export 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";
     1import React from "react";
     2import axios from "axios";
    23import WelcomeContent from "./WelcomeContent";
    34import AuthContent from "./AuthContent";
    45import LoginForm from "./LoginForm";
    5 import { request, setAuthToken } from "../axios_helper";
    6 import Buttons from './Buttons'
     6import AuthForm from "./AuthForm";
     7import Buttons from './Buttons';
     8import restaurants from "./Restaurants";
    79
    8 export default class AppContent extends React.Component {
     10class AppContent extends React.Component {
    911    constructor(props) {
    1012        super(props);
    1113        this.state = {
    12             componentToShow: "welcome"
     14            componentToShow: "welcome",
     15            isAuthenticated: false,
     16            user: null,
     17            loading: false // Add loading state
    1318        };
     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            });
    1440    };
    1541
    1642    login = () => {
    17         this.setState({componentToShow: "login"})
     43        this.setState({ componentToShow: "login" });
    1844    }
    1945
    2046    logout = () => {
    21         this.setState({componentToShow: "welcome"})
     47        localStorage.removeItem('token');
     48        this.setAuthToken(null);
     49        this.setState({ componentToShow: "welcome", isAuthenticated: false });
    2250    }
    2351
    2452    onLogin = (e, email, password) => {
    2553        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
    3668    };
    3769
    3870    onRegister = (e, firstName, lastName, email, password) => {
    3971        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        }
    5592    };
    5693
     
    5895        return (
    5996            <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 */}
    64102            </div>
    65         )
     103        );
    66104    }
    67105}
     106
     107
     108export default AppContent;
  • my-react-app/src/components/AuthContent.js

    rdb39d9e r8ca35dc  
    2828                        <p>Cuisine Type: {restaurant.cuisineType}</p>
    2929                        <p>Address: {restaurant.address}</p>
    30 
     30                        <p>User: {}</p>
    3131                    </div>
    3232                ))}
  • my-react-app/src/components/CuisineContext.js

    rdb39d9e r8ca35dc  
    1010        const fetchCuisineTypes = async () => {
    1111            try {
    12                 const response = await axios.get('http://localhost:8080/api/cuisineTypes');
     12                const response = await axios.get('http://localhost:8081/api/cuisineTypes');
    1313                setCuisineTypes(response.data);
    1414            } catch (error) {
  • my-react-app/src/components/CustomerContext.js

    rdb39d9e r8ca35dc  
    1010        const fetchCustomers = async () => {
    1111            try {
    12                 const response = await axios.get("http://localhost:8080/api/customers");
     12                const response = await axios.get("http://localhost:8081/api/customers");
    1313                setCustomers(response.data)
    1414            } catch (error) {
  • my-react-app/src/components/CustomerDetails.js

    rdb39d9e r8ca35dc  
    1010        const fetchCustomer = async () => {
    1111            try {
    12                 const response = await axios.get(`http://localhost:8080/api/customers/${id}`);
     12                const response = await axios.get(`http://localhost:8081/api/customers/${id}`);
    1313                setCustomer(response.data);
    1414            } catch (error) {
  • my-react-app/src/components/CustomerFormContainer.js

    rdb39d9e r8ca35dc  
    2626            const fetchCustomer = async () => {
    2727                try {
    28                     const response = await axios.get(`http://localhost:8080/api/customers/${id}`);
     28                    const response = await axios.get(`http://localhost:8081/api/customers/${id}`);
    2929                    const customerData = response.data;
    3030                    setFormData({
     
    5454        try {
    5555            if (customer) {
    56                 await axios.put(`http://localhost:8080/api/customers/edit/${customer.id}`, formData);
     56                await axios.put(`http://localhost:8081/api/customers/edit/${customer.id}`, formData);
    5757            } else {
    58                 await axios.post("http://localhost:8080/api/customers", formData);
     58                await axios.post("http://localhost:8081/api/customers", formData);
    5959            }
    6060            navigate("/customers");
  • my-react-app/src/components/Customers.js

    rdb39d9e r8ca35dc  
    2626    const handleDeleteClick = async (customerId) => {
    2727        try {
    28             await axios.delete(`http://localhost:8080/api/customers/delete/${customerId}`);
     28            await axios.delete(`http://localhost:8081/api/customers/delete/${customerId}`);
    2929            setCustomers(customers.filter(customer => customer.customerID !== customerId));
    3030            window.location.reload();
     
    4848                                    <p className="card-text"><strong>Phone:</strong> {customer.phone}</p>
    4949                                    <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>
    5251                                    {/*<p className="card-text"><strong>Registration*/}
    5352                                    {/*    Date:</strong> {new Date(customer.registrationDate).toLocaleString()}</p>*/}
  • my-react-app/src/components/Header.js

    rdb39d9e r8ca35dc  
    11import React from 'react';
    2 import { Link } from 'react-router-dom';
     2import { Link, useNavigate } from 'react-router-dom';
    33
    44const 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
    517    return (
    618        <header className="header navbar navbar-expand-lg navbar-light bg-light">
     
    1527                        </li>
    1628                        <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">
    2329                            <Link className="nav-link" to="/restaurants">Restaurants</Link>
    2430                        </li>
     
    2632                            <Link className="nav-link" to="/reservations">Reservations</Link>
    2733                        </li>
     34                        <li className="nav-item">
     35                            <Link className="nav-link" to="/reservations-past">Reservation history</Link>
     36                        </li>
    2837                        <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                            )}
    3043                        </form>
    3144                    </ul>
  • my-react-app/src/components/Login.js

    rdb39d9e r8ca35dc  
    66    const navigate = useNavigate();
    77    const [credentials, setCredentials] = useState({ username: '', password: '' });
     8    const [error, setError] = useState('');
    89
    910    const handleChange = (e) => {
     
    1516        e.preventDefault();
    1617        try {
    17             const response = await axios.post('http://localhost:8080/api/login', {
     18            const response = await axios.post('http://localhost:8081/api/login', {
    1819                email: credentials.username,
    1920                password: credentials.password
    2021            });
    2122            const { token } = response.data;
    22             // Store token securely (e.g., using HTTP cookies)
     23
     24            // Store token securely (consider httpOnly cookies)
    2325            localStorage.setItem('token', token);
    2426
     
    2729            // Handle login failure
    2830            console.error('Login failed:', error);
     31            setError('Login failed. Please check your credentials and try again.');
    2932        }
    3033    };
    31 
    3234
    3335    return (
     
    5355                    />
    5456                </div>
     57                {error && <div style={{ color: 'red' }}>{error}</div>}
    5558                <button type="submit">Login</button>
    5659            </form>
  • my-react-app/src/components/LoginForm.js

    rdb39d9e r8ca35dc  
    5555                    <div className="tab-content">
    5656                        <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">
    5859                            <form onSubmit={this.onSubmitLogin}>
    5960                                <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}/>
    6163                                    <label className="form-label" htmlFor="email">Email</label>
    6264                                </div>
    6365                                <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}/>
    6568                                    <label className="form-label" htmlFor="loginPassword">Password</label>
    6669                                </div>
     
    7174
    7275                        <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">
    7478                            <form onSubmit={this.onSubmitRegister}>
    7579                                <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}/>
    7782                                    <label className="form-label" htmlFor="firstName">First Name</label>
    7883                                </div>
    7984                                <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}/>
    8187                                    <label className="form-label" htmlFor="lastName">Last Name</label>
    8288                                </div>
    8389                                <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}/>
    8592                                    <label className="form-label" htmlFor="email">Email</label>
    8693                                </div>
    8794                                <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}/>
    8997                                    <label className="form-label" htmlFor="loginPassword">Password</label>
    9098                                </div>
    9199
    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>
    93101                            </form>
    94102                        </div>
     
    96104                </div>
    97105            </div>
    98         )
     106        );
     107
    99108    }
    100109}
  • my-react-app/src/components/MembershipsEnum.js

    rdb39d9e r8ca35dc  
    33
    44const 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'];
    226};
    237
  • my-react-app/src/components/ReservationConfirmation.js

    rdb39d9e r8ca35dc  
    33import axios from 'axios';
    44import { useNavigate } from 'react-router-dom';
     5import {jwtDecode} from "jwt-decode";
    56
    67const ReservationConfirmation = () => {
     
    1718        const fetchTableDetails = async () => {
    1819            try {
    19                 const tableResponse = await axios.get(`http://localhost:8080/api/tables/${tableNumber}`);
     20                const tableResponse = await axios.get(`http://localhost:8081/api/tables/${tableNumber}`);
    2021                setTable(tableResponse.data);
    2122
    22                 const restaurantResponse = await axios.get(`http://localhost:8080/api/restaurants/${restaurantId}`);
     23                const restaurantResponse = await axios.get(`http://localhost:8081/api/restaurants/${restaurantId}`);
    2324                setRestaurant(restaurantResponse.data);
    2425            } catch (error) {
     
    3132    const handleSubmit = async (e) => {
    3233        e.preventDefault();
    33         // Handle form submission here
     34
     35        if (!restaurant || !table) {
     36            console.error("Restaurant or table is missing.");
     37            return;
     38        }
     39
    3440        try {
    35             // Check if restaurant and table are valid
    36             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");
    3844                return;
    3945            }
    4046
    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");
    5169        } catch (error) {
    5270            console.error("Error creating reservation:", error);
  • my-react-app/src/components/ReservationEdit.js

    rdb39d9e r8ca35dc  
    33import {useNavigate, useParams} from 'react-router-dom';
    44import StarRating from "./StarRating";
     5import {jwtDecode} from "jwt-decode";
    56
    67const ReservationEdit = () => {
     
    1415    const [timeSlots, setTimeSlots] = useState([]);
    1516    const [filteredTimeSlots, setFilteredTimeSlots] = useState([]);
     17    const [checkInTime, setCheckInTime] = useState([]);
    1618
    1719    useEffect(() => {
     
    1921            try {
    2022                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);
    2326                setTable(response.data.table);
    2427                setRestaurant(response.data.restaurant);
     
    5659    const handleSubmit = async (e) => {
    5760        e.preventDefault();
     61
    5862        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
    6275            navigate(`/reservations`)
    6376        } catch (error) {
     
    7184        const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    7285        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}`;
    7393    };
    7494
     
    100120                                ))}
    101121                            </select>
     122                            <label className=".text-danger">Current check in time: {formatTimeSlot(checkInTime)}</label>
    102123                        </div>
    103124                        <div className="mb-3">
  • my-react-app/src/components/Reservations.js

    rdb39d9e r8ca35dc  
    33import 'bootstrap/dist/css/bootstrap.min.css';
    44import {useNavigate} from "react-router-dom";
     5import {jwtDecode} from "jwt-decode";
    56
    67
     
    1314        const fetchReservations = async () => {
    1415            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}`);
    1626                setReservations(response.data);
    1727            } catch (error) {
     
    3141    const handleCancelReservation = async (reservationID) => {
    3242        try {
    33             await axios.delete(`http://localhost:8080/api/reservations/delete/${reservationID}`);
     43            await axios.delete(`http://localhost:8081/api/reservations/delete/${reservationID}`);
    3444            setReservations(reservations.filter(reservation => reservation.reservationID !== reservationID));
    3545            alert('Reservation canceled successfully!');
  • my-react-app/src/components/RestaurantContext.js

    rdb39d9e r8ca35dc  
    1010        const fetchRestaurants = async () => {
    1111            try {
    12                 const response = await axios.get('http://localhost:8080/api/restaurants');
     12                const response = await axios.get('http://localhost:8081/api/restaurants');
    1313                setRestaurants(response.data);
    1414            } catch (error) {
     
    1717        };
    1818
    19         fetchRestaurants();
     19        fetchRestaurants().then(r => console.log(fetchRestaurants()));
    2020    }, []);
    2121
  • my-react-app/src/components/RestaurantDetails.js

    rdb39d9e r8ca35dc  
    2121            try {
    2222                if (!id) return;
    23                 const response = await axios.get(`http://localhost:8080/api/restaurants/${id}`);
     23                const response = await axios.get(`http://localhost:8081/api/restaurants/${id}`);
    2424                setRestaurant(response.data);
    2525            } catch (error) {
     
    3636        const fetchTableDetails = async () => {
    3737            try {
    38                 const response = await axios.get(`http://localhost:8080/api/tables/${selectedTableId}`);
     38                const response = await axios.get(`http://localhost:8081/api/tables/${selectedTableId}`);
    3939                setSelectedTable(response.data);
    4040            } catch (error) {
  • package-lock.json

    rdb39d9e r8ca35dc  
    66    "": {
    77      "dependencies": {
     8        "classnames": "^2.5.1",
    89        "react-router-dom": "^6.22.1",
    910        "swagger-ui-express": "^5.0.0",
  • package.json

    rdb39d9e r8ca35dc  
    11{
    22  "dependencies": {
     3    "classnames": "^2.5.1",
    34    "react-router-dom": "^6.22.1",
    45    "swagger-ui-express": "^5.0.0",
  • pom.xml

    rdb39d9e r8ca35dc  
    108108                        <version>4.3.0</version>
    109109                </dependency>
     110
     111                <dependency>
     112                        <groupId>javax.xml.bind</groupId>
     113                        <artifactId>jaxb-api</artifactId>
     114                        <version>2.3.1</version>
     115                </dependency>
     116
    110117        </dependencies>
    111118
  • 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 @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.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  
    77import org.springframework.http.HttpMethod;
    88import org.springframework.security.authentication.AuthenticationManager;
     9import org.springframework.security.config.Customizer;
    910import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    1011import org.springframework.security.config.annotation.web.builders.HttpSecurity;
     
    1516import org.springframework.security.core.userdetails.UserDetailsService;
    1617import org.springframework.security.web.SecurityFilterChain;
     18import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    1719import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
     20import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    1821import org.springframework.web.servlet.config.annotation.CorsRegistry;
     22import org.springframework.context.annotation.Bean;
     23import org.springframework.context.annotation.Configuration;
     24import org.springframework.security.config.annotation.web.builders.HttpSecurity;
     25import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
     26import org.springframework.security.web.SecurityFilterChain;
    1927import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    2028
     
    4048    public void addCorsMappings(CorsRegistry registry) {
    4149        registry.addMapping("/**")
     50                .allowedOrigins("http://localhost:3000")
     51                .allowedMethods("GET", "POST", "PUT", "DELETE")
     52                .allowedHeaders("*")
    4253                .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);
    4755    }
    4856
    4957//    @Bean
    50 //    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception  {
    51 //
     58//    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    5259//        http
     60//                .exceptionHandling(exception -> exception.authenticationEntryPoint(customerAuthenticationEntryPoint))
     61//                .addFilterBefore(new JwtAuthFilter(userAuthProvider), BasicAuthenticationFilter.class)
    5362//                .csrf(AbstractHttpConfigurer::disable)
    54 //                .authorizeHttpRequests( (requests) -> requests
    55 //                        .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()
    5968//                )
    60 //                .formLogin((form) -> form
    61 //                        .permitAll()
    62 //                        .failureUrl("/login?error=BadCredentials")
    63 //                        .defaultSuccessUrl("/restaurants", true)
    64 //                )
    65 //                .logout((logout) -> logout
     69//                .logout(logout -> logout
    6670//                        .logoutUrl("/logout")
    6771//                        .clearAuthentication(true)
    6872//                        .invalidateHttpSession(true)
    6973//                        .deleteCookies("JSESSIONID")
    70 //                        .logoutSuccessUrl("/")
     74//                        .logoutSuccessUrl("/api/login")  // Redirect to login page after logout
    7175//                );
    7276//
     
    8387                .authorizeHttpRequests((requests) -> requests
    8488                        .requestMatchers(HttpMethod.POST, "/api/login", "/api/register").permitAll()
    85                         .anyRequest().authenticated()
    86                 );
     89                        .anyRequest().authenticated());
    8790        return http.build();
    8891    }
     92
    8993    @Bean
    9094    public AuthenticationManager authManager(HttpSecurity http) throws Exception {
     
    9599    }
    96100}
     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  
    77import com.example.rezevirajmasa.demo.dto.UserDto;
    88import com.example.rezevirajmasa.demo.service.UserService;
     9import io.jsonwebtoken.Claims;
     10import io.jsonwebtoken.Jwts;
    911import jakarta.annotation.PostConstruct;
    1012import lombok.RequiredArgsConstructor;
     
    1214import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    1315import org.springframework.security.core.Authentication;
     16import org.springframework.security.core.userdetails.UserDetails;
    1417import org.springframework.stereotype.Component;
    1518
    16 import java.util.Base64;
    17 import java.util.Collections;
    18 import java.util.Date;
     19import java.util.*;
     20import java.util.function.Function;
    1921
    2022@RequiredArgsConstructor
     
    2931    protected void init() {
    3032        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());
    3138    }
    3239
     
    5057        return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
    5158    }
     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    }
    5280}
  • src/main/java/com/example/rezevirajmasa/demo/dto/CredentialsDto.java

    rdb39d9e r8ca35dc  
    1111@Data
    1212public class CredentialsDto {
    13     private String login;
     13    private String email;
    1414    private char[] password;
    1515}
  • src/main/java/com/example/rezevirajmasa/demo/dto/SignUpDto.java

    rdb39d9e r8ca35dc  
    1515    private String email;
    1616    private char[] password;
     17    private String phone;
     18    private String address;
     19    private String membershipLevel;
    1720}
  • src/main/java/com/example/rezevirajmasa/demo/dto/UserDto.java

    rdb39d9e r8ca35dc  
    1616    private String email;
    1717    private String token;
     18    private String phone;
     19    private String address;
     20    private String membershipLevel;
    1821}
  • src/main/java/com/example/rezevirajmasa/demo/mappers/UserMapper.java

    rdb39d9e r8ca35dc  
    1414    @Mapping(target = "password", ignore = true)
    1515    User signUpToUser(SignUpDto userDto);
     16
     17    SignUpDto toSignUpDto(UserDto userDto);
     18    User toUser(UserDto userDto);
    1619}
  • src/main/java/com/example/rezevirajmasa/demo/mappers/UserMapperImpl.java

    rdb39d9e r8ca35dc  
    33import com.example.rezevirajmasa.demo.dto.SignUpDto;
    44import com.example.rezevirajmasa.demo.dto.UserDto;
     5import com.example.rezevirajmasa.demo.model.MembershipLevel;
    56import com.example.rezevirajmasa.demo.model.User;
    67import org.springframework.stereotype.Component;
     
    3637        user.setFirstName(userDto.getFirstName());
    3738        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());
    3976
    4077        return user;
  • src/main/java/com/example/rezevirajmasa/demo/model/Reservation.java

    rdb39d9e r8ca35dc  
    1616
    1717    @ManyToOne
    18     @JoinColumn(name = "CustomerID")
    19     private Customer customer;
     18    @JoinColumn(name = "UserID")
     19    private User user;
    2020
    2121    @ManyToOne
     
    6868    }
    6969
    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) {
    7171//        this.customer = customer;
    7272        this.table = table;
     73        this.user = user;
    7374        this.restaurant = restaurant;
    7475        this.reservationDateTime = reservationDateTime;
     
    8182    }
    8283
     84    public User getUser() {
     85        return user;
     86    }
     87
     88    public void setUser(User user) {
     89        this.user = user;
     90    }
     91
    8392    public Long getReservationID() {
    8493        return reservationID;
     
    8998    }
    9099
    91     public Customer getCustomer() {
    92         return customer;
    93     }
    94 
    95     public void setCustomer(Customer customer) {
    96         this.customer = customer;
    97     }
    98100
    99101    public TableEntity getTable() {
     
    173175        return "Reservation{" +
    174176                "reservationID=" + reservationID +
    175                 ", customer=" + customer +
     177                ", customer=" + user +
    176178                ", table=" + table +
    177179                ", restaurant=" + restaurant +
  • src/main/java/com/example/rezevirajmasa/demo/model/Restaurant.java

    rdb39d9e r8ca35dc  
    151151        @ManyToOne
    152152        @JoinColumn(name = "customer_id")
    153         private Customer customer;
     153        private User user;
    154154
    155155        @ManyToOne
     
    179179        private LocalDateTime checkInDate;
    180180
    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;
    183183            this.table = table;
    184184            this.restaurant = restaurant;
     
    202202        }
    203203
    204         public Customer getCustomer() {
    205             return customer;
    206         }
    207 
    208         public void setCustomer(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;
    210210        }
    211211
     
    278278            return "ReservationHistory{" +
    279279                    "id=" + id +
    280                     ", customer=" + customer +
     280                    ", user=" + user +
    281281                    ", table=" + table +
    282282                    ", restaurant=" + restaurant +
  • src/main/java/com/example/rezevirajmasa/demo/model/User.java

    rdb39d9e r8ca35dc  
    77import lombok.NoArgsConstructor;
    88import org.springframework.web.bind.annotation.GetMapping;
     9
     10import java.util.Date;
    911
    1012@AllArgsConstructor
     
    3133    @Column(nullable = false)
    3234    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;
    3352}
  • src/main/java/com/example/rezevirajmasa/demo/repository/ReservationHistoryRepository.java

    rdb39d9e r8ca35dc  
    44import com.example.rezevirajmasa.demo.model.Reservation;
    55import com.example.rezevirajmasa.demo.model.Restaurant;
     6import com.example.rezevirajmasa.demo.model.User;
    67import org.springframework.cglib.core.Local;
    78import org.springframework.data.jpa.repository.JpaRepository;
     
    1112
    1213public interface ReservationHistoryRepository extends JpaRepository<Restaurant.ReservationHistory, Long> {
    13     List<Restaurant.ReservationHistory> findAllByCustomer(Customer customer);
     14    List<Restaurant.ReservationHistory> findALlByUser(User user);
    1415    List<Restaurant.ReservationHistory> findByCheckInDateBeforeAndStatus(LocalDateTime currentTime, String scheduled);
    1516    List<Restaurant.ReservationHistory> findAllByCheckInDateBefore(LocalDateTime currentTime);
  • src/main/java/com/example/rezevirajmasa/demo/repository/ReservationRepository.java

    rdb39d9e r8ca35dc  
    11package com.example.rezevirajmasa.demo.repository;
    22
    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;
     3import com.example.rezevirajmasa.demo.model.*;
    74import org.springframework.data.jpa.repository.JpaRepository;
    85
     
    118
    129public interface ReservationRepository extends JpaRepository<Reservation, Long> {
    13     List<Reservation> findAllByCustomer(Customer customer);
     10    List<Reservation> findALlByUserAndCheckInTimeAfter(User user, LocalDateTime now);
    1411    List<Reservation> findByTableAndCheckInTimeBetween(TableEntity table, LocalDateTime startTime, LocalDateTime endTime);
    1512
     
    1714    List<Reservation> findAllByCheckInTimeBefore(LocalDateTime currentTime);
    1815    List<Reservation> findByCheckInTimeAfterAndCheckInTimeBefore(LocalDateTime startTime, LocalDateTime endTime);
     16    List<Reservation> findALlByUserAndCheckInTimeBefore(User user, LocalDateTime now);
    1917}
  • src/main/java/com/example/rezevirajmasa/demo/service/ReservationHistoryService.java

    rdb39d9e r8ca35dc  
    44import com.example.rezevirajmasa.demo.model.Reservation;
    55import com.example.rezevirajmasa.demo.model.Restaurant;
     6import com.example.rezevirajmasa.demo.model.User;
    67
    78import java.time.LocalDateTime;
     
    1112    public void moveReservationToHistory(Reservation reservation, String status, String cancellationReason);
    1213    public void moveReservationsToPast(List<Restaurant.ReservationHistory> reservationsToMove);
    13     List<Restaurant.ReservationHistory> findByCustomer(Customer customer);
     14    List<Restaurant.ReservationHistory> findByUser(User user);
    1415    List<Restaurant.ReservationHistory> findAll();
    1516    List<Restaurant.ReservationHistory> findReservationsToMove(LocalDateTime currentTime);
  • src/main/java/com/example/rezevirajmasa/demo/service/ReservationService.java

    rdb39d9e r8ca35dc  
    11package com.example.rezevirajmasa.demo.service;
    22
    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;
     3import com.example.rezevirajmasa.demo.model.*;
     4import org.springframework.security.core.userdetails.UserDetails;
    75
    86import java.time.LocalDateTime;
     
    108
    119public 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);
    1412    public List<Reservation> listAll();
    1513    public Reservation findById(Long id);
    1614    public Reservation getReservationById(Long reservationId);
    1715    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);
    1918    public List<Reservation> findReservationsByTableAndDateRange(TableEntity table, LocalDateTime startDateTime, LocalDateTime endDateTime);
    2019    List<Reservation> findReservationsToMove(LocalDateTime currentTime);
  • src/main/java/com/example/rezevirajmasa/demo/service/UserService.java

    rdb39d9e r8ca35dc  
    44import com.example.rezevirajmasa.demo.dto.SignUpDto;
    55import com.example.rezevirajmasa.demo.dto.UserDto;
     6import com.example.rezevirajmasa.demo.model.User;
    67import lombok.RequiredArgsConstructor;
    78
     
    910public interface UserService {
    1011    public UserDto findByEmail(String email);
     12    public User findByMail(String email);
    1113    public UserDto login(CredentialsDto credentialsDto);
    1214    public UserDto register(SignUpDto userDto);
     15    public User findUserById(Long userId);
    1316}
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/ReservationHistoryServiceImpl.java

    rdb39d9e r8ca35dc  
    44import com.example.rezevirajmasa.demo.model.Reservation;
    55import com.example.rezevirajmasa.demo.model.Restaurant;
     6import com.example.rezevirajmasa.demo.model.User;
    67import com.example.rezevirajmasa.demo.repository.ReservationHistoryRepository;
    78import com.example.rezevirajmasa.demo.service.ReservationHistoryService;
     
    2223    public void moveReservationToHistory(Reservation reservation, String status, String cancellationReason) {
    2324        Restaurant.ReservationHistory history = new Restaurant.ReservationHistory();
    24         history.setCustomer(reservation.getCustomer());
     25        history.setUser(reservation.getUser());
    2526        history.setTable(reservation.getTable());
    2627        history.setReservationDateTime(reservation.getReservationDateTime());
     
    4243
    4344    @Override
    44     public List<Restaurant.ReservationHistory> findByCustomer(Customer customer) {
    45         return reservationHistoryRepository.findAllByCustomer(customer);
     45    public List<Restaurant.ReservationHistory> findByUser(User user) {
     46        return reservationHistoryRepository.findALlByUser(user);
    4647    }
    4748
    4849    @Override
    4950    public void moveReservationsToPast(List<Restaurant.ReservationHistory> reservationsToMove) {
    50         // Update the status of reservations to "Past"
    5151        for (Restaurant.ReservationHistory reservation : reservationsToMove) {
    5252            reservation.setStatus("Past");
    5353        }
    5454
    55         // Save the updated reservations
    5655        reservationHistoryRepository.saveAll(reservationsToMove);
    5756    }
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/ReservationImpl.java

    rdb39d9e r8ca35dc  
    11package com.example.rezevirajmasa.demo.service.impl;
    22
    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;
     3import com.example.rezevirajmasa.demo.dto.UserDto;
     4import com.example.rezevirajmasa.demo.mappers.UserMapper;
     5import com.example.rezevirajmasa.demo.model.*;
    76import com.example.rezevirajmasa.demo.model.exceptions.InvalidReservationException;
    87import com.example.rezevirajmasa.demo.model.exceptions.InvalidReservationIdException;
     
    1110import com.example.rezevirajmasa.demo.repository.RestaurantRepository;
    1211import com.example.rezevirajmasa.demo.repository.TableRepository;
     12import com.example.rezevirajmasa.demo.service.ReservationHistoryService;
    1313import com.example.rezevirajmasa.demo.service.ReservationService;
     14import com.example.rezevirajmasa.demo.service.UserService;
    1415import org.springframework.beans.factory.annotation.Autowired;
     16import org.springframework.cglib.core.Local;
     17import org.springframework.security.core.Authentication;
     18import org.springframework.security.core.annotation.AuthenticationPrincipal;
     19import org.springframework.security.core.context.SecurityContextHolder;
     20import org.springframework.security.core.userdetails.UserDetails;
    1521import org.springframework.stereotype.Service;
     22import org.springframework.web.bind.annotation.RequestBody;
    1623
    1724import javax.swing.text.html.Option;
     
    2734    private TableRepository tableRepository;
    2835    @Autowired
    29     private RestaurantRepository restaurantRepository;
     36    private ReservationHistoryService reservationHistoryService;
     37    private final UserMapper userMapper;
    3038    @Autowired
    31     private CustomerRepository customerRepository;
     39    private UserService userService;
    3240    @Autowired
    3341    private ReservationRepository reservationRepository;
     42
     43    public ReservationImpl(UserMapper userMapper) {
     44        this.userMapper = userMapper;
     45    }
    3446
    3547    @Override
     
    3951
    4052    @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) {
    4254        if (!table.isAvailable(checkInTime)) {
    4355            // Handle unavailability (throw an exception, return a specific response, etc.)
     
    4658
    4759        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);
    4961
    5062//        // Update table status or perform additional logic if needed
     
    5668
    5769    @Override
    58     public Reservation makeReservationRest(Reservation reservation) {
     70    public Reservation makeReservationRest(Reservation reservation, User user) {
    5971        Optional<TableEntity> optionalTable = tableRepository.findById(reservation.getTable().getId());
    60         if(optionalTable.isPresent()) {
     72        if (optionalTable.isPresent()) {
    6173            TableEntity table = optionalTable.get();
     74
     75            reservation.setUser(user);
    6276
    6377            LocalDateTime startTime = reservation.getCheckInTime().minusHours(2);
     
    6781                    x -> x.isAfter(startTime) && x.isBefore(endTime)
    6882            );
    69 
     83            reservation.setReservationDateTime(LocalDateTime.now());
    7084            return reservationRepository.save(reservation);
    7185        } else {
    72             throw new InvalidReservationException("Unsuccessful reservation -> time slot not avalaible");
     86            throw new InvalidReservationException("Unsuccessful reservation -> time slot not available");
    7387        }
    7488    }
     89
    7590
    7691    @Override
     
    109124                from = from.plusMinutes(15);
    110125            }
     126            reservationHistoryService.moveReservationToHistory(reservation, "Canceled", "Canceled by user");
    111127            reservationRepository.delete(reservation);
    112             return true; // Return true indicating successful cancellation
     128            return true;
    113129        } else {
    114             return false; // Return false indicating reservation with the given ID not found
     130            return false;
    115131        }
    116132    }
     
    118134
    119135    @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);
    122145    }
    123146
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/RestaurantServiceImpl.java

    rdb39d9e r8ca35dc  
    175175                    .collect(Collectors.toList());
    176176        } else {
    177             List<Restaurant> restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(search);
     177            String searchTerm = "%" + search + "%";
     178            List<Restaurant> restaurantList = restaurantRepository.findAllByNameLikeIgnoreCase(searchTerm);
    178179            if (restaurantList.isEmpty()) {
    179180                restaurantList = restaurantRepository.findAllByCuisineTypeContaining(search);
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/UserServiceImpl.java

    rdb39d9e r8ca35dc  
    66import com.example.rezevirajmasa.demo.mappers.UserMapper;
    77import com.example.rezevirajmasa.demo.mappers.UserMapperImpl;
     8import com.example.rezevirajmasa.demo.model.MembershipLevel;
     9import com.example.rezevirajmasa.demo.model.Role;
    810import com.example.rezevirajmasa.demo.model.User;
    911import com.example.rezevirajmasa.demo.model.exceptions.AppException;
     
    1214import lombok.RequiredArgsConstructor;
    1315import org.mapstruct.control.MappingControl;
     16import org.openqa.selenium.InvalidArgumentException;
    1417import org.springframework.http.HttpStatus;
    1518import org.springframework.security.crypto.password.PasswordEncoder;
    1619import org.springframework.stereotype.Service;
    1720import java.nio.CharBuffer;
     21import java.sql.Date;
     22import java.time.LocalDate;
    1823import java.util.Optional;
    1924
     
    3035    }
    3136
     37    @Override
     38    public User findByMail(String email) {
     39        return userRepository.findByEmail(email).orElseThrow(() -> new AppException(("Unknown user"), HttpStatus.NOT_FOUND));
     40    }
     41
    3242    public UserDto login(CredentialsDto credentialsDto) {
    33         User user = userRepository.findByEmail(credentialsDto.getLogin())
     43        User user = userRepository.findByEmail(credentialsDto.getEmail())
    3444                .orElseThrow(() -> new AppException("Unknown user", HttpStatus.NOT_FOUND));
    3545
     
    5161        user.setPassword(passwordEncoder.encode(CharBuffer.wrap(userDto.getPassword())));
    5262
     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
    5371        User savedUser = userRepository.save(user);
    5472
    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"));
    5679    }
    5780}
  • src/main/java/com/example/rezevirajmasa/demo/web/controller/ReservationController.java

    rdb39d9e r8ca35dc  
    11package com.example.rezevirajmasa.demo.web.controller;
    22
     3import com.example.rezevirajmasa.demo.dto.SignUpDto;
     4import com.example.rezevirajmasa.demo.dto.UserDto;
     5import com.example.rezevirajmasa.demo.mappers.UserMapper;
    36import com.example.rezevirajmasa.demo.model.*;
    47import com.example.rezevirajmasa.demo.model.exceptions.ExpiredReservationException;
     
    1922public class ReservationController {
    2023    private final ReservationService reservationService;
    21     private final CustomerService customerService;
     24    private final UserService userService;
    2225    private final TableService tableService;
    2326    private final ReservationHistoryService reservationHistoryService;
    2427
    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) {
    2631        this.reservationService = reservationService;
    27         this.customerService = customerService;
     32        this.userService = userService;
    2833        this.tableService = tableService;
    2934        this.reservationHistoryService = reservationHistoryService;
     35        this.userMapper = userMapper;
    3036    }
    3137
    3238    @GetMapping("/reservations")
    3339    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
    4148        model.addAttribute("bodyContent", "reservationList");
    4249        model.addAttribute("reservations", reservationList);
    4350        return "index";
    4451    }
     52
    4553
    4654    @GetMapping("/reservations/edit/{reservationId}")
     
    6270        Restaurant restaurant = table.getRestaurant();
    6371
    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);
    6577
    6678        if(!table.isAvailable(reservationDateTime)) {
     
    6880        }
    6981        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);
    7183        return "redirect:/reservations";
    7284    }
  • src/main/java/com/example/rezevirajmasa/demo/web/controller/ReservationHistoryController.java

    rdb39d9e r8ca35dc  
    11package com.example.rezevirajmasa.demo.web.controller;
    22
     3import com.example.rezevirajmasa.demo.dto.SignUpDto;
     4import com.example.rezevirajmasa.demo.dto.UserDto;
     5import com.example.rezevirajmasa.demo.mappers.UserMapper;
    36import com.example.rezevirajmasa.demo.model.Customer;
    47import com.example.rezevirajmasa.demo.model.Restaurant;
    58import com.example.rezevirajmasa.demo.model.Role;
     9import com.example.rezevirajmasa.demo.model.User;
    610import com.example.rezevirajmasa.demo.service.CustomerService;
    711import com.example.rezevirajmasa.demo.service.ReservationHistoryService;
     12import com.example.rezevirajmasa.demo.service.UserService;
    813import org.springframework.security.core.Authentication;
    914import org.springframework.stereotype.Controller;
     
    1823public class ReservationHistoryController {
    1924    private final ReservationHistoryService reservationHistoryService;
    20     private final CustomerService customerService;
     25    private final UserService userService;
     26    private final UserMapper userMapper;
    2127
    22     public ReservationHistoryController(ReservationHistoryService reservationHistoryService, CustomerService customerService) {
     28    public ReservationHistoryController(ReservationHistoryService reservationHistoryService, UserService userService, UserMapper userMapper) {
    2329        this.reservationHistoryService = reservationHistoryService;
    24         this.customerService = customerService;
     30        this.userService = userService;
     31        this.userMapper = userMapper;
    2532    }
    2633
     
    2835    public String showPastReservations(Authentication authentication, Model model) {
    2936        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//        }
    3649        model.addAttribute("historyReservations", reservationHistoryList);
    3750        model.addAttribute("bodyContent", "pastReservations");
  • src/main/java/com/example/rezevirajmasa/demo/web/filters/JwtAuthFilter.java

    rdb39d9e r8ca35dc  
    22
    33import com.example.rezevirajmasa.demo.config.UserAuthProvider;
     4import io.jsonwebtoken.ExpiredJwtException;
    45import jakarta.servlet.FilterChain;
    56import jakarta.servlet.ServletException;
     
    78import jakarta.servlet.http.HttpServletResponse;
    89import lombok.RequiredArgsConstructor;
     10import org.springframework.beans.factory.annotation.Autowired;
    911import org.springframework.http.HttpHeaders;
     12import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    1013import org.springframework.security.core.context.SecurityContextHolder;
    1114import org.springframework.web.filter.OncePerRequestFilter;
     
    1720
    1821    private final UserAuthProvider userAuthProvider;
     22
    1923    @Override
    2024    protected void doFilterInternal(
     
    2428        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    2529
     30        String username = null;
     31        String jwt = null;
     32
    2633        if(header != null) {
     34            jwt = header.substring(7);
    2735            String[] elements = header.split(" ");
    2836
    2937            if(elements.length == 2 && "Bearer".equals(elements[0])) {
    3038                try {
     39                    username = userAuthProvider.extractUsername(jwt); // logikata vidi ja
    3140                    SecurityContextHolder.getContext().setAuthentication(
    3241                            userAuthProvider.validateToken(elements[1])
    3342                    );
     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
    3457                } catch (RuntimeException e) {
    3558                    SecurityContextHolder.clearContext();
     
    4063        filterChain.doFilter(request, response);
    4164    }
     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    }
    4272}
  • src/main/java/com/example/rezevirajmasa/demo/web/rest/AuthController.java

    rdb39d9e r8ca35dc  
    1414import org.springframework.http.ResponseEntity;
    1515import org.springframework.security.authentication.AuthenticationManager;
     16import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
     17import org.springframework.security.core.Authentication;
    1618import org.springframework.security.crypto.password.PasswordEncoder;
    1719import org.springframework.web.bind.annotation.CrossOrigin;
     
    3032    public ResponseEntity<UserDto> login(@RequestBody CredentialsDto credentialsDto) {
    3133        UserDto user = userService.login(credentialsDto);
    32         user.setToken(userAuthProvider.createToken(user.getEmail()));
     34        String token = userAuthProvider.createToken(user.getEmail());
     35        user.setToken(token);
     36
    3337        return ResponseEntity.ok(user);
    3438    }
     
    3842        UserDto user = userService.register(signUpDto);
    3943        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);
    4245    }
    4346}
  • src/main/java/com/example/rezevirajmasa/demo/web/rest/testController.java

    rdb39d9e r8ca35dc  
    22
    33import com.example.rezevirajmasa.demo.dto.CustomerDTO;
     4import com.example.rezevirajmasa.demo.dto.UserDto;
     5import com.example.rezevirajmasa.demo.mappers.UserMapper;
    46import 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;
     7import com.example.rezevirajmasa.demo.service.*;
     8import com.example.rezevirajmasa.demo.service.impl.TokenService;
     9import jakarta.servlet.http.HttpServletRequest;
    910import jdk.jfr.consumer.RecordingStream;
    1011import org.apache.coyote.Response;
     12import org.apache.http.protocol.HTTP;
    1113import org.springframework.format.annotation.DateTimeFormat;
    1214import org.springframework.http.HttpStatus;
    1315import org.springframework.http.ResponseEntity;
     16import org.springframework.security.core.Authentication;
     17import org.springframework.security.core.annotation.AuthenticationPrincipal;
     18import org.springframework.security.core.context.SecurityContextHolder;
     19import org.springframework.security.core.parameters.P;
     20import org.springframework.security.core.userdetails.UserDetails;
    1421import org.springframework.web.bind.annotation.*;
    1522
     23import java.nio.file.attribute.UserPrincipal;
     24import java.security.Principal;
    1625import java.time.LocalDateTime;
    1726import java.time.format.DateTimeFormatter;
     
    2635    private final RestaurantService restaurantService;
    2736    private final CustomerService customerService;
     37    private final UserService userService;
    2838    private final ReservationService reservationService;
     39    private final ReservationHistoryService reservationHistoryService;
    2940    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) {
    3244        this.restaurantService = restaurantService;
    3345        this.customerService = customerService;
     46        this.userService = userService;
    3447        this.reservationService = reservationService;
     48        this.reservationHistoryService = reservationHistoryService;
    3549        this.tableService = tableService;
     50        this.userMapper = userMapper;
     51        this.tokenService = tokenService;
    3652    }
    3753
     
    114130        );
    115131    }
     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
    116144
    117145    @PostMapping("/api/customers")
     
    137165//    Reservation Calls
    138166
    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
    148178        return new ResponseEntity<>(savedReservation, HttpStatus.CREATED);
    149179    }
     180
    150181
    151182    @GetMapping("/api/reservations/{reservationId}")
     
    159190    }
    160191
    161     @PostMapping("/api/reservations/{reservationId}")
     192    @PostMapping("/api/reservations/{reservationId}/{email}")
    162193    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
    164198        if (!reservation.getReservationID().equals(reservationId)) {
    165199            return ResponseEntity.badRequest().build();
    166200        }
    167201
    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());
    185223        return ResponseEntity.ok(updatedReservation);
    186224    }
     225
    187226
    188227    @DeleteMapping("/api/reservations/delete/{reservationId}")
     
    196235    }
    197236
     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
    198243//    TableEntity Calls
    199244
     
    203248    }
    204249
     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
    205258}
  • src/main/resources/application.properties

    rdb39d9e r8ca35dc  
    99spring.jpa.show-sql=true
    1010spring.main.allow-bean-definition-overriding=true
     11
     12server.port=8081
Note: See TracChangeset for help on using the changeset viewer.