Compare commits

..

19 Commits

Author SHA1 Message Date
262aa33c21 правки 2023-07-11 18:58:01 +04:00
df9c01f3c2 Добавил отчёты 2023-05-24 13:33:36 +04:00
Katerina881
1f4e80cc2b fix 2023-05-15 15:47:28 +04:00
Katerina881
9f428fa251 fix 2023-05-15 14:04:15 +04:00
69a18d420b image 2023-05-14 22:04:04 +04:00
29605e7fbe сделал красиво, не тестил, скорее всего сломается 2023-05-11 17:18:01 +04:00
b468a84b1a поменял на ласт версию спринга 2023-05-11 16:52:19 +04:00
1317a2824d добавленна проверка по логину 2023-05-11 16:29:35 +04:00
b5c2db3e02 теперь вместо id login 2023-05-11 16:09:51 +04:00
0a6ba9f820 подропал не юзаемые методы 2023-05-01 19:00:36 +04:00
728b166be0 думаю на этом всё, осталось сделать реакт 2023-05-01 18:55:32 +04:00
8f17dd6365 fix 2023-05-01 18:17:44 +04:00
47c87e6e8a работает осталось сделать код менее уродливым и мб добавить некоторый дополнительный функцианал 2023-05-01 15:26:09 +04:00
70f597fac8 осталось ограничить функцианал 2023-05-01 14:45:13 +04:00
ee2f2cd7df теперь пользователь и создатель объедененны и можно использовать старый функционал 2023-05-01 13:48:06 +04:00
0463cef7fa связал юзера с создателем, нужно будет пофиксить код, так как из создателя убрал логин и пароль 2023-05-01 12:38:20 +04:00
182427a9cf fix 2023-05-01 12:33:42 +04:00
306ce2350d ещё нужно объеденить юзера с читателем и создателем, а потом разграничить их возможности 2023-05-01 12:16:06 +04:00
ba86843ae3 Можно работать 2023-04-30 23:37:07 +04:00
89 changed files with 1126 additions and 8251 deletions

View File

@ -15,21 +15,24 @@ jar {
enabled = false
}
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-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
//implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

26
front/.gitignore vendored
View File

@ -1,26 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.parcel-cache

View File

@ -1,58 +0,0 @@
import com.github.gradle.node.util.PlatformHelper
import groovy.text.SimpleTemplateEngine
plugins {
id 'java'
id 'com.github.node-gradle.node' version '3.5.1'
id "de.undercouch.download" version '5.3.1'
}
node {
version = '18.15.0'
download = true
}
jar.dependsOn 'npmBuild'
clean.dependsOn 'npmClean'
nodeSetup.dependsOn 'downloadNode'
jar {
from 'dist'
into 'static'
final devHost = 'http://localhost:8080'
final prodHost = ''
filesMatching('index.html') {
filter { line -> line.replaceAll(devHost, prodHost) }
}
}
task downloadNode(type: Download) {
final helper = new PlatformHelper()
final templateData = [
"url" : node.distBaseUrl.get(),
"version": node.version.get(),
"os" : helper.osName,
"arch" : helper.osArch,
"ext" : helper.windows ? 'zip' : 'tar.gz'
]
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
final engine = new SimpleTemplateEngine()
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
final String destDir = '.gradle/'
file(destDir).mkdirs()
src url
dest destDir
overwrite false
}
tasks.register('npmBuild', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'build']
}
tasks.register('npmClean', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'clean']
}

View File

@ -1,16 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="module" src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<title>ReManga</title>
</head>
<body >
<div id="app" class="d-flex flex-column h-100" ></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

3026
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +0,0 @@
{
"name": "front",
"version": "1.0.0",
"source": "index.html",
"scripts": {
"start": "parcel --port 3000",
"build": "npm run clean && parcel build",
"clean": "rimraf dist"
},
"dependencies": {
"bootstrap": "5.3.0-alpha2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8",
"parcel": "2.8.3",
"process": "^0.11.10",
"rimraf": "4.4.0"
}
}

View File

@ -1,49 +0,0 @@
import { Routes, BrowserRouter, Route } from 'react-router-dom';
import Header from './components/Header';
import CreatorAction from './Main/CreatorAction';
import ReaderAction from './Main/ReaderAction';
import UsersPage from './Main/UsersPage';
import Catalog from './Main/Catalog';
import LoginPage from './Main/LoginPage';
import SingupPage from './Main/SingupPage';
import PrivateRoutes from "./components/PrivateRoutes";
import MangaPage from "./Main/MangaPage";
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const links = [
{ path: 'catalog', label: "Catalog", userGroup: "AUTH" },
{ path: 'readerAction', label: "ReaderAction", userGroup: "USER" },
{ path: 'creatorAction', label: "CreatorAction", userGroup: "ADMIN" },
{ path: 'users', label: "Users", userGroup: "ADMIN" }
];
return (
<>
<BrowserRouter>
<Header links={links}></Header>
<div className="content-div">
<Routes>
<Route element={<LoginPage />} path="/login" />
<Route element={<SingupPage />} path="/singup" />
<Route element={<PrivateRoutes userGroup="AUTH" />}>
<Route element={<MangaPage />} path="/mangapage" />
<Route element={<Catalog />} path="/catalog" />
<Route element={<Catalog />} path="*" />
</Route>
<Route element={<PrivateRoutes userGroup="USER" />}>
<Route element={<ReaderAction />} path="/readerAction" />
</Route>
<Route element={<PrivateRoutes userGroup="ADMIN" />}>
<Route element={<UsersPage />} path="/users" />
<Route element={<CreatorAction />} path="/creatorAction" />
</Route>
</Routes>
</div>
</BrowserRouter>
</>
);
}

View File

@ -1,9 +0,0 @@
export default class MangaDto {
constructor(args) {
this.id = args.id || null;
this.creatorId = args.creatorId || 0;
this.mangaName = args.mangaName || "";
this.image = args.image;
this.chapterCount = args.chapterCount || 0;
}
}

View File

@ -1,8 +0,0 @@
export default class UserSignupDto {
constructor(args) {
this.login = args.login;
this.email = args.email;
this.password = args.password;
this.passwordConfirm = args.passwordConfirm;
}
}

View File

@ -1,47 +0,0 @@
import React, { useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom';
export default function Catalog() {
const host = "http://localhost:8080/api/1.0";
const [mangs, setMangs] = useState([]);
useEffect(() => {
getMangs()
.then(_data =>setMangs(_data));
console.log(2);
console.log(mangs);
},[]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const getMangs = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + "/manga", requestParams);
const _data = await response.json()
console.log(_data);
return _data;
}
return (
<article className="p-2 catalog_article">
<div className = "catalog_wrapper">
<h1>Каталог</h1>
<div className="p-2 d-flex flex-wrap">
{mangs.map((manga, index) => (
<NavLink key={manga.id} to={`/mangapage?id=${manga.id}`}><img src={manga.image} alt={manga.mangaName} className="slideshow"/></NavLink>
))}
</div>
</div>
</article>
);
}

View File

