я надеюсь это все и ничего не сломается

This commit is contained in:
dasha 2023-05-13 13:29:35 +04:00
parent d1011d0537
commit 4e3dfdab49
34 changed files with 1457 additions and 550 deletions

View File

@ -19,11 +19,16 @@ jar {
dependencies {
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-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
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'
implementation 'org.hibernate.validator:hibernate-validator'

View File

@ -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 FilmPage from './pages/FilmPage'
import Header from './pages/components/Header'
@ -7,39 +7,40 @@ import SearchSame from './pages/SearchSame'
import Registration from './pages/Registration'
import Sessions from './pages/Sessions'
import Orders from './pages/Orders'
function Router(props) {
return useRoutes(props.rootRoute);
}
import Users from "./pages/Users";
import PrivateRoutes from "./pages/components/PrivateRoutes";
export default function App() {
const routes = [
{ index: true, element: <Films /> },
{ path: '/films', element: <Films />, label: 'Главная' },
{ path: '/registration', element: <Registration />, label: 'Регистрация' },
{ path: '/sessions', element: <Sessions />, label: 'Сеансы' },
{ path: '/orders', element: <Orders />, label: 'Заказы' },
{ path: '/films/:id', element: <FilmPage /> },
{ path: '/search-same/:request', element: <SearchSame /> }
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
const links = [
{path: 'films', label: 'Главная', userAccess: 'NONE'},
{path: 'registration', label: 'Регистрация', userAccess: 'NONE'},
{path: 'entry', label: 'Вход', userAccess: 'NONE'},
{path: 'users', label: 'Пользователи', userAccess: 'ADMIN'},
{path: 'sessions', label: 'Сеансы', userAccess: 'NONE'},
{path: 'orders', label: 'Заказы', userAccess: 'USER'}
];
function render(links) {
return (
<>
<Header links={links} />
<Outlet />
<Footer />
</>
<>
<BrowserRouter>
<Header links={links}/>
<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/>
</BrowserRouter>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View File

@ -1,5 +1,5 @@
import { React, useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {React, useState, useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import FilmItem from './components/FilmItem'
import ContentBlock from './components/ContentBlock'
import ModalEdit from './components/ModalEdit'
@ -20,26 +20,51 @@ export default function Films() {
const [filmNameEdit, setFilmNameEdit] = useState('');
// хук для запоминания индекса элемента, вызвавшего модальное окно
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(() => {
Service.readAll('cinema')
getAll('cinema')
.then(data => setItems(data));
}, []);
function handleDeleteFilm(id) {
async function handleDeleteFilm(id) {
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(() => {
setItems(items.filter(elem => elem.id !== id))
console.log("Removed")
});
};
}
function handleEditFilm(id) {
async function handleEditFilm(id) {
console.info(`Start edit script`);
Service.read(`cinema/${id}`)
const requestParams = {
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) {
setFilmNameEdit(data.name);
setCurrEditItem(data.id);
@ -49,12 +74,20 @@ export default function Films() {
};
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = (e) => {
const handleSubmitCreate = async (e) => {
e.preventDefault(); // страница перестает перезагружаться
const itemObject = new CinemaDto(selectedImage, filmName);
console.info('Try to add item');
Service.create('cinema', itemObject)
const requestParams = {
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) => {
setItems([...items, data]);
@ -66,14 +99,23 @@ export default function Films() {
throw "Can't add item";
});
};
// принимаем событие от кнопки "сохранить изменения"
const handleSubmitEdit = (e, id) => {
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
e.preventDefault(); // страница перестает перезагружаться
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) => {
setItems(
items.map(item =>
@ -95,83 +137,88 @@ export default function Films() {
fileReader.onloadend = () => (
setSelectedImage(fileReader.result)
)
function changePicture(e) {
e.preventDefault();
const file = e.target.files[0]
fileReader.readAsDataURL(file)
}
function handleAddFilmToWillSee(data) {
const elem = CinemaDto.createFrom(data)
Service.create('willSee/', data)
}
// форма для добавления данных
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">
<label className="form-label" htmlFor="filmPicture">Изображение</label>
<input required className="form-control" name="filmPicture" id="filmPicture"
type="file"
onChange={changePicture} />
</div>
<div className="col">
<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="Введите название" />
</div>
<div className="form-check mx-2">
<input required className="form-check-input" name="film16" id="film16" type="checkbox" />
<label className="form-check-label" htmlFor="film16">Мне уже 16 лет</label>
<div className="invalid-feedback">Подтвердите, что вам уже есть 16 лет</div>
</div>
<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>
</div>
</form>
)
const Content = (
<div>
{Form}
<hr className="border border-0 bg-black" />
{(localStorage.getItem("role") === 'ADMIN') &&
<form className="row g-3 fs-4 description fw-bold needs-validation-content" id="frm-items"
onSubmit={handleSubmitCreate}>
<div className="col-md-3">
<label className="form-label" htmlFor="filmPicture">Изображение</label>
<input required className="form-control" name="filmPicture" id="filmPicture"
type="file"
onChange={changePicture}/>
</div>
<div className="col">
<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="Введите название"/>
</div>
<div className="form-check mx-2">
<input required className="form-check-input" name="film16" id="film16" type="checkbox"/>
<label className="form-check-label" htmlFor="film16">Мне уже 16 лет</label>
<div className="invalid-feedback">Подтвердите, что вам уже есть 16 лет</div>
</div>
<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>
</div>
</form>}
<hr className="border border-0 bg-black"/>
<table className="table" id="tbl-items">
<tbody>
{items.map((item) =>
<FilmItem
item={item}
key={item.id}
removeFunc={handleDeleteFilm}
editFunc={handleEditFilm}
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
/>
)}
{items.map((item) =>
<FilmItem
item={item}
key={item.id}
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDeleteFilm : null}
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEditFilm : null}
openFilmPageFunc={(index) => navigate(`/films/${index}`)}
/>
)}
</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)}>
{(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)}>
<div className="row">
<label className="form-label" htmlFor="filmPictureEdit">Изображение</label>
<input required className="form-control" name="filmPictureEdit" id="filmPictureEdit"
type="file"
onChange={changePicture} />
type="file"
onChange={changePicture}/>
</div>
<div className="row">
<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 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>
<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>
</ModalEdit>}
</div>
);
return (
<div>
<Banner />
<ContentBlock valueBlock={Content} title='Фильмы' />
<Banner/>
<ContentBlock valueBlock={Content} title='Фильмы'/>
</div>
)
}

View File

@ -1,4 +1,4 @@
import { React, useState, useEffect } from 'react'
import {useEffect, useState} from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
@ -12,33 +12,37 @@ export default function Orders() {
const [currEditItem, setCurrEditItem] = useState(0);
// для выпадающих значений
const [customerName, setCustomerName] = useState('');
const [customer, setCustomer] = useState([]);
const [sessionName, setSessionName] = useState('');
const [count, setCount] = useState(1);
const [session, setSession] = useState([]);
const [orderSessions, setOrderSessions] = useState([]);
useEffect(() => {
getAll('customer').then((data) => setCustomer(data))
const user = localStorage.getItem('user')
setCustomerName(user)
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) {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl)
const result = await response.json()
return result
const response = await fetch(requestUrl, requestParams)
return await response.json()
}
function handleSubmit(e) {
e.preventDefault();
if (customer.length <= 0) {
throw 'Form not submit'
}
handleSubmitCreate(e)
console.log('Form submit')
setCustomer('')
}
// принимаем событие от кнопки "добавить"
@ -49,13 +53,13 @@ export default function Orders() {
const requestParams = {
method: "POST",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
await fetch(`http://localhost:8080/order?customer=${customerName}`, requestParams)
.then((data) => {
getCustomerOrders(customerName)
getAll('customer').then((data) => setCustomer(data))
await fetch(`http://localhost:8080/order/${customerName}`, requestParams)
.then(() => {
getAll(`customer?login=${customerName}`).then((data) => setUsers(data.orders))
})
.catch(function (error) {
console.error('Error:', error);
@ -65,15 +69,14 @@ export default function Orders() {
function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`order/${id}`)
getAll(`order/${id}`)
.then(function (data) {
setCurrEditItem(data.id);
setOrderSessions(data.sessions)
setModalTable(true)
console.info('End edit script');
})
};
}
const handleSubmitAdd = async (e, id) => {
console.info('Start add session');
@ -81,6 +84,7 @@ export default function Orders() {
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
@ -103,6 +107,7 @@ export default function Orders() {
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"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');
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(() => {
setUsers(users.filter(elem => elem.id !== id))
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) {
@ -141,6 +145,7 @@ export default function Orders() {
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
@ -158,15 +163,6 @@ export default function Orders() {
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">
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Добавить</button>
@ -174,63 +170,72 @@ export default function Orders() {
</form>
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Customer</th>
<th scope="col">DateOfPurchase</th>
<th scope="col"></th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">Customer</th>
<th scope="col">DateOfPurchase</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<OrderItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}
/>
))}
{users.map((user) => (
<OrderItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}
/>
))}
</tbody>
</table>
<ModalEdit visible={modalTable} setVisible={setModalTable}>
<form className="fs-4 description fw-bold d-flex flex-column align-items-center" id="frm-items-edit">
<div className="col-6">
<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>
{session ? session.map(elem =>
<option key={elem.id} value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
) : null}
{session && session.map(elem =>
<option key={elem.id}
value={elem.id}>{elem.cinema.name} {new Date(elem.timestamp).toLocaleString('RU-ru')}</option>
)}
</select>
</div>
<div className="col-6">
<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 className="text-center mt-3">
<button className="btn btn-success mx-1" type="button" onClick={e => handleSubmitAdd(e, currEditItem)}>Добавить</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>
<button className="btn btn-success mx-1" type="button"
onClick={e => handleSubmitAdd(e, currEditItem)}>Добавить
</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>
<p>Мои сеансы</p>
<table className="table fs-6 table-bordered" id="tbl-items">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Count</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
{orderSessions ? orderSessions.map((item) =>
<OrderSessionItem
item={item}
key={parseInt(item.sessionId+''+item.orderId)}
removeFunc={e => handleDeleteOrderSession(e, currEditItem, item.sessionId)}
/>
) : null}
{orderSessions && orderSessions.map((item) =>
<OrderSessionItem
item={item}
key={parseInt(item.sessionId + '' + item.orderId)}
removeFunc={e => handleDeleteOrderSession(e, currEditItem, item.session.id)}
/>
)}
</tbody>
</table>
</form>
@ -239,6 +244,6 @@ export default function Orders() {
)
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='Заказы'/>
)
}

View File

@ -1,36 +1,23 @@
import { React, useState, useEffect } from 'react'
import {useState, useEffect} from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
import MyButton from './components/MyButton';
import UserItem from './components/UserItem';
import {useNavigate} from "react-router-dom";
export default function Registration() {
const hostURL = "http://localhost:8080";
const navigate = useNavigate();
const [login, setLogin] = useState('');
const [password, setPassword] = useState('');
const [loginEdit, setLoginEdit] = useState('');
const [passwordEdit, setPasswordEdit] = useState('');
const [users, setUsers] = useState([]);
const [passwordConfirm, setPasswordConfirm] = useState('');
const [error, setError] = useState(false);
const [modalTable, setModalTable] = useState(false);
// хук для запоминания индекса элемента, вызвавшего модальное окно
const [currEditItem, setCurrEditItem] = useState(0);
useEffect(() => {
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) {
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)
throw 'Form not submit'
}
@ -39,131 +26,93 @@ export default function Registration() {
setError(false)
setLogin('')
setPassword('')
setPasswordConfirm('')
}
// принимаем событие от кнопки "добавить"
const handleSubmitCreate = async (e) => {
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 = {
method: "POST",
headers: {
"Content-Type": "application/json"
}
"Content-Type": "application/json",
},
body: requestData,
};
await fetch(`http://localhost:8080/customer?login=${login}&password=${password}`, requestParams)
.then(() => {
getAll()
})
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);
};
function handleEdit(id) {
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(); // страница перестает перезагружаться
async function getRole(token) {
// вызываем поиск пользователя по токену
const requestParams = {
method: "PUT",
method: "GET",
headers: {
"Content-Type": "application/json"
}
"Content-Type": "application/json",
},
};
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 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 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>
<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>
{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>
<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>
{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>
<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>
</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 (
<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' ? 'Регистрация' : 'Вход'}/>
)
}

View File

@ -1,4 +1,4 @@
import { React, useState, useEffect } from 'react'
import {React, useState, useEffect} from 'react'
import ContentBlock from './components/ContentBlock'
import Service from './services/Service';
import ModalEdit from './components/ModalEdit';
@ -18,7 +18,9 @@ export default function Sessions() {
// для выпадающих значений
const [cinemaName, setCinemaName] = useState('');
const [cinema, setCinema] = useState([]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
useEffect(() => {
setError(false)
getAll('cinema').then((data) => setCinema(data))
@ -26,10 +28,12 @@ export default function Sessions() {
}, [])
async function getAll(elem) {
const requestParams = {
method: "GET"
};
const requestUrl = `http://localhost:8080/${elem}`
const response = await fetch(requestUrl)
const result = await response.json()
return result
const response = await fetch(requestUrl, requestParams)
return await response.json()
}
function handleSubmit(e) {
@ -66,17 +70,24 @@ export default function Sessions() {
});
};
function handleEdit(id) {
async function handleEdit(id) {
console.info(`Start edit script`);
Service.read(`session/${id}`)
const requestParams = {
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) {
setPriceEdit(data.price);
setCurrEditItem(data.id);
setModalTable(true)
console.info('End edit script');
})
};
}
const handleSubmitEdit = async (e, id) => {
console.info('Start synchronize edit');
@ -84,6 +95,7 @@ export default function Sessions() {
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json"
}
};
@ -106,86 +118,113 @@ export default function Sessions() {
});
};
function handleDelete(id) {
async function handleDelete(id) {
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(() => {
setUsers(users.filter(elem => elem.id !== id))
console.log("Removed")
})
.catch((error) => {
console.error('Error:', error);
});
};
}
const Content = (
<>
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
<div>
<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="Введите цену" />
</div>
{error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Фильм</label>
<select required className="form-select" name="filmCountry" id="filmCountry" value={cinema.value} onChange={e => setCinemaName(e.target.value)} >
<option value='' defaultValue disabled>Выберите значение</option>
{cinema ? cinema.map(elem =>
<option key={elem.id} value={elem.id}>{elem.name}</option>
) : null }
</select>
</div>
{error && cinema.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод фильма</label> : null}
<div>
<label className="form-label">Кол-во сеансов</label>
<input className="form-control mainInput" min="1" type="number" value={maxCount} onChange={e => setMaxCount(e.target.value)} placeholder="Введите количество" />
</div>
{error && price.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Дата</label>
<input className="form-control mainInput" type="datetime-local" value={timestamp} onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату" />
</div>
{error && timestamp.length <= 0 ? <label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
</div>
</form>
{(localStorage.getItem("role") === 'ADMIN') &&
<form className="d-flex flex-column fs-4 fw-bold text-white text-center align-items-center">
<div>
<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="Введите цену"/>
</div>
{error && price.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Фильм</label>
<select required className="form-select" name="filmCountry" id="filmCountry"
value={cinema.value} onChange={e => setCinemaName(e.target.value)}>
<option value='' defaultValue disabled>Выберите значение</option>
{cinema ? cinema.map(elem =>
<option key={elem.id} value={elem.id}>{elem.name}</option>
) : null}
</select>
</div>
{error && cinema.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод фильма</label> : null}
<div>
<label className="form-label">Кол-во сеансов</label>
<input className="form-control mainInput" min="1" type="number" value={maxCount}
onChange={e => setMaxCount(e.target.value)} placeholder="Введите количество"/>
</div>
{error && price.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод цены</label> : null}
<div>
<label className="form-label">Дата</label>
<input className="form-control mainInput" type="datetime-local" value={timestamp}
onChange={e => setTimestamp(e.target.value)} placeholder="Введите дату"/>
</div>
{error && timestamp.length <= 0 ?
<label className="fs-6 text-danger">Неправильный ввод даты</label> : null}
<div>
<button className="btn btn-success my-3" type="button" onClick={handleSubmit}>Сохранить</button>
</div>
</form>}
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Capacity</th>
<th scope="col">MaxCount</th>
<th scope="col"></th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">Price</th>
<th scope="col">Cinema</th>
<th scope="col">Timestamp</th>
<th scope="col">Capacity</th>
<th scope="col">MaxCount</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="tbody">
{users.map((user) => (
<SessionItem
item={user}
key={user.id}
editFunc={handleEdit}
removeFunc={handleDelete}
/>
))}
{users.map((user) => (
<SessionItem
item={user}
key={user.id}
editFunc={(localStorage.getItem("role") === 'ADMIN') ? handleEdit : null}
removeFunc={(localStorage.getItem("role") === 'ADMIN') ? handleDelete : null}
/>
))}
</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)}>
{(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)}>
<div className="row">
<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 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>
<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>
</ModalEdit>}
</>
)
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='Сеансы'/>
)
}

181
front/src/pages/Users.jsx Normal file
View 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='Вход'/>
)
}

View File

@ -1,12 +1,64 @@
import { React, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import searchImage from '../../images/search.jpg'
import {useEffect, useState} from 'react'
import {useNavigate, Link} from 'react-router-dom'
import '../../styles/styleHeader.css'
import searchImage from '../../images/search.jpg'
export default function Header() {
export default function Header(props) {
const navigate = useNavigate();
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) {
console.info('Try to search data');
@ -15,25 +67,62 @@ export default function Header() {
setSearchName('');
}
const handleSubmitLogout = function () {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
// вызвали событие
window.dispatchEvent(new Event("storage"));
}
return (
<div>
<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">
<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>
</button>
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
<div id="main"> <a onClick={() => navigate("/films")} className="text-decoration-none mx-5" style={{ cursor: "pointer" }}>Главная</a></div>
<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="Введите название" />
<button className="border border-0 p-0 ms-2" type="submit"><img className="icon" src={searchImage} alt="Поиск" /></button>
<div className="collapse navbar-collapse menu" id="navbarNav">
<ul className="navbar-nav">
{
props.links.map((route) => (
<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>
<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>
</nav>

View 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;

View File

@ -69,4 +69,15 @@ a:hover {
.fs-1 {
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;
}

View File

@ -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")));
}
}

View File

@ -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();
}
}

View File

@ -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");
}
}

View File

@ -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.WebServerFactoryCustomizer;
@ -7,29 +7,25 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
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.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
// Alternative way (404 error hits the console):
// > registry.addViewController("/notFound").setViewName("forward:/index.html");
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
};
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}
}

View File

@ -1,7 +1,9 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.UserRole;
import com.labwork1.app.student.service.CinemaService;
import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -35,16 +37,19 @@ public class CinemaController {
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public CinemaDto createCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.addCinema(cinemaDto));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CinemaDto updateCinema(@RequestBody @Valid CinemaDto cinemaDto) {
return new CinemaDto(cinemaService.updateCinema(cinemaDto));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CinemaDto deleteCinema(@PathVariable Long id) {
return new CinemaDto(cinemaService.deleteCinema(id));
}

View File

@ -1,45 +1,90 @@
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.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 java.util.List;
import java.util.stream.IntStream;
@RestController
@RequestMapping("/customer")
public class CustomerController {
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) {
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) {
return new CustomerDto(customerService.findCustomer(id));
}
@GetMapping
public List<CustomerDto> getCustomers() {
return customerService.findAllCustomers().stream()
.map(CustomerDto::new)
@GetMapping(URL_MAIN)
public CustomerDto getCustomerByLogin(@RequestParam("login") String login) {
return new CustomerDto(customerService.findByLogin(login));
}
@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();
return Pair.of(users, pageNumbers);*/
final Page<CustomerDto> users = customerService.findAllPages(page, size)
.map(CustomerDto::new);
return users;
}
@PostMapping
public CustomerDto createCustomer(@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.addCustomer(login, password));
}
@PutMapping("/{id}")
@PutMapping(URL_MAIN + "/{id}")
@Secured({UserRole.AsString.ADMIN})
public CustomerDto updateCustomer(@PathVariable Long id,
@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.updateCustomer(id, login, password));
@RequestBody @Valid CustomerDto userDto) {
return new CustomerDto(customerService.updateCustomer(id, userDto.getLogin(), userDto.getPassword()));
}
@DeleteMapping("/{id}")
@DeleteMapping(URL_MAIN + "/{id}")
public CustomerDto deleteCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}

View File

@ -26,8 +26,8 @@ public class OrderController {
.toList();
}
@PostMapping
public OrderDto createOrder(@RequestParam("customer") Long customer) {
@PostMapping("/{customer}")
public OrderDto createOrder(@PathVariable String customer) {
return new OrderDto(orderService.addOrder(customer));
}

View File

@ -1,6 +1,10 @@
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 org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
@ -31,6 +35,7 @@ public class SessionController {
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public SessionDto createSession(@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp,
@RequestParam("cinemaid") Long cinemaId,
@ -44,6 +49,7 @@ public class SessionController {
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public SessionDto updateSession(@PathVariable Long id,
@RequestParam("price") String price) {
return new SessionDto(sessionService.findSession(sessionService
@ -51,8 +57,8 @@ public class SessionController {
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public SessionDto deleteSession(@PathVariable Long id) {
return new SessionDto(sessionService.deleteSession(id));
}
}

View File

@ -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;
}
}

View File

@ -2,6 +2,7 @@ package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
@ -12,12 +13,17 @@ public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank(message = "login can't be null or empty")
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank(message = "password can't be null or empty")
@Size(min = 6, max = 64)
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = {CascadeType.MERGE,CascadeType.REMOVE})
private List<Order> orders;
private UserRole role;
public Customer() {
}
@ -26,6 +32,14 @@ public class Customer {
this.login = login;
this.password = password;
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
@ -50,6 +64,10 @@ public class Customer {
'}';
}
public UserRole getRole() {
return role;
}
public Long getId() {
return id;
}

View 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";
}
}

View File

@ -8,4 +8,5 @@ import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Customer findOneByLoginIgnoreCase(String login);
}

View File

@ -4,4 +4,7 @@ public class CustomerNotFoundException extends RuntimeException {
public CustomerNotFoundException(Long 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));
}
}

View File

@ -1,29 +1,94 @@
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.UserRole;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidationException;
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.transaction.annotation.Transactional;
import com.labwork1.app.configuration.jwt.JwtException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class CustomerService {
public class CustomerService implements UserDetailsService {
private final CustomerRepository customerRepository;
private final PasswordEncoder passwordEncoder;
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.passwordEncoder = passwordEncoder;
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
public Customer addCustomer(String login, String password) {
final Customer customer = new Customer(login, password);
validatorUtil.validate(customer);
return customerRepository.save(customer);
public Customer addCustomer(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
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)
@ -41,7 +106,7 @@ public class CustomerService {
public Customer updateCustomer(Long id, String login, String password) {
final Customer currentCustomer = findCustomer(id);
currentCustomer.setLogin(login);
currentCustomer.setPassword(password);
currentCustomer.setPassword(passwordEncoder.encode(password));
validatorUtil.validate(currentCustomer);
return customerRepository.save(currentCustomer);
}

View File

@ -34,6 +34,15 @@ public class OrderService {
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
public Order addSession(Long id, Long sessionId, Integer count) {
final Session currentSession = sessionService.findSession(sessionId);

View File

@ -10,6 +10,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
@Service
public class SessionService {
@ -38,6 +39,12 @@ public class SessionService {
.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)
public List<SessionExtension> findAllSessions() {
return sessionRepository.getSessionsWithCapacity();
@ -45,7 +52,7 @@ public class SessionService {
@Transactional
public Session updateSession(Long id, Double price) {
final Session currentSession = findSession(id);
final Session currentSession = findBaseSession(id);
currentSession.setPrice(price);
validatorUtil.validate(currentSession);
return sessionRepository.save(currentSession);
@ -53,7 +60,7 @@ public class SessionService {
@Transactional
public Session deleteSession(Long id) {
final Session currentSession = findSession(id);
final Session currentSession = findBaseSession(id);
// все равно сеанс не удалился бы, который участвует в заказах
// для отслеживания операции с ошибкой
if (currentSession.getOrders().size() > 0)

View File

@ -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));
}
}

View File

@ -3,6 +3,10 @@ package com.labwork1.app.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}

View File

@ -7,4 +7,6 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
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

View File

@ -1,129 +1,129 @@
package com.labwork1.app;
import com.labwork1.app.student.model.*;
import com.labwork1.app.student.service.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.Timestamp;
import java.util.List;
@SpringBootTest
public class JpaCustomerTests {
private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
@Autowired
private CustomerService customerService;
@Autowired
private SessionService sessionService;
@Autowired
private OrderService orderService;
@Autowired
private CinemaService cinemaService;
@Test
void testOrder() {
sessionService.deleteAllSessions();
cinemaService.deleteAllCinemas();
orderService.deleteAllOrders();
customerService.deleteAllCustomers();
// 2 кино
final Cinema cinema1 = cinemaService.addCinema("Меню");
final Cinema cinema2 = cinemaService.addCinema("Аватар");
// 2 сеанса
final Session session1 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
final Session session2 = sessionService.addSession( 200.0,
new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
// проверка 2 сеанса у 1 кино
Assertions.assertEquals(cinemaService
.findCinema(cinema1.getId()).getSessions().size(), 2);
// 1 покупатель
final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
// 1 заказ, 1 копия заказа
final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId());
final Order order1 = orderService.findOrder(order0.getId());
Assertions.assertEquals(order0, order1);
// у клиента точно есть заказ?
Assertions.assertEquals(customerService
.findCustomer(customer1.getId()).getOrders().size(), 1);
// 0 заказов
orderService.deleteAllOrders();
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
// 2 покупателя
final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
// 1 заказ
final Order order2 = orderService
.addOrder(customerService.findCustomer(customer2.getId()).getId());
// у заказа 2 сеанса
orderService.addSession(order2.getId(), session1.getId(), 2);
List<SessionExtension> result = sessionService.findAllSessions();
Assertions.assertEquals(sessionService.getCapacity(session1.getId()), 2);
orderService.addSession(order2.getId(), session2.getId(), 5);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 5);
Assertions.assertThrows(IllegalArgumentException.class, () ->
orderService.addSession(order2.getId(), session2.getId(), 6));
// у заказа 1 сеанс
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 10);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
// заполнили всю 2 сессию
orderService.addSession(order2.getId(), session2.getId(), 10);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 4);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 6);
orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 6);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().size(), 1);
Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().get(0).getId().getSessionId(), session1.getId());
// у заказа 1 сеанс
// 3 сеанса всего
final Session session3 = sessionService.addSession(300.0,
new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
// удалили заказ2, у которого был сеанс1
orderService.deleteOrder(order2.getId());
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// создали 3 заказ у 2 покупателя
final Order order3 = orderService
.addOrder(customerService.findCustomer(customer2.getId()).getId());
orderService.addSession(order3.getId(), session2.getId(), 2);
orderService.addSession(order3.getId(), session3.getId(), 8);
orderService.addSession(order3.getId(), session1.getId(), 8);
// 2-ой покупатель удален
// 0 заказов после его удаления
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
customerService.deleteCustomer(customer2.getId());
Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
Assertions.assertEquals(sessionService.getCapacity(session3.getId()), 0);
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
cinemaService.deleteCinema(cinema2.getId());
Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
}
}
//package com.labwork1.app;
//
//import com.labwork1.app.student.model.*;
//import com.labwork1.app.student.service.*;
//import org.junit.jupiter.api.Assertions;
//import org.junit.jupiter.api.Test;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//
//import java.sql.Timestamp;
//import java.util.List;
//
//@SpringBootTest
//public class JpaCustomerTests {
// private static final Logger log = LoggerFactory.getLogger(JpaCustomerTests.class);
// @Autowired
// private CustomerService customerService;
// @Autowired
// private SessionService sessionService;
// @Autowired
// private OrderService orderService;
// @Autowired
// private CinemaService cinemaService;
//
// @Test
// void testOrder() {
// sessionService.deleteAllSessions();
// cinemaService.deleteAllCinemas();
// orderService.deleteAllOrders();
// customerService.deleteAllCustomers();
// // 2 кино
// final Cinema cinema1 = cinemaService.addCinema("Меню");
// final Cinema cinema2 = cinemaService.addCinema("Аватар");
//
// // 2 сеанса
// final Session session1 = sessionService.addSession(300.0,
// new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
// final Session session2 = sessionService.addSession( 200.0,
// new Timestamp(System.currentTimeMillis()), cinema1.getId(), 10);
//
// // проверка 2 сеанса у 1 кино
// Assertions.assertEquals(cinemaService
// .findCinema(cinema1.getId()).getSessions().size(), 2);
// // 1 покупатель
// final Customer customer1 = customerService.addCustomer("Родион", "Иванов");
// customerService.updateCustomer(customer1.getId(), "Пчел", "Пчелов");
// Assertions.assertEquals(customerService.findCustomer(customer1.getId()).getLogin(), "Пчел");
// // 1 заказ, 1 копия заказа
// final Order order0 = orderService.addOrder(customerService.findCustomer(customer1.getId()).getId());
// final Order order1 = orderService.findOrder(order0.getId());
// Assertions.assertEquals(order0, order1);
//
// // у клиента точно есть заказ?
// Assertions.assertEquals(customerService
// .findCustomer(customer1.getId()).getOrders().size(), 1);
// // 0 заказов
// orderService.deleteAllOrders();
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
// // 2 покупателя
// final Customer customer2 = customerService.addCustomer("Иннокентий", "Иванов");
//
// // 1 заказ
// final Order order2 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId());
// // у заказа 2 сеанса
// orderService.addSession(order2.getId(), session1.getId(), 2);
//
// List<SessionExtension> result = sessionService.findAllSessions();
//
// Assertions.assertEquals(sessionService.getCapacity(session1.getId()), 2);
//
// orderService.addSession(order2.getId(), session2.getId(), 5);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 5);
//
// Assertions.assertThrows(IllegalArgumentException.class, () ->
// orderService.addSession(order2.getId(), session2.getId(), 6));
//
// // у заказа 1 сеанс
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 10);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
// // заполнили всю 2 сессию
// orderService.addSession(order2.getId(), session2.getId(), 10);
//
// Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
//
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 4);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 6);
// orderService.deleteSessionInOrder(order2.getId(), session2.getId(), 6);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
//
// Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().size(), 1);
// Assertions.assertEquals(orderService.findOrder(order2.getId()).getSessions().get(0).getId().getSessionId(), session1.getId());
//
// // у заказа 1 сеанс
// // 3 сеанса всего
// final Session session3 = sessionService.addSession(300.0,
// new Timestamp(System.currentTimeMillis()), cinema2.getId(), 10);
// // удалили заказ2, у которого был сеанс1
// orderService.deleteOrder(order2.getId());
// Assertions.assertEquals(orderService.findAllOrders().size(), 0);
// Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
//
// // создали 3 заказ у 2 покупателя
// final Order order3 = orderService
// .addOrder(customerService.findCustomer(customer2.getId()).getId());
// orderService.addSession(order3.getId(), session2.getId(), 2);
// orderService.addSession(order3.getId(), session3.getId(), 8);
// orderService.addSession(order3.getId(), session1.getId(), 8);
// // 2-ой покупатель удален
// // 0 заказов после его удаления
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 2);
// customerService.deleteCustomer(customer2.getId());
//
// Assertions.assertThrows(CustomerNotFoundException.class, () -> customerService.findCustomer(customer2.getId()));
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(order3.getId()));
// Assertions.assertEquals(orderService.findAllOrders().size(), 0);
// Assertions.assertEquals(sessionService.getCapacity(session2.getId()), 0);
// Assertions.assertEquals(sessionService.getCapacity(session3.getId()), 0);
//
// Assertions.assertEquals(cinemaService.findAllCinemas().size(), 2);
// Assertions.assertEquals(sessionService.findAllSessions().size(), 3);
// // у синема1 1 и 2 сеанс, у синема2 3 сеанс. он удален
// cinemaService.deleteCinema(cinema2.getId());
// Assertions.assertEquals(cinemaService.findAllCinemas().size(), 1);
// Assertions.assertEquals(sessionService.findAllSessions().size(), 2);
// }
//}