DONE: add customer pages, implement auth on teller page

This commit is contained in:
ISMAIL MASSERAN
2026-07-21 10:24:14 +08:00
parent 3189e3a1e3
commit a671f7ad5c
48 changed files with 5627 additions and 273 deletions
+47 -6
View File
@@ -1,20 +1,61 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { Route, Routes } from 'react-router-dom';
import StationIntroPage from './pages/StationIntroPage/StationIntroPage.jsx';
import ShowQueuesForTellerPage from './pages/ShowQueuesForTellerPage/ShowQueuesForTellerPage';
import Header from './components/Header/Header.jsx';
import CurrentTicketPage from './pages/CurrentTicketPage/CurrentTicketPage.jsx';
import LoginPage from './pages/LoginPage/LoginPage.jsx';
import AuthGuard from './components/AuthGuard/AuthGuard.jsx';
import { UserContext } from './context/UserContext.jsx';
import { clearSession, getToken, getUserData } from './utils/session.js';
import { SERVER_URL } from './constants.js';
import { fetchData } from './fetching/Fetch.js';
export default function App() {
const [user, setUser] = useState(() => getUserData());
useEffect(() => {
const token = getToken();
if (!token) {
return;
}
fetchData(`${SERVER_URL}/api/v1/auth`, 'GET').then(({ success }) => {
if (success) {
setUser(getUserData());
} else {
clearSession();
setUser(null);
}
});
}, []);
return (
<>
<UserContext.Provider value={{ user, setUser }}>
<Header />
<Routes>
<Route exact path='/' element={<StationIntroPage />} />
<Route exact path="/teller-queue/:stationId" element={<ShowQueuesForTellerPage />} />
<Route path="/display/:stationId" element={<CurrentTicketPage/>} />
<Route exact path="/login" element={<LoginPage />} />
<Route
exact
path="/"
element={
<AuthGuard>
<StationIntroPage />
</AuthGuard>
}
/>
<Route
exact
path="/teller-queue/:stationId"
element={
<AuthGuard>
<ShowQueuesForTellerPage />
</AuthGuard>
}
/>
{/* Public display board for waiting area screens */}
<Route path="/display/:stationId" element={<CurrentTicketPage />} />
</Routes>
</>
</UserContext.Provider>
);
}
@@ -0,0 +1,37 @@
import { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../../context/UserContext.jsx';
import { getUserData } from '../../utils/session.js';
import { ROLES } from '../../constants.js';
const TELLER_ROLES = [
ROLES.ROLE_USER,
ROLES.ROLE_SUPER_ADMIN,
ROLES.ROLE_BRANCH_ADMIN,
];
export default function AuthGuard({ children }) {
const navigate = useNavigate();
const { user: contextUser } = useContext(UserContext);
const [allowed, setAllowed] = useState(false);
useEffect(() => {
const user = contextUser ?? getUserData();
const roles = Array.isArray(user?.roles) ? user.roles : [];
const hasAccess = roles.some((role) => TELLER_ROLES.includes(role));
if (!user || !hasAccess) {
setAllowed(false);
navigate('/login', { replace: true });
return;
}
setAllowed(true);
}, [contextUser, navigate]);
if (!allowed) {
return null;
}
return <>{children}</>;
}
@@ -15,4 +15,25 @@ header.main-header {
margin-top: 7px;
margin-right: auto;
margin-left: 2%;
}
.header-user {
display: flex;
align-items: center;
gap: 12px;
margin-right: 2%;
}
.header-email {
font-size: 14px;
color: #334257;
}
.header-logout-btn {
border: 1px solid #334257;
background: white;
color: #334257;
border-radius: 4px;
padding: 6px 12px;
cursor: pointer;
}
@@ -1,13 +1,32 @@
import './Header.css';
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../../context/UserContext.jsx';
import { clearSession } from '../../utils/session.js';
export default function Header() {
const navigate = useNavigate();
const { user, setUser } = useContext(UserContext);
function handleLogout() {
clearSession();
setUser(null);
navigate('/login', { replace: true });
}
return (
<header className="main-header">
<h2 className="header-logo" onClick={() => navigate(`/`)}>BBQMS</h2>
<h2 className="header-logo" onClick={() => navigate(user ? '/' : '/login')}>
BBQMS Teller
</h2>
{user ? (
<div className="header-user">
<span className="header-email">{user.email}</span>
<button type="button" className="header-logout-btn" onClick={handleLogout}>
Logout
</button>
</div>
) : null}
</header>
);
}
}
+6
View File
@@ -1 +1,7 @@
export const SERVER_URL = 'http://localhost:8080';
export const ROLES = {
ROLE_USER: 'ROLE_USER',
ROLE_SUPER_ADMIN: 'ROLE_SUPER_ADMIN',
ROLE_BRANCH_ADMIN: 'ROLE_BRANCH_ADMIN',
};
@@ -0,0 +1,6 @@
import { createContext } from 'react';
export const UserContext = createContext({
user: null,
setUser: () => {},
});
+8 -7
View File
@@ -1,12 +1,14 @@
/*
Koristiti ovu funkciju za fetchanje u buducnosti kad god je to moguce.
*/
import { getToken, setToken } from '../utils/session.js';
export async function fetchData(url, method, body) {
const headers = new Headers();
const token = localStorage.getItem('token');
const token = getToken();
if (token) {
headers.append('Authorization', `Bearer ${ token }`);
headers.append('Authorization', `Bearer ${token}`);
}
headers.append('Content-Type', 'application/json');
@@ -14,7 +16,7 @@ export async function fetchData(url, method, body) {
const res = await fetch(url, {
method: method || 'GET',
headers: headers,
body: body ? JSON.stringify(body) : null
body: body ? JSON.stringify(body) : null,
});
if (!res) {
@@ -24,12 +26,11 @@ export async function fetchData(url, method, body) {
const data = res.ok && res.body ? await res.json() : null;
if (res.ok) {
//na svaki ispravan rezultat treba da dobijemo novi token da refreshamo stari
const newToken = res.headers.get('Auth-Token');
if (newToken) {
localStorage.setItem('token', newToken);
setToken(newToken);
}
}
return { data: data, success: res.ok };
}
return { data, success: res.ok };
}
@@ -0,0 +1,67 @@
#teller-login-form {
width: 420px;
max-width: 100%;
margin: 80px auto 40px;
background-color: #334257;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
#teller-login-form h1 {
margin: 0;
padding: 20px 0;
text-align: center;
font-size: 28px;
font-weight: bold;
color: white;
}
#teller-login-form form {
padding: 20px;
background-color: white;
border-radius: 10px;
}
#teller-login-form .form-group {
margin-bottom: 16px;
}
#teller-login-form label {
display: block;
margin-bottom: 8px;
font-size: 14px;
color: #555;
}
#teller-login-form input {
width: 100%;
padding: 12px;
border: 1px solid #d0d0d0;
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
}
#teller-login-form button {
width: 100%;
margin-top: 8px;
padding: 12px;
border: none;
border-radius: 5px;
background-color: #548ca8;
color: white;
font-size: 16px;
font-weight: bold;
cursor: pointer;
}
#teller-login-form button:disabled {
opacity: 0.7;
cursor: default;
}
#teller-login-form .error {
margin: 0 0 12px;
color: #b00020;
font-size: 14px;
}
@@ -0,0 +1,130 @@
import { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ROLES, SERVER_URL } from '../../constants.js';
import { fetchData } from '../../fetching/Fetch.js';
import { UserContext } from '../../context/UserContext.jsx';
import { clearSession, getToken, setSession } from '../../utils/session.js';
import './LoginPage.css';
const TELLER_ROLES = [
ROLES.ROLE_USER,
ROLES.ROLE_SUPER_ADMIN,
ROLES.ROLE_BRANCH_ADMIN,
];
function canAccessTellerApp(userData) {
const roles = Array.isArray(userData?.roles) ? userData.roles : [];
return roles.some((role) => TELLER_ROLES.includes(role));
}
export default function LoginPage() {
const navigate = useNavigate();
const { user, setUser } = useContext(UserContext);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
if (user && getToken()) {
navigate('/', { replace: true });
}
}, [user, navigate]);
async function handleSubmit(event) {
event.preventDefault();
if (!email.trim()) {
setError('Email is required.');
return;
}
if (!password.trim()) {
setError('Password is required.');
return;
}
setLoading(true);
setError('');
try {
const { data, success } = await fetchData(`${SERVER_URL}/api/v1/auth/login`, 'POST', {
email: email.trim(),
password: password.trim(),
});
if (!success || !data) {
setError('Your credentials are incorrect.');
return;
}
const userData = data.userData ?? data;
const token = data.token;
if (!canAccessTellerApp(userData)) {
clearSession();
setUser(null);
setError('This account cannot access the teller app.');
return;
}
if (!token) {
setError('Two-factor login is not supported in the teller app yet. Disable 2FA for this account or use an account without 2FA.');
return;
}
if (!userData?.tenantCode) {
setError('Login succeeded but tenant information is missing.');
return;
}
setSession({ userData, token });
setUser(userData);
navigate('/', { replace: true });
} catch (err) {
console.error(err);
setError('An error occurred. Please try again.');
} finally {
setLoading(false);
}
}
return (
<div id="teller-login-form">
<h1>Teller Login</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
autoComplete="username"
onChange={(event) => {
setEmail(event.target.value);
setError('');
}}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
autoComplete="current-password"
onChange={(event) => {
setPassword(event.target.value);
setError('');
}}
/>
</div>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
);
}
@@ -1,73 +1,148 @@
import React, { useState, useEffect } from 'react';
import { Dropdown, Button } from 'react-bootstrap';
import React, { useContext, useEffect, useState } from 'react';
import { Dropdown } from 'react-bootstrap';
import { fetchData } from '../../fetching/Fetch.js';
import 'bootstrap/dist/css/bootstrap.min.css';
import { SERVER_URL } from '../../constants.js';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../../context/UserContext.jsx';
const StationIntroPage = () => {
const navigate = useNavigate();
const { user } = useContext(UserContext);
const [branches, setBranches] = useState([]);
const [selectedBranch, setSelectedBranch] = useState(null);
const [stations, setStations] = useState([]);
const [selectedStation, setSelectedStation] = useState(null);
const [error, setError] = useState('');
const [loadingBranches, setLoadingBranches] = useState(false);
const [loadingStations, setLoadingStations] = useState(false);
const url = `${ SERVER_URL }/api/v1/`;
const tenantCode = user?.tenantCode;
const url = `${SERVER_URL}/api/v1/`;
useEffect(() => {
fetchData(`${ url }branches/DFLT`, 'GET')
.then(response => response.data)
.then(setBranches)
.catch(console.error)
}, []);
if (!tenantCode) {
setBranches([]);
setError('Missing tenant on your account.');
return;
}
setLoadingBranches(true);
setError('');
fetchData(`${url}branches/${encodeURIComponent(tenantCode)}`, 'GET')
.then(({ data, success }) => {
if (!success) {
setBranches([]);
setError('Could not load branches for your tenant.');
return;
}
setBranches(Array.isArray(data) ? data : []);
if (!data?.length) {
setError(`No branches found for tenant ${tenantCode}.`);
}
})
.catch((err) => {
console.error(err);
setError('Could not load branches.');
})
.finally(() => setLoadingBranches(false));
}, [tenantCode]);
function handleBranchSelect(branch) {
setSelectedBranch(branch)
fetchData(`${ url }stations/DFLT/${ branch.id }`, 'GET')
.then(response => response.data)
.then(setStations)
.catch(console.error)
setSelectedBranch(branch);
setSelectedStation(null);
setStations([]);
setLoadingStations(true);
setError('');
fetchData(`${url}stations/${encodeURIComponent(tenantCode)}/${branch.id}`, 'GET')
.then(({ data, success }) => {
if (!success) {
setStations([]);
setError('Could not load stations for this branch.');
return;
}
setStations(Array.isArray(data) ? data : []);
if (!data?.length) {
setError('No stations found for this branch.');
}
})
.catch((err) => {
console.error(err);
setError('Could not load stations.');
})
.finally(() => setLoadingStations(false));
}
function handleStationSelect(station) {
navigate(`/teller-queue/${ station.id }`)
setSelectedStation(station);
navigate(`/teller-queue/${station.id}`);
}
return (
<div className="text-center mt-5">
<div className="border p-3" style={{ maxWidth: '500px', margin: '0 auto' }}>
<h1 className="mb-4">Select Branch and Station</h1>
<h1 className="mb-2">Select Branch and Station</h1>
{tenantCode ? (
<p className="text-muted mb-4">Tenant: {tenantCode}</p>
) : null}
{error ? <p className="text-danger">{error}</p> : null}
<Dropdown>
<Dropdown.Toggle variant="primary" id="dropdown-branch" style={{ width: '100%' }}>
{selectedBranch ? selectedBranch.name : 'Select Branch'}
<Dropdown.Toggle
variant="primary"
id="dropdown-branch"
style={{ width: '100%' }}
disabled={loadingBranches || branches.length === 0}
>
{loadingBranches
? 'Loading branches…'
: selectedBranch
? selectedBranch.name
: 'Select Branch'}
</Dropdown.Toggle>
<Dropdown.Menu style={{ width: '100%' }}>
{branches.map(branch => (
<Dropdown.Item key={branch.id} onClick={() => handleBranchSelect(branch)}>
{branches.map((branch) => (
<Dropdown.Item
key={branch.id}
onClick={() => handleBranchSelect(branch)}
>
{branch.name}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
{selectedBranch && (
{selectedBranch ? (
<div className="mt-3">
<Dropdown>
<Dropdown.Toggle variant="primary" id="dropdown-station" style={{ width: '100%' }}>
{selectedStation ? selectedStation.name : 'Select Station'}
<Dropdown.Toggle
variant="primary"
id="dropdown-station"
style={{ width: '100%' }}
disabled={loadingStations || stations.length === 0}
>
{loadingStations
? 'Loading stations…'
: selectedStation
? selectedStation.name
: 'Select Station'}
</Dropdown.Toggle>
<Dropdown.Menu style={{ width: '100%' }}>
{stations.map(station => (
<Dropdown.Item key={station.id} onClick={() => handleStationSelect(station)}>
{stations.map((station) => (
<Dropdown.Item
key={station.id}
onClick={() => handleStationSelect(station)}
>
{station.name}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
</div>
)}
) : null}
</div>
</div>
);
+87
View File
@@ -0,0 +1,87 @@
const TOKEN_KEY = 'teller_token';
const USER_DATA_KEY = 'teller_userData';
/** Matches backend jwt.token-validity-time (PT30M). */
const SESSION_MAX_AGE_SECONDS = 30 * 60;
function getCookie(name) {
const prefix = `${encodeURIComponent(name)}=`;
const parts = document.cookie ? document.cookie.split('; ') : [];
for (const part of parts) {
if (part.startsWith(prefix)) {
return decodeURIComponent(part.slice(prefix.length));
}
}
return null;
}
function setCookie(name, value, maxAgeSeconds = SESSION_MAX_AGE_SECONDS) {
const secure = window.location.protocol === 'https:' ? '; Secure' : '';
document.cookie = [
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
'Path=/',
`Max-Age=${maxAgeSeconds}`,
'SameSite=Lax',
secure,
].join('; ');
}
function removeCookie(name) {
document.cookie = `${encodeURIComponent(name)}=; Path=/; Max-Age=0; SameSite=Lax`;
}
export function getToken() {
return getCookie(TOKEN_KEY);
}
export function setToken(token) {
if (token == null || token === '') {
removeCookie(TOKEN_KEY);
return;
}
setCookie(TOKEN_KEY, token);
}
export function getUserData() {
const raw = getCookie(USER_DATA_KEY) ?? sessionStorage.getItem(USER_DATA_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw);
} catch {
removeCookie(USER_DATA_KEY);
sessionStorage.removeItem(USER_DATA_KEY);
return null;
}
}
export function setUserData(userData) {
if (userData == null) {
removeCookie(USER_DATA_KEY);
sessionStorage.removeItem(USER_DATA_KEY);
return;
}
const serialized = JSON.stringify(userData);
setCookie(USER_DATA_KEY, serialized);
sessionStorage.setItem(USER_DATA_KEY, serialized);
}
export function setSession({ token, userData } = {}) {
if (token !== undefined) {
setToken(token);
}
if (userData !== undefined) {
setUserData(userData);
}
}
export function clearSession() {
removeCookie(TOKEN_KEY);
removeCookie(USER_DATA_KEY);
sessionStorage.removeItem(USER_DATA_KEY);
}