@ -1,213 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../components/Table/TableCreator';
import MangaDto from "../Dto/Manga-Dto";
import MangaCreatorList from "../components/List/MangaCreatorList";
import AddMangaModal from "../components/Modal/AddMangaModal";
import EditMangaModal from "../components/Modal/EditMangaModal";
export default function CreatorAction() {
const host = "http://localhost:8080/api/1.0";
const [creatorData, setCreatorData] = useState([]);
const [creator, setCreator] = useState([]);
const [mangaId, setMangaId] = useState(0);
const [chapterCount, setChapterCount] = useState(0);
const [mangaName, setMangaName] = useState("");
const [mangaModel, setMangaModel] = useState(new MangaDto({}));
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
/* useEffect(() => {
getCreatorData()
.then(_data =>setCreatorData(_data));
},[]);*/
useEffect(() => {
getCreator().then(_data => {
setCreator(_data)
console.log(_data);
});
}, []);
const getCreator = async function () {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
let login = localStorage.getItem("user");
console.log(host + `/creator/` + login);
const response = await fetch(host + `/creator/` + login, requestParams);
const _data = await response.json()
return _data;
}
const getCreatorData = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + "/creator", requestParams);
console.log(response);
const _data = await response.json()
return _data;
}
const updateButton = (e) =>{
e.preventDefault();
update().then((result) => {
alert(`Manga[id=${result.id}, mangaName=${result.mangaName}, chapterCount=${result.chapterCount}]`);
getCreator(creator.id)
.then(_data =>setCreator(_data));
});
}
const update = async function (){
console.info('Try to update item');
if (mangaId === 0) {
return;
}
mangaModel.id = mangaId;
mangaModel.chapterCount = chapterCount;
mangaModel.creatorId = creator.id;
mangaModel.image = imageURL;
mangaModel.mangaName = mangaName;
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
},
body: JSON.stringify(mangaModel),
};
const response = await fetch(host + `/manga/` + mangaModel.id, requestParams);
return await response.json();
}
const setMangaIdButton = (id) =>{
setMangaId(id);
}
const removeButton = (id) =>{
remove(id).then(() => {
getCreator(creator.id)
.then(_data =>setCreator(_data));
});
}
const remove = async function (id){
console.info('Try to remove item');
if (id !== 0) {
if (!confirm('Do you really want to remove this item?')) {
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/manga/` + id, requestParams);
}
const createButton = (e) =>{
e.preventDefault()
create().then((result) => {
alert(`Manga[id=${result.id}, mangaName=${result.mangaName}, chapterCount=${result.chapterCount}]`);
getCreator(creator.id)
.then(_data =>setCreator(_data));
});
}
const create = async function (){
mangaModel.chapterCount = chapterCount;
mangaModel.creatorId = creator.id;
mangaModel.image = imageURL;
mangaModel.mangaName = mangaName;
console.log(mangaModel);
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
},
body: JSON.stringify(mangaModel),
};
const response = await fetch(host + `/manga`, requestParams);
return await response.json();
}
const [imageURL, setImageURL] = useState();
const fileReader = new FileReader();
fileReader.onloadend = () => {
setImageURL(fileReader.result);
};
const handleOnChange = (event) => {
event.preventDefault();
if (event.target.files && event.target.files.length) {
const file = event.target.files[0];
fileReader.readAsDataURL(file);
}
};
return (
<main>
<div className="container" id="root-div">
<div className="content">
<h1>Creator</h1>
<form id="form">
<div className="d-flex mt-3">
<div className="d-grid col-sm-2">
<button type="button" className="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal2">Добавить</button>
</div>
</div>
</form>
<MangaCreatorList
creator={creator}
setMangaIdButton={setMangaIdButton}
removeButton={removeButton}
/>
<EditMangaModal
chapterCount={chapterCount}
setChapterCount={setChapterCount}
handleOnChange={handleOnChange}
updateButton={updateButton}
/>
<AddMangaModal
chapterCount={chapterCount}
setChapterCount={setChapterCount}
mangaName={mangaName}
setMangaName={setMangaName}
handleOnChange={handleOnChange}
createButton={createButton}
/>
</div>
</div>
</main>
);
}

View File

@ -1,90 +0,0 @@
import { useState, useEffect } from "react";
import { Link, useNavigate } from 'react-router-dom';
import { useRef } from "react";
const hostURL = "http://localhost:8080";
const LoginPage = function () {
const loginInput = useRef();
const passwordInput = useRef();
const navigate = useNavigate();
useEffect(() => {
}, []);
const login = async function (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({login: login, password: password}),
};
const response = await fetch(hostURL + "/jwt/login", requestParams);
const result = await response.text();
if (response.status === 200) {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
getRole(result);
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
}
}
const getRole = async function (token) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json"
}
};
const requestUrl = hostURL + `/who_am_i?token=${token}`;
const response = await fetch(requestUrl, requestParams);
const result = await response.text();
localStorage.setItem("role", result);
window.dispatchEvent(new Event("storage"));
navigate("/reader");
}
const loginFormOnSubmit = function (event) {
event.preventDefault();
login(loginInput.current.value, passwordInput.current.value);
};
return (
<>
<div>
<form onSubmit={(event) => loginFormOnSubmit(event)}>
<div className="mb-3">
<p className="mb-1">Login</p>
<input className="form-control"
type="text" required autoFocus
ref={loginInput} />
</div>
<div className="mb-3">
<p className="mb-1">Password</p>
<input className="form-control"
type="password" required
ref={passwordInput} />
</div>
<div className="mb-3">
<button type="submit" className="btn btn-success">
Sing in
</button>
</div>
<div>
<p>
<span>Not a member yet?&nbsp;</span>
<Link to="/singup">Sing Up here</Link>
</p>
</div>
</form>
</div>
</>
)
}
export default LoginPage;

View File

@ -1,119 +0,0 @@
import React, {useState, useEffect} from 'react';
import MangaDto from '../Dto/Manga-Dto';
import ReaderList from "../components/List/ReaderList";
export default function MangaPage() {
const [mangaModel, setMangaModel] = useState(new MangaDto({}));
const [readerData, setReaderData] = useState([]);
const host = "http://localhost:8080/api/1.0";
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
useEffect(() => {
const quryString = window.location.search;
const urlParams = new URLSearchParams(quryString);
const id = urlParams.get('id');
getCreator(id)
.then(_data =>setMangaModel(_data));
getReaderData(id)
.then(_data =>setReaderData(_data));
console.log(readerData);
}, []);
const transformer = (mangaModel) => new MangaDto(mangaModel);
const url = "manga/";
const getReaderData = async function (id) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/manga/` + id + `/readers`, requestParams);
const _data = await response.json()
console.log(_data);
return _data;
}
useEffect(() => {
console.log(mangaModel);
console.log(readerData);
}, [mangaModel]);
useEffect(() => {
console.log(readerData);
});
const getCreator = async function (id) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/manga/` + id, requestParams);
const _data = await response.json()
return _data;
}
const addMangaButton = (e) =>{
e.preventDefault()
getReaderData(253)
.then(_data =>setReaderData(_data));
console.log(readerData);
}
return (
<main className="p-3">
<div className="container d-flex" >
<div className="d-flex flex-column">
<img className="img_style01" style={{borderRadius: "3%"}}src={mangaModel.image} alt={mangaModel.mangaName}/>
</div>
<div className="container table text-white fs-4 ms-4">
<div className="row text-white fw-bold fs-3">О манге</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Год производства</div>
<div className="col-xs-6 col-sm-3">1000</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Страна</div>
<div className="col-xs-6 col-sm-3">Россия</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Жанр</div>
<div className="col-xs-6 col-sm-3">Драма</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Количество глав</div>
<div className="col-xs-6 col-sm-3">{mangaModel.chapterCount}</div>
</div>
<div className="row">
<div className="col-xs-6 col-sm-3">Возраст</div>
<div className="col-xs-6 col-sm-3">16+</div>
</div>
<div className="row text-white fw-bold fs-3">Описание</div>
<div className="row">
<div className="col-xs-6 col-sm-12">
<p>Ким Кон Чжа спокойно живет в своей халупе, завидуя всем популярным охотникам. Однажды его желание быть лучше всех сбывается и он получает легендарный навык Копирование способностей... ценой своей жизни.</p>
<p>Прежде чем он успевает понять это, его убивает охотник 1, Летний дух! Но это активирует его навык, и теперь он скопировал новый, Путешествие во времени после смерти.</p>
<p>Как Ким Кон Чжа же будет использовать эти навыки, чтобы победить конкурентов и подняться на вершину?</p>
</div>
</div>
<ReaderList
readers={mangaModel.readers}
/>
</div>
</div>
</main>
);
}

View File

@ -1,195 +0,0 @@
import { useEffect, useState } from "react";
import TableReader from '../components/Table/TableReader';
import { NavLink } from 'react-router-dom';
import MangaReaderList from "../components/List/MangaReaderList";
import AddMangaReaderModal from "../components/Modal/AddMangaReaderModal";
export default function ReaderAction() {
const host = "http://localhost:8080/api/1.0";
const [mangaData, setMangaData] = useState([]);
const [readerData, setReaderData] = useState([]);
const [reader, setReader] = useState([]);
const [mangaId, setMangaId] = useState(0);
const [chapterCount, setChapterCount] = useState(0);
const [mangaName, setMangaName] = useState("");
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
useEffect(() => {
const quryString = window.location.search;
const urlParams = new URLSearchParams(quryString);
const id = urlParams.get('id');
console.log(id);
if (id !== null) setReaderId(id);
getReaderData()
.then(_data =>setReaderData(_data));
getMangaData()
.then(_data =>setMangaData(_data));
console.log(2);
console.log(readerData);
},[]);
const getReaderData = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + "/reader", requestParams);
const _data = await response.json()
console.log(_data);
return _data;
}
const getMangaData = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + "/manga", requestParams);
const _data = await response.json()
console.log(_data);
return _data;
}
useEffect(() => {
getReader().then(_data => {
setReader(_data);
console.log(_data);
});
}, []);
const getReader = async function () {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
let login = localStorage.getItem("user");
console.log(host + `/reader/` + login);
const response = await fetch(host + `/reader/` + login, requestParams);
const _data = await response.json()
return _data;
}
const updateButton = (e) =>{
e.preventDefault();
update().then((result) => {
alert(`Manga[id=${result.id}, mangaName=${result.mangaName}, chapterCount=${result.chapterCount}]`);
getReader()
.then(_data =>setReader(_data));
});
console.log(reader);
}
const update = async function (){
console.info('Try to update item');
if (mangaId === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/manga/${mangaId}?chapterCount=${chapterCount}`, requestParams);
return await response.json();
}
const setMangaIdButton = (id) =>{
setMangaId(id);
}
const removeButton = (id) =>{
remove(id).then((result) => {
getReader()
.then(_data =>setReader(_data));
});
}
const remove = async function (id){
console.info('Try to remove item');
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
console.log(host + `/reader/${reader.id}/removeManga?mangaId=${id}`, requestParams);
const response = await fetch(host + `/reader/${reader.id}/removeManga?mangaId=${id}`, requestParams);
return await response.json();
}
const addMangaButton = (e) =>{
e.preventDefault()
addManga().then((result) => {
alert(`Manga[id=${result.id}, mangaName=${result.mangaName}, chapterCount=${result.chapterCount}]`);
console.log(result);
getReader()
.then(_data =>setReader(_data));
});
}
const addManga = async function (){
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
console.log(host + `/reader/${reader.id}/addManga?mangaId=${mangaId}`, requestParams);
const response = await fetch(host + `/reader/${reader.id}/addManga?mangaId=${mangaId}`, requestParams);
return await response.json();
}
return (
<main>
<div className="container" id="root-div">
<div className="content">
<h1>Reader</h1>
<form id="form">
<div className="d-flex mt-3">
<div className="d-grid col-sm-2">
<button type="button" className="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal2">Добавить</button>
</div>
</div>
</form>
<MangaReaderList
reader={reader}
removeButton={removeButton}
/>
<AddMangaReaderModal
mangaId={mangaId}
setMangaId={setMangaId}
mangaData={mangaData}
addMangaButton={addMangaButton}
/>
</div>
</div>
</main>
);
}

View File

@ -1,88 +0,0 @@
import { useState, useEffect } from "react";
import { Link } from 'react-router-dom';
import { useRef } from "react";
const hostURL = "http://localhost:8080";
const SingupPage = function () {
const loginInput = useRef();
const emailInput = useRef();
const passwordInput = useRef();
const passwordConfirmInput = useRef();
useEffect(() => {
}, []);
const singup = async function (userSinginDto) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userSinginDto),
};
console.log(hostURL + "/sing_up");
console.log(userSinginDto);
const response = await fetch(hostURL + "/sing_up", requestParams);
const result = await response.text();
alert(result);
}
const singupFormOnSubmit = function (event) {
event.preventDefault();
const userSinginDto = {
login: loginInput.current.value,
email: emailInput.current.value,
password: passwordInput.current.value,
passwordConfirm: passwordConfirmInput.current.value
}
singup(userSinginDto);
};
return (
<>
<div>
<form onSubmit={(event) => singupFormOnSubmit(event)}>
<div className="mb-3">
<p className="mb-1">Login</p>
<input className="form-control"
type="text" required maxLength="64"
ref={loginInput} />
</div>
<div className="mb-3">
<p className="mb-1">Email</p>
<input className="form-control"
type="text" required
ref={emailInput} />
</div>
<div className="mb-3">
<p className="mb-1">Password</p>
<input className="form-control"
type="password" required minLength="3" maxLength="64"
ref={passwordInput} />
</div>
<div className="mb-3">
<p className="mb-1">Confirm Password</p>
<input className="form-control"
type="password" required minLength="3" maxLength="64"
ref={passwordConfirmInput} />
</div>
<div className="mb-3">
<button type="submit" className="btn btn-success">
Create account
</button>
</div>
<div>
<p>
<span>Already have an account?&nbsp;</span>
<Link to="/login">Sing In here</Link>
</p>
</div>
</form>
</div>
</>
)
}
export default SingupPage;

View File

@ -1,112 +0,0 @@
import { useState, useEffect } from "react";
const hostURL = "http://localhost:8080";
const host = hostURL + "/api/1.0";
const UsersPage = function () {
const [users, setUsers] = useState([]);
const [pageNumbers, setPageNumbers] = useState([]);
const [pageNumber, setPageNumber] = useState();
useEffect(() => {
getUsers(1);
}, []);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const getUsers = async function (page) {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/users?page=${page}`;
const response = await fetch(requestUrl, requestParams);
const data = await response.json();
setUsers(data.first.content);
setPageNumber(data.first.number);
setPageNumbers(data.second);
}
const removeUser = async function (id) {
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/user/${id}`;
await fetch(requestUrl, requestParams);
}
const pageButtonOnClick = function (page) {
getUsers(page);
}
const removeButtonOnClick = function (id) {
const confirmResult = confirm("Are you sure you want to remove " +
"the selected user?");
if (confirmResult === false) {
return;
}
removeUser(id).then(() => getUsers(pageNumber + 1));
}
return (
<>
<div className="table-shell mb-3">
<table className="table text-white">
<thead>
<tr>
<th style={{ width: "10%" }} scope="col">#</th>
<th style={{ width: "15%" }} scope="col">ID</th>
<th style={{ width: "30%" }} scope="col">Login</th>
<th style={{ width: "30%" }} scope="col">Email</th>
<th style={{ width: "15%" }} scope="col">Role</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr>
<th style={{ width: "10%" }} scope="row">{index}</th>
<td style={{ width: "15%" }}>{user.id}</td>
<td style={{ width: "30%" }}>{user.login}</td>
<td style={{ width: "30%" }}>{user.email}</td>
<td style={{ width: "15%" }}>{user.role}</td>
{user.login !== localStorage.getItem("user") ?
<td style={{ width: "1%" }}>
<button className="btn btn-secondary btn-sm"
onClick={() => removeButtonOnClick(user.id)}>
del
</button>
</td> : null}
</tr>
))}
</tbody>
</table>
</div>
<div>
<p>
Pages:
</p>
<nav>
<ul className="pagination">
{pageNumbers.map((number) => (
<li className={`page-item ${number === pageNumber + 1 ? "active" : ""}`}
onClick={() => pageButtonOnClick(number)}>
<a className="page-link" href="#">{number}</a>
</li>
))}
</ul>
</nav>
</div>
</>
);
}
export default UsersPage;

View File

