я надеюсь это все и ничего не сломается
This commit is contained in:
parent
d1011d0537
commit
4e3dfdab49
@ -19,11 +19,16 @@ jar {
|
|||||||
dependencies {
|
dependencies {
|
||||||
implementation(project(':front'))
|
implementation(project(':front'))
|
||||||
|
|
||||||
|
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
|
||||||
|
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||||
implementation 'com.h2database:h2:2.1.210'
|
implementation 'com.h2database:h2:2.1.210'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
|
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
|
implementation 'com.auth0:java-jwt:4.4.0'
|
||||||
|
|
||||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||||
implementation 'org.hibernate.validator:hibernate-validator'
|
implementation 'org.hibernate.validator:hibernate-validator'
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom'
|
import {BrowserRouter, Route, Routes} from 'react-router-dom'
|
||||||
import Films from './pages/Films'
|
import Films from './pages/Films'
|
||||||
import FilmPage from './pages/FilmPage'
|
import FilmPage from './pages/FilmPage'
|
||||||
import Header from './pages/components/Header'
|
import Header from './pages/components/Header'
|
||||||
@ -7,39 +7,40 @@ import SearchSame from './pages/SearchSame'
|
|||||||
import Registration from './pages/Registration'
|
import Registration from './pages/Registration'
|
||||||
import Sessions from './pages/Sessions'
|
import Sessions from './pages/Sessions'
|
||||||
import Orders from './pages/Orders'
|
import Orders from './pages/Orders'
|
||||||
|
import Users from "./pages/Users";
|
||||||
function Router(props) {
|
import PrivateRoutes from "./pages/components/PrivateRoutes";
|
||||||
return useRoutes(props.rootRoute);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const routes = [
|
const links = [
|
||||||
{ index: true, element: <Films /> },
|
{path: 'films', label: 'Главная', userAccess: 'NONE'},
|
||||||
{ path: '/films', element: <Films />, label: 'Главная' },
|
{path: 'registration', label: 'Регистрация', userAccess: 'NONE'},
|
||||||
{ path: '/registration', element: <Registration />, label: 'Регистрация' },
|
{path: 'entry', label: 'Вход', userAccess: 'NONE'},
|
||||||
{ path: '/sessions', element: <Sessions />, label: 'Сеансы' },
|
{path: 'users', label: 'Пользователи', userAccess: 'ADMIN'},
|
||||||
{ path: '/orders', element: <Orders />, label: 'Заказы' },
|
{path: 'sessions', label: 'Сеансы', userAccess: 'NONE'},
|
||||||
{ path: '/films/:id', element: <FilmPage /> },
|
{path: 'orders', label: 'Заказы', userAccess: 'USER'}
|
||||||
{ path: '/search-same/:request', element: <SearchSame /> }
|
|
||||||
];
|
|
||||||
const links = routes.filter(route => route.hasOwnProperty('label'));
|
|
||||||
const rootRoute = [
|
|
||||||
{ path: '/', element: render(links), children: routes }
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function render(links) {
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<BrowserRouter>
|
||||||
<Header links={links}/>
|
<Header links={links}/>
|
||||||
<Outlet />
|
<Routes>
|
||||||
|
<Route element={<Films/>} path='/'/>
|
||||||
|
<Route element={<Films/>} path='/films'/>
|
||||||
|
<Route element={<FilmPage/>} path='/films:id'/>
|
||||||
|
<Route element={<SearchSame/>} path='/search-same/:request'/>
|
||||||
|
<Route element={<Registration/>} path="/registration"/>
|
||||||
|
<Route element={<Registration/>} path="/entry"/>
|
||||||
|
<Route element={<Sessions/>} path="/sessions"/>
|
||||||
|
<Route element={<PrivateRoutes userAccess='USER'/>}>
|
||||||
|
<Route element={<Orders/>} path="/orders"/>
|
||||||
|
</Route>
|
||||||
|
<Route element={<PrivateRoutes userAccess="ADMIN"/>}>
|
||||||
|
<Route element={<Users/>} path="/users"/>
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
<Footer/>
|
<Footer/>
|
||||||
|
</BrowserRouter>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
|
||||||
<BrowserRouter>
|
|
||||||
<Router rootRoute={ rootRoute } />
|
|
||||||
</BrowserRouter>
|
|
||||||
);
|
|
||||||
}
|
|
@ -20,26 +20,51 @@ export default function Films() {
|
|||||||
const [filmNameEdit, setFilmNameEdit] = useState('');
|
const [filmNameEdit, setFilmNameEdit] = useState('');
|
||||||
// хук для запоминания индекса элемента, вызвавшего модальное окно
|
// хук для запоминания индекса элемента, вызвавшего модальное окно
|
||||||
const [currEditItem, setCurrEditItem] = useState(0);
|
const [currEditItem, setCurrEditItem] = useState(0);
|
||||||
|
const getTokenForHeader = function () {
|
||||||
// фильмы, страны, жанры
|
return "Bearer " + localStorage.getItem("token");
|
||||||
|
}
|
||||||
|
async function getAll(elem) {
|
||||||
|
const requestParams = {
|
||||||
|
method: "GET"
|
||||||
|
};
|
||||||
|
const requestUrl = `http://localhost:8080/${elem}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
// фильмы
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
Service.readAll('cinema')
|
getAll('cinema')
|
||||||
.then(data => setItems(data));
|
.then(data => setItems(data));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
function handleDeleteFilm(id) {
|
async function handleDeleteFilm(id) {
|
||||||
console.info('Try to remove item');
|
console.info('Try to remove item');
|
||||||
Service.delete(`cinema/${id}`)
|
const requestParams = {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const response = await fetch(`http://localhost:8080/cinema/${id}`, requestParams)
|
||||||
|
await response.json()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setItems(items.filter(elem => elem.id !== id))
|
setItems(items.filter(elem => elem.id !== id))
|
||||||
console.log("Removed")
|
console.log("Removed")
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
function handleEditFilm(id) {
|
async function handleEditFilm(id) {
|
||||||
console.info(`Start edit script`);
|
console.info(`Start edit script`);
|
||||||
|
const requestParams = {
|
||||||
Service.read(`cinema/${id}`)
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const requestUrl = `http://localhost:8080/cinema/${id}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
return await response.json()
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
setFilmNameEdit(data.name);
|
setFilmNameEdit(data.name);
|
||||||
setCurrEditItem(data.id);
|
setCurrEditItem(data.id);
|
||||||
@ -49,12 +74,20 @@ export default function Films() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// принимаем событие от кнопки "добавить"
|
// принимаем событие от кнопки "добавить"
|
||||||
const handleSubmitCreate = (e) => {
|
const handleSubmitCreate = async (e) => {
|
||||||
e.preventDefault(); // страница перестает перезагружаться
|
e.preventDefault(); // страница перестает перезагружаться
|
||||||
const itemObject = new CinemaDto(selectedImage, filmName);
|
const itemObject = new CinemaDto(selectedImage, filmName);
|
||||||
console.info('Try to add item');
|
console.info('Try to add item');
|
||||||
|
const requestParams = {
|
||||||
Service.create('cinema', itemObject)
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify(itemObject)
|
||||||
|
};
|
||||||
|
await fetch(`http://localhost:8080/cinema`, requestParams)
|
||||||
|
.then((response) => response.json())
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
setItems([...items, data]);
|
setItems([...items, data]);
|
||||||
|
|
||||||
@ -66,14 +99,23 @@ export default function Films() {
|
|||||||
throw "Can't add item";
|
throw "Can't add item";
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// принимаем событие от кнопки "сохранить изменения"
|
// принимаем событие от кнопки "сохранить изменения"
|
||||||
const handleSubmitEdit = (e, id) => {
|
const handleSubmitEdit = async (e, id) => {
|
||||||
console.info('Start synchronize edit');
|
console.info('Start synchronize edit');
|
||||||
e.preventDefault(); // страница перестает перезагружаться
|
e.preventDefault(); // страница перестает перезагружаться
|
||||||
const itemObject = new CinemaDto(selectedImage, filmNameEdit, id);
|
const itemObject = new CinemaDto(selectedImage, filmNameEdit, id);
|
||||||
|
|
||||||
Service.update("cinema/" + id, itemObject)
|
const requestParams = {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify(itemObject)
|
||||||
|
};
|
||||||
|
const requestUrl = `http://localhost:8080/cinema/${id}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
await response.json()
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
setItems(
|
setItems(
|
||||||
items.map(item =>
|
items.map(item =>
|
||||||
@ -95,20 +137,18 @@ export default function Films() {
|
|||||||
fileReader.onloadend = () => (
|
fileReader.onloadend = () => (
|
||||||
setSelectedImage(fileReader.result)
|
setSelectedImage(fileReader.result)
|
||||||
)
|
)
|
||||||
|
|
||||||
function changePicture(e) {
|
function changePicture(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const file = e.target.files[0]
|
const file = e.target.files[0]
|
||||||
fileReader.readAsDataURL(file)
|
fileReader.readAsDataURL(file)
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleAddFilmToWillSee(data) {
|
const Content = (
|
||||||
const elem = CinemaDto.createFrom(data)
|
<div>
|
||||||
Service.create('willSee/', data)
|
{(localStorage.getItem("role") === 'ADMIN') &&
|
||||||
}
|
<form className="row g-3 fs-4 description fw-bold needs-validation-content" id="frm-items"
|
||||||
|
onSubmit={handleSubmitCreate}>
|
||||||
// форма для добавления данных
|
|
||||||
const Form = (
|
|
||||||
<form className="row g-3 fs-4 description fw-bold needs-validation-content" id="frm-items" onSubmit={handleSubmitCreate}>
|
|
||||||
<div className="col-md-3">
|
<div className="col-md-3">
|
||||||
<label className="form-label" htmlFor="filmPicture">Изображение</label>
|
<label className="form-label" htmlFor="filmPicture">Изображение</label>
|
||||||
<input required className="form-control" name="filmPicture" id="filmPicture"
|
<input required className="form-control" name="filmPicture" id="filmPicture"
|
||||||
@ -117,7 +157,9 @@ export default function Films() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="col">
|
<div className="col">
|
||||||
<label className="form-label" htmlFor="filmName">Название</label>
|
<label className="form-label" htmlFor="filmName">Название</label>
|
||||||
<input required className="form-control" name="filmName" id="filmName" type="text" value={filmName} onChange={e => setFilmName(e.target.value)} placeholder="Введите название" />
|
<input required className="form-control" name="filmName" id="filmName" type="text"
|
||||||
|
value={filmName} onChange={e => setFilmName(e.target.value)}
|
||||||
|
placeholder="Введите название"/>
|
||||||
</div>
|
</div>
|
||||||
<div className="form-check mx-2">
|
<div className="form-check mx-2">
|
||||||
<input required className="form-check-input" name="film16" id="film16" type="checkbox"/>
|
<input required className="form-check-input" name="film16" id="film16" type="checkbox"/>
|
||||||
@ -125,14 +167,11 @@ export default function Films() {
|
|||||||
<div className="invalid-feedback">Подтвердите, что вам уже есть 16 лет</div>
|
<div className="invalid-feedback">Подтвердите, что вам уже есть 16 лет</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-start">
|
<div className="text-start">
|
||||||
<button className="willSee p-1 border border-0 rounded text-white fw-bold fs-4" id="btn-add-item" type="submit">Добавить</button>
|
<button className="willSee p-1 border border-0 rounded text-white fw-bold fs-4"
|
||||||
|
id="btn-add-item" type="submit">Добавить
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>}
|
||||||
)
|
|
||||||
|
|
||||||
const Content = (
|
|
||||||
<div>
|
|
||||||
{Form}
|
|
||||||
<hr className="border border-0 bg-black"/>
|
<hr className="border border-0 bg-black"/>
|
||||||
<table className="table" id="tbl-items">
|
<table className="table" id="tbl-items">
|
||||||
<tbody>
|
<tbody>
|
||||||
@ -140,15 +179,16 @@ export default function Films() {
|
|||||||
<FilmItem
|
<FilmItem
|
||||||
item={item}
|
item={item}
|
||||||
key={item.id}
|
key={item.id}
|
||||||
removeFunc={handleDeleteFilm}
|
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDeleteFilm : null}
|
||||||
editFunc={handleEditFilm}
|
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEditFilm : null}
|
||||||
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
|
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
{(localStorage.getItem("role") === 'ADMIN') && <ModalEdit visible={modalTable} setVisible={setModalTable}>
|
||||||
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
|
||||||
|
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<label className="form-label" htmlFor="filmPictureEdit">Изображение</label>
|
<label className="form-label" htmlFor="filmPictureEdit">Изображение</label>
|
||||||
<input required className="form-control" name="filmPictureEdit" id="filmPictureEdit"
|
<input required className="form-control" name="filmPictureEdit" id="filmPictureEdit"
|
||||||
@ -157,14 +197,21 @@ export default function Films() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<label className="form-label" htmlFor="filmNameEdit">Название</label>
|
<label className="form-label" htmlFor="filmNameEdit">Название</label>
|
||||||
<input value={filmNameEdit} onChange={e => setFilmNameEdit(e.target.value)} className="form-control" name='filmNameEdit' id="filmNameEdit" type="text" placeholder="Введите название" required />
|
<input value={filmNameEdit} onChange={e => setFilmNameEdit(e.target.value)}
|
||||||
|
className="form-control" name='filmNameEdit' id="filmNameEdit" type="text"
|
||||||
|
placeholder="Введите название" required/>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-3">
|
<div className="text-center mt-3">
|
||||||
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
|
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
|
||||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
изменения
|
||||||
|
</button>
|
||||||
|
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
|
||||||
|
onClick={() => setModalTable(false)}>Отмена
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</ModalEdit>
|
</ModalEdit>}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { React, useState, useEffect } from 'react'
|
import {useEffect, useState} from 'react'
|
||||||
import ContentBlock from './components/ContentBlock'
|
import ContentBlock from './components/ContentBlock'
|
||||||
import Service from './services/Service';
|
import Service from './services/Service';
|
||||||
import ModalEdit from './components/ModalEdit';
|
import ModalEdit from './components/ModalEdit';
|
||||||
@ -12,33 +12,37 @@ export default function Orders() {
|
|||||||
const [currEditItem, setCurrEditItem] = useState(0);
|
const [currEditItem, setCurrEditItem] = useState(0);
|
||||||
// для выпадающих значений
|
// для выпадающих значений
|
||||||
const [customerName, setCustomerName] = useState('');
|
const [customerName, setCustomerName] = useState('');
|
||||||
const [customer, setCustomer] = useState([]);
|
|
||||||
const [sessionName, setSessionName] = useState('');
|
const [sessionName, setSessionName] = useState('');
|
||||||
const [count, setCount] = useState(1);
|
const [count, setCount] = useState(1);
|
||||||
const [session, setSession] = useState([]);
|
const [session, setSession] = useState([]);
|
||||||
const [orderSessions, setOrderSessions] = useState([]);
|
const [orderSessions, setOrderSessions] = useState([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getAll('customer').then((data) => setCustomer(data))
|
const user = localStorage.getItem('user')
|
||||||
|
setCustomerName(user)
|
||||||
getAll('session').then((data) => setSession(data))
|
getAll('session').then((data) => setSession(data))
|
||||||
getAll('order').then((data) => setUsers(data))
|
getAll(`customer?login=${user}`).then((data) => setUsers(data.orders))
|
||||||
}, [])
|
}, [])
|
||||||
|
const getTokenForHeader = function () {
|
||||||
|
return "Bearer " + localStorage.getItem("token");
|
||||||
|
}
|
||||||
|
|
||||||
async function getAll(elem) {
|
async function getAll(elem) {
|
||||||
|
const requestParams = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}
|
||||||
|
};
|
||||||
const requestUrl = `http://localhost:8080/${elem}`
|
const requestUrl = `http://localhost:8080/${elem}`
|
||||||
const response = await fetch(requestUrl)
|
const response = await fetch(requestUrl, requestParams)
|
||||||
const result = await response.json()
|
return await response.json()
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSubmit(e) {
|
function handleSubmit(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (customer.length <= 0) {
|
|
||||||
throw 'Form not submit'
|
|
||||||
}
|
|
||||||
handleSubmitCreate(e)
|
handleSubmitCreate(e)
|
||||||
console.log('Form submit')
|
console.log('Form submit')
|
||||||
setCustomer('')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// принимаем событие от кнопки "добавить"
|
// принимаем событие от кнопки "добавить"
|
||||||
@ -49,13 +53,13 @@ export default function Orders() {
|
|||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
await fetch(`http://localhost:8080/order?customer=${customerName}`, requestParams)
|
await fetch(`http://localhost:8080/order/${customerName}`, requestParams)
|
||||||
.then((data) => {
|
.then(() => {
|
||||||
getCustomerOrders(customerName)
|
getAll(`customer?login=${customerName}`).then((data) => setUsers(data.orders))
|
||||||
getAll('customer').then((data) => setCustomer(data))
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
console.error('Error:', error);
|
console.error('Error:', error);
|
||||||
@ -65,15 +69,14 @@ export default function Orders() {
|
|||||||
|
|
||||||
function handleEdit(id) {
|
function handleEdit(id) {
|
||||||
console.info(`Start edit script`);
|
console.info(`Start edit script`);
|
||||||
|
getAll(`order/${id}`)
|
||||||
Service.read(`order/${id}`)
|
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
setCurrEditItem(data.id);
|
setCurrEditItem(data.id);
|
||||||
setOrderSessions(data.sessions)
|
setOrderSessions(data.sessions)
|
||||||
setModalTable(true)
|
setModalTable(true)
|
||||||
console.info('End edit script');
|
console.info('End edit script');
|
||||||
})
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
const handleSubmitAdd = async (e, id) => {
|
const handleSubmitAdd = async (e, id) => {
|
||||||
console.info('Start add session');
|
console.info('Start add session');
|
||||||
@ -81,6 +84,7 @@ export default function Orders() {
|
|||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -103,6 +107,7 @@ export default function Orders() {
|
|||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -118,22 +123,21 @@ export default function Orders() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleDelete(id) {
|
async function handleDelete(id) {
|
||||||
console.info('Try to remove item');
|
console.info('Try to remove item');
|
||||||
Service.delete(`order/${id}`)
|
const requestParams = {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const response = await fetch(`http://localhost:8080/order/${id}`, requestParams)
|
||||||
|
await response.json()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setUsers(users.filter(elem => elem.id !== id))
|
setUsers(users.filter(elem => elem.id !== id))
|
||||||
console.log("Removed")
|
console.log("Removed")
|
||||||
});
|
});
|
||||||
};
|
|
||||||
|
|
||||||
async function getCustomerOrders(id) {
|
|
||||||
Service.read(`customer/${id}`)
|
|
||||||
.then(function (data) {
|
|
||||||
setUsers(data.orders);
|
|
||||||
console.info('End');
|
|
||||||
})
|
|
||||||
.catch(e => { console.log('Error get orders') })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleDeleteOrderSession(e, id, sessionId) {
|
async function handleDeleteOrderSession(e, id, sessionId) {
|
||||||
@ -141,6 +145,7 @@ export default function Orders() {
|
|||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -158,15 +163,6 @@ export default function Orders() {
|
|||||||
|
|
||||||
const Content = (
|
const Content = (
|
||||||
<>
|
<>
|
||||||
<select required className="form-select" name="customer" id="customer" value={customer.value} onChange={e => {
|
|
||||||
setCustomerName(e.target.value)
|
|
||||||
getCustomerOrders(e.target.value)
|
|
||||||
}} >
|
|
||||||
<option value='' defaultValue disabled>Выберите значение</option>
|
|
||||||
{customer ? customer.map(elem =>
|
|
||||||
<option key={elem.id} value={elem.id}>{elem.login}</option>
|
|
||||||
) : null}
|
|
||||||
</select>
|
|
||||||
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
||||||
<div>
|
<div>
|
||||||
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Добавить</button>
|
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Добавить</button>
|
||||||
@ -196,21 +192,30 @@ export default function Orders() {
|
|||||||
<form className="fs-4 description fw-bold d-flex flex-column align-items-center" id="frm-items-edit">
|
<form className="fs-4 description fw-bold d-flex flex-column align-items-center" id="frm-items-edit">
|
||||||
<div className="col-6">
|
<div className="col-6">
|
||||||
<label className="form-label" htmlFor="session">Сеанс</label>
|
<label className="form-label" htmlFor="session">Сеанс</label>
|
||||||
<select required className="form-control" name="session" id="session" value={session.value} onChange={e => setSessionName(e.target.value)} >
|
<select required className="form-control" name="session" id="session" value={session.value}
|
||||||
|
onChange={e => setSessionName(e.target.value)}>
|
||||||
<option value='' defaultValue disabled>Выберите значение</option>
|
<option value='' defaultValue disabled>Выберите значение</option>
|
||||||
{session ? session.map(elem =>
|
{session && session.map(elem =>
|
||||||
<option key={elem.id} value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
|
<option key={elem.id}
|
||||||
) : null}
|
value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
|
||||||
|
)}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-6">
|
<div className="col-6">
|
||||||
<label className="form-label" htmlFor="count">Количество</label>
|
<label className="form-label" htmlFor="count">Количество</label>
|
||||||
<input required className="form-control" name="count" id="count" type="number" min="1" value={count} onChange={e => setCount(e.target.value)} placeholder="Введите количество" />
|
<input required className="form-control" name="count" id="count" type="number" min="1"
|
||||||
|
value={count} onChange={e => setCount(e.target.value)} placeholder="Введите количество"/>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-3">
|
<div className="text-center mt-3">
|
||||||
<button className="btn btn-success mx-1" type="button" onClick={e => handleSubmitAdd(e, currEditItem)}>Добавить</button>
|
<button className="btn btn-success mx-1" type="button"
|
||||||
<button className="btn btn-danger mx-1" type="button" onClick={e => handleSubmitDelete(e, currEditItem)}>Удалить</button>
|
onClick={e => handleSubmitAdd(e, currEditItem)}>Добавить
|
||||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
</button>
|
||||||
|
<button className="btn btn-danger mx-1" type="button"
|
||||||
|
onClick={e => handleSubmitDelete(e, currEditItem)}>Удалить
|
||||||
|
</button>
|
||||||
|
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
|
||||||
|
onClick={() => setModalTable(false)}>Отмена
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<p>Мои сеансы</p>
|
<p>Мои сеансы</p>
|
||||||
<table className="table fs-6 table-bordered" id="tbl-items">
|
<table className="table fs-6 table-bordered" id="tbl-items">
|
||||||
@ -224,13 +229,13 @@ export default function Orders() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{orderSessions ? orderSessions.map((item) =>
|
{orderSessions && orderSessions.map((item) =>
|
||||||
<OrderSessionItem
|
<OrderSessionItem
|
||||||
item={item}
|
item={item}
|
||||||
key={parseInt(item.sessionId + '' + item.orderId)}
|
key={parseInt(item.sessionId + '' + item.orderId)}
|
||||||
removeFunc={e => handleDeleteOrderSession(e, currEditItem, item.sessionId)}
|
removeFunc={e => handleDeleteOrderSession(e, currEditItem, item.session.id)}
|
||||||
/>
|
/>
|
||||||
) : null}
|
)}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</form>
|
</form>
|
||||||
|
@ -1,36 +1,23 @@
|
|||||||
import { React, useState, useEffect } from 'react'
|
import {useState, useEffect} from 'react'
|
||||||
import ContentBlock from './components/ContentBlock'
|
import ContentBlock from './components/ContentBlock'
|
||||||
import Service from './services/Service';
|
import {useNavigate} from "react-router-dom";
|
||||||
import ModalEdit from './components/ModalEdit';
|
|
||||||
import MyButton from './components/MyButton';
|
|
||||||
import UserItem from './components/UserItem';
|
|
||||||
|
|
||||||
export default function Registration() {
|
export default function Registration() {
|
||||||
|
const hostURL = "http://localhost:8080";
|
||||||
|
const navigate = useNavigate();
|
||||||
const [login, setLogin] = useState('');
|
const [login, setLogin] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [loginEdit, setLoginEdit] = useState('');
|
const [passwordConfirm, setPasswordConfirm] = useState('');
|
||||||
const [passwordEdit, setPasswordEdit] = useState('');
|
|
||||||
const [users, setUsers] = useState([]);
|
|
||||||
const [error, setError] = useState(false);
|
const [error, setError] = useState(false);
|
||||||
const [modalTable, setModalTable] = useState(false);
|
|
||||||
// хук для запоминания индекса элемента, вызвавшего модальное окно
|
|
||||||
const [currEditItem, setCurrEditItem] = useState(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setError(false)
|
setError(false)
|
||||||
getAll()
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
async function getAll() {
|
|
||||||
const requestUrl = "http://localhost:8080/customer"
|
|
||||||
const response = await fetch(requestUrl)
|
|
||||||
const temp = await response.json()
|
|
||||||
setUsers(temp)
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleSubmit(e) {
|
function handleSubmit(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (login.length <= 0 || password.length <= 0) {
|
if (login.length <= 0 || password.length <= 0 ||
|
||||||
|
window.location.pathname === '/registration' && passwordConfirm.length <= 0) {
|
||||||
setError(true)
|
setError(true)
|
||||||
throw 'Form not submit'
|
throw 'Form not submit'
|
||||||
}
|
}
|
||||||
@ -39,131 +26,93 @@ export default function Registration() {
|
|||||||
setError(false)
|
setError(false)
|
||||||
setLogin('')
|
setLogin('')
|
||||||
setPassword('')
|
setPassword('')
|
||||||
|
setPasswordConfirm('')
|
||||||
}
|
}
|
||||||
|
|
||||||
// принимаем событие от кнопки "добавить"
|
// принимаем событие от кнопки "добавить"
|
||||||
const handleSubmitCreate = async (e) => {
|
const handleSubmitCreate = async (e) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
console.info('Try to add item');
|
console.info('Try to signup/login');
|
||||||
|
let requestURL = "/jwt/login"
|
||||||
|
let requestData = JSON.stringify({login: login, password: password})
|
||||||
|
if (window.location.pathname === '/registration') {
|
||||||
|
requestURL = "/signup"
|
||||||
|
requestData = JSON.stringify({login: login, password: password, passwordConfirm: passwordConfirm})
|
||||||
|
}
|
||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: requestData,
|
||||||
|
};
|
||||||
|
const response = await fetch(hostURL + requestURL, requestParams);
|
||||||
|
const result = await response.text();
|
||||||
|
if (response.status === 200 && window.location.pathname === '/entry') {
|
||||||
|
localStorage.setItem("token", result);
|
||||||
|
localStorage.setItem("user", login);
|
||||||
|
getRole(result);
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
}
|
}
|
||||||
};
|
alert(result);
|
||||||
await fetch(`http://localhost:8080/customer?login=${login}&password=${password}`, requestParams)
|
|
||||||
.then(() => {
|
|
||||||
getAll()
|
|
||||||
})
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleEdit(id) {
|
async function getRole(token) {
|
||||||
console.info(`Start edit script`);
|
// вызываем поиск пользователя по токену
|
||||||
|
|
||||||
Service.read(`customer/${id}`)
|
|
||||||
.then(function (data) {
|
|
||||||
setLoginEdit(data.login);
|
|
||||||
setPasswordEdit(data.password);
|
|
||||||
setCurrEditItem(data.id);
|
|
||||||
setModalTable(true)
|
|
||||||
console.info('End edit script');
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmitEdit = async (e, id) => {
|
|
||||||
console.info('Start synchronize edit');
|
|
||||||
e.preventDefault(); // страница перестает перезагружаться
|
|
||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "PUT",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const response = await fetch(hostURL + `/get-role?token=${token}`, requestParams);
|
||||||
|
const result = await response.text();
|
||||||
|
localStorage.setItem("role", result);
|
||||||
|
// вызвали событие
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
navigate('/orders')
|
||||||
|
navigate('/orders')
|
||||||
}
|
}
|
||||||
};
|
|
||||||
const requestUrl = `http://localhost:8080/customer/${id}?login=${loginEdit}&password=${passwordEdit}`
|
|
||||||
const response = await fetch(requestUrl, requestParams)
|
|
||||||
const temp = await response.json()
|
|
||||||
.then((data) => {
|
|
||||||
setUsers(
|
|
||||||
users.map(item =>
|
|
||||||
item.id === id ? {
|
|
||||||
...item,
|
|
||||||
login: data.login,
|
|
||||||
password: data.password
|
|
||||||
} : item)
|
|
||||||
)
|
|
||||||
console.info('End synchronize edit');
|
|
||||||
setModalTable(false)
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error('Error:', error);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
function handleDelete(id) {
|
|
||||||
console.info('Try to remove item');
|
|
||||||
Service.delete(`customer/${id}`)
|
|
||||||
.then(() => {
|
|
||||||
setUsers(users.filter(elem => elem.id !== id))
|
|
||||||
console.log("Removed")
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const Content = (
|
const Content = (
|
||||||
<>
|
<>
|
||||||
<form onSubmit={handleSubmit} className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
<form onSubmit={handleSubmit}
|
||||||
|
className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Логин</label>
|
<label className="form-label">Логин</label>
|
||||||
<input className="form-control mainInput" type="text" value={login} onChange={e => setLogin(e.target.value)} placeholder="Введите логин" />
|
<input className="form-control mainInput" type="text" value={login}
|
||||||
|
onChange={e => setLogin(e.target.value)} placeholder="Введите логин"/>
|
||||||
</div>
|
</div>
|
||||||
{error && login.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод логина</label> : null}
|
{error && login.length <= 2 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод логина</label> : null}
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Пароль</label>
|
<label className="form-label">Пароль</label>
|
||||||
<input className="form-control mainInput" type="text" value={password} onChange={e => setPassword(e.target.value)} placeholder="Введите пароль" />
|
<input className="form-control mainInput" type="password" value={password}
|
||||||
|
onChange={e => setPassword(e.target.value)} placeholder="Введите пароль"/>
|
||||||
</div>
|
</div>
|
||||||
{error && password.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
|
{error && password.length <= 5 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
|
||||||
|
{window.location.pathname === '/registration' ? <div>
|
||||||
|
<label className="form-label">Подтверждение</label>
|
||||||
|
<input className="form-control mainInput" type="password" value={passwordConfirm}
|
||||||
|
onChange={e => setPasswordConfirm(e.target.value)} placeholder="Введите повторно"/>
|
||||||
|
{error && password.length <= 5 || error && passwordConfirm.length <= 5 || error && passwordConfirm !== password ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод пароля</label> : null}
|
||||||
|
</div> : null}
|
||||||
<div>
|
<div>
|
||||||
<button className="btn btn-success my-3" type="submit">Регистрация</button>
|
<button className="btn btn-success my-3" type="submit">
|
||||||
|
{window.location.pathname === '/registration' ? 'Регистрация' : 'Вход'}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
<table className="table mt-3 text-white">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th scope="col">#</th>
|
|
||||||
<th scope="col">Login</th>
|
|
||||||
<th scope="col">Password</th>
|
|
||||||
<th scope="col"></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody id="tbody">
|
|
||||||
{users.map((user) => (
|
|
||||||
<UserItem
|
|
||||||
item={user}
|
|
||||||
key={user.id}
|
|
||||||
editFunc={handleEdit}
|
|
||||||
removeFunc={handleDelete} />
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
|
||||||
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
|
||||||
<div className="row">
|
|
||||||
<label className="form-label" htmlFor="loginEdit">Логин</label>
|
|
||||||
<input value={loginEdit} onChange={e => setLoginEdit(e.target.value)} className="form-control" name='loginEdit' id="loginEdit" type="text" placeholder="Введите логин" required />
|
|
||||||
</div>
|
|
||||||
<div className="row">
|
|
||||||
<label className="form-label" htmlFor="passwordEdit">Пароль</label>
|
|
||||||
<input value={passwordEdit} onChange={e => setPasswordEdit(e.target.value)} className="form-control" name='passwordEdit' id="passwordEdit" type="text" placeholder="Введите пароль" required />
|
|
||||||
</div>
|
|
||||||
<div className="text-center mt-3">
|
|
||||||
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
|
|
||||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</ModalEdit>
|
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Регистрация' />
|
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content}
|
||||||
|
title={window.location.pathname === '/registration' ? 'Регистрация' : 'Вход'}/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,9 @@ export default function Sessions() {
|
|||||||
// для выпадающих значений
|
// для выпадающих значений
|
||||||
const [cinemaName, setCinemaName] = useState('');
|
const [cinemaName, setCinemaName] = useState('');
|
||||||
const [cinema, setCinema] = useState([]);
|
const [cinema, setCinema] = useState([]);
|
||||||
|
const getTokenForHeader = function () {
|
||||||
|
return "Bearer " + localStorage.getItem("token");
|
||||||
|
}
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setError(false)
|
setError(false)
|
||||||
getAll('cinema').then((data) => setCinema(data))
|
getAll('cinema').then((data) => setCinema(data))
|
||||||
@ -26,10 +28,12 @@ export default function Sessions() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
async function getAll(elem) {
|
async function getAll(elem) {
|
||||||
|
const requestParams = {
|
||||||
|
method: "GET"
|
||||||
|
};
|
||||||
const requestUrl = `http://localhost:8080/${elem}`
|
const requestUrl = `http://localhost:8080/${elem}`
|
||||||
const response = await fetch(requestUrl)
|
const response = await fetch(requestUrl, requestParams)
|
||||||
const result = await response.json()
|
return await response.json()
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSubmit(e) {
|
function handleSubmit(e) {
|
||||||
@ -66,17 +70,24 @@ export default function Sessions() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleEdit(id) {
|
async function handleEdit(id) {
|
||||||
console.info(`Start edit script`);
|
console.info(`Start edit script`);
|
||||||
|
const requestParams = {
|
||||||
Service.read(`session/${id}`)
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const requestUrl = `http://localhost:8080/session/${id}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
return await response.json()
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
setPriceEdit(data.price);
|
setPriceEdit(data.price);
|
||||||
setCurrEditItem(data.id);
|
setCurrEditItem(data.id);
|
||||||
setModalTable(true)
|
setModalTable(true)
|
||||||
console.info('End edit script');
|
console.info('End edit script');
|
||||||
})
|
})
|
||||||
};
|
}
|
||||||
|
|
||||||
const handleSubmitEdit = async (e, id) => {
|
const handleSubmitEdit = async (e, id) => {
|
||||||
console.info('Start synchronize edit');
|
console.info('Start synchronize edit');
|
||||||
@ -84,6 +95,7 @@ export default function Sessions() {
|
|||||||
const requestParams = {
|
const requestParams = {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -106,47 +118,67 @@ export default function Sessions() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
function handleDelete(id) {
|
async function handleDelete(id) {
|
||||||
console.info('Try to remove item');
|
console.info('Try to remove item');
|
||||||
Service.delete(`session/${id}`)
|
const requestParams = {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const response = await fetch(`session/${id}`, requestParams)
|
||||||
|
await response.json()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setUsers(users.filter(elem => elem.id !== id))
|
setUsers(users.filter(elem => elem.id !== id))
|
||||||
console.log("Removed")
|
console.log("Removed")
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Error:', error);
|
||||||
});
|
});
|
||||||
};
|
}
|
||||||
|
|
||||||
const Content = (
|
const Content = (
|
||||||
<>
|
<>
|
||||||
|
{(localStorage.getItem("role") === 'ADMIN') &&
|
||||||
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Цена</label>
|
<label className="form-label">Цена</label>
|
||||||
<input className="form-control mainInput" min="1" type="number" step="0.01" value={price} onChange={e => setPrice(e.target.value)} placeholder="Введите цену" />
|
<input className="form-control mainInput" min="1" type="number" step="0.01" value={price}
|
||||||
|
onChange={e => setPrice(e.target.value)} placeholder="Введите цену"/>
|
||||||
</div>
|
</div>
|
||||||
{error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
|
{error && price.length <= 0 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Фильм</label>
|
<label className="form-label">Фильм</label>
|
||||||
<select required className="form-select" name="filmCountry" id="filmCountry" value={cinema.value} onChange={e => setCinemaName(e.target.value)} >
|
<select required className="form-select" name="filmCountry" id="filmCountry"
|
||||||
|
value={cinema.value} onChange={e => setCinemaName(e.target.value)}>
|
||||||
<option value='' defaultValue disabled>Выберите значение</option>
|
<option value='' defaultValue disabled>Выберите значение</option>
|
||||||
{cinema ? cinema.map(elem =>
|
{cinema ? cinema.map(elem =>
|
||||||
<option key={elem.id} value={elem.id}>{elem.name}</option>
|
<option key={elem.id} value={elem.id}>{elem.name}</option>
|
||||||
) : null}
|
) : null}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
{error && cinema.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод фильма</label> : null}
|
{error && cinema.length <= 0 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод фильма</label> : null}
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Кол-во сеансов</label>
|
<label className="form-label">Кол-во сеансов</label>
|
||||||
<input className="form-control mainInput" min="1" type="number" value={maxCount} onChange={e => setMaxCount(e.target.value)} placeholder="Введите количество" />
|
<input className="form-control mainInput" min="1" type="number" value={maxCount}
|
||||||
|
onChange={e => setMaxCount(e.target.value)} placeholder="Введите количество"/>
|
||||||
</div>
|
</div>
|
||||||
{error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
|
{error && price.length <= 0 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
|
||||||
<div>
|
<div>
|
||||||
<label className="form-label">Дата</label>
|
<label className="form-label">Дата</label>
|
||||||
<input className="form-control mainInput" type="datetime-local" value={timestamp} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" />
|
<input className="form-control mainInput" type="datetime-local" value={timestamp}
|
||||||
|
onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату"/>
|
||||||
</div>
|
</div>
|
||||||
{error && timestamp.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
|
{error && timestamp.length <= 0 ?
|
||||||
|
<label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
|
||||||
<div>
|
<div>
|
||||||
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
|
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>}
|
||||||
<table className="table mt-3 text-white">
|
<table className="table mt-3 text-white">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@ -164,24 +196,31 @@ export default function Sessions() {
|
|||||||
<SessionItem
|
<SessionItem
|
||||||
item={user}
|
item={user}
|
||||||
key={user.id}
|
key={user.id}
|
||||||
editFunc={handleEdit}
|
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEdit : null}
|
||||||
removeFunc={handleDelete}
|
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDelete : null}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
{(localStorage.getItem("role") === 'ADMIN') && <ModalEdit visible={modalTable} setVisible={setModalTable}>
|
||||||
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
|
||||||
|
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<label className="form-label" htmlFor="priceEdit">Цена</label>
|
<label className="form-label" htmlFor="priceEdit">Цена</label>
|
||||||
<input value={priceEdit} onChange={e => setPriceEdit(e.target.value)} className="form-control" name='priceEdit' id="priceEdit" type="number" step="0.01" min="1" placeholder="Введите цену" required />
|
<input value={priceEdit} onChange={e => setPriceEdit(e.target.value)} className="form-control"
|
||||||
|
name='priceEdit' id="priceEdit" type="number" step="0.01" min="1"
|
||||||
|
placeholder="Введите цену" required/>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center mt-3">
|
<div className="text-center mt-3">
|
||||||
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
|
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
|
||||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
изменения
|
||||||
|
</button>
|
||||||
|
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
|
||||||
|
onClick={() => setModalTable(false)}>Отмена
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</ModalEdit>
|
</ModalEdit>}
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
181
front/src/pages/Users.jsx
Normal file
181
front/src/pages/Users.jsx
Normal file
@ -0,0 +1,181 @@
|
|||||||
|
import {useState, useEffect} from 'react'
|
||||||
|
import ContentBlock from './components/ContentBlock'
|
||||||
|
import ModalEdit from './components/ModalEdit';
|
||||||
|
import UserItem from './components/UserItem';
|
||||||
|
import axios from "axios";
|
||||||
|
|
||||||
|
export default function Users() {
|
||||||
|
const [loginEdit, setLoginEdit] = useState('');
|
||||||
|
const [passwordEdit, setPasswordEdit] = useState('');
|
||||||
|
const [users, setUsers] = useState([]);
|
||||||
|
const [modalTable, setModalTable] = useState(false);
|
||||||
|
// хук для запоминания индекса элемента, вызвавшего модальное окно
|
||||||
|
const [currEditItem, setCurrEditItem] = useState(0);
|
||||||
|
|
||||||
|
const [pageNumbers, setPageNumbers] = useState([]);
|
||||||
|
const [currPage, setCurrPage] = useState(1);
|
||||||
|
const url = 'http://localhost:8080/api/1.0/customer'
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
axios
|
||||||
|
.get(`${url}?page=${currPage}`, {
|
||||||
|
headers:{
|
||||||
|
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then((response) => {
|
||||||
|
setUsers(response.data.content)
|
||||||
|
setPageNumbers(response.data.totalPages);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
});
|
||||||
|
}, [currPage, pageNumbers]);
|
||||||
|
const getTokenForHeader = function () {
|
||||||
|
return "Bearer " + localStorage.getItem("token");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEdit(id) {
|
||||||
|
console.info(`Start edit script`);
|
||||||
|
const requestParams = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const requestUrl = `customer/${id}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
return await response.json()
|
||||||
|
.then(function (data) {
|
||||||
|
setLoginEdit(data.login);
|
||||||
|
setPasswordEdit(data.password);
|
||||||
|
setCurrEditItem(data.id);
|
||||||
|
setModalTable(true)
|
||||||
|
console.info('End edit script');
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmitEdit = async (e, id) => {
|
||||||
|
console.info('Start synchronize edit');
|
||||||
|
e.preventDefault(); // страница перестает перезагружаться
|
||||||
|
const requestParams = {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({login: loginEdit, password: passwordEdit})
|
||||||
|
};
|
||||||
|
const requestUrl = `http://localhost:8080/customer/${id}`
|
||||||
|
const response = await fetch(requestUrl, requestParams)
|
||||||
|
const temp = await response.json()
|
||||||
|
.then((data) => {
|
||||||
|
setUsers(
|
||||||
|
users.map(item =>
|
||||||
|
item.id === id ? {
|
||||||
|
...item,
|
||||||
|
login: data.login,
|
||||||
|
password: data.password
|
||||||
|
} : item)
|
||||||
|
)
|
||||||
|
console.info('End synchronize edit');
|
||||||
|
setModalTable(false)
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
async function handleDelete(id) {
|
||||||
|
console.info('Try to remove item');
|
||||||
|
const requestParams = {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const response = await fetch(`customer/${id}`, requestParams)
|
||||||
|
await response.json()
|
||||||
|
.then(() => {
|
||||||
|
setUsers(users.filter(elem => elem.id !== id))
|
||||||
|
console.log("Removed")
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageOnClick = function (page) {
|
||||||
|
setCurrPage(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderPageNumbers = () => {
|
||||||
|
const pageNumbersRender = [];
|
||||||
|
for (let i = 0; i < pageNumbers; i++) {
|
||||||
|
pageNumbersRender.push(
|
||||||
|
<li key={i} className={`${i+1 === currPage ? "active" : ""}`}
|
||||||
|
onClick={() => pageOnClick(i+1)}>
|
||||||
|
<a className="text-white" href="#">{i+1}</a>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return pageNumbersRender;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Content = (
|
||||||
|
<>
|
||||||
|
<table className="table mt-3 text-white">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">#</th>
|
||||||
|
<th scope="col">Login</th>
|
||||||
|
<th scope="col">Password</th>
|
||||||
|
<th scope="col"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="tbody">
|
||||||
|
{users.map((user) => (
|
||||||
|
<UserItem
|
||||||
|
item={user}
|
||||||
|
key={user.id}
|
||||||
|
editFunc={handleEdit}
|
||||||
|
removeFunc={handleDelete}/>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<ul className="pagination text-white">
|
||||||
|
<span style={{float: "left", padding: "5px 5px"}}>Страницы:</span>
|
||||||
|
{renderPageNumbers()}
|
||||||
|
</ul>
|
||||||
|
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
||||||
|
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit"
|
||||||
|
onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
||||||
|
<div className="row">
|
||||||
|
<label className="form-label" htmlFor="loginEdit">Логин</label>
|
||||||
|
<input value={loginEdit} onChange={e => setLoginEdit(e.target.value)} className="form-control"
|
||||||
|
name='loginEdit' id="loginEdit" type="text" placeholder="Введите логин" required/>
|
||||||
|
</div>
|
||||||
|
<div className="row">
|
||||||
|
<label className="form-label" htmlFor="passwordEdit">Пароль</label>
|
||||||
|
<input value={passwordEdit} onChange={e => setPasswordEdit(e.target.value)}
|
||||||
|
className="form-control" name='passwordEdit' id="passwordEdit" type="text"
|
||||||
|
placeholder="Введите пароль" required/>
|
||||||
|
</div>
|
||||||
|
<div className="text-center mt-3">
|
||||||
|
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить
|
||||||
|
изменения
|
||||||
|
</button>
|
||||||
|
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal"
|
||||||
|
onClick={() => setModalTable(false)}>Отмена
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</ModalEdit>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ContentBlock className="d-flex justify-content-center flex-wrap" valueBlock={Content} title='Вход'/>
|
||||||
|
)
|
||||||
|
}
|
@ -1,12 +1,64 @@
|
|||||||
import { React, useState } from 'react'
|
import {useEffect, useState} from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import {useNavigate, Link} from 'react-router-dom'
|
||||||
import searchImage from '../../images/search.jpg'
|
|
||||||
import '../../styles/styleHeader.css'
|
import '../../styles/styleHeader.css'
|
||||||
|
import searchImage from '../../images/search.jpg'
|
||||||
|
|
||||||
export default function Header() {
|
export default function Header(props) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const [searchName, setSearchName] = useState('');
|
const [searchName, setSearchName] = useState('');
|
||||||
|
const [userRole, setUserRole] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
console.log('im here')
|
||||||
|
window.addEventListener("storage", () => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
const user = localStorage.getItem("user");
|
||||||
|
if (token) {
|
||||||
|
getRole(token)
|
||||||
|
.then((role) => {
|
||||||
|
if (localStorage.getItem("role") !== role) {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
|
// вызвали событие
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
navigate("/entry");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!token || !user) {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
|
navigate("/entry");
|
||||||
|
}
|
||||||
|
getUserRole();
|
||||||
|
});
|
||||||
|
getUserRole();
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
async function getRole(token) {
|
||||||
|
// вызываем поиск пользователя по токену
|
||||||
|
const requestParams = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const response = await fetch(`http://localhost:8080/get-role?token=${token}`, requestParams);
|
||||||
|
return await response.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
const getUserRole = function () {
|
||||||
|
const role = localStorage.getItem("role") || "";
|
||||||
|
setUserRole(role);
|
||||||
|
}
|
||||||
|
|
||||||
|
const validate = function (userAccess) {
|
||||||
|
if (userAccess === 'NONE')
|
||||||
|
return true;
|
||||||
|
return userAccess === 'USER' && userRole !== '' || userAccess === userRole;
|
||||||
|
}
|
||||||
|
|
||||||
function handleSubmit(e) {
|
function handleSubmit(e) {
|
||||||
console.info('Try to search data');
|
console.info('Try to search data');
|
||||||
@ -15,25 +67,62 @@ export default function Header() {
|
|||||||
setSearchName('');
|
setSearchName('');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleSubmitLogout = function () {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
|
// вызвали событие
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<header className="fs-4 fw-bold p-1">
|
<header className="fs-4 fw-bold p-1">
|
||||||
<nav className="navbar navbar-expand-md navbar-dark">
|
<nav className="navbar navbar-expand-lg navbar-dark text-white">
|
||||||
<div className="container-fluid">
|
<div className="container-fluid">
|
||||||
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
<a className="navbar-brand" href="/">
|
||||||
|
<i className="fa-solid fa-font-awesome"></i>
|
||||||
|
</a>
|
||||||
|
<button className="navbar-toggler" type="button"
|
||||||
|
data-bs-toggle="collapse" data-bs-target="#navbarNav"
|
||||||
|
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
||||||
<span className="navbar-toggler-icon"></span>
|
<span className="navbar-toggler-icon"></span>
|
||||||
</button>
|
</button>
|
||||||
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
|
<div className="collapse navbar-collapse menu" id="navbarNav">
|
||||||
<div id="main"> <a onClick={() => navigate("/films")} className="text-decoration-none mx-5" style={{ cursor: "pointer" }}>Главная</a></div>
|
<ul className="navbar-nav">
|
||||||
<form onSubmit={handleSubmit} className="col d-flex align-items-center needs-validation">
|
{
|
||||||
<input value={searchName} onChange={e => setSearchName(e.target.value)} className="form-control mainInput" type="text" name="text" search="true" rounded="true" required placeholder="Введите название" />
|
props.links.map((route) => (
|
||||||
<button className="border border-0 p-0 ms-2" type="submit"><img className="icon" src={searchImage} alt="Поиск" /></button>
|
<li key={route.path} className="nav-link">
|
||||||
|
{
|
||||||
|
validate(route.userAccess) &&
|
||||||
|
<Link className="nav-link" to={route.path}>
|
||||||
|
{route.label}
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
{
|
||||||
|
(userRole !== '') &&
|
||||||
|
<li className="nav-link">
|
||||||
|
<Link className="nav-link" to='entry' onClick={handleSubmitLogout}>
|
||||||
|
Выход
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
|
||||||
|
</ul>
|
||||||
|
<form onSubmit={handleSubmit}
|
||||||
|
className="col d-flex align-items-center needs-validation justify-content-end">
|
||||||
|
<input value={searchName} onChange={e => setSearchName(e.target.value)}
|
||||||
|
className="form-control mainInput" type="text" name="text" search="true"
|
||||||
|
rounded="true" required placeholder="Введите название"/>
|
||||||
|
<button className="border border-0 p-0 ms-2" type="submit">
|
||||||
|
<img className="icon"
|
||||||
|
src={searchImage}
|
||||||
|
alt="Поиск"/>
|
||||||
|
</button>
|
||||||
</form>
|
</form>
|
||||||
<div className="d-flex justify-content-end flex-grow-1 navbar-nav">
|
|
||||||
<a onClick={() => navigate("/registration")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Регистрация</a>
|
|
||||||
<a onClick={() => navigate("/orders")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Заказы</a>
|
|
||||||
<a onClick={() => navigate("/sessions")} className="text-decoration-none mx-3" style={{ cursor: "pointer" }}>Сеансы</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
16
front/src/pages/components/PrivateRoutes.jsx
Normal file
16
front/src/pages/components/PrivateRoutes.jsx
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import {Navigate, Outlet} from 'react-router-dom';
|
||||||
|
|
||||||
|
const PrivateRoutes = (props) => {
|
||||||
|
const userRole = localStorage.getItem("role");
|
||||||
|
|
||||||
|
function validate() {
|
||||||
|
if ((props.userAccess === "USER" && userRole) || (props.userAccess === userRole)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return validate() ? <Outlet/> : <Navigate to="/entry"/>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PrivateRoutes;
|
@ -70,3 +70,14 @@ a:hover {
|
|||||||
font-size: large !important;
|
font-size: large !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.pagination li {
|
||||||
|
color: white;
|
||||||
|
float: left;
|
||||||
|
padding: 5px 5px;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.pagination li.active {
|
||||||
|
background-color: gray;
|
||||||
|
color: white;
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.labwork1.app.configuration;
|
||||||
|
|
||||||
|
import com.labwork1.app.configuration.jwt.JwtFilter;
|
||||||
|
import io.swagger.v3.oas.models.Components;
|
||||||
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class OpenAPI30Configuration {
|
||||||
|
public static final String API_PREFIX = "/api/1.0";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public OpenAPI customizeOpenAPI() {
|
||||||
|
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
|
||||||
|
return new OpenAPI()
|
||||||
|
.addSecurityItem(new SecurityRequirement()
|
||||||
|
.addList(securitySchemeName))
|
||||||
|
.components(new Components()
|
||||||
|
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
|
||||||
|
.name(securitySchemeName)
|
||||||
|
.type(SecurityScheme.Type.HTTP)
|
||||||
|
.scheme("bearer")
|
||||||
|
.bearerFormat("JWT")));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.labwork1.app.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class PasswordEncoderConfiguration {
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,87 @@
|
|||||||
|
package com.labwork1.app.configuration;
|
||||||
|
|
||||||
|
import com.labwork1.app.configuration.jwt.JwtFilter;
|
||||||
|
import com.labwork1.app.student.controller.CustomerController;
|
||||||
|
import com.labwork1.app.student.model.UserRole;
|
||||||
|
import com.labwork1.app.student.service.CustomerService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SecurityConfiguration {
|
||||||
|
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||||
|
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||||
|
private final CustomerService userService;
|
||||||
|
private final JwtFilter jwtFilter;
|
||||||
|
|
||||||
|
public SecurityConfiguration(CustomerService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
this.jwtFilter = new JwtFilter(userService);
|
||||||
|
createAdminOnStartup();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createAdminOnStartup() {
|
||||||
|
final String admin = "admin";
|
||||||
|
if (userService.findByLogin(admin) == null) {
|
||||||
|
log.info("Admin user successfully created");
|
||||||
|
userService.createUser(admin, admin, admin, UserRole.ADMIN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
|
log.info("Creating security configuration");
|
||||||
|
http.cors()
|
||||||
|
.and()
|
||||||
|
.csrf().disable()
|
||||||
|
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
|
.and()
|
||||||
|
.authorizeHttpRequests()
|
||||||
|
.requestMatchers("/", SPA_URL_MASK).permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, CustomerController.URL_LOGIN).permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, CustomerController.URL_SIGNUP).permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, CustomerController.URL_GET_ROLE).permitAll()
|
||||||
|
.anyRequest()
|
||||||
|
.authenticated()
|
||||||
|
.and()
|
||||||
|
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
|
.anonymous();
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
|
||||||
|
AuthenticationManagerBuilder authenticationManagerBuilder = http
|
||||||
|
.getSharedObject(AuthenticationManagerBuilder.class);
|
||||||
|
authenticationManagerBuilder.userDetailsService(userService);
|
||||||
|
return authenticationManagerBuilder.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||||
|
return web -> web.ignoring()
|
||||||
|
.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||||
|
.requestMatchers("/*.js")
|
||||||
|
.requestMatchers("/*.html")
|
||||||
|
.requestMatchers("/*.css")
|
||||||
|
.requestMatchers("/*.png")
|
||||||
|
.requestMatchers("/*.jpg")
|
||||||
|
.requestMatchers("/favicon.ico")
|
||||||
|
.requestMatchers("/swagger-ui/index.html")
|
||||||
|
.requestMatchers("/webjars/**")
|
||||||
|
.requestMatchers("/swagger-resources/**")
|
||||||
|
.requestMatchers("/v3/api-docs/**")
|
||||||
|
.requestMatchers("/h2-console");
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package com.labwork1.app;
|
package com.labwork1.app.configuration;
|
||||||
|
|
||||||
import org.springframework.boot.web.server.ErrorPage;
|
import org.springframework.boot.web.server.ErrorPage;
|
||||||
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||||
@ -7,29 +7,25 @@ import org.springframework.context.annotation.Bean;
|
|||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
|
|
||||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class WebConfiguration implements WebMvcConfigurer {
|
class WebConfiguration implements WebMvcConfigurer {
|
||||||
@Override
|
|
||||||
public void addCorsMappings(CorsRegistry registry) {
|
|
||||||
registry.addMapping("/**").allowedMethods("*");
|
|
||||||
}
|
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(ViewControllerRegistry registry) {
|
public void addViewControllers(ViewControllerRegistry registry) {
|
||||||
ViewControllerRegistration registration = registry.addViewController("/notFound");
|
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
|
||||||
registration.setViewName("forward:/index.html");
|
registry.addViewController("/notFound").setViewName("forward:/");
|
||||||
registration.setStatusCode(HttpStatus.OK);
|
|
||||||
|
|
||||||
// Alternative way (404 error hits the console):
|
|
||||||
// > registry.addViewController("/notFound").setViewName("forward:/index.html");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
|
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
|
||||||
return container -> {
|
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
|
||||||
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
|
}
|
||||||
};
|
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
registry.addMapping("/**").allowedMethods("*");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.labwork1.app.configuration.jwt;
|
||||||
|
|
||||||
|
public class JwtException extends RuntimeException {
|
||||||
|
public JwtException(Throwable throwable) {
|
||||||
|
super(throwable);
|
||||||
|
}
|
||||||
|
|
||||||
|
public JwtException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.labwork1.app.configuration.jwt;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.labwork1.app.student.service.CustomerService;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.ServletRequest;
|
||||||
|
import jakarta.servlet.ServletResponse;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.GenericFilterBean;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class JwtFilter extends GenericFilterBean {
|
||||||
|
private static final String AUTHORIZATION = "Authorization";
|
||||||
|
public static final String TOKEN_BEGIN_STR = "Bearer ";
|
||||||
|
|
||||||
|
private final CustomerService userService;
|
||||||
|
|
||||||
|
public JwtFilter(CustomerService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTokenFromRequest(HttpServletRequest request) {
|
||||||
|
String bearer = request.getHeader(AUTHORIZATION);
|
||||||
|
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
|
||||||
|
return bearer.substring(TOKEN_BEGIN_STR.length());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void raiseException(ServletResponse response, int status, String message) throws IOException {
|
||||||
|
if (response instanceof final HttpServletResponse httpResponse) {
|
||||||
|
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
httpResponse.setStatus(status);
|
||||||
|
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
|
||||||
|
response.getOutputStream().write(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void doFilter(ServletRequest request,
|
||||||
|
ServletResponse response,
|
||||||
|
FilterChain chain) throws IOException, ServletException {
|
||||||
|
if (request instanceof final HttpServletRequest httpRequest) {
|
||||||
|
final String token = getTokenFromRequest(httpRequest);
|
||||||
|
if (StringUtils.hasText(token)) {
|
||||||
|
try {
|
||||||
|
final UserDetails user = userService.loadUserByToken(token);
|
||||||
|
final UsernamePasswordAuthenticationToken auth =
|
||||||
|
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
} catch (JwtException e) {
|
||||||
|
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
|
||||||
|
return;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
|
||||||
|
String.format("Internal error: %s", e.getMessage()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.labwork1.app.configuration.jwt;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||||
|
public class JwtProperties {
|
||||||
|
private String devToken = "";
|
||||||
|
private Boolean isDev = true;
|
||||||
|
|
||||||
|
public String getDevToken() {
|
||||||
|
return devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDevToken(String devToken) {
|
||||||
|
this.devToken = devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean isDev() {
|
||||||
|
return isDev;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDev(Boolean dev) {
|
||||||
|
isDev = dev;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,107 @@
|
|||||||
|
package com.labwork1.app.configuration.jwt;
|
||||||
|
|
||||||
|
import com.auth0.jwt.JWT;
|
||||||
|
import com.auth0.jwt.algorithms.Algorithm;
|
||||||
|
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||||
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||||
|
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtProvider {
|
||||||
|
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||||
|
|
||||||
|
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||||
|
private final static String ISSUER = "auth0";
|
||||||
|
|
||||||
|
private final Algorithm algorithm;
|
||||||
|
private final JWTVerifier verifier;
|
||||||
|
|
||||||
|
public JwtProvider(JwtProperties jwtProperties) {
|
||||||
|
if (!jwtProperties.isDev()) {
|
||||||
|
LOG.info("Generate new JWT key for prod");
|
||||||
|
try {
|
||||||
|
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||||
|
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||||
|
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new JwtException(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||||
|
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||||
|
}
|
||||||
|
verifier = JWT.require(algorithm)
|
||||||
|
.withIssuer(ISSUER)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String bytesToHex(byte[] bytes) {
|
||||||
|
byte[] hexChars = new byte[bytes.length * 2];
|
||||||
|
for (int j = 0; j < bytes.length; j++) {
|
||||||
|
int v = bytes[j] & 0xFF;
|
||||||
|
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||||
|
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||||
|
}
|
||||||
|
return new String(hexChars, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateToken(String login) {
|
||||||
|
final Date issueDate = Date.from(LocalDate.now()
|
||||||
|
.atStartOfDay(ZoneId.systemDefault())
|
||||||
|
.toInstant());
|
||||||
|
final Date expireDate = Date.from(LocalDate.now()
|
||||||
|
.plusDays(15)
|
||||||
|
.atStartOfDay(ZoneId.systemDefault())
|
||||||
|
.toInstant());
|
||||||
|
return JWT.create()
|
||||||
|
.withIssuer(ISSUER)
|
||||||
|
.withIssuedAt(issueDate)
|
||||||
|
.withExpiresAt(expireDate)
|
||||||
|
.withSubject(login)
|
||||||
|
.sign(algorithm);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DecodedJWT validateToken(String token) {
|
||||||
|
try {
|
||||||
|
return verifier.verify(token);
|
||||||
|
} catch (JWTVerificationException e) {
|
||||||
|
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTokenValid(String token) {
|
||||||
|
if (!StringUtils.hasText(token)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
validateToken(token);
|
||||||
|
return true;
|
||||||
|
} catch (JwtException e) {
|
||||||
|
LOG.error(e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<String> getLoginFromToken(String token) {
|
||||||
|
try {
|
||||||
|
return Optional.ofNullable(validateToken(token).getSubject());
|
||||||
|
} catch (JwtException e) {
|
||||||
|
LOG.error(e.getMessage());
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,9 @@
|
|||||||
package com.labwork1.app.student.controller;
|
package com.labwork1.app.student.controller;
|
||||||
|
|
||||||
|
import com.labwork1.app.student.model.UserRole;
|
||||||
import com.labwork1.app.student.service.CinemaService;
|
import com.labwork1.app.student.service.CinemaService;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.security.access.annotation.Secured;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -35,16 +37,19 @@ public class CinemaController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public CinemaDto createCinema(@RequestBody @Valid CinemaDto cinemaDto) {
|
public CinemaDto createCinema(@RequestBody @Valid CinemaDto cinemaDto) {
|
||||||
return new CinemaDto(cinemaService.addCinema(cinemaDto));
|
return new CinemaDto(cinemaService.addCinema(cinemaDto));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public CinemaDto updateCinema(@RequestBody @Valid CinemaDto cinemaDto) {
|
public CinemaDto updateCinema(@RequestBody @Valid CinemaDto cinemaDto) {
|
||||||
return new CinemaDto(cinemaService.updateCinema(cinemaDto));
|
return new CinemaDto(cinemaService.updateCinema(cinemaDto));
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public CinemaDto deleteCinema(@PathVariable Long id) {
|
public CinemaDto deleteCinema(@PathVariable Long id) {
|
||||||
return new CinemaDto(cinemaService.deleteCinema(id));
|
return new CinemaDto(cinemaService.deleteCinema(id));
|
||||||
}
|
}
|
||||||
|
@ -1,45 +1,90 @@
|
|||||||
package com.labwork1.app.student.controller;
|
package com.labwork1.app.student.controller;
|
||||||
|
|
||||||
|
import com.labwork1.app.configuration.OpenAPI30Configuration;
|
||||||
|
import com.labwork1.app.student.model.Customer;
|
||||||
|
import com.labwork1.app.student.model.UserRole;
|
||||||
import com.labwork1.app.student.service.CustomerService;
|
import com.labwork1.app.student.service.CustomerService;
|
||||||
|
import com.labwork1.app.util.validation.ValidationException;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.apache.commons.lang3.tuple.Pair;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.security.access.annotation.Secured;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/customer")
|
|
||||||
public class CustomerController {
|
public class CustomerController {
|
||||||
private final CustomerService customerService;
|
private final CustomerService customerService;
|
||||||
|
public static final String URL_LOGIN = "/jwt/login";
|
||||||
|
public static final String URL_SIGNUP = "/signup";
|
||||||
|
public static final String URL_MAIN = "/customer";
|
||||||
|
public static final String URL_GET_ROLE = "/get-role";
|
||||||
public CustomerController(CustomerService customerService) {
|
public CustomerController(CustomerService customerService) {
|
||||||
this.customerService = customerService;
|
this.customerService = customerService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}")
|
@PostMapping(URL_LOGIN)
|
||||||
|
public String login(@RequestBody @Valid CustomerDto userDto) {
|
||||||
|
return customerService.loginAndGetToken(userDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(URL_SIGNUP)
|
||||||
|
public String signup(@RequestBody @Valid UserSignupDto userSignupDto){
|
||||||
|
try {
|
||||||
|
Customer user = customerService.addCustomer(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
|
||||||
|
return user.getLogin() + " was created";
|
||||||
|
}
|
||||||
|
catch(ValidationException e){
|
||||||
|
return e.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(URL_MAIN + "/{id}")
|
||||||
public CustomerDto getCustomer(@PathVariable Long id) {
|
public CustomerDto getCustomer(@PathVariable Long id) {
|
||||||
return new CustomerDto(customerService.findCustomer(id));
|
return new CustomerDto(customerService.findCustomer(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping(URL_MAIN)
|
||||||
public List<CustomerDto> getCustomers() {
|
public CustomerDto getCustomerByLogin(@RequestParam("login") String login) {
|
||||||
return customerService.findAllCustomers().stream()
|
return new CustomerDto(customerService.findByLogin(login));
|
||||||
.map(CustomerDto::new)
|
}
|
||||||
|
|
||||||
|
@GetMapping(URL_GET_ROLE)
|
||||||
|
public String getRole(@RequestParam("token") String token) {
|
||||||
|
UserDetails userDetails = customerService.loadUserByToken(token);
|
||||||
|
Customer user = customerService.findByLogin(userDetails.getUsername());
|
||||||
|
return user.getRole().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(OpenAPI30Configuration.API_PREFIX + URL_MAIN)
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
|
public Page<CustomerDto> getCustomers(@RequestParam(defaultValue = "1") int page,
|
||||||
|
@RequestParam(defaultValue = "5") int size) {
|
||||||
|
/*final Page<CustomerDto> users = customerService.findAllPages(page, size)
|
||||||
|
.map(CustomerDto::new);
|
||||||
|
final int totalPages = users.getTotalPages();
|
||||||
|
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||||
|
.boxed()
|
||||||
.toList();
|
.toList();
|
||||||
|
return Pair.of(users, pageNumbers);*/
|
||||||
|
final Page<CustomerDto> users = customerService.findAllPages(page, size)
|
||||||
|
.map(CustomerDto::new);
|
||||||
|
return users;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PutMapping(URL_MAIN + "/{id}")
|
||||||
public CustomerDto createCustomer(@RequestParam("login") String login,
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
@RequestParam("password") String password) {
|
|
||||||
return new CustomerDto(customerService.addCustomer(login, password));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
|
||||||
public CustomerDto updateCustomer(@PathVariable Long id,
|
public CustomerDto updateCustomer(@PathVariable Long id,
|
||||||
@RequestParam("login") String login,
|
@RequestBody @Valid CustomerDto userDto) {
|
||||||
@RequestParam("password") String password) {
|
return new CustomerDto(customerService.updateCustomer(id, userDto.getLogin(), userDto.getPassword()));
|
||||||
return new CustomerDto(customerService.updateCustomer(id, login, password));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping(URL_MAIN + "/{id}")
|
||||||
public CustomerDto deleteCustomer(@PathVariable Long id) {
|
public CustomerDto deleteCustomer(@PathVariable Long id) {
|
||||||
return new CustomerDto(customerService.deleteCustomer(id));
|
return new CustomerDto(customerService.deleteCustomer(id));
|
||||||
}
|
}
|
||||||
|
@ -26,8 +26,8 @@ public class OrderController {
|
|||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping("/{customer}")
|
||||||
public OrderDto createOrder(@RequestParam("customer") Long customer) {
|
public OrderDto createOrder(@PathVariable String customer) {
|
||||||
return new OrderDto(orderService.addOrder(customer));
|
return new OrderDto(orderService.addOrder(customer));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,6 +1,10 @@
|
|||||||
package com.labwork1.app.student.controller;
|
package com.labwork1.app.student.controller;
|
||||||
|
|
||||||
|
import com.labwork1.app.student.model.Session;
|
||||||
|
import com.labwork1.app.student.model.SessionExtension;
|
||||||
|
import com.labwork1.app.student.model.UserRole;
|
||||||
import com.labwork1.app.student.service.SessionService;
|
import com.labwork1.app.student.service.SessionService;
|
||||||
|
import org.springframework.security.access.annotation.Secured;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.sql.Timestamp;
|
import java.sql.Timestamp;
|
||||||
@ -31,6 +35,7 @@ public class SessionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public SessionDto createSession(@RequestParam("price") String price,
|
public SessionDto createSession(@RequestParam("price") String price,
|
||||||
@RequestParam("timestamp") String timestamp,
|
@RequestParam("timestamp") String timestamp,
|
||||||
@RequestParam("cinemaid") Long cinemaId,
|
@RequestParam("cinemaid") Long cinemaId,
|
||||||
@ -44,6 +49,7 @@ public class SessionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{id}")
|
@PutMapping("/{id}")
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public SessionDto updateSession(@PathVariable Long id,
|
public SessionDto updateSession(@PathVariable Long id,
|
||||||
@RequestParam("price") String price) {
|
@RequestParam("price") String price) {
|
||||||
return new SessionDto(sessionService.findSession(sessionService
|
return new SessionDto(sessionService.findSession(sessionService
|
||||||
@ -51,8 +57,8 @@ public class SessionController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
public SessionDto deleteSession(@PathVariable Long id) {
|
public SessionDto deleteSession(@PathVariable Long id) {
|
||||||
return new SessionDto(sessionService.deleteSession(id));
|
return new SessionDto(sessionService.deleteSession(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.labwork1.app.student.controller;
|
||||||
|
|
||||||
|
public class UserSignupDto {
|
||||||
|
private String login;
|
||||||
|
private String password;
|
||||||
|
private String passwordConfirm;
|
||||||
|
|
||||||
|
public String getLogin() {
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLogin(String login) {
|
||||||
|
this.login = login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPasswordConfirm() {
|
||||||
|
return passwordConfirm;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPasswordConfirm(String passwordConfirm) {
|
||||||
|
this.passwordConfirm = passwordConfirm;
|
||||||
|
}
|
||||||
|
}
|
@ -2,6 +2,7 @@ package com.labwork1.app.student.model;
|
|||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -12,12 +13,17 @@ public class Customer {
|
|||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
private Long id;
|
private Long id;
|
||||||
|
@Column(nullable = false, unique = true, length = 64)
|
||||||
@NotBlank(message = "login can't be null or empty")
|
@NotBlank(message = "login can't be null or empty")
|
||||||
|
@Size(min = 3, max = 64)
|
||||||
private String login;
|
private String login;
|
||||||
|
@Column(nullable = false, length = 64)
|
||||||
@NotBlank(message = "password can't be null or empty")
|
@NotBlank(message = "password can't be null or empty")
|
||||||
|
@Size(min = 6, max = 64)
|
||||||
private String password;
|
private String password;
|
||||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
|
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
|
||||||
private List<Order> orders;
|
private List<Order> orders;
|
||||||
|
private UserRole role;
|
||||||
|
|
||||||
public Customer() {
|
public Customer() {
|
||||||
}
|
}
|
||||||
@ -26,6 +32,14 @@ public class Customer {
|
|||||||
this.login = login;
|
this.login = login;
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.orders = new ArrayList<>();
|
this.orders = new ArrayList<>();
|
||||||
|
this.role = UserRole.USER;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer(String login, String password, UserRole role) {
|
||||||
|
this.login = login;
|
||||||
|
this.password = password;
|
||||||
|
this.orders = new ArrayList<>();
|
||||||
|
this.role = role;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -50,6 +64,10 @@ public class Customer {
|
|||||||
'}';
|
'}';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public UserRole getRole() {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
public Long getId() {
|
public Long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
20
src/main/java/com/labwork1/app/student/model/UserRole.java
Normal file
20
src/main/java/com/labwork1/app/student/model/UserRole.java
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package com.labwork1.app.student.model;
|
||||||
|
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
|
||||||
|
public enum UserRole implements GrantedAuthority {
|
||||||
|
ADMIN,
|
||||||
|
USER;
|
||||||
|
|
||||||
|
private static final String PREFIX = "ROLE_";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAuthority() {
|
||||||
|
return PREFIX + this.name();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class AsString {
|
||||||
|
public static final String ADMIN = PREFIX + "ADMIN";
|
||||||
|
public static final String USER = PREFIX + "USER";
|
||||||
|
}
|
||||||
|
}
|
@ -8,4 +8,5 @@ import org.springframework.data.repository.query.Param;
|
|||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
public interface CustomerRepository extends JpaRepository<Customer, Long> {
|
public interface CustomerRepository extends JpaRepository<Customer, Long> {
|
||||||
|
Customer findOneByLoginIgnoreCase(String login);
|
||||||
}
|
}
|
||||||
|
@ -4,4 +4,7 @@ public class CustomerNotFoundException extends RuntimeException {
|
|||||||
public CustomerNotFoundException(Long id) {
|
public CustomerNotFoundException(Long id) {
|
||||||
super(String.format("Customer with id [%s] is not found", id));
|
super(String.format("Customer with id [%s] is not found", id));
|
||||||
}
|
}
|
||||||
|
public CustomerNotFoundException(String login) {
|
||||||
|
super(String.format("Customer with login [%s] is not found", login));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,29 +1,94 @@
|
|||||||
package com.labwork1.app.student.service;
|
package com.labwork1.app.student.service;
|
||||||
|
|
||||||
|
import com.labwork1.app.configuration.jwt.JwtProvider;
|
||||||
|
import com.labwork1.app.student.controller.CustomerDto;
|
||||||
import com.labwork1.app.student.model.Customer;
|
import com.labwork1.app.student.model.Customer;
|
||||||
|
import com.labwork1.app.student.model.UserRole;
|
||||||
import com.labwork1.app.student.repository.CustomerRepository;
|
import com.labwork1.app.student.repository.CustomerRepository;
|
||||||
|
import com.labwork1.app.util.validation.ValidationException;
|
||||||
import com.labwork1.app.util.validation.ValidatorUtil;
|
import com.labwork1.app.util.validation.ValidatorUtil;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import com.labwork1.app.configuration.jwt.JwtException;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class CustomerService {
|
public class CustomerService implements UserDetailsService {
|
||||||
private final CustomerRepository customerRepository;
|
private final CustomerRepository customerRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final ValidatorUtil validatorUtil;
|
private final ValidatorUtil validatorUtil;
|
||||||
|
private final JwtProvider jwtProvider;
|
||||||
|
|
||||||
public CustomerService(CustomerRepository customerRepository, ValidatorUtil validatorUtil) {
|
public CustomerService(CustomerRepository customerRepository, PasswordEncoder passwordEncoder, ValidatorUtil validatorUtil, JwtProvider jwtProvider) {
|
||||||
this.customerRepository = customerRepository;
|
this.customerRepository = customerRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
this.validatorUtil = validatorUtil;
|
this.validatorUtil = validatorUtil;
|
||||||
|
this.jwtProvider = jwtProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<Customer> findAllPages(int page, int size) {
|
||||||
|
return customerRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Customer findByLogin(String login) {
|
||||||
|
return customerRepository.findOneByLoginIgnoreCase(login);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Customer addCustomer(String login, String password) {
|
public Customer addCustomer(String login, String password, String passwordConfirm) {
|
||||||
final Customer customer = new Customer(login, password);
|
return createUser(login, password, passwordConfirm, UserRole.USER);
|
||||||
validatorUtil.validate(customer);
|
}
|
||||||
return customerRepository.save(customer);
|
|
||||||
|
public Customer createUser(String login, String password, String passwordConfirm, UserRole role) {
|
||||||
|
if (findByLogin(login) != null) {
|
||||||
|
throw new UserExistsException(login);
|
||||||
|
}
|
||||||
|
final Customer user = new Customer(login, passwordEncoder.encode(password), role);
|
||||||
|
validatorUtil.validate(user);
|
||||||
|
if (!Objects.equals(password, passwordConfirm)) {
|
||||||
|
throw new ValidationException("Passwords not equals");
|
||||||
|
}
|
||||||
|
return customerRepository.save(user);
|
||||||
|
}
|
||||||
|
public String loginAndGetToken(CustomerDto userDto) {
|
||||||
|
final Customer user = findByLogin(userDto.getLogin());
|
||||||
|
if (user == null) {
|
||||||
|
throw new CustomerNotFoundException(userDto.getLogin());
|
||||||
|
}
|
||||||
|
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
|
||||||
|
throw new CustomerNotFoundException(user.getLogin());
|
||||||
|
}
|
||||||
|
return jwtProvider.generateToken(user.getLogin());
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
|
||||||
|
if (!jwtProvider.isTokenValid(token)) {
|
||||||
|
throw new JwtException("Bad token");
|
||||||
|
}
|
||||||
|
final String userLogin = jwtProvider.getLoginFromToken(token)
|
||||||
|
.orElseThrow(() -> new JwtException("Token is not contain Login"));
|
||||||
|
return loadUserByUsername(userLogin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
final Customer userEntity = findByLogin(username);
|
||||||
|
if (userEntity == null) {
|
||||||
|
throw new UsernameNotFoundException(username);
|
||||||
|
}
|
||||||
|
return new org.springframework.security.core.userdetails.User(
|
||||||
|
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
@ -41,7 +106,7 @@ public class CustomerService {
|
|||||||
public Customer updateCustomer(Long id, String login, String password) {
|
public Customer updateCustomer(Long id, String login, String password) {
|
||||||
final Customer currentCustomer = findCustomer(id);
|
final Customer currentCustomer = findCustomer(id);
|
||||||
currentCustomer.setLogin(login);
|
currentCustomer.setLogin(login);
|
||||||
currentCustomer.setPassword(password);
|
currentCustomer.setPassword(passwordEncoder.encode(password));
|
||||||
validatorUtil.validate(currentCustomer);
|
validatorUtil.validate(currentCustomer);
|
||||||
return customerRepository.save(currentCustomer);
|
return customerRepository.save(currentCustomer);
|
||||||
}
|
}
|
||||||
|
@ -34,6 +34,15 @@ public class OrderService {
|
|||||||
return orderRepository.save(order);
|
return orderRepository.save(order);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Order addOrder(String customerName) {
|
||||||
|
final Order order = new Order(new Date(System.currentTimeMillis()));
|
||||||
|
final Customer customer = customerService.findByLogin(customerName);
|
||||||
|
order.setCustomer(customer);
|
||||||
|
validatorUtil.validate(order);
|
||||||
|
return orderRepository.save(order);
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Order addSession(Long id, Long sessionId, Integer count) {
|
public Order addSession(Long id, Long sessionId, Integer count) {
|
||||||
final Session currentSession = sessionService.findSession(sessionId);
|
final Session currentSession = sessionService.findSession(sessionId);
|
||||||
|
@ -10,6 +10,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
|
|
||||||
import java.sql.Timestamp;
|
import java.sql.Timestamp;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class SessionService {
|
public class SessionService {
|
||||||
@ -38,6 +39,12 @@ public class SessionService {
|
|||||||
.orElseThrow(() -> new SessionNotFoundException(id));
|
.orElseThrow(() -> new SessionNotFoundException(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Session findBaseSession(Long id) {
|
||||||
|
final Optional<Session> session = sessionRepository.findById(id);
|
||||||
|
return session.orElseThrow(() -> new SessionNotFoundException(id));
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public List<SessionExtension> findAllSessions() {
|
public List<SessionExtension> findAllSessions() {
|
||||||
return sessionRepository.getSessionsWithCapacity();
|
return sessionRepository.getSessionsWithCapacity();
|
||||||
@ -45,7 +52,7 @@ public class SessionService {
|
|||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Session updateSession(Long id, Double price) {
|
public Session updateSession(Long id, Double price) {
|
||||||
final Session currentSession = findSession(id);
|
final Session currentSession = findBaseSession(id);
|
||||||
currentSession.setPrice(price);
|
currentSession.setPrice(price);
|
||||||
validatorUtil.validate(currentSession);
|
validatorUtil.validate(currentSession);
|
||||||
return sessionRepository.save(currentSession);
|
return sessionRepository.save(currentSession);
|
||||||
@ -53,7 +60,7 @@ public class SessionService {
|
|||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public Session deleteSession(Long id) {
|
public Session deleteSession(Long id) {
|
||||||
final Session currentSession = findSession(id);
|
final Session currentSession = findBaseSession(id);
|
||||||
// все равно сеанс не удалился бы, который участвует в заказах
|
// все равно сеанс не удалился бы, который участвует в заказах
|
||||||
// для отслеживания операции с ошибкой
|
// для отслеживания операции с ошибкой
|
||||||
if (currentSession.getOrders().size() > 0)
|
if (currentSession.getOrders().size() > 0)
|
||||||
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.labwork1.app.student.service;
|
||||||
|
|
||||||
|
public class UserExistsException extends RuntimeException {
|
||||||
|
public UserExistsException(String login) {
|
||||||
|
super(String.format("User '%s' already exists", login));
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,10 @@ package com.labwork1.app.util.validation;
|
|||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
public class ValidationException extends RuntimeException {
|
public class ValidationException extends RuntimeException {
|
||||||
|
public ValidationException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
public ValidationException(Set<String> errors) {
|
public ValidationException(Set<String> errors) {
|
||||||
super(String.join("\n", errors));
|
super(String.join("\n", errors));
|
||||||
}
|
}
|
||||||
|
@ -8,3 +8,5 @@ spring.jpa.hibernate.ddl-auto=update
|
|||||||
spring.h2.console.enabled=true
|
spring.h2.console.enabled=true
|
||||||
spring.h2.console.settings.trace=false
|
spring.h2.console.settings.trace=false
|
||||||
spring.h2.console.settings.web-allow-others=false
|
spring.h2.console.settings.web-allow-others=false
|
||||||
|
jwt.dev-token=my-secret-jwt
|
||||||
|
jwt.dev=true
|
@ -1,129 +1,129 @@
|
|||||||
package com.labwork1.app;
|
//package com.labwork1.app;
|
||||||
|
//
|
||||||
import com.labwork1.app.student.model.*;
|
//import com.labwork1.app.student.model.*;
|
||||||
import com.labwork1.app.student.service.*;
|
//import com.labwork1.app.student.service.*;
|
||||||
import org.junit.jupiter.api.Assertions;
|
//import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.api.Test;
|
//import org.junit.jupiter.api.Test;
|
||||||
import org.slf4j.Logger;
|
//import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
//import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
//import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
//import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
//
|
||||||
import java.sql.Timestamp;
|
//import java.sql.Timestamp;
|
||||||
import java.util.List;
|
//import java.util.List;
|
||||||
|
//
|
||||||
@SpringBootTest
|
//@SpringBootTest
|
||||||
public class JpaCustomerTests {
|
//public class JpaCustomerTests {
|
||||||
private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
|
// private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
|
||||||
@Autowired
|
// @Autowired
|
||||||
private CustomerService customerService;
|
// private CustomerService customerService;
|
||||||
@Autowired
|
// @Autowired
|
||||||
private SessionService sessionService;
|
// private SessionService sessionService;
|
||||||
@Autowired
|
// @Autowired
|
||||||
private OrderService orderService;
|
// private OrderService orderService;
|
||||||
@Autowired
|
// @Autowired
|
||||||
private CinemaService cinemaService;
|
// private CinemaService cinemaService;
|
||||||
|
//
|
||||||
@Test
|
// @Test
|
||||||
void testOrder() {
|
// void testOrder() {
|
||||||
sessionService.deleteAllSessions();
|
// sessionService.deleteAllSessions();
|
||||||
cinemaService.deleteAllCinemas();
|
// cinemaService.deleteAllCinemas();
|
||||||
orderService.deleteAllOrders();
|
// orderService.deleteAllOrders();
|
||||||
customerService.deleteAllCustomers();
|
// customerService.deleteAllCustomers();
|
||||||
// 2 кино
|
// // 2 кино
|
||||||
final Cinema cinema1 = cinemaService.addCinema("Меню");
|
// final Cinema cinema1 = cinemaService.addCinema("Меню");
|
||||||
final Cinema cinema2 = cinemaService.addCinema("Аватар");
|
// final Cinema cinema2 = cinemaService.addCinema("Аватар");
|
||||||
|
//
|
||||||
// 2 сеанса
|
// // 2 сеанса
|
||||||
final Session session1 = sessionService.addSession(300.0,
|
// final Session session1 = sessionService.addSession(300.0,
|
||||||
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
|
// new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
|
||||||
final Session session2 = sessionService.addSession( 200.0,
|
// final Session session2 = sessionService.addSession( 200.0,
|
||||||
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
|
// new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
|
||||||
|
//
|
||||||
// проверка 2 сеанса у 1 кино
|
// // проверка 2 сеанса у 1 кино
|
||||||
Assertions.assertEquals(cinemaService
|
// Assertions.assertEquals(cinemaService
|
||||||
.findCinema(cinema1.getId()).getSessions().size(), 2);
|
// .findCinema(cinema1.getId()).getSessions().size(), 2);
|
||||||
// 1 покупатель
|
// // 1 покупатель
|
||||||
final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
|
// final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
|
||||||
customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
|
// customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
|
||||||
Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
|
// Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
|
||||||
// 1 заказ, 1 копия заказа
|
// // 1 заказ, 1 копия заказа
|
||||||
final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId());
|
// final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId());
|
||||||
final Order order1 = orderService.findOrder(order0.getId());
|
// final Order order1 = orderService.findOrder(order0.getId());
|
||||||
Assertions.assertEquals(order0, order1);
|
// Assertions.assertEquals(order0, order1);
|
||||||
|
//
|
||||||
// у клиента точно есть заказ?
|
// // у клиента точно есть заказ?
|
||||||
Assertions.assertEquals(customerService
|
// Assertions.assertEquals(customerService
|
||||||
.findCustomer(customer1.getId()).getOrders().size(), 1);
|
// .findCustomer(customer1.getId()).getOrders().size(), 1);
|
||||||
// 0 заказов
|
// // 0 заказов
|
||||||
orderService.deleteAllOrders();
|
// orderService.deleteAllOrders();
|
||||||
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
|
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
|
||||||
// 2 покупателя
|
// // 2 покупателя
|
||||||
final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
|
// final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
|
||||||
|
//
|
||||||
// 1 заказ
|
// // 1 заказ
|
||||||
final Order order2 = orderService
|
// final Order order2 = orderService
|
||||||
.addOrder(customerService.findCustomer(customer2.getId()).getId());
|
// .addOrder(customerService.findCustomer(customer2.getId()).getId());
|
||||||
// у заказа 2 сеанса
|
// // у заказа 2 сеанса
|
||||||
orderService.addSession(order2.getId(), session1.getId(), 2);
|
// orderService.addSession(order2.getId(), session1.getId(), 2);
|
||||||
|
//
|
||||||
List<SessionExtension> result = sessionService.findAllSessions();
|
// List<SessionExtension> result = sessionService.findAllSessions();
|
||||||
|
//
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session1.getId()), 2);
|
// Assertions.assertEquals(sessionService.getCapacity(session1.getId()), 2);
|
||||||
|
//
|
||||||
orderService.addSession(order2.getId(), session2.getId(), 5);
|
// orderService.addSession(order2.getId(), session2.getId(), 5);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 5);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 5);
|
||||||
|
//
|
||||||
Assertions.assertThrows(IllegalArgumentException.class, () ->
|
// Assertions.assertThrows(IllegalArgumentException.class, () ->
|
||||||
orderService.addSession(order2.getId(), session2.getId(), 6));
|
// orderService.addSession(order2.getId(), session2.getId(), 6));
|
||||||
|
//
|
||||||
// у заказа 1 сеанс
|
// // у заказа 1 сеанс
|
||||||
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 10);
|
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 10);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
||||||
// заполнили всю 2 сессию
|
// // заполнили всю 2 сессию
|
||||||
orderService.addSession(order2.getId(), session2.getId(), 10);
|
// orderService.addSession(order2.getId(), session2.getId(), 10);
|
||||||
|
//
|
||||||
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
|
// Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
|
||||||
|
//
|
||||||
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 4);
|
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 4);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 6);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 6);
|
||||||
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 6);
|
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 6);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
||||||
|
//
|
||||||
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().size(), 1);
|
// Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().size(), 1);
|
||||||
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().get(0).getId().getSessionId(), session1.getId());
|
// Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().get(0).getId().getSessionId(), session1.getId());
|
||||||
|
//
|
||||||
// у заказа 1 сеанс
|
// // у заказа 1 сеанс
|
||||||
// 3 сеанса всего
|
// // 3 сеанса всего
|
||||||
final Session session3 = sessionService.addSession(300.0,
|
// final Session session3 = sessionService.addSession(300.0,
|
||||||
new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
|
// new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
|
||||||
// удалили заказ2, у которого был сеанс1
|
// // удалили заказ2, у которого был сеанс1
|
||||||
orderService.deleteOrder(order2.getId());
|
// orderService.deleteOrder(order2.getId());
|
||||||
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
|
// Assertions.assertEquals(orderService.findAllOrders().size(), 0);
|
||||||
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
|
// Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
|
||||||
|
//
|
||||||
// создали 3 заказ у 2 покупателя
|
// // создали 3 заказ у 2 покупателя
|
||||||
final Order order3 = orderService
|
// final Order order3 = orderService
|
||||||
.addOrder(customerService.findCustomer(customer2.getId()).getId());
|
// .addOrder(customerService.findCustomer(customer2.getId()).getId());
|
||||||
orderService.addSession(order3.getId(), session2.getId(), 2);
|
// orderService.addSession(order3.getId(), session2.getId(), 2);
|
||||||
orderService.addSession(order3.getId(), session3.getId(), 8);
|
// orderService.addSession(order3.getId(), session3.getId(), 8);
|
||||||
orderService.addSession(order3.getId(), session1.getId(), 8);
|
// orderService.addSession(order3.getId(), session1.getId(), 8);
|
||||||
// 2-ой покупатель удален
|
// // 2-ой покупатель удален
|
||||||
// 0 заказов после его удаления
|
// // 0 заказов после его удаления
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
|
||||||
customerService.deleteCustomer(customer2.getId());
|
// customerService.deleteCustomer(customer2.getId());
|
||||||
|
//
|
||||||
Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
|
// Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
|
||||||
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
|
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
|
||||||
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
|
// Assertions.assertEquals(orderService.findAllOrders().size(), 0);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
|
||||||
Assertions.assertEquals(sessionService.getCapacity(session3.getId()), 0);
|
// Assertions.assertEquals(sessionService.getCapacity(session3.getId()), 0);
|
||||||
|
//
|
||||||
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
|
// Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
|
||||||
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
|
// Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
|
||||||
// у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
|
// // у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
|
||||||
cinemaService.deleteCinema(cinema2.getId());
|
// cinemaService.deleteCinema(cinema2.getId());
|
||||||
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
|
// Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
|
||||||
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
|
// Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
|
||||||
}
|
// }
|
||||||
}
|
//}
|
||||||
|
Loading…
Reference in New Issue
Block a user