diff --git a/README.md b/README.md index 13cafa1..7b1bae8 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Aplikace sestává ze dvou (tří) modulů. - [ ] Popsat nginx - [x] Popsat závislosti, co je nutné provést před vývojem a postup spuštění pro vývoj - [x] Popsat dostupné env -- [ ] Přesunout autentizaci na server (JWT?) +- [x] Přesunout autentizaci na server (JWT?) - [x] Zavést .env.template a přidat .env do .gitignore - [x] Zkrášlit dialog pro vyplnění čísla účtu, vypadá mizerně - [ ] Podpora pro notifikace v externích systémech (Gotify, Discord, MS Teams) diff --git a/client/src/Api.ts b/client/src/Api.ts index 327c3b5..ff89e73 100644 --- a/client/src/Api.ts +++ b/client/src/Api.ts @@ -1,10 +1,14 @@ import { PizzaOrder } from "./Types"; -import { getBaseUrl } from "./Utils"; +import { getBaseUrl, getToken } from "./Utils"; async function request( url: string, config: RequestInit = {} ): Promise { + if (!config.headers) { + config.headers = {}; + } + config.headers["Authorization"] = `Bearer ${getToken()}`; return fetch(getBaseUrl() + url, config).then(response => { if (!response.ok) { throw new Error(response.statusText); @@ -18,8 +22,8 @@ const api = { post: (url: string, body: TBody) => request(url, { method: 'POST', body, headers: { 'Content-Type': 'application/json' } }), } -export const getQrUrl = (login: string) => { - return `${getBaseUrl()}/api/qr?login=${login}`; +export const getQrUrl = () => { + return `${getBaseUrl()}/api/qr`; } export const getData = async () => { @@ -34,46 +38,46 @@ export const getPizzy = async () => { return await api.get('/api/pizza'); } -export const createPizzaDay = async (creator) => { - return await api.post('/api/createPizzaDay', JSON.stringify({ creator })); +export const createPizzaDay = async () => { + return await api.post('/api/createPizzaDay', undefined); } -export const deletePizzaDay = async (login) => { - return await api.post('/api/deletePizzaDay', JSON.stringify({ login })); +export const deletePizzaDay = async () => { + return await api.post('/api/deletePizzaDay', undefined); } -export const lockPizzaDay = async (login) => { - return await api.post('/api/lockPizzaDay', JSON.stringify({ login })); +export const lockPizzaDay = async () => { + return await api.post('/api/lockPizzaDay', undefined); } -export const unlockPizzaDay = async (login) => { - return await api.post('/api/unlockPizzaDay', JSON.stringify({ login })); +export const unlockPizzaDay = async () => { + return await api.post('/api/unlockPizzaDay', undefined); } -export const finishOrder = async (login) => { - return await api.post('/api/finishOrder', JSON.stringify({ login })); +export const finishOrder = async () => { + return await api.post('/api/finishOrder', undefined); } -export const finishDelivery = async (login, bankAccount, bankAccountHolder) => { - return await api.post('/api/finishDelivery', JSON.stringify({ login, bankAccount, bankAccountHolder })); +export const finishDelivery = async (bankAccount, bankAccountHolder) => { + return await api.post('/api/finishDelivery', JSON.stringify({ bankAccount, bankAccountHolder })); } -export const updateChoice = async (name: string, choice: number | null) => { - return await api.post('/api/updateChoice', JSON.stringify({ name, choice })); +export const updateChoice = async (choice: number | null) => { + return await api.post('/api/updateChoice', JSON.stringify({ choice })); } -export const addPizza = async (login: string, pizzaIndex: number, pizzaSizeIndex: number) => { - return await api.post('/api/addPizza', JSON.stringify({ login, pizzaIndex, pizzaSizeIndex })); +export const addPizza = async (pizzaIndex: number, pizzaSizeIndex: number) => { + return await api.post('/api/addPizza', JSON.stringify({ pizzaIndex, pizzaSizeIndex })); } -export const removePizza = async (login: string, pizzaOrder: PizzaOrder) => { - return await api.post('/api/removePizza', JSON.stringify({ login, pizzaOrder })); +export const removePizza = async (pizzaOrder: PizzaOrder) => { + return await api.post('/api/removePizza', JSON.stringify({ pizzaOrder })); } -export const updateNote = async (login: string, note?: string) => { - return await api.post('/api/updateNote', JSON.stringify({ login, note })); +export const updateNote = async (note?: string) => { + return await api.post('/api/updateNote', JSON.stringify({ note })); } export const login = async (login: string) => { return await api.post('/api/login', JSON.stringify({ login })); -} \ No newline at end of file +} diff --git a/client/src/App.tsx b/client/src/App.tsx index dafa7e6..745f1ed 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -31,8 +31,11 @@ function App() { const choiceRef = useRef(null); const poznamkaRef = useRef(null); - // Prvotní načtení aktuálního stavu + // Načtení dat po přihlášení useEffect(() => { + if (!auth || !auth.login) { + return + } getPizzy().then(pizzy => { setPizzy(pizzy); }); @@ -42,7 +45,7 @@ function App() { getFood().then(food => { setFood(food); }) - }, []); + }, [auth, auth?.login]); // Registrace socket eventů useEffect(() => { @@ -91,13 +94,13 @@ function App() { const changeChoice = async (event: React.ChangeEvent) => { const index = Object.values(Locations).indexOf(event.target.value as unknown as Locations); if (auth?.login) { - await updateChoice(auth.login, index > -1 ? index : null); + await updateChoice(index > -1 ? index : null); } } const removeChoice = async (key: string) => { if (auth?.login) { - await updateChoice(auth.login, null); + await updateChoice(null); if (choiceRef?.current?.value) { choiceRef.current.value = ""; } @@ -126,24 +129,20 @@ function App() { const s = value.split('|'); const pizzaIndex = Number.parseInt(s[0]); const pizzaSizeIndex = Number.parseInt(s[1]); - await addPizza(auth.login, pizzaIndex, pizzaSizeIndex); + await addPizza(pizzaIndex, pizzaSizeIndex); } } const handlePizzaDelete = async (pizzaOrder: PizzaOrder) => { - if (auth?.login) { - await removePizza(auth?.login, pizzaOrder); - } + await removePizza(pizzaOrder); } const handlePoznamkaChange = async () => { - if (auth?.login) { - if (poznamkaRef.current?.value && poznamkaRef.current.value.length > 100) { - alert("Poznámka může mít maximálně 100 znaků"); - return; - } - updateNote(auth.login, poznamkaRef.current?.value); + if (poznamkaRef.current?.value && poznamkaRef.current.value.length > 100) { + alert("Poznámka může mít maximálně 100 znaků"); + return; } + updateNote(poznamkaRef.current?.value); } // const addToCart = async () => { @@ -205,10 +204,7 @@ function App() { Poslední změny:
    -
  • Nová žárovka zatím funguje
  • -
  • Funkční generování a zobrazení QR kódů pro Pizza day
  • -
  • Možnost zadat k Pizza day objednávce poznámku
  • -
  • Zbavení se Food API, přepsání a zahrnutí parseru do serveru
  • +
  • Zavedení JWT, přesun autentizace na server

Dnes je {data.date}

@@ -260,7 +256,7 @@ function App() {

Pro dnešní den není aktuálně založen Pizza day.

} @@ -279,10 +275,10 @@ function App() { data.pizzaDay.creator === auth.login && <> } @@ -295,13 +291,13 @@ function App() { {data.pizzaDay.creator === auth.login && <> {/* */} } @@ -314,10 +310,10 @@ function App() { {data.pizzaDay.creator === auth.login &&
} @@ -357,7 +353,7 @@ function App() {

QR platba

Částka: {myOrder.totalPrice} Kč
- QR kód + QR kód

Generování QR kódů je v experimentální fázi - doporučujeme si překontrolovat údaje před odesláním platby.

} diff --git a/client/src/Login.tsx b/client/src/Login.tsx index c7628e5..c5228ae 100644 --- a/client/src/Login.tsx +++ b/client/src/Login.tsx @@ -1,8 +1,8 @@ import React, { useCallback, useRef } from 'react'; import { Button } from 'react-bootstrap'; import { useAuth } from './context/auth'; -import './Login.css'; import { login } from './Api'; +import './Login.css'; /** * Formulář pro prvotní zadání přihlašovacího jména. @@ -17,7 +17,6 @@ export default function Login() { // TODO odchytávat cokoliv mimo 200 const token = await login(loginRef.current.value); if (token) { - console.log("Přijali jsme token", token); // TODO smazat auth?.setToken(token); } } diff --git a/client/src/Utils.tsx b/client/src/Utils.tsx index a019057..bfece64 100644 --- a/client/src/Utils.tsx +++ b/client/src/Utils.tsx @@ -10,29 +10,29 @@ export const getBaseUrl = (): string => { return 'http://127.0.0.1:3001'; } -const LOGIN_KEY = "login"; +const TOKEN_KEY = "token"; /** - * Uloží login do local storage prohlížeče. + * Uloží token do local storage prohlížeče. * - * @param login login + * @param token token */ -export const storeLogin = (login: string) => { - localStorage.setItem(LOGIN_KEY, login); +export const storeToken = (token: string) => { + localStorage.setItem(TOKEN_KEY, token); } /** - * Vrátí login z local storage, pokud tam je. + * Vrátí token z local storage, pokud tam je. * - * @returns login nebo null + * @returns token nebo null */ -export const getLogin = (): string | null => { - return localStorage.getItem(LOGIN_KEY); +export const getToken = (): string | null => { + return localStorage.getItem(TOKEN_KEY); } /** - * Odstraní login z local storage, pokud tam je. + * Odstraní token z local storage, pokud tam je. */ -export const deleteLogin = () => { - localStorage.removeItem(LOGIN_KEY); +export const deleteToken = () => { + localStorage.removeItem(TOKEN_KEY); } \ No newline at end of file diff --git a/client/src/components/Header.tsx b/client/src/components/Header.tsx index caa361c..01f24aa 100644 --- a/client/src/components/Header.tsx +++ b/client/src/components/Header.tsx @@ -83,7 +83,7 @@ export default function Header() { diff --git a/client/src/context/auth.tsx b/client/src/context/auth.tsx index bf809f7..7eb654c 100644 --- a/client/src/context/auth.tsx +++ b/client/src/context/auth.tsx @@ -1,8 +1,7 @@ import React, { ReactNode, useContext, useState } from "react" import { useEffect } from "react" import { useJwt } from "react-jwt"; - -const TOKEN_KEY = 'token'; +import { deleteToken, getToken, storeToken } from "../Utils"; export type AuthContextProps = { login?: string, @@ -26,50 +25,34 @@ export const useAuth = () => { } function useProvideAuth(): AuthContextProps { - const token = localStorage.getItem(TOKEN_KEY); const [loginName, setLoginName] = useState(); - let decodedToken, isExpired; - if (token) { - const payload = useJwt(token); - decodedToken = payload?.decodedToken; - isExpired = payload?.isExpired - } + const [token, setToken] = useState(getToken()); + const { decodedToken } = useJwt(token || ''); useEffect(() => { - if (token) { - if (decodedToken && !isExpired) { - doSetToken(token); - setLoginName((decodedToken as any).login); - } - } - }, [decodedToken, isExpired]) - - useEffect(() => { - if (token) { - localStorage.setItem(TOKEN_KEY, token); + if (token && token.length > 0) { + storeToken(token); } else { - localStorage.removeItem(TOKEN_KEY); + deleteToken(); } }, [token]); - function doSetToken(token: string) { - - if (!decodedToken || !((decodedToken as any).login)) { - throw Error("Chyba dekódování tokenu"); + useEffect(() => { + if (decodedToken) { + setLoginName((decodedToken as any).login); + } else { + setLoginName(undefined); } - if (isExpired) { - throw Error("Platnost tokenu vypršela"); - } - setLoginName((decodedToken as any).login); - } + }, [decodedToken]); function logout() { + setToken(null); setLoginName(undefined); } return { login: loginName, - setToken: doSetToken, + setToken, logout, } } diff --git a/server/.env.template b/server/.env.template index c7b516f..b6c4389 100644 --- a/server/.env.template +++ b/server/.env.template @@ -1,3 +1,6 @@ +# Secret pro podepisování JWT tokenů. Minimální délka 32 znaků. +# JWT_SECRET='CHANGE_ME' + # Zapne režim mockování obědových menu. # Vhodné pro vývoj o víkendech, svátcích a dalších dnech, pro které podniky nenabízejí obědové menu. # V tomto režimu vrací server vždy falešné datum (pracovní den) a pevně nadefinovanou, smyšlenou nabídku jídel. diff --git a/server/src/auth.ts b/server/src/auth.ts index 89509ff..85c837b 100644 --- a/server/src/auth.ts +++ b/server/src/auth.ts @@ -7,13 +7,13 @@ import jwt from 'jsonwebtoken'; * @returns JWT token */ export function generateToken(login: string): string { - if (!process.env.JWT_TOKEN) { - throw Error("Není vyplněna proměnná prostředí JWT_TOKEN"); + if (!process.env.JWT_SECRET) { + throw Error("Není vyplněna proměnná prostředí JWT_SECRET"); } - if (process.env.JWT_TOKEN.length < 32) { - throw Error("Proměnná prostředí JWT_TOKEN musí být minimálně 32 znaků"); + if (process.env.JWT_SECRET.length < 32) { + throw Error("Proměnná prostředí JWT_SECRET musí být minimálně 32 znaků"); } - return jwt.sign({ login }, process.env.JWT_TOKEN); + return jwt.sign({ login }, process.env.JWT_SECRET); } /** @@ -22,11 +22,11 @@ export function generateToken(login: string): string { * @param token JWT token */ export function verify(token: string): boolean { - if (!process.env.JWT_TOKEN) { - throw Error("Není vyplněna proměnná prostředí JWT_TOKEN"); + if (!process.env.JWT_SECRET) { + throw Error("Není vyplněna proměnná prostředí JWT_SECRET"); } try { - jwt.verify(token, process.env.JWT_TOKEN); + jwt.verify(token, process.env.JWT_SECRET); return true; } catch (err) { return false; @@ -38,10 +38,13 @@ export function verify(token: string): boolean { * * @param token JWT token */ -export function getLogin(token: string): string { - if (!process.env.JWT_TOKEN) { - throw Error("Není vyplněna proměnná prostředí JWT_TOKEN"); +export function getLogin(token?: string): string { + if (!process.env.JWT_SECRET) { + throw Error("Není vyplněna proměnná prostředí JWT_SECRET"); } - const payload: any = jwt.verify(token, process.env.JWT_TOKEN); + if (!token) { + throw Error("Nebyl předán token"); + } + const payload: any = jwt.verify(token, process.env.JWT_SECRET); return payload.login; } \ No newline at end of file diff --git a/server/src/index.ts b/server/src/index.ts index 67a3e00..99cf5c9 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -9,7 +9,7 @@ import path from 'path'; import { getMenuSladovnicka, getMenuTechTower, getMenuUMotliku } from "./restaurants"; import { getQr } from "./qr"; import { Restaurants } from "./types"; -import { generateToken, verify } from "./auth"; +import { generateToken, getLogin, verify } from "./auth"; const ENVIRONMENT = process.env.NODE_ENV || 'production' dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) }); @@ -30,6 +30,14 @@ app.use(cors({ origin: '*' })); +const parseToken = (req: any) => { + if (req?.headers?.authorization) { + return req.headers.authorization.split(' ')[1]; + } +} + +// ----------- Metody nevyžadující token -------------- + app.post("/api/login", (req, res) => { if (!req.body?.login) { throw Error("Nebyl předán login"); @@ -39,14 +47,18 @@ app.post("/api/login", (req, res) => { res.status(200).json(token); }); -app.post("/api/verify", (req, res) => { - if (!req.body?.token) { - res.status(401).send(); - } else if (verify(req.body.token)) { - res.status(200).send(); - } else { - res.status(403).send(); +// ---------------------------------------------------- + +/** Middleware ověřující JWT token */ +app.use((req, res, next) => { + if (!req.headers.authorization) { + return res.status(401).json({ error: 'Nebyl předán autentizační token' }); } + const token = req.headers.authorization.split(' ')[1]; + if (!verify(token)) { + return res.status(403).json({ error: 'Neplatný autentizační token' }); + } + next(); }); /** Vrátí data pro aktuální den. */ @@ -76,27 +88,21 @@ app.get("/api/pizza", (req, res) => { /** Založí pizza day pro aktuální den, za předpokladu že dosud neexistuje. */ app.post("/api/createPizzaDay", (req, res) => { - if (!req.body?.creator) { - throw Error("Nebyl předán název zakládajícího"); - } - const data = createPizzaDay(req.body.creator); + const login = getLogin(parseToken(req)); + const data = createPizzaDay(login); res.status(200).json(data); io.emit("message", data); }); /** Smaže pizza day pro aktuální den, za předpokladu že existuje. */ app.post("/api/deletePizzaDay", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login uživatele"); - } - const data = deletePizzaDay(req.body.login); + const login = getLogin(parseToken(req)); + const data = deletePizzaDay(login); io.emit("message", data); }); app.post("/api/addPizza", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } + const login = getLogin(parseToken(req)); if (isNaN(req.body?.pizzaIndex)) { throw Error("Nebyl předán index pizzy"); } @@ -112,74 +118,60 @@ app.post("/api/addPizza", (req, res) => { if (!pizzy[pizzaIndex].sizes[pizzaSizeIndex]) { throw Error("Neplatný index velikosti pizzy: " + pizzaSizeIndex); } - const data = addPizzaOrder(req.body.login, pizzy[pizzaIndex], pizzy[pizzaIndex].sizes[pizzaSizeIndex]); + const data = addPizzaOrder(login, pizzy[pizzaIndex], pizzy[pizzaIndex].sizes[pizzaSizeIndex]); io.emit("message", data); res.status(200).json({}); }) }); app.post("/api/removePizza", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } + const login = getLogin(parseToken(req)); if (!req.body?.pizzaOrder) { throw Error("Nebyla předána objednávka"); } - const data = removePizzaOrder(req.body.login, req.body?.pizzaOrder); + const data = removePizzaOrder(login, req.body?.pizzaOrder); io.emit("message", data); res.status(200).json({}); }); app.post("/api/lockPizzaDay", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } - const data = lockPizzaDay(req.body.login); + const login = getLogin(parseToken(req)); + const data = lockPizzaDay(login); io.emit("message", data); res.status(200).json({}); }); app.post("/api/unlockPizzaDay", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } - const data = unlockPizzaDay(req.body.login); + const login = getLogin(parseToken(req)); + const data = unlockPizzaDay(login); io.emit("message", data); res.status(200).json({}); }); app.post("/api/finishOrder", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } - const data = finishPizzaOrder(req.body.login); + const login = getLogin(parseToken(req)); + const data = finishPizzaOrder(login); io.emit("message", data); res.status(200).json({}); }); app.post("/api/finishDelivery", (req, res) => { - if (!req.body?.login) { - throw Error("Nebyl předán login"); - } - const data = finishPizzaDelivery(req.body.login, req.body.bankAccount, req.body.bankAccountHolder); + const login = getLogin(parseToken(req)); + const data = finishPizzaDelivery(login, req.body.bankAccount, req.body.bankAccountHolder); io.emit("message", data); res.status(200).json({}); }); app.post("/api/updateChoice", (req, res) => { - if (!req.body.hasOwnProperty('name')) { - res.status(400).json({}); - } - const data = updateChoice(req.body.name, req.body.choice); + const login = getLogin(parseToken(req)); + const data = updateChoice(login, req.body.choice); io.emit("message", data); res.status(200).json(data); }); app.get("/api/qr", (req, res) => { - if (!req.query?.login || typeof req.query.login !== 'string') { - throw Error("Nebyl předán login"); - } - const img = getQr(req.query.login); + const login = getLogin(parseToken(req)); + const img = getQr(login); res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': img.length @@ -188,13 +180,11 @@ app.get("/api/qr", (req, res) => { }); app.post("/api/updateNote", (req, res) => { - if (!req.body.login) { - throw Error("Nebyl předán login"); - } + const login = getLogin(parseToken(req)); if (req.body.note && req.body.note.length > 100) { throw Error("Poznámka může mít maximálně 100 znaků"); } - const data = updateNote(req.body.login, req.body.note); + const data = updateNote(login, req.body.note); io.emit("message", data); res.status(200).json(data); }); diff --git a/server/src/service.ts b/server/src/service.ts index 6711358..683124a 100644 --- a/server/src/service.ts +++ b/server/src/service.ts @@ -218,6 +218,7 @@ export function finishPizzaDelivery(login: string, bankAccount?: string, bankAcc clientData.pizzaDay.state = PizzaDayState.DELIVERED; // Vygenerujeme QR kód, pokud k tomu máme data + // TODO berka je potřeba počkat na resolve promises z generateQr a až poté volat save do DB if (bankAccount?.length && bankAccountHolder?.length) { for (const order of clientData.pizzaDay.orders) { if (order.customer !== login) { // zatím platí creator = objednávající, a pro toho nemá QR kód smysl