@ -1,174 +0,0 @@
import { useEffect, useState } from "react";
import TableCreator from '../components/Table/TableCreator';
import MangaDto from '../Dto/Manga-Dto';
export default function Creator() {
const host = "http://localhost:8080/api/1.0";
const [creatorId, setCreatorId] = useState(0);
const [creatorName, setCreatorName] = useState("");
const [password, setPassword] = useState("");
const [mangaModel, setMangaModel] = useState(new MangaDto({}));
const [data, setData] = useState([]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const table = document.getElementById("tbody");
useEffect(() => {
getData()
},[]);
const getData = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/creator`;
const response = await fetch(requestUrl, requestParams);
setData(await response.json())
console.log(data);
}
const create = async function (){
const requestParams = {
method: "POST",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
console.log((host + `/creator?creatorName=${creatorName}&password=${password}`));
const response = await fetch(host + `/creator?creatorName=${creatorName}&password=${password}`, requestParams);
getData();
}
const remove = async function (){
console.info('Try to remove item');
if (creatorId !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/creator/` + creatorId, requestParams);
console.log("REMOVE");
getData();
return await response.json();
}
const removeAll = async function (){
console.info('Try to remove item');
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
}
};
await fetch(host + `/creator/`, requestParams);
}
const update = async function (){
console.info('Try to update item');
if (creatorId === 0 || creatorName == null || password === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/creator/${creatorId}?creatorName=${creatorName}&password=${password}`, requestParams);
getData();
return await response.json();
}
const createButton = (e) =>{
e.preventDefault()
create();
}
const removeButton = (e) =>{
e.preventDefault()
remove();
}
const updateButton = (e) =>{
e.preventDefault()
update();
}
return (
<main>
<div className="container" id="root-div">
<div className="content">
<h1>Creator</h1>
<form id="form">
<div className="d-flex justify-content-evenly mt-3">
<div className="col-sm-2">
<label htmlFor="creatorId" className="form-label">creatorId</label>
<input type='number' value = {creatorId} onChange={event => setCreatorId(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="creatorName" className="form-label">creatorName</label>
<input type='text' value = {creatorName} onChange={event => setCreatorName(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="password" className="form-label">password</label>
<input type='text' value = {password} onChange={event => setPassword(event.target.value)} className="form-control"/>
</div>
</div>
<div className="row mt-3">
<div className="d-grid col-sm-3 mx-auto">
<button type="submit" onClick={createButton} className="btn btn-success">Добавить</button>
</div>
<div className="d-grid col-sm-3 mx-auto">
<button type="submit" onClick={updateButton} className="btn btn-success" id="btnUpdate" >Обновить</button>
</div>
<div className="d-grid col-sm-3 mx-auto">
<button id="btnRemove" onClick={removeButton} className="btn btn-success">Удалить</button>
</div>
</div>
</form>
<div className="row table-responsive text-white">
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">CreatorName</th>
<th scope="col">Password</th>
<th scope="col">Mangs</th>
</tr>
</thead>
<TableCreator items = {data}/>
{/* <tbody id="tbody">
</tbody> */}
</table>
</div>
</div>
</div>
</main>
);
}

View File

@ -1,235 +0,0 @@
import { useEffect, useState } from "react";
import TableReader from '../components/Table/TableReader';
export default function ReaderS() {
const host = "http://localhost:8080/api/1.0";
const [readerId, setReaderId] = useState(0);
const [mangaId, setMangaId] = useState(0);
const [readerName, setReaderName] = useState("");
const [password, setPassword] = useState("");
const [data, setData] = useState([]);
const getTokenForHeader = function () {
return "Bearer " + localStorage.getItem("token");
}
const table = document.getElementById("tbody");
useEffect(() => {
getData();
console.log(2);
},[]);
const getData = async function () {
const requestParams = {
method: "GET",
headers: {
"Authorization": getTokenForHeader(),
}
};
const requestUrl = host + `/reader`;
const response = await fetch(requestUrl, requestParams);
setData(await response.json())
console.log(data);
}
const create = async function (){
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/reader?readerName=${readerName}&password=${password}`, requestParams);
alert(response);
console.log(response);
getData();
}
const remove = async function (id){
console.info('Try to remove item');
if (id !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": getTokenForHeader(),
}
};
const response = await fetch(host + `/reader/` + id, requestParams);
getData();
return await response.json();
}
const removeAll = async function (){
console.info('Try to remove item');
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
const requestParams = {
method: "DELETE",
headers: {
"Authorization": getTokenForHeader(),
}
};
await fetch(host + `/reader/`, requestParams);
getData();
}
const update = async function (){
console.info('Try to update item');
if (readerId === 0 || readerName == null || password === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/reader/${readerId}?readerName=${readerName}&password=${password}`, requestParams);
getData();
return await response.json();
}
const removeManga = async function (){
console.info('Try to remove item');
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
console.log(host + `/reader/${readerId}/removeManga?mangaId=${mangaId}`, requestParams);
const response = await fetch(host + `/reader/${readerId}/removeManga?mangaId=${mangaId}`, requestParams);
return await response.json();
}
const addManga = async function () {
const requestParams = {
method: "PUT",
headers: {
"Authorization": getTokenForHeader(),
"Content-Type": "application/json",
}
};
console.log(host + `/reader/${readerId}/addManga?mangaId=${mangaId}`, requestParams);
const response = await fetch(host + `/reader/${readerId}/addManga?mangaId=${mangaId}`, requestParams);
return await response.json();
}
const createButton = (e) =>{
e.preventDefault()
create();
}
const removeButton = (id) =>{
remove(id);
}
const updateButton = (e) =>{
e.preventDefault()
update();
}
const removeMangaButton = (e) =>{
e.preventDefault()
removeManga();
}
const addMangaButton = (e) =>{
e.preventDefault()
addManga();
}
const setModal_Click = (e) =>{
e.preventDefault()
setModal(true)
//setData({type:'', name:'', description:'' })
}
return (
<main>
<div className="container" id="root-div">
<div className="content">
<h1>Readers</h1>
<form id="form">
<div className="d-flex justify-content-evenly mt-3">
<div className="col-sm-2">
<label htmlFor="readerId" className="form-label">readerId</label>
<input type='number' value = {readerId} onChange={event => setReaderId(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="mangaId" className="form-label">mangaId</label>
<input type='number' value = {mangaId} onChange={event => setMangaId(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="readerName" className="form-label">readerName</label>
<input type='text' value = {readerName} onChange={event => setReaderName(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="password" className="form-label">password</label>
<input type='text' value = {password} onChange={event => setPassword(event.target.value)} className="form-control"/>
</div>
</div>
<div className="row m-3">
<div className="d-grid col-sm-3 m-3 mx-auto">
<button onClick={createButton} className="btn btn-success">Добавить</button>
</div>
<div className="d-grid col-sm-3 m-3 mx-auto">
<button onClick={updateButton} className="btn btn-success">Обновить</button>
</div>
<div className="d-grid col-sm-2 m-3 mx-auto">
<button onClick={removeMangaButton} className="btn btn-success">Удалить мангу</button>
</div>
<div className="d-grid col-sm-2 m-3 mx-auto">
<button onClick={addMangaButton} className="btn btn-success">Добавить мангу</button>
</div>
</div>
</form>
<div className="row table-responsive text-white">
<table className="table mt-3 text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">readerName</th>
<th scope="col">Password</th>
<th scope="col">Mangs</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<TableReader
items = {data}
remove ={removeButton}
update ={updateButton}
/>
{/* <tbody id="tbody">
</tbody> */}
</table>
</div>
</div>
</div>
</main>
);
}

View File

@ -1,43 +0,0 @@
import React from 'react';
const EditReaderForm =(props) => {
const types = ([
{name:'Манга'},
{name:'Манхва'},
{name:'Маньхуа'},
])
function done(e) {
e.preventDefault();
// if (formRef.current.checkValidity()) {
// props.onDone();
// props.setModalEdit();
// props.setData({type:'', name:'', description:'' })
// }else {
// formRef.current.reportValidity();
// props.setData({type:'', name:'', description:'' })
// }
}
const formRef = React.createRef();
return (
<form id="frm-items" ref={formRef} className="row g-3 text-dark">
<div className="col-md-3 ">
</div>
<div className="col-sm-2">
<label htmlFor="readerName" className="form-label">readerName</label>
<input type='text' value = {props.readerName} onChange={event => props.setReaderName(event.target.value)} className="form-control"/>
</div>
<div className="col-sm-2">
<label htmlFor="password" className="form-label">password</label>
<input type='text' value = {props.password} onChange={event => props.setPassword(event.target.value)} className="form-control"/>
</div>
<div className="col-md-3">
<button onClick={() => props.update(item.id)} id="btn-add-item" className="btn btn-primary" type="submit">Изменить</button>
</div>
</form>
);
}
export default EditReaderForm

View File

@ -1,99 +0,0 @@
import {NavLink, useNavigate} from 'react-router-dom';
import {useEffect, useState} from "react";
export default function Header(props) {
const navigate = useNavigate();
useEffect(() => {
window.addEventListener("storage", () => {
let token = localStorage.getItem("token");
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("/catalog");
}
});
}
});
}, [])
const getRole = async function (token) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/who_am_i?token=${token}`;
const response = await fetch(requestUrl, requestParams);
return await response.text();
}
const logoutButtonOnClick = function () {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
window.dispatchEvent(new Event("storage"));
navigate("/login");
}
const [userRole, setUserRole] = useState("NONE");
useEffect(() => {
window.addEventListener("storage", () => {
getUserRole();
});
getUserRole();
}, [])
const getUserRole = function () {
const role = localStorage.getItem("role") || "NONE";
setUserRole(role);
}
const validate = function (userGroup) {
return (userGroup === "AUTH" && userRole !== "NONE") || (userGroup === userRole);
}
console.log(userRole);
return (
<nav className="navbar navbar-expand-lg navbar-dark">
<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">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav">
{props.links.map(route =>{
if (validate(route.userGroup)) {
return (
<li key={route.path}
className="nav-item">
<NavLink className="nav-link" to={route.path}>
{route.label}
</NavLink>
</li>
);}}
)}
{userRole === "NONE"?
null
:
<div className="border-bottom pb-3 mb-3">
<button className="btn btn-primary"
onClick={logoutButtonOnClick}>
Log Out
</button>
</div>
}
</ul>
</div>
</div>
</nav >
);
}

View File

@ -1,36 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../Table/TableCreator';
import MangaDto from "../../Dto/Manga-Dto";
export default function MangaCreatorList(props) {
return (
<div className="row table-responsive text-white">
{
props.creator.mangas?.map((manga) =>
<div key={manga.id} className="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div className="me-3">
<NavLink to={`/mangapage?id=${manga.id}`} ><img src={manga.image} alt={manga.mangaName} className="slideshow" /></NavLink>
</div>
<div>
<div className="pt-3 description d-flex flex-column justify-content-start mb-3 fs-6 fw-bold">
<NavLink className="text-white fs-5 unic_class fw-bold pt-3 mb-3"
to={`/mangapage?id=${manga.id}`}>Название: {manga.mangaName}
</NavLink>
<p>Глав: {manga.chapterCount}</p>
</div>
<div>
<button type="button" className="btn btn-primary" onClick = {() => props.setMangaIdButton(manga.id)} data-bs-toggle="modal" data-bs-target="#exampleModal">
<i className="fas fa-edit"></i>
</button>
<button className="delete bg-danger p-2 px-2 mx-2 border border-0 rounded text-white fw-bold" onClick = {() => props.removeButton(manga.id)} type="button">Удалить</button>
</div>
</div>
</div>
)
}
</div>
);
}

View File

@ -1,33 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../Table/TableCreator';
import MangaDto from "../../Dto/Manga-Dto";
export default function MangaReaderList(props) {
return (
<div className="row table-responsive text-white">
{
props.reader.mangas?.map((manga) =>
<div key={manga.id} className="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div className="me-3">
<NavLink to={`/mangapage?id=${manga.id}`} ><img src={manga.image} alt={manga.mangaName} className="slideshow" /></NavLink>
</div>
<div>
<div className="pt-3 description d-flex flex-column justify-content-start mb-3 fs-6 fw-bold">
<NavLink className="text-white fs-5 unic_class fw-bold pt-3 mb-3"
to={`/mangapage?id=${manga.id}`}>Название: {manga.mangaName}
</NavLink>
<p>Глав: {manga.chapterCount}</p>
</div>
<div>
<button className="delete bg-danger p-2 px-2 mx-2 border border-0 rounded text-white fw-bold" onClick = {() => props.removeButton(manga.id)} type="button">Удалить</button>
</div>
</div>
</div>
)
}
</div>
);
}

View File

@ -1,22 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
export default function ReaderList(props) {
return (
<div className="row table-responsive text-white">
{
props.readers?.map((reader) =>
<div key={reader.id} className="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div>
<div className="text-white pt-3 description d-flex flex-column justify-content-start mb-3 fs-6 fw-bold">
Имя пользователя: {reader.readerName}
</div>
</div>
</div>
)
}
</div>
);
}

View File

@ -1,49 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../Table/TableCreator';
import MangaDto from "../../Dto/Manga-Dto";
export default function AddMangaModal(props) {
return (
<div className="modal fade text-black" id="exampleModal2" tabIndex="-1" aria-labelledby="exampleModalLabel2" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel2">Создание манги</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<div>
<label htmlFor="chapterCount" className="form-label">chapterCount</label>
<input type='number' value = {props.chapterCount} onChange={event => props.setChapterCount(event.target.value)} className="form-control"/>
</div>
<div>
<label htmlFor="mangaName" className="form-label">mangaName</label>
<input type='text' value = {props.mangaName} onChange={event => props.setMangaName(event.target.value)} className="form-control"/>
</div>
<div>
<label
htmlFor="file-loader-button"
className="form-label">
Загрузить файл
</label>
<input
id="file-loader-button"
type="file"
className="form-control text-white"
onChange={props.handleOnChange}
/>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" onClick={props.createButton} className="btn btn-primary" data-bs-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,37 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../Table/TableCreator';
import MangaDto from "../../Dto/Manga-Dto";
export default function AddMangaReaderModal(props) {
return (
<div className="modal fade text-black" id="exampleModal2" tabIndex="-1" aria-labelledby="exampleModalLabel2" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel2">Добавление манги к читателю</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<div>
<select className="form-select" value={props.mangaId} onChange={event => props.setMangaId(event.target.value)} aria-label="Default select example">
<option value={0}>Manga</option>
{
props.mangaData.map((mangaD) =>
<option key={mangaD.id} value={mangaD.id}>{mangaD.mangaName}</option>
)
}
</select>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" onClick={props.addMangaButton} className="btn btn-primary" data-bs-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,44 +0,0 @@
import { useEffect, useState } from "react";
import { NavLink } from 'react-router-dom';
import TableCreator from '../Table/TableCreator';
import MangaDto from "../../Dto/Manga-Dto";
export default function EditMangaModal(props) {
return (
<div className="modal fade text-black" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">Изменение манги</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<div>
<label htmlFor="chapterCount" className="form-label">chapterCount</label>
<input type='number' value={props.chapterCount} onChange={event => props.setChapterCount(event.target.value)} className="form-control"/>
</div>
<div>
<label
htmlFor="file-loader-button"
className="form-label">
Загрузить файл
</label>
<input
id="file-loader-button"
type="file"
className="form-control text-white"
onChange={props.handleOnChange}
/>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" onClick={props.updateButton} className="btn btn-primary" data-bs-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,17 +0,0 @@
import {Navigate, Outlet, useNavigate} from 'react-router-dom';
import {useEffect} from "react";
const PrivateRoutes = (props) => {
let isAllowed = false;
let userRole = localStorage.getItem("role");
if ((props.userGroup === "AUTH" && userRole) || (props.userGroup === userRole)) {
isAllowed = true;
}
return isAllowed ? <Outlet /> : <Navigate to="/login" />;
}
export default PrivateRoutes;

View File

@ -1,26 +0,0 @@
import { useState } from 'react';
export default function TableCreator(props) {
return (
<tbody>
{
props.items?.map((item, index) =>
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.creatorName}</td>
<td>{item.hashedPassword}</td>
<td>
<select className="form-select" aria-label="Default select example">{item.mangas?.map(manga =>
<option key={manga.mangaName } >{manga.mangaName + " " +manga.chapterCount}</option>)}
</select>
</td>
</tr>
)
}
</tbody >
);
}

View File

@ -1,27 +0,0 @@
import { useState } from 'react';
export default function TableReader(props) {
return (
<tbody>
{
props.items?.map((item, index) =>
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.readerName}</td>
<td>{item.hashedPassword}</td>
<td>
<select className="form-select" aria-label="Default select example">{item.mangas?.map(manga =>
<option key={manga.id}>{manga.mangaName}</option>)}
</select>
</td>
<td>
<button onClick={() => props.remove(item.id)} className="btn btn-success">Удалить</button>
</td>
</tr>
)
}
</tbody >
);
}

View File

@ -1,8 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './style.css'
ReactDOM.createRoot(document.getElementById('app')).render(
<App />
)

View File

@ -1,107 +0,0 @@
html,
body {
background-color: #000000;
color: #ffffff;
padding: 0;
margin: 0;
font-family: sans-serif;
line-height: 1.15;
height: 100%;
}
header {
background-color: #3c3c3c;
color: #ffffff;
}
header a {
color: #ffffff;
text-decoration: none;
margin: 0 0.5em;
}
header a:hover {
text-decoration: underline;
}
#logo {
margin-left: 0.5em;
}
article a {
color: #ffffff;
text-decoration: none;
margin: 0.5em 0.5em;
}
header a:hover {
text-decoration: underline;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
footer {
background-color: #9c9c9c;
color: #ffffff;
height: 32px;
padding: 0.5em;
}
.manga_pages{
display: flex;
flex-direction: column;
align-items: center;
}
.catalog_wrapper{
display: flex;
width: 73%;
flex-direction: column;
}
.catalog_article{
display: flex;
}
.poster{
width:140px;
}
th {
border: 0px solid rgb(255, 255, 255);
}
.added_manga{
display: flex;
flex-direction: column;
}
@media (min-width: 992px) {
.manga_pages img{
max-width: 900px;
width: auto;
height: auto;
}
}
.flex_grow {
flex-grow: 1;
display: flex;
align-items: center;
}
@media (min-width: 1024px){
.article_1 {
max-width: -webkit-calc(1600px + (100vw/64*7)*2);
max-width: -moz-calc(1600px + (100vw/64*7)*2);
max-width: calc(1600px + (100vw/64*7)*2);
padding-left: -webkit-calc(100vw/64*7);
padding-left: -moz-calc(100vw/64*7);
padding-left: calc(100vw/64*7);
padding-right: -webkit-calc(100vw/64*7);
padding-right: -moz-calc(100vw/64*7);
padding-right: calc(100vw/64*7);
}
}
.registration_div {
width: 100%;
height: 100%;
}
.slideshow{
height: 250px;
width: auto;/*maintain aspect ratio*/
max-width:180px;
border-radius: 7%;
}

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

6
gradlew vendored
View File

@ -205,12 +205,6 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.

14
gradlew.bat vendored
View File

@ -14,7 +14,7 @@
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@ -25,7 +25,7 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -75,15 +75,13 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@ -1,2 +1 @@
rootProject.name = 'app'
include 'front'

View File

@ -1,28 +0,0 @@
package com.LabWork.app.MangaStore.configuration;
import com.LabWork.app.MangaStore.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

@ -8,7 +8,8 @@ import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -1,7 +1,6 @@
package com.LabWork.app.MangaStore.configuration;
import com.LabWork.app.MangaStore.configuration.jwt.JwtFilter;
import com.LabWork.app.MangaStore.controller.UserController;
import com.LabWork.app.MangaStore.controller.User.UserSignupMvcController;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.service.UserService;
import org.slf4j.Logger;
@ -11,28 +10,22 @@ 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.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private static final String LOGIN_URL = "/login";
private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
@ -40,27 +33,24 @@ public class SecurityConfiguration {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.addUser(admin, "admin@gmail.com", admin, admin, UserRole.ADMIN);
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors()
.and()
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SING_UP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_WHO_AM_I).permitAll()
.anyRequest()
.authenticated()
.requestMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.and()
.logout().permitAll();
return http.build();
}
@ -74,18 +64,11 @@ public class SecurityConfiguration {
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
return web -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**")
.requestMatchers("/h2-console");
.requestMatchers("/vk.jpg");
}
}

View File

@ -1,30 +1,27 @@
package com.LabWork.app.MangaStore.configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
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.*;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseTrailingSlashMatch(true);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}
}

View File

@ -1,11 +0,0 @@
package com.LabWork.app.MangaStore.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -1,72 +0,0 @@
package com.LabWork.app.MangaStore.configuration.jwt;
import com.LabWork.app.MangaStore.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
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 UserService userService;
public JwtFilter(UserService 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

@ -1,27 +0,0 @@
package com.LabWork.app.MangaStore.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

@ -1,107 +0,0 @@
package com.LabWork.app.MangaStore.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

@ -0,0 +1,106 @@
package com.LabWork.app.MangaStore.controller.Creator;
import com.LabWork.app.MangaStore.model.Dto.CreatorMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.CreatorService;
import com.LabWork.app.MangaStore.service.MangaService;
import jakarta.validation.Valid;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.Principal;
import java.util.Base64;
@Controller
@RequestMapping("/creatorAction")
@Secured({UserRole.AsString.ADMIN})
public class CreatorActionMvcController {
private final CreatorService creatorService;
private static final Logger log = LoggerFactory.getLogger(CreatorActionMvcController.class);
private final MangaService mangaService;
public CreatorActionMvcController(CreatorService creatorService, MangaService mangaService) {
this.creatorService = creatorService;
this.mangaService = mangaService;
}
@GetMapping()
public String getCreator(Model model, Principal principal) {
model.addAttribute("creators",
creatorService.findAllCreators().stream()
.map(CreatorMangaDto::new)
.toList());
CreatorMangaDto currentCreator = new CreatorMangaDto(creatorService.findByLogin(principal.getName()));
model.addAttribute("currentCreator", currentCreator);
return "creatorAction";
}
@GetMapping("/edit/{id}")
public String editManga(@PathVariable Long id, Model model, Principal principal) {
if (principal.getName().equals(principal.getName())) {
model.addAttribute("Id", id);
model.addAttribute("mangaDto", new MangaDto(mangaService.findManga(id)));
model.addAttribute("controller", "manga/");
return "creatorAction-edit";
}
return "creatorAction";
}
@GetMapping("/create")
public String createManga(Model model, Principal principal) {
model.addAttribute("mangaDto", new MangaDto());
model.addAttribute("controller", "creator/");
return "creatorAction-edit";
}
@PostMapping( "/creator")
public String saveManga(@RequestParam("multipartFile") MultipartFile multipartFile,
@ModelAttribute @Valid MangaDto mangaDto,
BindingResult bindingResult,
Model model,
Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "creatorAction-edit";
}
mangaDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
mangaDto.setLogin(principal.getName());
mangaService.addManga(mangaDto);
return "redirect:/creatorAction";
}
@PostMapping( "/manga/{mangaId}")
public String updateManga(@PathVariable(value = "mangaId", required = false) Long mangaId, @RequestParam("multipartFile") MultipartFile multipartFile,
@ModelAttribute @Valid MangaDto mangaDto,
BindingResult bindingResult,
Model model,
Principal principal) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "creatorAction-edit";
}
mangaDto.setImage("data:" + multipartFile.getContentType() + ";base64," + Base64.getEncoder().encodeToString(multipartFile.getBytes()));
mangaService.updateManga(mangaId, mangaDto.getChapterCount(), mangaDto.getImage());
return "redirect:/creatorAction";
}
@PostMapping("/delete/{mangaId}")
public String deleteCreator(@PathVariable Long mangaId, Principal principal) {
Long creatorId = mangaService.findManga(mangaId).getCreatorId();
mangaService.deleteManga(mangaId);
if (creatorId != null){
return "redirect:/creatorAction";
} else {
return "redirect:/creatorAction";
}
}
}

View File

@ -1,58 +0,0 @@
package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.model.Dto.CreatorMangaDto;
import com.LabWork.app.MangaStore.service.CreatorService;
import com.LabWork.app.MangaStore.service.UserService;
import org.springframework.web.bind.annotation.*;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/creator")
public class CreatorController {
private final CreatorService creatorService;
private final UserService userService;
public CreatorController(CreatorService creatorService,
UserService userService) {
this.creatorService = creatorService;
this.userService = userService;
}
@GetMapping("/{login}")
public CreatorMangaDto getCreator(@PathVariable String login) {
return new CreatorMangaDto(creatorService.findCreator(userService.findByLogin(login).getCreator().getId()));
}
@GetMapping
public List<CreatorMangaDto> getCreators() {
return creatorService.findAllCreators().stream()
.map(CreatorMangaDto::new)
.toList();
}
/* @PostMapping
public CreatorMangaDto createCreator(@RequestParam("creatorName") String creatorName,
@RequestParam("password") String password) {
return new CreatorMangaDto(creatorService.addCreator());
}*/
/* @PutMapping("/{id}")
public CreatorMangaDto updateCreator(@PathVariable Long id,
@RequestParam("creatorName") String creatorName,
@RequestParam("password") String password) {
return new CreatorMangaDto(creatorService.updateCreator(id, creatorName, password));
}*/
@DeleteMapping("/{id}")
public CreatorMangaDto deleteCreator(@PathVariable Long id) {
//creatorService.deleteAllCreators();
return new CreatorMangaDto(creatorService.deleteCreator(id));
}
@DeleteMapping
public void deleteAllCreator() {
creatorService.deleteAllCreators();
}
}

View File

@ -0,0 +1,38 @@
package com.LabWork.app.MangaStore.controller.Manga;
import com.LabWork.app.MangaStore.model.Dto.MangaReaderDto;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.MangaService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/manga")
public class MangaMvcController {
private final MangaService mangaService;
public MangaMvcController(MangaService mangaService) {
this.mangaService = mangaService;
}
@GetMapping()
public String getMangaAndReaders(Model model) {
model.addAttribute("mangaList", mangaService.findAllMangas().stream()
.map(x -> new MangaDto(x))
.toList());
return "catalog";
}
@GetMapping("/{id}")
public String getMangaAndReaders(@PathVariable Long id, Model model) {
model.addAttribute("manga", new MangaReaderDto(mangaService.findManga(id), mangaService.getReader(id)));
model.addAttribute("readers", mangaService.getReader(id).stream()
.map(x -> new ReaderMangaDto(x))
.toList());
return "mangaPage";
}
}

View File

@ -1,64 +0,0 @@
package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.model.Dto.MangaReaderDto;
import com.LabWork.app.MangaStore.model.Dto.MangaUserDto;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.MangaService;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import com.LabWork.app.MangaStore.service.UserService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/manga")
public class MangaController {
private final MangaService mangaService;
private final UserService userService;
public MangaController(MangaService mangaService,
UserService userService) {
this.mangaService = mangaService;
this.userService = userService;
}
@GetMapping("/{id}")
public MangaUserDto getManga(@PathVariable Long id) {
return new MangaUserDto(mangaService.findManga(id), mangaService.getReader(id).stream()
.map(x -> userService.findUser(x.getId()))
.toList());
}
@GetMapping
public List<MangaReaderDto> getMangas() {
return mangaService.findAllMangas().stream()
.map(x -> new MangaReaderDto(x, mangaService.getReader(x.getId())))
.toList();
}
@GetMapping("/{id}/readers")
public List<ReaderMangaDto> getReaders(@PathVariable Long id) {
return mangaService.getReader(id).stream()
.map(x -> new ReaderMangaDto(x))
.toList();
}
@DeleteMapping("/{id}")
public MangaDto deleteManga(@PathVariable Long id) {
return new MangaDto(mangaService.deleteManga(id));
}
@PostMapping
public MangaDto createManga(@RequestBody @Valid MangaDto mangaDto) {
return new MangaDto(mangaService.addManga(mangaDto));
}
@PutMapping("/{id}")
public MangaDto updateManga(@RequestBody @Valid MangaDto mangaDto) {
return new MangaDto(mangaService.updateManga(mangaDto));
}
}

View File

@ -1,19 +0,0 @@
package com.LabWork.app.MangaStore.controller;
public class Pair<F, S> {
private final F first;
private final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
}

View File

@ -0,0 +1,85 @@
package com.LabWork.app.MangaStore.controller.Reader;
import com.LabWork.app.MangaStore.model.Dto.CreatorMangaDto;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.ReaderService;
import com.LabWork.app.MangaStore.service.MangaService;
import jakarta.validation.Valid;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@Controller
@RequestMapping("/readerAction")
@Secured({UserRole.AsString.USER})
public class ReaderActionMvcController {
private final ReaderService readerService;
private static final Logger log = LoggerFactory.getLogger(ReaderActionMvcController.class);
private final MangaService mangaService;
public ReaderActionMvcController(ReaderService readerService, MangaService mangaService) {
this.readerService = readerService;
this.mangaService = mangaService;
}
@GetMapping()
public String getReader(Model model, Principal principal) {
model.addAttribute("readers",
readerService.findAllReaders().stream()
.map(ReaderMangaDto::new)
.toList());
ReaderMangaDto currentReader = new ReaderMangaDto(readerService.findByLogin(principal.getName()));
model.addAttribute("readerId", currentReader.getId());
model.addAttribute("reader", new ReaderMangaDto(readerService.findReader(currentReader.getId())));
model.addAttribute("MangaDto", new MangaDto());
model.addAttribute("mangaList", mangaService.findAllMangas());
return "readerAction";
}
/* @GetMapping()
public String getReader(@RequestParam(value = "readerId", required = false) Long readerId, Model model) {
model.addAttribute("readers",
readerService.findAllReaders().stream()
.map(ReaderMangaDto::new)
.toList());
if (readerId != null){
model.addAttribute("readerId", readerId);
model.addAttribute("reader", new ReaderMangaDto(readerService.findReader(readerId)));
} else {
model.addAttribute("readerId", 0);
model.addAttribute("reader", new ReaderMangaDto());
}
model.addAttribute("MangaDto", new MangaDto());
model.addAttribute("mangaList", mangaService.findAllMangas());
return "readerAction";
}*/
@PostMapping("/manga")
public String saveManga(@RequestParam("mangaId") Long mangaId,
@ModelAttribute @Valid MangaDto MangaDto,
BindingResult bindingResult,
Model model,
Principal principal){
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "readerAction";
}
readerService.addManga(mangaId, principal.getName());
return "redirect:/readerAction";
}
@PostMapping("/removeManga/{mangaId}")
public String removeManga(@PathVariable Long mangaId, Principal principal) {
readerService.removeManga(mangaId, principal.getName());
return "redirect:/readerAction/?readerLogin=" + principal.getName();
}
}

View File

@ -1,75 +0,0 @@
package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.model.Dto.ReaderMangaDto;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.MangaDto;
import com.LabWork.app.MangaStore.service.ReaderService;
import com.LabWork.app.MangaStore.service.UserService;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/reader")
public class ReaderController {
private final ReaderService readerService;
private final UserService userService;
public ReaderController(ReaderService readerService,
UserService userService) {
this.readerService = readerService;
this.userService = userService;
}
@GetMapping("/{login}")
public ReaderMangaDto getReader(@PathVariable String login) {
return new ReaderMangaDto(readerService.findReader(userService.findByLogin(login).getReader().getId()));
}
@GetMapping
public List<ReaderMangaDto> getReaders() {
return readerService.findAllReaders().stream()
.map(ReaderMangaDto::new)
.toList();
}
/* @PostMapping
@Secured({UserRole.AsString.ADMIN})
public String createReader(@RequestParam("readerName") String readerName,
@RequestParam("password") String password) {
try {
return new ReaderMangaDto(readerService.addReader(readerName, password)).toString();
} catch (ValidationException e) {
return e.getMessage();
}
}
@PutMapping("/{id}")
public ReaderMangaDto updateReader(@PathVariable Long id,
@RequestParam("readerName") String readerName,
@RequestParam("password") String password) {
return new ReaderMangaDto(readerService.updateReader(id, readerName, password));
}*/
@PutMapping("/{id}/addManga")
public MangaDto addManga(@PathVariable Long id,
@RequestParam("mangaId") Long mangaId) {
return new MangaDto(readerService.addManga(mangaId, id));
}
@PutMapping("/{id}/removeManga")
public MangaDto removeManga(@PathVariable Long id,
@RequestParam("mangaId") Long mangaId) {
return new MangaDto(readerService.removeManga(mangaId, id));
}
@DeleteMapping("/{id}")
public ReaderMangaDto deleteReader(@PathVariable Long id) {
return new ReaderMangaDto(readerService.deleteReader(id));
}
}

View File

@ -0,0 +1,42 @@
package com.LabWork.app.MangaStore.controller.User;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@Secured({UserRole.AsString.ADMIN})
@GetMapping
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -0,0 +1,51 @@
package com.LabWork.app.MangaStore.controller.User;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Dto.UserSignupDto;
import com.LabWork.app.MangaStore.service.UserService;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.validation.Valid;
@Controller
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
public class UserSignupMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignupMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("userDto", new UserSignupDto());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), userSignupDto.getUserRole());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -1,90 +0,0 @@
package com.LabWork.app.MangaStore.controller;
import com.LabWork.app.MangaStore.configuration.OpenAPI30Configuration;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.model.Dto.UserSignupDto;
import com.LabWork.app.MangaStore.service.UserService;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
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
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SING_UP = "/sing_up";
public static final String URL_WHO_AM_I = "/who_am_i";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
@PostMapping(URL_SING_UP)
public String singUp(@RequestBody @Valid UserSignupDto userSignupDto) {
try {
final User user = userService.addUser(userSignupDto.getLogin(), userSignupDto.getEmail(),
userSignupDto.getPassword(), userSignupDto.getPasswordConfirm(), UserRole.USER);
return "created " + user.getLogin();
} catch (ValidationException e) {
return e.getMessage();
}
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public UserDto getUser(@RequestParam("login") String login) {
User user = userService.findByLogin(login);
return new UserDto(user);
}
@Secured(UserRole.AsString.ADMIN)
@PostMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public String updateUser(@RequestBody @Valid UserDto userDto) {
try {
userService.updateUser(userDto);
return "Profile updated";
} catch (ValidationException e) {
return e.getMessage();
}
}
@Secured(UserRole.AsString.ADMIN)
@DeleteMapping(OpenAPI30Configuration.API_PREFIX + "/user/{id}")
public UserDto removeUser(@PathVariable Long id) {
User user = userService.deleteUser(id);
return new UserDto(user);
}
@Secured(UserRole.AsString.ADMIN)
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/users")
public Pair<Page<UserDto>, List<Integer>> getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size) {
final Page<UserDto> users = userService.findAllPages(page, size)
.map(UserDto::new);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
return new Pair<>(users, pageNumbers);
}
@GetMapping(URL_WHO_AM_I)
public String whoAmI(@RequestParam("token") String token) {
UserDetails userDetails = userService.loadUserByToken(token);
User user = userService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
}

View File

@ -1,7 +1,6 @@
package com.LabWork.app.MangaStore.model.Default;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@ -10,13 +9,21 @@ import java.util.Objects;
@Entity
public class Creator {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.EAGER)
@MapsId
private User user;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "creator", cascade = CascadeType.REMOVE)
private List<Manga> mangas;
public Creator() {
}
public Creator(User user) {
this.user = user;
this.id = user.getId();
this.mangas = new ArrayList<>();
}
@ -32,6 +39,8 @@ public class Creator {
this.mangas = mangas;
}
public User getUser() { return user; }
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -25,8 +25,6 @@ public class Manga {
@JoinColumn(name="creator_fk")
private Creator creator;
private Long creatorId;
@Lob
private byte[] image;
public Manga() {

View File

@ -1,7 +1,6 @@
package com.LabWork.app.MangaStore.model.Default;
import jakarta.persistence.*;
import org.hibernate.annotations.Cascade;
import java.util.ArrayList;
import java.util.List;
@ -10,27 +9,31 @@ import java.util.Objects;
@Entity
public class Reader {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private User user;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
/*@Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)*/
/*orphanRemoval=true*/
private List<Manga> mangas;
@OneToOne
@MapsId
@JoinColumn(name = "user_id")
private User user;
public Reader(User user) {
this.mangas = new ArrayList<>();
this.user = user;
}
public Reader() {
}
public Reader(String creatorName, String hashedPassword) {
this.user = user;
this.id = user.getId();
this.mangas = new ArrayList<>();
}
public Reader(User user) {
this.user = user;
this.id = user.getId();
this.mangas = new ArrayList<>();
}
public Long getId() {
return id;
@ -40,6 +43,8 @@ public class Reader {
public void setMangas(List<Manga> mangas) { this.mangas = mangas; }
public User getUser() { return user; }
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -1,12 +1,8 @@
package com.LabWork.app.MangaStore.model.Default;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.model.Dto.UserSignupDto;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@ -15,51 +11,29 @@ public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Login can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect login length")
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank(message = "Email can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect login length")
private String email;
@NotBlank(message = "Password can't be null or empty")
@Size(min = 3, max = 64, message = "Incorrect password length")
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
@OneToOne
@JoinColumn(name = "creator_id")
private Creator creator;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Reader reader;
public User() {
}
public User(String login, String email, String password, UserRole role) {
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.email = email;
this.password = password;
this.role = role;
}
public User(UserDto userDto) {
this.login = userDto.getLogin();
this.email = userDto.getEmail();
this.password = userDto.getPassword();
this.role = userDto.getRole();
}
public User(UserSignupDto userSignupDto) {
this.login = userSignupDto.getLogin();
this.email = userSignupDto.getEmail();
this.password = userSignupDto.getPassword();
this.role = UserRole.USER;
}
// Properties
public Long getId() {
return id;
}
@ -72,14 +46,6 @@ public class User {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
@ -92,53 +58,16 @@ public class User {
return role;
}
public void setRole(UserRole role) {
this.role = role;
}
public void setCreator(Creator creator) {
this.creator = creator;
}
public Creator getCreator() {
return creator;
}
public void setReader(Reader reader) {
this.reader = reader;
}
public Reader getReader() {
return reader;
}
// ![Properties]
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User marketUser = (User) o;
return Objects.equals(id, marketUser.id);
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + login + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
return Objects.hash(id, login);
}
}

View File

@ -16,6 +16,8 @@ public class CreatorMangaDto {
public CreatorMangaDto(Creator creator) {
this.id = creator.getId();
this.creatorName = creator.getUser().getLogin();
this.hashedPassword = creator.getUser().getPassword();
this.mangas = creator.getMangas().stream()
.map(x -> new MangaDto(x))
.toList();

View File

@ -1,75 +0,0 @@
package com.LabWork.app.MangaStore.model.Dto;
import com.LabWork.app.MangaStore.model.Default.Manga;
import com.LabWork.app.MangaStore.model.Default.Reader;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Dto.SupportDto.ReaderDto;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class MangaUserDto {
private Long id;
private Long creatorId;
private String mangaName;
private Integer chapterCount;
private List<ReaderDto> readers;
private String image;
public MangaUserDto() {
}
public MangaUserDto(Manga manga, List<User> listUser) {
this.id = manga.getId();
this.creatorId = manga.getCreator().getId();
this.mangaName = manga.getMangaName();
this.chapterCount = manga.getChapterCount();
this.image = new String(manga.getImage(), StandardCharsets.UTF_8);
this.readers = listUser.stream()
.map(y -> new ReaderDto(y.getReader(), y.getLogin()))
.toList();
}
public Long getId() {
return id;
}
public String getImage() {
return image;
}
public String getMangaName() {
return mangaName;
}
public List<ReaderDto> getReaders() {
return readers;
}
public Integer getChapterCount() {
return chapterCount;
}
public Long getCreatorId() {
return creatorId;
}
public void setImage(String image) {
this.image = image;
}
public void setMangaName(String mangaName) {
this.mangaName = mangaName;
}
public void setReaders(List<ReaderDto> readers) {
this.readers = readers;
}
public void setChapterCount(Integer chapterCount) {
this.chapterCount = chapterCount;
}
public void setCreatorIdString(Long creatorId) {this.creatorId = creatorId;}
}

View File

@ -19,6 +19,8 @@ public class ReaderMangaDto {
public ReaderMangaDto(Reader reader) {
this.id = reader.getId();
this.readerName = reader.getUser().getLogin();
this.hashedPassword = reader.getUser().getPassword();
this.mangas = reader.getMangas().stream()
.map(y -> new MangaDto(y))
.toList();

View File

@ -14,6 +14,8 @@ public class MangaDto {
private Integer chapterCount;
private String image;
private String login;
public MangaDto() {
}
@ -22,6 +24,7 @@ public class MangaDto {
this.creatorId = manga.getCreator().getId();
this.mangaName = manga.getMangaName();
this.chapterCount = manga.getChapterCount();
this.login = null;
this.image = new String(manga.getImage(), StandardCharsets.UTF_8);
}
public Long getId() {
@ -44,6 +47,10 @@ public class MangaDto {
return image;
}
public String getLogin() {
return login;
}
public void setMangaName(String mangaName) {
this.mangaName = mangaName;
}
@ -57,4 +64,10 @@ public class MangaDto {
}
public void setImage(String image) {this.image = image;}
public void setLogin(String login) {
this.login = login;
}
}

View File

@ -16,11 +16,8 @@ public class ReaderDto {
public ReaderDto(Reader reader) {
this.id = reader.getId();
}
public ReaderDto(Reader reader, String readerName) {
this.id = reader.getId();
this.readerName = readerName;
this.readerName = reader.getUser().getLogin();
this.hashedPassword = reader.getUser().getPassword();
}
public Long getId() {

View File

@ -1,71 +1,28 @@
package com.LabWork.app.MangaStore.model.Dto;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
public class UserDto {
private Long id;
private String login;
private String email;
private String password;
private UserRole role;
private Long creatortId;
private Long readerId;
public UserDto() {
}
private final long id;
private final String login;
private final UserRole role;
public UserDto(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.email = user.getEmail();
this.password = user.getPassword();
this.role = user.getRole();
}
public void setId(Long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setLogin(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
public Long getReaderId() {
return readerId;
}
public Long getCreatorId() {
return creatortId;
}
}

View File

@ -1,11 +1,23 @@
package com.LabWork.app.MangaStore.model.Dto;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
private String email;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
private UserRole userRole;
public String getLogin() {
return login;
}
@ -14,14 +26,6 @@ public class UserSignupDto {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
@ -37,4 +41,14 @@ public class UserSignupDto {
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
if (userRole.equals("creator"))this.userRole = UserRole.ADMIN;
else this.userRole = UserRole.USER;
}
}

View File

@ -5,6 +5,8 @@ import com.LabWork.app.MangaStore.model.Default.Manga;
import com.LabWork.app.MangaStore.model.Default.Reader;
import com.LabWork.app.MangaStore.service.Repository.CreatorRepository;
import com.LabWork.app.MangaStore.service.Exception.CreatorNotFoundException;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import com.LabWork.app.MangaStore.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -14,13 +16,17 @@ import java.util.Optional;
@Service
public class CreatorService {
private final CreatorRepository creatorRepository;
private final UserRepository userRepository;
private final MangaService mangaService;
private final ValidatorUtil validatorUtil;
public CreatorService(CreatorRepository creatorRepository,
MangaService mangaService,
ValidatorUtil validatorUtil) {
ValidatorUtil validatorUtil,
UserRepository userRepository) {
this.creatorRepository = creatorRepository;
this.userRepository = userRepository;
this.mangaService = mangaService;
this.validatorUtil = validatorUtil;
}
@ -31,40 +37,17 @@ public class CreatorService {
return creator.orElseThrow(() -> new CreatorNotFoundException(id));
}
public Creator findByLogin(String login) {
return findCreator(userRepository.findOneByLoginIgnoreCase(login).getId());
}
@Transactional(readOnly = true)
public List<Creator> findAllCreators() { return creatorRepository.findAll(); }
@Transactional
public Creator addCreator() {
final Creator creator = new Creator();
public Creator addCreator(User user) {
final Creator creator = new Creator(user);
validatorUtil.validate(creator);
return creatorRepository.save(creator);
}
/* @Transactional
public Creator updateCreator(Long id, String creatorName, String password) {
final Creator currentCreator = findCreator(id);
currentCreator.setCreatorName(creatorName);
currentCreator.setHashedPassword(password);
validatorUtil.validate(currentCreator);
return currentCreator;
}*/
@Transactional
public Creator deleteCreator(Long id) {
final Creator currentCreator = findCreator(id);
List<Manga> listManga = currentCreator.getMangas();
for (Manga manga : listManga){
for (final Reader reader :mangaService.getReader(manga.getId())){
reader.getMangas().remove(manga);
}
}
creatorRepository.delete(currentCreator);
return currentCreator;
}
@Transactional
public void deleteAllCreators() {
creatorRepository.deleteAll();
}
}

View File

@ -1,10 +0,0 @@
package com.LabWork.app.MangaStore.service.Exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super(String.format("User with id [%s] is not found", id));
}
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -8,6 +8,7 @@ import com.LabWork.app.MangaStore.service.Repository.MangaRepository;
import com.LabWork.app.MangaStore.service.Exception.CreatorNotFoundException;
import com.LabWork.app.MangaStore.service.Exception.MangaNotFoundException;
import com.LabWork.app.MangaStore.service.Repository.ReaderRepository;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import com.LabWork.app.MangaStore.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -18,17 +19,20 @@ import java.util.Optional;
public class MangaService {
public final MangaRepository mangaRepository;
public final CreatorRepository creatorRepository;
public final UserRepository userRepository;
public final ReaderService readerService;
private final ValidatorUtil validatorUtil;
public MangaService(MangaRepository mangaRepository,
CreatorRepository creatorRepository,
ReaderService readerService,
ValidatorUtil validatorUtil) {
ValidatorUtil validatorUtil,
UserRepository userRepository) {
this.mangaRepository = mangaRepository;
this.readerService = readerService;
this.creatorRepository = creatorRepository;
this.validatorUtil = validatorUtil;
this.userRepository = userRepository;
}
@Transactional(readOnly = true)
@ -36,6 +40,9 @@ public class MangaService {
final Optional<Manga> manga = mangaRepository.findById(id);
return manga.orElseThrow(() -> new MangaNotFoundException(id));
}
public Creator findCreatorByLogin(String login) {
return findCreator(userRepository.findOneByLoginIgnoreCase(login).getId());
}
@Transactional
public List<Reader> getReader(Long id) {
@ -55,17 +62,9 @@ public class MangaService {
return creator.orElseThrow(() -> new CreatorNotFoundException(id));
}
@Transactional
public Manga addManga(Long creatorId, Integer chapterCount, String mangaName, String Image) {
final Creator currentCreator = findCreator(creatorId);
final Manga manga = new Manga(currentCreator, mangaName, chapterCount, Image);
validatorUtil.validate(manga);
return mangaRepository.save(manga);
}
@Transactional
public Manga addManga(MangaDto mangaDto) {
final Creator currentCreator = findCreator(mangaDto.getCreatorId());
final Creator currentCreator = findCreatorByLogin(mangaDto.getLogin());
final Manga manga = new Manga(currentCreator, mangaDto);
validatorUtil.validate(manga);
return mangaRepository.save(manga);
@ -80,15 +79,6 @@ public class MangaService {
return currentManga;
}
@Transactional
public Manga updateManga(MangaDto mangaDto) {
final Manga currentManga = findManga(mangaDto.getId());
currentManga.setChapterCount(mangaDto.getChapterCount());
currentManga.setImage(mangaDto.getImage().getBytes());
validatorUtil.validate(currentManga);
return currentManga;
}
@Transactional
public Manga deleteManga(Long id) {
final Manga currentManga = findManga(id);
@ -99,9 +89,4 @@ public class MangaService {
mangaRepository.delete(currentManga);
return currentManga;
}
@Transactional
public void deleteAllMangas() {
mangaRepository.deleteAll();
}
}

View File

@ -2,11 +2,13 @@ package com.LabWork.app.MangaStore.service;
import com.LabWork.app.MangaStore.model.Default.Manga;
import com.LabWork.app.MangaStore.model.Default.Reader;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.service.Exception.CreatorNotFoundException;
import com.LabWork.app.MangaStore.service.Repository.MangaRepository;
import com.LabWork.app.MangaStore.service.Repository.ReaderRepository;
import com.LabWork.app.MangaStore.service.Exception.MangaNotFoundException;
import com.LabWork.app.MangaStore.service.Exception.ReaderNotFoundException;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import com.LabWork.app.MangaStore.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -17,15 +19,18 @@ import java.util.Optional;
@Service
public class ReaderService {
private final ReaderRepository readerRepository;
private final UserRepository userRepository;
private final MangaRepository mangaRepository;
private final ValidatorUtil validatorUtil;
public ReaderService(ReaderRepository readerRepository,
ValidatorUtil validatorUtil,
UserRepository userRepository,
MangaRepository mangaRepository) {
this.readerRepository = readerRepository;
this.mangaRepository = mangaRepository;
this.validatorUtil = validatorUtil;
this.userRepository = userRepository;
}
@Transactional
@ -34,6 +39,10 @@ public class ReaderService {
return reader.orElseThrow(() -> new ReaderNotFoundException(id));
}
public Reader findByLogin(String login) {
return findReader(userRepository.findOneByLoginIgnoreCase(login).getId());
}
@Transactional(readOnly = true)
public List<Reader> findAllReaders() {
return readerRepository.findAll();
@ -46,28 +55,6 @@ public class ReaderService {
return readerRepository.save(reader);
}
/* @Transactional
public Reader updateReader(Long id, String readername, String password) {
final Reader currentReader = findReader(id);
currentReader.setReaderName(readername);
currentReader.setHashedPassword(password);
validatorUtil.validate(currentReader);
return currentReader;
}*/
@Transactional
public Reader deleteReader(Long id) {
final Reader currentReader = findReader(id);
currentReader.getMangas().clear();
readerRepository.delete(currentReader);
return currentReader;
}
@Transactional
public void deleteAllReaders() {
readerRepository.deleteAll();
}
@Transactional(readOnly = true)
public Manga findManga(Long id) {
final Optional<Manga> manga = mangaRepository.findById(id);
@ -75,9 +62,9 @@ public class ReaderService {
}
@Transactional
public Manga addManga(Long mangaId, Long readerId) {
public Manga addManga(Long mangaId, String readerLogin) {
final Manga manga = findManga(mangaId);
final Reader reader = findReader(readerId);
final Reader reader = findByLogin(readerLogin);
validatorUtil.validate(reader);
if (reader.getMangas().contains(manga))
{
@ -88,8 +75,8 @@ public class ReaderService {
}
@Transactional
public Manga removeManga(Long mangaId, Long readerId) {
final Reader currentReader = findReader(readerId);
public Manga removeManga(Long mangaId, String readerLogin) {
final Reader currentReader = findByLogin(readerLogin);
final Manga currentManga = findManga(mangaId);
currentReader.getMangas().remove(currentManga);
return currentManga;

View File

@ -3,6 +3,7 @@ package com.LabWork.app.MangaStore.service.Repository;
import com.LabWork.app.MangaStore.model.Default.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -1,16 +1,10 @@
package com.LabWork.app.MangaStore.service;
import com.LabWork.app.MangaStore.configuration.jwt.JwtException;
import com.LabWork.app.MangaStore.configuration.jwt.JwtProvider;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.service.CreatorService;
import com.LabWork.app.MangaStore.service.ReaderService;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.model.Dto.UserDto;
import com.LabWork.app.MangaStore.service.Exception.UserNotFoundException;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import com.LabWork.app.MangaStore.util.validation.ValidationException;
import com.LabWork.app.MangaStore.util.validation.ValidatorUtil;
import com.LabWork.app.MangaStore.model.Default.Creator;
import com.LabWork.app.MangaStore.model.Default.Reader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
@ -19,141 +13,54 @@ 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.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.service.Repository.UserRepository;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final ValidatorUtil validatorUtil;
private final PasswordEncoder passwordEncoder;
private final JwtProvider jwtProvider;
private final CreatorService creatorService;
private final ReaderService readerService;
private final CreatorService creatorService;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
public UserService(UserRepository userRepository,
ValidatorUtil validatorUtil,
PasswordEncoder passwordEncoder,
CreatorService creatorService,
ReaderService readerService,
JwtProvider jwtProvider) {
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil) {
this.userRepository = userRepository;
this.validatorUtil = validatorUtil;
this.passwordEncoder = passwordEncoder;
this.jwtProvider = jwtProvider;
this.creatorService = creatorService;
this.readerService = readerService;
}
@Transactional(readOnly = true)
public User findUser(Long id) {
final Optional<User> user = userRepository.findById(id);
return user.orElseThrow(() -> new UserNotFoundException(id));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
@Transactional(readOnly = true)
public List<User> findAllUsers() {
return userRepository.findAll();
this.creatorService = creatorService;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
@Transactional
public User addUser(String login, String email, String password, String passwordConfirm, UserRole role) {
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
final User user = new User(login, email, passwordEncoder.encode(password), role);
//validatorUtil.validate(user);
userRepository.save(user);
if (role.toString().equals("ADMIN")){
final Creator creator = creatorService.addCreator();
bindCreator(user.getId(), creator.getId());
}
if (role.toString().equals("USER")){
final Reader reader = readerService.addReader(user);
bindReader(user.getId(), reader.getId());
}
if (user.getRole() == UserRole.ADMIN) creatorService.addCreator(user);
else readerService.addReader(user);
return user;
}
@Transactional
public User updateUser(UserDto userDto) {
final User currentUser = findUser(userDto.getId());
final User sameUser = findByLogin(userDto.getLogin());
if (sameUser != null && !Objects.equals(sameUser.getId(), currentUser.getId())) {
throw new ValidationException(String.format("User '%s' already exists", userDto.getLogin()));
}
if (!passwordEncoder.matches(userDto.getPassword(), currentUser.getPassword())) {
throw new ValidationException("Incorrect password");
}
currentUser.setLogin(userDto.getLogin());
currentUser.setEmail(userDto.getEmail());
validatorUtil.validate(currentUser);
return userRepository.save(currentUser);
}
@Transactional
public User deleteUser(Long id) {
final User currentUser = findUser(id);
userRepository.delete(currentUser);
return currentUser;
}
@Transactional
public void deleteAllUsers() {
userRepository.deleteAll();
}
@Transactional
public User bindCreator(Long id, Long creatorId) {
final User user = findUser(id);
final Creator creator = creatorService.findCreator(creatorId);
user.setCreator(creator);
return userRepository.save(user);
}
@Transactional
public User bindReader(Long id, Long readerId) {
final User user = findUser(id);
final Reader reader = readerService.findReader(readerId);
user.setReader(reader);
return userRepository.save(user);
}
public String loginAndGetToken(UserDto userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
throw new UserNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new ValidationException("Incorrect password");
}
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 User userEntity = findByLogin(username);

View File

@ -13,7 +13,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
/*@ControllerAdvice*/
public class AdviceController {
@ExceptionHandler({
CreatorNotFoundException.class,

View File

@ -9,5 +9,3 @@ 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
jwt.dev-token=my-secret-jwt
jwt.dev=true

View File

@ -0,0 +1,111 @@
html,
body {
background-color: #000000;
color: #ffffff;
padding: 0;
margin: 0;
font-family: sans-serif;
line-height: 1.15;
height: 100%;
}
header {
background-color: #3c3c3c;
color: #ffffff;
}
header a {
color: #ffffff;
text-decoration: none;
margin: 0 0.5em;
}
header a:hover {
text-decoration: underline;
}
#logo {
margin-left: 0.5em;
}
article a {
color: #ffffff;
text-decoration: none;
margin: 0.5em 0.5em;
}
header a:hover {
text-decoration: underline;
}
h2 {
font-size: 1.25em;
}
h3 {
font-size: 1.1em;
}
footer {
background-color: #9c9c9c;
color: #ffffff;
height: 32px;
padding: 0.5em;
}
.manga_pages{
display: flex;
flex-direction: column;
align-items: center;
}
.catalog_wrapper{
display: flex;
width: 73%;
flex-direction: column;
}
.catalog_article{
display: flex;
}
.poster{
width:140px;
}
th {
border: 0px solid rgb(255, 255, 255);
}
.added_manga{
display: flex;
flex-direction: column;
}
@media (min-width: 992px) {
.manga_pages img{
max-width: 900px;
width: auto;
height: auto;
}
}
.flex_grow {
flex-grow: 1;
display: flex;
align-items: center;
}
@media (min-width: 1024px){
.article_1 {
max-width: -webkit-calc(1600px + (100vw/64*7)*2);
max-width: -moz-calc(1600px + (100vw/64*7)*2);
max-width: calc(1600px + (100vw/64*7)*2);
padding-left: -webkit-calc(100vw/64*7);
padding-left: -moz-calc(100vw/64*7);
padding-left: calc(100vw/64*7);
padding-right: -webkit-calc(100vw/64*7);
padding-right: -moz-calc(100vw/64*7);
padding-right: calc(100vw/64*7);
}
}
.registration_div {
width: 100%;
height: 100%;
}
.slideshow{
height: 250px;
width: auto;/*maintain aspect ratio*/
max-width:180px;
border-radius: 7%;
}
.table > :not(:first-child) {
border-top: 0;
}

View File

@ -0,0 +1,37 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="1280.000000pt" height="1280.000000pt" viewBox="0 0 1280.000000 1280.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.15, written by Peter Selinger 2001-2017
</metadata>
<g transform="translate(0.000000,1280.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M6090 12534 c-883 -44 -1693 -246 -2418 -604 -635 -313 -1146 -683
-1683 -1220 -1069 -1067 -1655 -2308 -1794 -3795 -22 -238 -30 -735 -16 -980
78 -1331 506 -2470 1306 -3470 280 -349 669 -743 1015 -1026 886 -725 1894
-1159 3035 -1308 299 -39 429 -46 870 -46 460 1 593 9 955 61 1137 162 2166
630 3055 1390 193 164 595 566 759 759 605 708 1027 1507 1251 2368 309 1191
269 2518 -110 3662 -317 956 -904 1845 -1705 2581 -1050 964 -2228 1484 -3640
1609 -167 15 -721 27 -880 19z m-141 -848 c-2 -2 -53 -25 -114 -50 -560 -238
-1123 -701 -1404 -1153 -235 -379 -358 -823 -380 -1369 -32 -790 142 -1362
564 -1852 156 -181 413 -398 660 -558 228 -147 595 -288 1140 -439 704 -195
876 -254 1145 -391 69 -35 159 -85 200 -112 41 -27 116 -72 165 -102 395 -233
696 -560 910 -987 122 -245 201 -498 247 -793 18 -114 18 -599 0 -740 -23
-182 -62 -360 -113 -516 -190 -578 -549 -979 -1124 -1255 -378 -182 -772 -281
-1360 -341 -73 -8 -274 -13 -515 -13 -415 0 -507 7 -785 56 -678 122 -1390
456 -1991 934 -1176 936 -1894 2146 -2088 3518 -44 309 -51 415 -51 792 0 377
7 487 51 793 137 964 544 1858 1207 2652 909 1089 2055 1733 3377 1899 91 11
181 22 200 24 19 2 41 5 49 5 8 1 12 0 10 -2z m576 -1850 c126 -41 218 -98
316 -195 74 -73 93 -100 132 -181 25 -52 51 -120 58 -150 20 -82 17 -300 -5
-380 -55 -201 -203 -378 -391 -470 -100 -49 -182 -69 -310 -76 -220 -12 -403
54 -568 206 -91 84 -156 184 -193 296 -27 83 -29 100 -29 239 1 143 2 154 32
232 87 228 281 414 508 486 77 24 90 26 235 23 114 -3 148 -8 215 -30z"/>
<path d="M6130 4301 c-162 -35 -293 -106 -419 -225 -116 -112 -199 -251 -242
-411 -32 -115 -32 -345 0 -460 85 -311 327 -549 639 -627 121 -31 313 -30 427
1 255 69 477 256 595 503 145 302 87 700 -137 939 -131 138 -252 215 -420 265
-120 36 -317 43 -443 15z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<article class="p-2 catalog_article">
<div class = "catalog_wrapper">
<h1>Каталог</h1>
<div class="p-2 d-flex flex-wrap">
<a th:each="manga: ${mangaList}" th:href="@{/manga/{id}(id=${manga.id})}"><img th:src="${manga.image}" class="slideshow"/></a>
</div>
</div>
</article>
</div>
</body>
</html>

View File

@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form th:if="${controller != 'creator/'}" action="#" th:action="@{/creatorAction/manga/{id}(id=${id})}" th:object="${mangaDto}" enctype="multipart/form-data" method="post">
<div class="mb-3" th:if="${controller == 'creator/'}">
<label for="mangaNameU" class="form-label">mangaName</label>
<input id="mangaNameU" type='text' class="form-control" th:field="${mangaDto.mangaName}" required="true"/>
</div>
<div class="mb-3">
<label for="chapterCountU" class="form-label">chapterCount</label>
<input id="chapterCountU" type='number' class="form-control" th:field="${mangaDto.chapterCount}" required="true"/>
</div>
<div class="mb-3">
<label for="multipartFileU" class="form-label">image</label>
<input type="file" id="multipartFileU" th:name="multipartFile" accept="image/png, image/jpeg" class="form-control" required="true"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/creator}">
Назад
</a>
</div>
</form>
<form th:if="${controller == 'creator/'}" action="#" th:action="@{/creatorAction/creator}" th:object="${mangaDto}" enctype="multipart/form-data" method="post">
<div class="mb-3" th:if="${controller == 'creator/'}">
<label for="mangaName" class="form-label">mangaName</label>
<input id="mangaName" type='text' class="form-control" th:field="${mangaDto.mangaName}" required="true"/>
</div>
<div class="mb-3">
<label for="chapterCount" class="form-label">chapterCount</label>
<input id="chapterCount" type='number' class="form-control" th:field="${mangaDto.chapterCount}" required="true"/>
</div>
<div class="mb-3">
<label for="multipartFile" class="form-label">image</label>
<input type="file" id="multipartFile" th:name="multipartFile" accept="image/png, image/jpeg" class="form-control" required="true"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Добавить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/creator}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<head>
<script type="text/javascript" src="/webjars/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container" id="root-div" layout:fragment="content">
<div class="content">
<h1>Creator</h1>
<form id="form mb-3">
<div class="d-flex mt-3">
<div class="d-grid col-sm-2">
<a class="btn btn-success"
th:href="@{/creatorAction/create}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
</div>
</form>
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<div class="row table-responsive text-white">
<div th:each="manga, iterator: ${currentCreator?.mangas}" class="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div class="me-3">
<a th:href="@{/manga/{id}(id=${manga.id})}"><img th:src="${manga.image}" th:alt="${manga.mangaName}" class="slideshow"/></a>
</div>
<div>
<div class="pt-3 description d-flex flex-column justify-content-start mb-3 fs-6 fw-bold">
<h4>Название манги: <a class="text-white fs-5 unic_class fw-bold pt-3 mb-3" th:href="@{/mangapage/{id}(id=${manga.id})}" th:text="${manga.mangaName}"></a></h4>
<h4>
Количество глав:
<span th:text="${manga.chapterCount}"/>
</h4>
</div>
<div>
<a class="btn btn-primary" th:href="@{/creatorAction/edit/{id}(id=${manga.id})}">
<i class="fas fa-edit"></i>
</a>
</button>
<button type="button" class="delete bg-danger p-2 px-2 mx-2 border border-0 rounded text-white fw-bold"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${manga.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<form th:action="@{/creatorAction/delete/{id}(id=${manga.id})}" method="post">
<button th:id="'remove-' + ${manga.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script>
$(document).ready(function() {
$('#creatorId').on('change', function() {
this.form.submit();
});
});
</script>
</th:block>
</html>

View File

@ -0,0 +1,55 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8"/>
<title>ReManga</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="icon" href="/favicon.svg">
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="fa-solid fa-yin-yang"></i>
ReManga
</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav" sec:authorize="!isAuthenticated()">
<a class="nav-link" href="/login">Вход</a>
</ul>
<ul class="navbar-nav" sec:authorize="isAuthenticated()">
<a class="nav-link" href="/">Index</a>
<!--(login=${#authentication.name})-->
<a class="nav-link" sec:authorize="hasRole('ROLE_ADMIN')" th:href="@{/creatorAction(login=${#authentication.name})}">CreatorAction</a>
<a class="nav-link" sec:authorize="hasRole('ROLE_USER')" th:href="@{/readerAction(readerLogin=${#authentication.name})}">ReaderAction</a>
<a sec:authorize="hasRole('ROLE_USER')" class="nav-link" href="/users">Users</a>
<a class="nav-link" href="/manga">Catalog</a>
<a class="nav-link" href="/swagger-ui/index.html">Документация REST API</a>
<a class="nav-link" href="/h2-console/">Консоль H2</a>
<a class="nav-link" href="/logout">
Выход (<span th:text="${#authentication.name}"></span>)
</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div><span th:text="${error}"></span></div>
<a href="/">На главную</a>
</div>
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content_header" th:text="'Главная'"></div>
<div layout:fragment="content">
<div>It's works!</div>
<a href="123">ERROR</a>
</div>
</body>
</html>

View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
Пользователь не найден или пароль указан не верно
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Выход успешно произведен
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
Пользователь '<span th:text="${param.created}"></span>' успешно создан
</div>
<form th:action="@{/login}" method="post" class="container-padding">
<div class="mb-3">
<input type="text" name="username" id="username" class="form-control"
placeholder="Логин" required="true" autofocus="true"/>
</div>
<div class="mb-3">
<input type="password" name="password" id="password" class="form-control"
placeholder="Пароль" required="true"/>
</div>
<button type="submit" class="btn btn-success button-fixed">Войти</button>
<a class="btn btn-primary button-fixed" href="/signup">Регистрация</a>
</form>
</div>
</body>
</html>
<!DOCTYPE html>

View File

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="container d-flex" >
<div class="d-flex flex-column">
<img class="img_style01" style={{borderRadius:"3%"}} th:src="${manga.image}" th:alt="${manga.mangaName}"/>
</div>
<div class="container table text-white fs-4 ms-4">
<div class="row text-white fw-bold fs-3">О манге</div>
<div class="row">
<div class="col-xs-6 col-sm-3">Год производства</div>
<div class="col-xs-6 col-sm-3">1000</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-3">Страна</div>
<div class="col-xs-6 col-sm-3">Россия</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-3">Жанр</div>
<div class="col-xs-6 col-sm-3">Драма</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-3">Количество глав</div>
<div class="col-xs-6 col-sm-3" th:text="${manga.chapterCount}"></div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-3">Возраст</div>
<div class="col-xs-6 col-sm-3">16+</div>
</div>
<div class="row text-white fw-bold fs-3">Описание</div>
<div class="row">
<div class="col-xs-6 col-sm-12">
<p>Ким Кон Чжа спокойно живет в своей халупе, завидуя всем популярным охотникам. Однажды его желание быть лучше всех сбывается и он получает легендарный навык “Копирование способностей”... ценой своей жизни.</p>
<p>Прежде чем он успевает понять это, его убивает охотник №1, Летний дух! Но это активирует его навык, и теперь он скопировал новый, “Путешествие во времени после смерти”.</p>
<p>Как Ким Кон Чжа же будет использовать эти навыки, чтобы победить конкурентов и подняться на вершину?</p>
</div>
</div>
<div class="row table-responsive text-white">
<div th:each="reader: ${readers}" class="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div>
<div class="pt-3 description mb-3 fs-6 fw-bold">
Имя пользователя:
<a th:href="@{/readerAction/(readerLogin=${reader.readerName})}" th:text="${reader.readerName}"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<head>
<script type="text/javascript" src="/webjars/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="container" id="root-div" layout:fragment="content">
<div class="content">
<h1>Reader</h1>
<div class="d-flex mt-3">
<div class="d-grid col-sm-2">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/readerAction/manga}" method="post">
<div class="mb-3">
<label for="mangaId" class="form-label">Манга</label>
<select th:name="mangaId" id="mangaId" class="form-select">
<option th:each="manga: ${mangaList}" th:value="${manga.id}" th:text="${manga.mangaName}"/>
</select>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<i class="fa-solid fa-plus">Добавить</i>
</button>
</div>
</form>
</div>
</div>
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<div class="row table-responsive text-white">
<div th:each="manga: ${reader?.mangas}" class="d-flex flex-row flex-wrap flex-grow-1 align-items-center mt-3">
<div class="me-3">
<a th:href="@{/manga/{id}(id=${manga.id})}"><img th:src="${manga.image}" th:alt="${manga.mangaName}" class="slideshow"/></a>
</div>
<div>
<div class="pt-3 description d-flex flex-column justify-content-start mb-3 fs-6 fw-bold">
<h4>Название манги: <a class="text-white fs-5 unic_class fw-bold pt-3 mb-3" th:href="@{/mangapage/{id}(id=${manga.id})}" th:text="${manga.mangaName}"></a></h4>
<h4>
Количество глав:
<span th:text="${manga.chapterCount}"/>
</h4>
</div>
<div>
</button>
<button type="button" class="delete bg-danger p-2 px-2 mx-2 border border-0 rounded text-white fw-bold"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${manga.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<form th:action="@{'/readerAction/' + 'removeManga/' + ${manga.id}}" method="post">
<button th:id="'remove-' + ${manga.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script>
$(document).ready(function() {
$('#readerId').on('change', function() {
this.form.submit();
});
});
</script>
</th:block>
</html>

View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container container-padding" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${userDto.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${userDto.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
<div class="mb-3">
<label for="userRole" class="form-label">Роль</label>
<select th:field="${userDto.userRole}" id="userRole" class="form-select">
<option th:value="'creator'" th:text="creator"></option>
<option th:value="'reader'" th:text="reader"></option>
</select>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table text-white">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination text-white">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active">
</a>
</div>
</div>
</body>
</html>

View File

@ -1,77 +0,0 @@
package com.LabWork.app;
import com.LabWork.app.MangaStore.model.Default.User;
import com.LabWork.app.MangaStore.model.Default.UserRole;
import com.LabWork.app.MangaStore.service.Exception.UserNotFoundException;
import com.LabWork.app.MangaStore.service.UserService;
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.util.List;
@SpringBootTest
public class JpaUserTests {
private static final Logger log = LoggerFactory.getLogger(JpaUserTests.class);
@Autowired
private UserService userService;
@Test
void testUserCreate() {
userService.deleteAllUsers();
final User user = userService.addUser("User 1", "email@gmail.com",
"123456", "123456", UserRole.USER);
log.info("testUserCreate: " + user.toString());
Assertions.assertNotNull(user.getId());
userService.deleteAllUsers();
}
@Test
void testUserRead() {
userService.deleteAllUsers();
final User user = userService.addUser("User 2", "email@gmail.com",
"123456", "123456", UserRole.USER);
log.info("testUserRead[0]: " + user.toString());
final User findUser = userService.findUser(user.getId());
log.info("testUserRead[1]: " + findUser.toString());
Assertions.assertEquals(user, findUser);
userService.deleteAllUsers();
}
@Test
void testUserReadNotFound() {
userService.deleteAllUsers();
Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(-1L));
}
@Test
void testUserReadAll() {
userService.deleteAllUsers();
userService.addUser("User 3", "email@gmail.com", "123456",
"123456", UserRole.USER);
userService.addUser("User 4", "email@gmail.com", "123456",
"123456", UserRole.USER);
final List<User> users = userService.findAllUsers();
log.info("testUserReadAll: " + users.toString());
Assertions.assertEquals(users.size(), 2);
userService.deleteAllUsers();
}
@Test
void testUserReadAllEmpty() {
userService.deleteAllUsers();
final List<User> users = userService.findAllUsers();
log.info("testUserReadAllEmpty: " + users.toString());
Assertions.assertEquals(users.size(), 0);
}
}