Compare commits
62 Commits
master
...
lab6(React
Author | SHA1 | Date | |
---|---|---|---|
c05294839e | |||
07a73fa1c4 | |||
99a8de13ba | |||
6da86fa98c | |||
3cb5f04ba6 | |||
0b8538198f | |||
053eab0019 | |||
814cc54767 | |||
c61553b284 | |||
dcb1c381c9 | |||
a22ff8d8bb | |||
ee165d350a | |||
62627de1ee | |||
58188e1dbe | |||
23af234a27 | |||
534654ffd5 | |||
bd695a00ba | |||
4977f33ed1 | |||
12d79028c6 | |||
d45c220d50 | |||
3acc25cbc6 | |||
6aa51bc74e | |||
ab9181004e | |||
e40639a883 | |||
18ee5ece77 | |||
26f94dab02 | |||
9cd8ce211d | |||
c88068f489 | |||
688fd255c6 | |||
4b9638ad2f | |||
62d5bd2394 | |||
1335f82494 | |||
eecfe393e4 | |||
6a071071e2 | |||
419eb0b15a | |||
08dad1b6a4 | |||
0c1764ab47 | |||
ee923e986d | |||
cbf337eea6 | |||
33f6f1dd21 | |||
55b8db56c7 | |||
b016ee75a3 | |||
32498b023a | |||
c1a8b9fe81 | |||
45a590f145 | |||
071d001e08 | |||
2cb40754c1 | |||
ca9a45d0b8 | |||
b620bbf62d | |||
6bee6f84ee | |||
b24242b20f | |||
903e6051e8 | |||
5ca10677cf | |||
b43f9e4ffa | |||
58bf3c0d25 | |||
a55af823c6 | |||
c65125a48e | |||
f0e3f4374b | |||
0df1eca957 | |||
41fff9ad53 | |||
23bb2f4187 | |||
843cf0b815 |
4
.gitignore
vendored
@ -4,7 +4,9 @@ build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
node_modules
|
||||
data.mv.db
|
||||
data.trace.db
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
|
24
FrontEnd/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# 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?
|
BIN
FrontEnd/Ped.pdf
Normal file
BIN
FrontEnd/Rasp(1-4).pdf
Normal file
BIN
FrontEnd/Rasp(5-11).pdf
Normal file
53
FrontEnd/build.gradle
Normal file
@ -0,0 +1,53 @@
|
||||
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'
|
||||
}
|
||||
|
||||
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']
|
||||
}
|
BIN
FrontEnd/img/6666.png
Normal file
After Width: | Height: | Size: 60 KiB |
BIN
FrontEnd/img/Emblema.png
Normal file
After Width: | Height: | Size: 77 KiB |
BIN
FrontEnd/img/Rasp.png
Normal file
After Width: | Height: | Size: 67 KiB |
BIN
FrontEnd/img/Shkola.jpg
Normal file
After Width: | Height: | Size: 166 KiB |
BIN
FrontEnd/img/banner1.png
Normal file
After Width: | Height: | Size: 522 KiB |
BIN
FrontEnd/img/banner2.png
Normal file
After Width: | Height: | Size: 903 KiB |
BIN
FrontEnd/img/banner3.png
Normal file
After Width: | Height: | Size: 471 KiB |
BIN
FrontEnd/img/icon.png
Normal file
After Width: | Height: | Size: 54 KiB |
BIN
FrontEnd/img/owl.png
Normal file
After Width: | Height: | Size: 147 KiB |
16
FrontEnd/index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="img/icon.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<script 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>МБОУ средняя общеобразовательная школа №10</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
18
FrontEnd/js/banner.js
Normal file
@ -0,0 +1,18 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
console.info('Loaded');
|
||||
const banners = document.querySelectorAll("#banner img");
|
||||
var old = banners.length - 1;
|
||||
var current = 0;
|
||||
function loop() {
|
||||
banners[current].setAttribute('className', 'show');
|
||||
banners[old].setAttribute('className', 'hide');
|
||||
console.info('Banner changed');
|
||||
old = current;
|
||||
current++;
|
||||
if (current === banners.length) {
|
||||
current = 0;
|
||||
}
|
||||
setTimeout(loop, 5000);
|
||||
}
|
||||
loop();
|
||||
});
|
1641
FrontEnd/package-lock.json
generated
Normal file
26
FrontEnd/package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "spa-react",
|
||||
"private": true,
|
||||
"source": "index.html",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.4.4",
|
||||
"axios": "^1.1.3",
|
||||
"bootstrap": "^5.2.2",
|
||||
"@fortawesome/fontawesome-free": "^6.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.0.24",
|
||||
"@types/react-dom": "^18.0.8",
|
||||
"vite": "^3.2.3",
|
||||
"@vitejs/plugin-react": "^2.2.0"
|
||||
}
|
||||
}
|
1
FrontEnd/public/favicon.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>
|
After Width: | Height: | Size: 611 B |
49
FrontEnd/src/App.jsx
Normal file
@ -0,0 +1,49 @@
|
||||
import { Routes, BrowserRouter, Route } from 'react-router-dom';
|
||||
import PrivateRoutes from "./components/common/PrivateRoutes";
|
||||
import MainPage from './components/catalogs/MainPage';
|
||||
import UsersPage from './components/catalogs/Users';
|
||||
import CatalogStudents from './components/catalogs/News';
|
||||
import Post from './components/catalogs/Post';
|
||||
import Footer from './components/common/Footer';
|
||||
import LoginPage from "./components/catalogs/LoginPage";
|
||||
import SignupPage from "./components/catalogs/SignupPage";
|
||||
import NavBar from "./components/common/NavBar";
|
||||
import Account from './components/catalogs/Account';
|
||||
|
||||
export default function App() {
|
||||
const links = [
|
||||
{ path: 'main', label: "Main", userGroup: "AUTH" },
|
||||
{ path: 'news', label: "News", userGroup: "AUTH" },
|
||||
{ path: 'users', label: "Users", userGroup: "ADMIN" },
|
||||
{ path: 'account', label: "Account", userGroup: "AUTH" },
|
||||
];
|
||||
return(
|
||||
<>
|
||||
<BrowserRouter>
|
||||
<div className='body_app'>
|
||||
<NavBar links={links}></NavBar>
|
||||
<div className="d-flex flex-column text-white bg-info bg-gradient fw-bold ">
|
||||
<Routes>
|
||||
<Route element={<LoginPage />} path="/login" />
|
||||
<Route element={<SignupPage />} path="/signup" />
|
||||
<Route element={<PrivateRoutes userGroup="AUTH" />}>
|
||||
<Route element={<CatalogStudents />} path="/news" />
|
||||
<Route element={<MainPage />} path="/main" exact />
|
||||
<Route element={<MainPage />} path="/main" exact />
|
||||
<Route element={<Account />} path="/account" exact />
|
||||
<Route element={<Post />} path="/Post" />
|
||||
</Route>
|
||||
<Route element={<PrivateRoutes userGroup="ADMIN" />}>
|
||||
<Route element={<UsersPage />} path="/users" />
|
||||
</Route>
|
||||
</Routes>
|
||||
</div>
|
||||
<Footer className="border-top">
|
||||
Footer
|
||||
</Footer >
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
</>
|
||||
);
|
||||
|
||||
}
|
22
FrontEnd/src/ModalEdit.module.css
Normal file
@ -0,0 +1,22 @@
|
||||
.myModal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
display: none;
|
||||
background: rgba(0,0,0, 0.5);
|
||||
}
|
||||
|
||||
.myModalContent {
|
||||
padding: 25px;
|
||||
background: white;
|
||||
border-radius: 16px;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.myModal.active {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
151
FrontEnd/src/components/catalogs/Account.jsx
Normal file
@ -0,0 +1,151 @@
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import News from './NewsForAccount';
|
||||
const hostURL = "http://localhost:8080";
|
||||
const host = hostURL + "/api/1.0";
|
||||
|
||||
const Account = function () {
|
||||
|
||||
const [currentUser, setCurrentUser] = useState({});
|
||||
|
||||
const loginInput = useRef();
|
||||
const emailInput = useRef();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
getUser().then(user => setCurrentUser(user));
|
||||
}, []);
|
||||
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
|
||||
const login = async function () {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(currentUser),
|
||||
};
|
||||
const requestUrl = hostURL + "/jwt/login";
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const result = await response.text();
|
||||
if (response.status === 200) {
|
||||
localStorage.setItem("token", result);
|
||||
localStorage.setItem("user", currentUser.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"));
|
||||
}
|
||||
|
||||
const updateUser = async function () {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
},
|
||||
body: JSON.stringify(currentUser),
|
||||
};
|
||||
const requestUrl = host + `/user`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const result = await response.text();
|
||||
return result;
|
||||
}
|
||||
|
||||
const getUser = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
let login = localStorage.getItem("user");
|
||||
const requestUrl = host + `/user?login=${login}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const user = await response.json();
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
const onSubmit = function (event) {
|
||||
event.preventDefault();
|
||||
updateUser().then((result) => {
|
||||
alert(result);
|
||||
if (result === "Profile updated") {
|
||||
login();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const onInput = function (event, fieldName) {
|
||||
setCurrentUser(oldUser => ({
|
||||
...oldUser, [fieldName]: event.target.value
|
||||
}));
|
||||
}
|
||||
|
||||
const logoutButtonOnClick = function () {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user");
|
||||
localStorage.removeItem("role");
|
||||
window.dispatchEvent(new Event("storage"));
|
||||
navigate("/login");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="border-bottom pb-3 mb-3">
|
||||
<button className="btn btn-primary"
|
||||
onClick={logoutButtonOnClick}>
|
||||
Log Out
|
||||
</button>
|
||||
</div>
|
||||
<h4 className="mb-4">Update profile</h4>
|
||||
<form onSubmit={onSubmit}>
|
||||
<div className="mb-3">
|
||||
<p className="mb-1">New Login</p>
|
||||
<input className="form-control" type="text" required
|
||||
ref={loginInput} value={currentUser.login}
|
||||
onInput={(event) => onInput(event, "login")} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<p className="mb-1">New Email</p>
|
||||
<input className="form-control" type="text" required
|
||||
ref={emailInput} value={currentUser.email}
|
||||
onInput={(event) => onInput(event, "email")} />
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<p className="mb-1">Enter password</p>
|
||||
<input className="form-control" type="password" required
|
||||
ref={emailInput}
|
||||
onInput={(event) => onInput(event, "password")} />
|
||||
</div>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
Save
|
||||
</button>
|
||||
</form>
|
||||
<News>
|
||||
</News>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Account;
|
96
FrontEnd/src/components/catalogs/Catalog.jsx
Normal file
@ -0,0 +1,96 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import Toolbar from "../common/Toolbar";
|
||||
import Table from "../common/Card";
|
||||
import Modal from "../common/Modal";
|
||||
|
||||
export default function Catalog(props) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [userId,setUserId] = useState(-1);
|
||||
const [value,setvalue]=useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
console.log("random");
|
||||
}, [items]);
|
||||
|
||||
useEffect(()=>
|
||||
{
|
||||
if(userId==-1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
loadItems1();
|
||||
},[userId])
|
||||
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
useEffect(()=>
|
||||
{
|
||||
if(value=="")
|
||||
{
|
||||
return;
|
||||
}
|
||||
loadItems2();
|
||||
},[value])
|
||||
const setUserIDd = async function(id)
|
||||
{
|
||||
setUserId(id);
|
||||
}
|
||||
const loadItems = async function() {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/api/1.0/post`;
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const posts = await response.json();
|
||||
|
||||
setItems(posts);
|
||||
}
|
||||
const loadItems1 = async function() {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/api/1.0/user/${userId}/posts`;
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const posts = await response.json();
|
||||
setItems(posts);
|
||||
}
|
||||
|
||||
const loadItems2 = async function() {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/api/1.0/post/filteredposts?Text=${value}`;
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const posts = await response.json();
|
||||
setItems(posts);
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-3 my-2"><input type="text" id="search" className="form-control" required onChange={(event)=> setvalue(event.target.value)}/></div>
|
||||
<Toolbar
|
||||
getUser={setUserIDd}
|
||||
/>
|
||||
<Table
|
||||
headers={props.headers}
|
||||
items={items}
|
||||
value={value}
|
||||
userId={userId}
|
||||
selectable={true}/>
|
||||
</>
|
||||
);
|
||||
}
|
164
FrontEnd/src/components/catalogs/CatalogAccount.jsx
Normal file
@ -0,0 +1,164 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import Toolbar from "../common/ToolbarAccount";
|
||||
import Table from "../common/CardForNews";
|
||||
import Modal from "../common/Modal";
|
||||
const hostURL = "http://localhost:8080";
|
||||
const host = hostURL + "/api/1.0";
|
||||
export default function CatalogAccount(props) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [modalHeader, setModalHeader] = useState('');
|
||||
const [modalConfirm, setModalConfirm] = useState('');
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [isEdit, setEdit] = useState(false);
|
||||
const [userId,setUserId]=useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
getUserId();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if(userId==0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
loadItems();
|
||||
}, [userId]);
|
||||
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
const getUserId = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
let login = localStorage.getItem("user");
|
||||
const requestUrl = host + `/userId?login=${login}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const user = await response.json();
|
||||
setUserId(user);
|
||||
}
|
||||
const loadItems = async function() {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
console.log(userId);
|
||||
const requestUrl = `http://localhost:8080/api/1.0/user/${userId}/posts`;
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const posts = await response.json();
|
||||
console.log(posts);
|
||||
setItems(posts);
|
||||
}
|
||||
|
||||
|
||||
const saveItem = async function() {
|
||||
if (!isEdit) {
|
||||
|
||||
const requestUrl = `http://localhost:8080/api/1.0/user/${userId}/Post`;
|
||||
const temppost=JSON.stringify(props.data)
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
},
|
||||
body: temppost,
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(() => loadItems());
|
||||
|
||||
} else {
|
||||
const requestUrl = "http://localhost:8080/api/1.0/post/"+props.data.id;
|
||||
const temppost=JSON.stringify(props.data)
|
||||
const requestParams = {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
},
|
||||
body: temppost,
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(() => loadItems());
|
||||
}
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
setEdit(false);
|
||||
setModalHeader('Добавление элемента');
|
||||
setModalConfirm('Добавить');
|
||||
setModalVisible(true);
|
||||
props.onAdd();
|
||||
}
|
||||
|
||||
|
||||
const edit = async function(editedId) {
|
||||
const requestUrl = "http://localhost:8080/api/1.0/post/"+editedId;
|
||||
const requestParams = {
|
||||
mode: 'cors',
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
},
|
||||
}
|
||||
await fetch(requestUrl,requestParams)
|
||||
.then(data => {
|
||||
setEdit(true);
|
||||
setModalHeader('Редактирование элемента');
|
||||
setModalConfirm('Сохранить');
|
||||
setModalVisible(true);
|
||||
//props.onEdit(data);
|
||||
return data.json();
|
||||
}).then(data =>{
|
||||
props.onEdit(data);
|
||||
});
|
||||
}
|
||||
|
||||
const handleRemove = async function(id) {
|
||||
if (confirm('Удалить выбранные элементы?')) {
|
||||
const requestUrl = `http://localhost:8080/api/1.0/user/${userId}/Post/`+id;
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
},
|
||||
};
|
||||
await fetch(requestUrl,requestParams).then(()=>loadItems());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
function handleModalHide() {
|
||||
setModalVisible(false);
|
||||
}
|
||||
|
||||
function handleModalDone() {
|
||||
saveItem();
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<Toolbar
|
||||
onAdd={handleAdd}
|
||||
/>
|
||||
<Table
|
||||
headers={props.headers}
|
||||
items={items}
|
||||
selectable={true}
|
||||
onEdit={edit}
|
||||
onRemove={handleRemove}/>
|
||||
<Modal
|
||||
header={modalHeader}
|
||||
confirm={modalConfirm}
|
||||
visible={modalVisible}
|
||||
onHide={handleModalHide}
|
||||
onDone={handleModalDone}>
|
||||
{props.children}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
90
FrontEnd/src/components/catalogs/LoginPage.jsx
Normal file
@ -0,0 +1,90 @@
|
||||
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("/main");
|
||||
}
|
||||
|
||||
const loginFormOnSubmit = function (event) {
|
||||
event.preventDefault();
|
||||
login(loginInput.current.value, passwordInput.current.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-auto my-3">
|
||||
<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? </span>
|
||||
<Link to="/signup">Sign Up here</Link>
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginPage;
|
23
FrontEnd/src/components/catalogs/MainPage.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { useEffect } from "react";
|
||||
import { useState } from "react";
|
||||
import Banner from '../common/Banner'
|
||||
|
||||
export default function Catalogs(props) {
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<Banner />
|
||||
<div className="lp"><img className="img-fluid img-school float-start my-2" src="img/Shkola.jpg" alt="shkola"/>
|
||||
<div>
|
||||
<p className="fs-4">Мы расположены по адресу: 423228, г. Нижневратовск, ул. Корзинова, д. 37</p>
|
||||
<div>
|
||||
<div className="fs-4">Контактные телефоны
|
||||
<p>(8228) 13-77-85</p>
|
||||
<p>(8800) 55-53-50</p>
|
||||
<p>факс (8911) 22-44-96</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div><a className="fs-4" href="mailto:Nizhnev.school10@mail.ru">email: Nizhnev.school10@mail.ru</a>
|
||||
</div>
|
||||
);
|
||||
}
|
59
FrontEnd/src/components/catalogs/News.jsx
Normal file
@ -0,0 +1,59 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Catalog from './Catalog';
|
||||
import New from '../../models/NewDto';
|
||||
|
||||
export default function News(props) {
|
||||
const url = '/api/1.0/post/';
|
||||
const transformer = (data) => new New(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: 'image', label: 'Картинка' },
|
||||
{ name: 'heading', label: 'Заголовок' },
|
||||
{ name: 'content', label: 'Новости' },
|
||||
];
|
||||
|
||||
const [data, setData] = useState(new New());
|
||||
const fileReader=new FileReader();
|
||||
fileReader.onloadend=()=>{
|
||||
const tempval=fileReader.result;
|
||||
setData({ ...data, ['image']: tempval})
|
||||
}
|
||||
const handleOnChange=(event)=>{
|
||||
event.preventDefault();
|
||||
const file=event.target.files[0];
|
||||
fileReader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new New());
|
||||
}
|
||||
|
||||
function handleOnEdit(data) {
|
||||
setData(new New(data));
|
||||
}
|
||||
function handleFormChange(event) {
|
||||
setData({ ...data, [event.target.id]: event.target.value })
|
||||
}
|
||||
|
||||
return (
|
||||
<Catalog
|
||||
headers={catalogStudHeaders}
|
||||
url={url}
|
||||
transformer={transformer}
|
||||
data={data}>
|
||||
<div className="mb-3 text-black">
|
||||
<label htmlFor="image" className="form-label">Изображение</label>
|
||||
<input type="file" id="image" className="form-control" required onChange={handleOnChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="heading" className="form-label text-black">Заголовок</label>
|
||||
<input type="text" id="heading" className="form-control" required
|
||||
value={data.heading} onChange={handleFormChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="content" className="form-label text-black">Содержание</label>
|
||||
<input type="text" id="content" className="form-control" required
|
||||
value={data.content} onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
);
|
||||
}
|
61
FrontEnd/src/components/catalogs/NewsForAccount.jsx
Normal file
@ -0,0 +1,61 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Catalog from './CatalogAccount';
|
||||
import New from '../../models/NewDto';
|
||||
|
||||
export default function NewsForAccount(props) {
|
||||
const url = '/api/1.0/post/';
|
||||
const transformer = (data) => new New(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: 'image', label: 'Картинка' },
|
||||
{ name: 'heading', label: 'Заголовок' },
|
||||
{ name: 'content', label: 'Новости' },
|
||||
];
|
||||
|
||||
const [data, setData] = useState(new New());
|
||||
const fileReader=new FileReader();
|
||||
fileReader.onloadend=()=>{
|
||||
const tempval=fileReader.result;
|
||||
setData({ ...data, ['image']: tempval})
|
||||
}
|
||||
const handleOnChange=(event)=>{
|
||||
event.preventDefault();
|
||||
const file=event.target.files[0];
|
||||
fileReader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new New());
|
||||
}
|
||||
|
||||
function handleOnEdit(data) {
|
||||
setData(new New(data));
|
||||
}
|
||||
function handleFormChange(event) {
|
||||
setData({ ...data, [event.target.id]: event.target.value })
|
||||
}
|
||||
|
||||
return (
|
||||
<Catalog
|
||||
headers={catalogStudHeaders}
|
||||
url={url}
|
||||
transformer={transformer}
|
||||
data={data}
|
||||
onAdd={handleOnAdd}
|
||||
onEdit={handleOnEdit}>
|
||||
<div className="mb-3 text-black">
|
||||
<label htmlFor="image" className="form-label">Изображение</label>
|
||||
<input type="file" id="image" className="form-control" required onChange={handleOnChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="heading" className="form-label text-black">Заголовок</label>
|
||||
<input type="text" id="heading" className="form-control" required
|
||||
value={data.heading} onChange={handleFormChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="content" className="form-label text-black">Содержание</label>
|
||||
<input type="text" id="content" className="form-control" required
|
||||
value={data.content} onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
);
|
||||
}
|
171
FrontEnd/src/components/catalogs/Post.jsx
Normal file
@ -0,0 +1,171 @@
|
||||
import React from "react";
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
import New from '../../models/NewDto';
|
||||
import TableComment from "../common/TableComment";
|
||||
|
||||
export default function Post(props) {
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const [userId,setUserId] = useState();
|
||||
const commentInput = document.getElementById("commentText");
|
||||
|
||||
|
||||
|
||||
const getAll = async function () {
|
||||
const queryString=window.location.search;
|
||||
const urlParams=new URLSearchParams(queryString);
|
||||
const id=urlParams.get('id');
|
||||
getCurrentPost(id).then(curPost => setad(curPost));
|
||||
getComments(id)
|
||||
getUserId();
|
||||
}
|
||||
|
||||
|
||||
|
||||
const refresh = async function(id,user,text)
|
||||
{
|
||||
const requestParams={
|
||||
method:"PUT",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const response=await fetch(`http://localhost:8080/api/1.0/comment/${id}/curUser/${userId}/commentUser/${user}?Text=${text}`,requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
|
||||
const create = async function (text, id) {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const response = await fetch(`http://localhost:8080/api/1.0/post/${ad.id}/Comment/${id}?Text=${text}`,requestParams);
|
||||
}
|
||||
|
||||
const getUserId = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
let login = localStorage.getItem("user");
|
||||
const requestUrl = "http://localhost:8080/api/1.0" + `/userId?login=${login}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const user = await response.json();
|
||||
setUserId(user);
|
||||
}
|
||||
|
||||
const getCurrentPost = async function (id) {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = "http://localhost:8080/api/1.0/post/"+id;
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const product = await response.json();
|
||||
return product;
|
||||
}
|
||||
|
||||
|
||||
|
||||
const remove = async function(id,user){
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = `http://localhost:8080/api/1.0/post/${ad.id}/Comment/${id}/curUser/${userId}/commentUser/${user}`;
|
||||
const response=await fetch(requestUrl,requestParams);
|
||||
return await response.json;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
const getComments = async function(id)
|
||||
{
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requesturl = "http://localhost:8080/api/1.0/post/"+id+"/comments"
|
||||
const response = await fetch(requesturl,requestParams);
|
||||
const comments = await response.json();
|
||||
setComments(comments);
|
||||
}
|
||||
const [ad, setad] = useState([]);
|
||||
const [comments,setComments] = useState([]);
|
||||
|
||||
|
||||
const rem_but = function(id,user,event)
|
||||
{
|
||||
remove(id,user).then((result)=>{
|
||||
getAll();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
const add_but = function(event)
|
||||
{
|
||||
event.preventDefault();
|
||||
create(commentInput.value, userId).then((result) => {
|
||||
getAll();
|
||||
commentInput.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
const edit_btn = function(id,user,event)
|
||||
{
|
||||
console.log("Обновление")
|
||||
refresh(id,user, commentInput.value).then((result)=>{
|
||||
getAll();
|
||||
commentInput.value = "";
|
||||
});
|
||||
}
|
||||
//Комменты удаляются в любом случае (не важно какой пользователь его написал (надо фиксить))
|
||||
return(
|
||||
<div>
|
||||
<div className="da d-flex my-2">
|
||||
<div><img className="imga img-fluid float-start mx-2" style={{width: "500px" ,height: "300px" }} src={ad.image}/></div>
|
||||
<div className="container-fluid my-2 mx-1">
|
||||
<h1>{ad.heading}</h1>
|
||||
<p>{ad.content}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="d-flex mx-2">
|
||||
<input className="form-control" id="commentText" type="text" defaultValue="" required/>
|
||||
<button type="button" className="btn btn-primary" onClick={(e)=>add_but(e)}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<div className="row table-responsive mx-2">
|
||||
<TableComment
|
||||
comments={comments}
|
||||
onRemove={rem_but}
|
||||
onEdit={edit_btn}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
);
|
||||
|
||||
}
|
86
FrontEnd/src/components/catalogs/SignupPage.jsx
Normal file
@ -0,0 +1,86 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useRef } from "react";
|
||||
|
||||
const hostURL = "http://localhost:8080";
|
||||
|
||||
const SignupPage = function () {
|
||||
|
||||
const loginInput = useRef();
|
||||
const emailInput = useRef();
|
||||
const passwordInput = useRef();
|
||||
const passwordConfirmInput = useRef();
|
||||
|
||||
useEffect(() => {
|
||||
}, []);
|
||||
|
||||
const signup = async function (userSignInDto) {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(userSignInDto),
|
||||
};
|
||||
const response = await fetch(hostURL + "/sign_up", requestParams);
|
||||
const result = await response.text();
|
||||
alert(result);
|
||||
}
|
||||
|
||||
const signupFormOnSubmit = function (event) {
|
||||
event.preventDefault();
|
||||
const userSignInDto = {
|
||||
login: loginInput.current.value,
|
||||
email: emailInput.current.value,
|
||||
password: passwordInput.current.value,
|
||||
passwordConfirm: passwordConfirmInput.current.value
|
||||
}
|
||||
signup(userSignInDto);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mx-auto my-3">
|
||||
<form onSubmit={(event) => signupFormOnSubmit(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? </span>
|
||||
<Link to="/login">Sing In here</Link>
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default SignupPage;
|
112
FrontEnd/src/components/catalogs/Users.jsx
Normal file
@ -0,0 +1,112 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
const hostURL = "http://localhost:8080";
|
||||
const host = hostURL + "/api/1.0";
|
||||
|
||||
const Users = 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 mx-3">
|
||||
<table className="table">
|
||||
<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 Users;
|
24
FrontEnd/src/components/common/Banner.jsx
Normal file
@ -0,0 +1,24 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import '../../style.css'
|
||||
export default function Banner(props) {
|
||||
const[bannerNum,setBanner]=useState(['show','hide','hide']);
|
||||
useEffect(() => {
|
||||
const length=3;
|
||||
var old = length-1;
|
||||
var current = 0;
|
||||
const timer = window.setInterval(()=>{
|
||||
setBanner([...bannerNum, bannerNum[current] = 'show', bannerNum[old] = 'hide']);
|
||||
old = current;
|
||||
current++;
|
||||
if (current ===length) {
|
||||
current = 0;
|
||||
}
|
||||
},5000);
|
||||
return()=>{
|
||||
window.clearInterval(timer);
|
||||
}
|
||||
},[]);
|
||||
return(
|
||||
<div id="banner"><img className={bannerNum[0]} src="img/banner1.png"/><img className={bannerNum[1]} src="img/banner2.png"/><img className={bannerNum[2]} src="img/banner3.png"/></div>
|
||||
);
|
||||
}
|
39
FrontEnd/src/components/common/Card.jsx
Normal file
@ -0,0 +1,39 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import ModalEdit from './ModalComment';
|
||||
import TablePostAndComment from './TablePostAndComment';
|
||||
export default function Card(props) {
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div className="container-fluid mt-3">
|
||||
{
|
||||
props.items.map((item, index) =>
|
||||
<div key={item.id}
|
||||
className="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
|
||||
<div className=''>
|
||||
<img className="col" style={{width: "300px" ,height: "200px" }} src={item.image}/>
|
||||
</div>
|
||||
<div className='d-flex flex-grow-1 flex-column'>
|
||||
<div className='flex-grow-1 mx-2'>
|
||||
{
|
||||
props.headers.map(header =>
|
||||
header.name == "image" ? null :
|
||||
<div className="" key={item.id + header.name}>{item[header.name]}</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
<div className="d-flex flex-row justify-content-end ">
|
||||
<a href={`/Post?id=${item.id}`} className='btn btn-outline-primary mx-2'><i className="fa-solid fa-envelopes-bulk"></i></a>
|
||||
</div>
|
||||
<TablePostAndComment
|
||||
comments={item.comments}
|
||||
value={props.value}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
120
FrontEnd/src/components/common/CardForNews.jsx
Normal file
@ -0,0 +1,120 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import ModalEdit from './ModalComment';
|
||||
import TablePostAndComment from './TablePostAndComment';
|
||||
export default function CardForNews(props) {
|
||||
|
||||
function edit(id) {
|
||||
props.onEdit(id);
|
||||
}
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
|
||||
const getUser = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
let login = localStorage.getItem("user");
|
||||
const requestUrl = host + `/user?login=${login}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const user = await response.json();
|
||||
return user;
|
||||
}
|
||||
function remove(id) {
|
||||
props.onRemove(id);
|
||||
}
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
|
||||
const [clients, setClients] = useState([]);
|
||||
const getAll = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = "http://localhost:8080/api/1.0/userList";
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const users = await response.json();
|
||||
setClients(users);
|
||||
}
|
||||
const [modalTable, setModalTable] = useState(false);
|
||||
const [currEditItem, setCurrEditItem] = useState(0);
|
||||
const [text, setText] = useState('');
|
||||
function handleEdit(id) {
|
||||
console.info("Start edit script");
|
||||
setCurrEditItem(id);
|
||||
setModalTable(true)
|
||||
console.info('End edit script');
|
||||
};
|
||||
const handleSubmitEdit = async (e, id) => {
|
||||
console.info('Start synchronize edit');
|
||||
e.preventDefault(); // страница перестает перезагружаться
|
||||
const requestUrl = `http://localhost:8080/api/1.0/post/${id}/Comment/${props.userId}?Text=${text}`;
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
};
|
||||
await fetch(requestUrl,requestParams);
|
||||
setText('');
|
||||
setModalTable(false);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className="container-fluid mt-3">
|
||||
{
|
||||
props.items.map((item, index) =>
|
||||
<div key={item.id}
|
||||
className="card border-dark mb-3 d-flex flex-row text-black justify-content-between">
|
||||
<div className=''>
|
||||
<img className="col" style={{width: "300px" ,height: "200px" }} src={item.image}/>
|
||||
</div>
|
||||
<div className='d-flex flex-grow-1 flex-column'>
|
||||
<div className='flex-grow-1 mx-2'>
|
||||
{
|
||||
props.headers.map(header =>
|
||||
header.name == "image" ? null :
|
||||
<div className="" key={item.id + header.name}>{item[header.name]}</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
<div className="d-flex flex-row justify-content-end ">
|
||||
<button type="button" className="btn btn-outline-primary text-center mx-2" data-bs-toggle="modal" data-bs-target="#redact" onClick={(e) => edit(item.id, e)}>
|
||||
<i className="fa-sharp fa-solid fa-pen"></i>
|
||||
</button>
|
||||
<button href="#"
|
||||
className="btn btn-outline-primary mx-3"
|
||||
onClick={(e) => remove(item.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button>
|
||||
<a href={`/Post?id=${item.id}`} className='btn btn-outline-primary mx-2'><i className="fa-solid fa-envelopes-bulk"></i></a>
|
||||
</div>
|
||||
<TablePostAndComment
|
||||
comments={item.comments}
|
||||
value={props.value}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
<ModalEdit visible={modalTable} setVisible={setModalTable}>
|
||||
<form className="g-3 fs-4 description fw-bold container" id="frm-items-edit" onSubmit={(e) => handleSubmitEdit(e, currEditItem)}>
|
||||
<div className="row">
|
||||
<label className="form-label" htmlFor="priceEdit">Комментарий</label>
|
||||
<input value={text} onChange={e => setText(e.target.value)} className="form-control" name='priceEdit' id="priceEdit" type="text" placeholder="Введите содержимое комментария" required />
|
||||
</div>
|
||||
<div className="text-center mt-3">
|
||||
<button className="btn btn-primary mx-1" type="submit" id="buttonSaveChanges">Сохранить изменения</button>
|
||||
<button className="btn btn-secondary mx-1" type="button" data-bs-dismiss="modal" onClick={() => setModalTable(false)}>Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</ModalEdit>
|
||||
</div>
|
||||
);
|
||||
}
|
7
FrontEnd/src/components/common/Footer.jsx
Normal file
@ -0,0 +1,7 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
|
||||
export default function Footer(props) {
|
||||
return (
|
||||
<footer className="container-fluid d-flex text-white bg-primary bg-gradient mt-auto">© 2022 МОУ "СОШ №10"</footer>
|
||||
);
|
||||
}
|
46
FrontEnd/src/components/common/Modal.jsx
Normal file
@ -0,0 +1,46 @@
|
||||
import React from "react";
|
||||
|
||||
export default function Modal(props) {
|
||||
const formRef = React.createRef();
|
||||
|
||||
function hide() {
|
||||
props.onHide();
|
||||
}
|
||||
|
||||
function done(e) {
|
||||
e.preventDefault();
|
||||
if (formRef.current.checkValidity()) {
|
||||
props.onDone();
|
||||
hide();
|
||||
} else {
|
||||
formRef.current.reportValidity();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal fade show" tabIndex="-1" aria-hidden="true"
|
||||
style={{ display: props.visible ? 'block' : 'none' }}>
|
||||
<div className="modal-dialog">
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h1 className="modal-title fs-5" id="exampleModalLabel">{props.header}</h1>
|
||||
<button className="btn-close" type="button" aria-label="Close"
|
||||
onClick={hide}></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<form ref={formRef} onSubmit={done}>
|
||||
{props.children}
|
||||
</form>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button className="btn btn-secondary" type="button" onClick={hide}>Закрыть</button>
|
||||
<button className="btn btn-primary" type="button" onClick={done}>
|
||||
{props.confirm}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
18
FrontEnd/src/components/common/ModalComment.jsx
Normal file
@ -0,0 +1,18 @@
|
||||
import { React } from 'react'
|
||||
import classes from '../../ModalEdit.module.css'
|
||||
|
||||
export default function ModalEdit({children, visible, setVisible}) {
|
||||
|
||||
const rootClasses = [classes.myModal]
|
||||
if (visible) {
|
||||
rootClasses.push(classes.active);
|
||||
}
|
||||
//onClick={()=>setVisible(false)}
|
||||
return (
|
||||
<div className={rootClasses.join(' ')} >
|
||||
<div className={classes.myModalContent}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
86
FrontEnd/src/components/common/NavBar.jsx
Normal file
@ -0,0 +1,86 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate,Link } from 'react-router-dom';
|
||||
|
||||
const NavBar = function (props) {
|
||||
|
||||
const [userRole, setUserRole] = useState("NONE");
|
||||
|
||||
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("/login");
|
||||
}
|
||||
});
|
||||
}
|
||||
getUserRole();
|
||||
});
|
||||
getUserRole();
|
||||
}, [])
|
||||
|
||||
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);
|
||||
const result = await response.text();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
const getUserRole = function () {
|
||||
const role = localStorage.getItem("role") || "NONE";
|
||||
setUserRole(role);
|
||||
}
|
||||
|
||||
const validate = function (userGroup) {
|
||||
if ((userGroup === "AUTH" && userRole !== "NONE") ||
|
||||
(userGroup === userRole)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="fs-4 fw-bold p-1 text-white bg-primary bg-gradient">
|
||||
<div><img className="img-fluid float-start" src="../img/Emblema.png" alt="Emblema"/>
|
||||
<p className="fs-5 Cont">Муниципальное бюджетное общеобразовательное учреждение средняя общеобразовательная школа №10</p>
|
||||
</div>
|
||||
<nav className="navbar navbar-expand-md 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="navbar-collapse collapse justify-content-end" id="navbarNav">
|
||||
<nav className="headers-problem navbar navbar-expand-lg d-flex">
|
||||
{props.links.map(route => {
|
||||
if (validate(route.userGroup)) {
|
||||
return (
|
||||
<button key={route.path} className="btn btn-outline-light mx-1">
|
||||
<Link className="nav-link" to={route.path}>
|
||||
{route.label}
|
||||
</Link>
|
||||
</button> );
|
||||
}
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export default NavBar;
|
15
FrontEnd/src/components/common/PrivateRoutes.jsx
Normal file
@ -0,0 +1,15 @@
|
||||
import { Outlet, Navigate, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useState } 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;
|
34
FrontEnd/src/components/common/TableComment.jsx
Normal file
@ -0,0 +1,34 @@
|
||||
export default function TableComment(props) {
|
||||
function edit(id,user,e) {
|
||||
props.onEdit(id,user);
|
||||
}
|
||||
|
||||
function remove(id,user,e) {
|
||||
props.onRemove(id,user,e);
|
||||
}
|
||||
|
||||
|
||||
return(
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Text</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{props.comments.map((comment) => (
|
||||
<tr key={comment.id}>
|
||||
{console.log(comment.user)}
|
||||
<th scope="row">{comment.user}</th>
|
||||
<td>{comment.text}</td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit(comment.id,comment.userId, e)}><i className="fa-sharp fa-solid fa-pen"></i></button></td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => remove(comment.id,comment.userId,e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
22
FrontEnd/src/components/common/TablePostAndComment.jsx
Normal file
@ -0,0 +1,22 @@
|
||||
export default function TablePostAndComment(props) {
|
||||
return(
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{props.comments.map((comment) => (
|
||||
<tr key={comment.id}>
|
||||
<th scope="row">{comment.user}</th>
|
||||
<td>{comment.text}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
43
FrontEnd/src/components/common/Toolbar.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
|
||||
export default function Toolbar(props) {
|
||||
const [clients, setClientst] = useState([]);
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const getAll = async function () {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = "http://localhost:8080/api/1.0/userList";
|
||||
const response = await fetch(requestUrl,requestParams);
|
||||
const users = await response.json();
|
||||
setClientst(users);
|
||||
}
|
||||
|
||||
function getuser(){
|
||||
var selectBox = document.getElementById("selectBox");
|
||||
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
|
||||
props.getUser(selectedValue);
|
||||
}
|
||||
return (
|
||||
<div className="d-flex float-start my-2">
|
||||
<div className="mx-1">
|
||||
<select id="selectBox" onChange={getuser}>
|
||||
<option disabled value="">Выбор...</option>
|
||||
{
|
||||
clients.map((client) => (
|
||||
<option className='text-black' key={client.id} value={client.id}>{client.login}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div >
|
||||
);
|
||||
}
|
18
FrontEnd/src/components/common/ToolbarAccount.jsx
Normal file
@ -0,0 +1,18 @@
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
|
||||
export default function Toolbar(props) {
|
||||
function add() {
|
||||
props.onAdd();
|
||||
}
|
||||
return (
|
||||
<div className="d-flex float-start my-2">
|
||||
<div>
|
||||
<button type="button" className="btn btn-primary" onClick={add}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div >
|
||||
);
|
||||
}
|
8
FrontEnd/src/main.jsx
Normal file
@ -0,0 +1,8 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './style.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('app')).render(
|
||||
<App />
|
||||
)
|
6
FrontEnd/src/models/CommentDto.js
Normal file
@ -0,0 +1,6 @@
|
||||
export default class CommentDto {
|
||||
constructor(args) {
|
||||
this.id = args.id || null;
|
||||
this.text = args.text;
|
||||
}
|
||||
}
|
9
FrontEnd/src/models/NewDto.js
Normal file
@ -0,0 +1,9 @@
|
||||
export default class NewDto {
|
||||
constructor(data) {
|
||||
this.id = data?.id || null;
|
||||
this.image = data?.image;
|
||||
this.heading = data?.heading;
|
||||
this.content = data?.content;
|
||||
}
|
||||
|
||||
}
|
8
FrontEnd/src/models/user-signup-dto.js
Normal file
@ -0,0 +1,8 @@
|
||||
export default class UserSignupDto {
|
||||
constructor(args) {
|
||||
this.login = args.login;
|
||||
this.email = args.email;
|
||||
this.password = args.password;
|
||||
this.passwordConfirm = args.passwordConfirm;
|
||||
}
|
||||
}
|
146
FrontEnd/src/style.css
Normal file
@ -0,0 +1,146 @@
|
||||
html
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
header .img-fluid
|
||||
{
|
||||
width:232px;
|
||||
height:100px;
|
||||
}
|
||||
|
||||
article .img-fluid
|
||||
{
|
||||
height:250px;
|
||||
}
|
||||
article .img-fluid1
|
||||
{
|
||||
height:100%;
|
||||
width: 96%;
|
||||
}
|
||||
.owl
|
||||
{
|
||||
width:300px;
|
||||
}
|
||||
.pdf-size
|
||||
{
|
||||
width:70px;
|
||||
}
|
||||
body
|
||||
{
|
||||
min-height: 100vh;
|
||||
}
|
||||
.body_app
|
||||
{
|
||||
display: grid;
|
||||
grid-template-rows:auto 1fr auto;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.lp
|
||||
{
|
||||
padding-left: 30px;
|
||||
}
|
||||
.img-school
|
||||
{
|
||||
margin-right: 1em;
|
||||
float: start;
|
||||
|
||||
}
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 1em;
|
||||
}
|
||||
.Cont
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 800px) {
|
||||
.owl {
|
||||
display:none;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 1164px) {
|
||||
.img-school
|
||||
{
|
||||
margin-right: 170px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 554px) {
|
||||
.img-school
|
||||
{
|
||||
height: 20% !important;
|
||||
width: 75%;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 727px) {
|
||||
.headers-problem
|
||||
{
|
||||
|
||||
flex-direction: column;
|
||||
}
|
||||
.navbar
|
||||
{
|
||||
align-items: flex-start !important;
|
||||
}
|
||||
|
||||
}
|
||||
@media only screen and (max-width: 959px) {
|
||||
.navbar
|
||||
{
|
||||
float:left !important;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 463px) {
|
||||
.Vnov
|
||||
{
|
||||
margin-right: 140px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 575px) {
|
||||
.Vnov1
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
@media only screen and (max-width: 585px) {
|
||||
.Cont
|
||||
{
|
||||
margin-right: 200px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#banner {
|
||||
margin: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
#banner img {
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
#banner img.show {
|
||||
height: 40%;
|
||||
width: 60%;
|
||||
opacity: 1;
|
||||
transition: opacity 1s, visibility 0s;
|
||||
}
|
||||
|
||||
#banner img.hide {
|
||||
height: 0;
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 1s, visibility 0s 1s;
|
||||
}
|
||||
|
||||
.Pole_height
|
||||
{
|
||||
height: 80px;
|
||||
}
|
7
FrontEnd/vite.config.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()]
|
||||
})
|
22
build.gradle
@ -1,22 +1,40 @@
|
||||
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.0.2'
|
||||
id 'io.spring.dependency-management' version '1.1.0'
|
||||
}
|
||||
|
||||
group = 'ru.ulstu.is'
|
||||
group = 'np'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
sourceCompatibility = '17'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(':FrontEnd'))
|
||||
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.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
}
|
195
data.trace.db
Normal file
@ -0,0 +1,195 @@
|
||||
2023-03-27 16:52:44 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "create table [*]user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id))"; ожидалось "identifier"
|
||||
Syntax error in SQL statement "create table [*]user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id))"; expected "identifier"; SQL statement:
|
||||
create table user (id bigint not null, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id)) [42001-210]
|
||||
2023-03-27 16:52:44 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references [*]user"; ожидалось "identifier"
|
||||
Syntax error in SQL statement "alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references [*]user"; expected "identifier"; SQL statement:
|
||||
alter table if exists comment add constraint FK8kcum44fvpupyw6f5baccx25c foreign key (user_id) references user [42001-210]
|
||||
2023-03-27 16:52:44 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references [*]user"; ожидалось "identifier"
|
||||
Syntax error in SQL statement "alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references [*]user"; expected "identifier"; SQL statement:
|
||||
alter table if exists post add constraint FK72mt33dhhs48hf9gcqrq4fxte foreign key (user_id) references user [42001-210]
|
||||
2023-03-27 21:45:28 database: wrong user or password; user: "SA"
|
||||
org.h2.message.DbException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.get(DbException.java:227)
|
||||
at org.h2.message.DbException.get(DbException.java:203)
|
||||
at org.h2.message.DbException.get(DbException.java:192)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:154)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:222)
|
||||
at org.h2.engine.Engine.createSession(Engine.java:201)
|
||||
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:338)
|
||||
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:122)
|
||||
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
|
||||
at org.h2.server.web.WebServer.getConnection(WebServer.java:807)
|
||||
at org.h2.server.web.WebApp.login(WebApp.java:1033)
|
||||
at org.h2.server.web.WebApp.process(WebApp.java:226)
|
||||
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
|
||||
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
|
||||
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
|
||||
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
|
||||
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
|
||||
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
|
||||
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
|
||||
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
|
||||
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
|
||||
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
|
||||
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
|
||||
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
|
||||
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
|
||||
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
|
||||
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
|
||||
at java.base/java.lang.Thread.run(Thread.java:833)
|
||||
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:529)
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
|
||||
... 50 more
|
||||
2023-03-27 21:45:50 database: wrong user or password; user: "SA"
|
||||
org.h2.message.DbException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.get(DbException.java:227)
|
||||
at org.h2.message.DbException.get(DbException.java:203)
|
||||
at org.h2.message.DbException.get(DbException.java:192)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:154)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:222)
|
||||
at org.h2.engine.Engine.createSession(Engine.java:201)
|
||||
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:338)
|
||||
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:122)
|
||||
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
|
||||
at org.h2.server.web.WebServer.getConnection(WebServer.java:807)
|
||||
at org.h2.server.web.WebApp.login(WebApp.java:1033)
|
||||
at org.h2.server.web.WebApp.process(WebApp.java:226)
|
||||
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
|
||||
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
|
||||
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
|
||||
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
|
||||
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
|
||||
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
|
||||
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
|
||||
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
|
||||
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
|
||||
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
|
||||
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
|
||||
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
|
||||
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
|
||||
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
|
||||
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
|
||||
at java.base/java.lang.Thread.run(Thread.java:833)
|
||||
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:529)
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
|
||||
... 50 more
|
||||
2023-04-10 17:11:04 database: wrong user or password; user: "SA"
|
||||
org.h2.message.DbException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.get(DbException.java:227)
|
||||
at org.h2.message.DbException.get(DbException.java:203)
|
||||
at org.h2.message.DbException.get(DbException.java:192)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:154)
|
||||
at org.h2.engine.Engine.openSession(Engine.java:222)
|
||||
at org.h2.engine.Engine.createSession(Engine.java:201)
|
||||
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:338)
|
||||
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:122)
|
||||
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
|
||||
at org.h2.server.web.WebServer.getConnection(WebServer.java:807)
|
||||
at org.h2.server.web.WebApp.login(WebApp.java:1033)
|
||||
at org.h2.server.web.WebApp.process(WebApp.java:226)
|
||||
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
|
||||
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
|
||||
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
|
||||
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
|
||||
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
|
||||
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
|
||||
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
|
||||
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
|
||||
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
|
||||
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
|
||||
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
|
||||
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
|
||||
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
|
||||
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
|
||||
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
|
||||
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
|
||||
at java.base/java.lang.Thread.run(Thread.java:833)
|
||||
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
|
||||
Wrong user name or password [28000-210]
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:529)
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
|
||||
... 50 more
|
||||
2023-05-06 13:42:52 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34414151536b5a4a5267414241... (1164871)"
|
||||
Value too long for column "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34414151536b5a4a5267414241... (1164871)" [22001-210]
|
||||
2023-05-06 13:48:55 jdbc[7]: exception
|
||||
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34624b6e525868705a67414153... (7951727)"
|
||||
Value too long for column "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34624b6e525868705a67414153... (7951727)" [22001-210]
|
||||
2023-05-06 13:49:23 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34534175525868705a67414154... (3767039)"
|
||||
Value too long for column "BINARY VARYING": "646174613a696d6167652f6a7065673b6261736536342c2f396a2f34534175525868705a67414154... (3767039)" [22001-210]
|
@ -1 +1,2 @@
|
||||
rootProject.name = 'sbapp'
|
||||
include 'FrontEnd'
|
@ -0,0 +1,47 @@
|
||||
package ru.ulstu.is.sbapp.Comment.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Configuration.OpenAPI30Configuration;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/comment")
|
||||
public class CommentController {
|
||||
private final CommentService commentService;
|
||||
public CommentController(CommentService commentService) {
|
||||
this.commentService = commentService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public CommentDto getComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.findComment(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<CommentDto> getComments() {
|
||||
return commentService.findAllComments().stream()
|
||||
.map(CommentDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public CommentDto createComment(@RequestParam("Text") String Text){
|
||||
return new CommentDto(commentService.addComment(Text));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/curUser/{userId}/commentUser/{userComId}")
|
||||
public CommentDto updateComment(@PathVariable Long id,
|
||||
@PathVariable Long userId,
|
||||
@PathVariable Long userComId,
|
||||
@RequestParam("Text") String Text){
|
||||
if(Objects.equals(userComId, userId))
|
||||
{
|
||||
return new CommentDto(commentService.updateComment(id,Text));
|
||||
}
|
||||
return new CommentDto(commentService.findComment(id));
|
||||
}
|
||||
@DeleteMapping("/{id}")
|
||||
public CommentDto deleteComment(@PathVariable Long id) {
|
||||
return new CommentDto(commentService.deleteComment(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package ru.ulstu.is.sbapp.Comment.controller;
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
public class CommentDto {
|
||||
private Long id;
|
||||
private String Text;
|
||||
private String userName;
|
||||
|
||||
private Long userId;
|
||||
public CommentDto(){}
|
||||
public CommentDto(Comment comment)
|
||||
{
|
||||
this.id= comment.getId();
|
||||
this.Text=comment.getText();
|
||||
this.userName=comment.getUser().getLogin();
|
||||
this.userId=comment.getUser().getId();
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getText() {return Text;}
|
||||
public Long getUserId(){return userId;}
|
||||
public String getUser()
|
||||
{
|
||||
return userName;
|
||||
}
|
||||
|
||||
|
||||
}
|
81
src/main/java/ru/ulstu/is/sbapp/Comment/model/Comment.java
Normal file
@ -0,0 +1,81 @@
|
||||
package ru.ulstu.is.sbapp.Comment.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Comment {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@NotBlank(message = "Text cannot be null")
|
||||
private String Text;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private Post post;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private User user;
|
||||
|
||||
public Comment()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Comment(String text)
|
||||
{
|
||||
this.Text=text;
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getText() {return Text;}
|
||||
public void setText(String text){this.Text=text;}
|
||||
public User getUser()
|
||||
{
|
||||
return user;
|
||||
}
|
||||
public Post getPost()
|
||||
{
|
||||
return post;
|
||||
}
|
||||
public void setPost(Post post, User user){
|
||||
if(post!=null)
|
||||
{
|
||||
post.getComments().add(this);
|
||||
this.post = post;
|
||||
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Comment comment = (Comment) o;
|
||||
return Objects.equals(id, comment.id);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Comment{" +
|
||||
"id=" + id +
|
||||
", Text='" + Text + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Comment.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
|
||||
public interface CommentRepository extends JpaRepository<Comment, Long> {
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Comment.service;
|
||||
|
||||
public class CommentNotFoundException extends RuntimeException{
|
||||
public CommentNotFoundException(Long id) {
|
||||
super(String.format("Comment with id [%s] is not found", id));
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package ru.ulstu.is.sbapp.Comment.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.repository.CommentRepository;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class CommentService {
|
||||
private final CommentRepository commentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public CommentService(CommentRepository commentRepository, ValidatorUtil validatorUtil)
|
||||
{
|
||||
this.commentRepository=commentRepository;
|
||||
this.validatorUtil=validatorUtil;
|
||||
}
|
||||
@Transactional
|
||||
public Comment addComment(String Text) {
|
||||
final Comment comment = new Comment(Text);
|
||||
validatorUtil.validate(comment);
|
||||
return commentRepository.save(comment);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void saveComment(Comment comment) {
|
||||
commentRepository.save(comment);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Comment findComment(Long id) {
|
||||
final Optional<Comment> client = commentRepository.findById(id);
|
||||
return client.orElseThrow(() -> new CommentNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Comment> findAllComments() {
|
||||
return commentRepository.findAll();
|
||||
}
|
||||
@Transactional
|
||||
public Comment updateComment(Long id,String Text) {
|
||||
final Comment currentComment = findComment(id);
|
||||
currentComment.setText(Text);
|
||||
validatorUtil.validate(currentComment);
|
||||
return commentRepository.save(currentComment);
|
||||
}
|
||||
@Transactional
|
||||
public Comment deleteComment(Long id) {
|
||||
final Comment currentComment = findComment(id);
|
||||
commentRepository.delete(currentComment);
|
||||
return currentComment;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllComments() {
|
||||
commentRepository.deleteAll();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package ru.ulstu.is.sbapp.Configuration.Jwt;
|
||||
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,72 @@
|
||||
package ru.ulstu.is.sbapp.Configuration.Jwt;
|
||||
|
||||
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 ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package ru.ulstu.is.sbapp.Configuration.Jwt;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||
public class JwtProperties {
|
||||
private String devToken = "";
|
||||
private Boolean isDev = true;
|
||||
|
||||
public String getDevToken() {
|
||||
return devToken;
|
||||
}
|
||||
|
||||
public void setDevToken(String devToken) {
|
||||
this.devToken = devToken;
|
||||
}
|
||||
|
||||
public Boolean isDev() {
|
||||
return isDev;
|
||||
}
|
||||
|
||||
public void setDev(Boolean dev) {
|
||||
isDev = dev;
|
||||
}
|
||||
}
|
@ -0,0 +1,107 @@
|
||||
package ru.ulstu.is.sbapp.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();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
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;
|
||||
import ru.ulstu.is.sbapp.Configuration.Jwt.JwtFilter;
|
||||
|
||||
@Configuration
|
||||
public class OpenAPI30Configuration {
|
||||
public static final String API_PREFIX = "/api/1.0";
|
||||
|
||||
@Bean
|
||||
public OpenAPI customizeOpenAPI() {
|
||||
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
|
||||
return new OpenAPI()
|
||||
.addSecurityItem(new SecurityRequirement()
|
||||
.addList(securitySchemeName))
|
||||
.components(new Components()
|
||||
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
|
||||
.name(securitySchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class PasswordEncoderConfiguration {
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
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;
|
||||
import ru.ulstu.is.sbapp.Configuration.Jwt.JwtFilter;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserController;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity(
|
||||
securedEnabled = true
|
||||
)
|
||||
public class SecurityConfiguration {
|
||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||
private final UserService userService;
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
public SecurityConfiguration(UserService userService) {
|
||||
this.userService = userService;
|
||||
this.jwtFilter = new JwtFilter(userService);
|
||||
createAdminOnStartup();
|
||||
}
|
||||
|
||||
private void createAdminOnStartup() {
|
||||
final String admin = "admin";
|
||||
if (userService.findByLogin(admin) == null) {
|
||||
log.info("Admin user successfully created");
|
||||
userService.addUser(admin, "admin@gmail.com", admin, admin, UserRole.ADMIN);
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.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_SIGN_UP).permitAll()
|
||||
.requestMatchers(HttpMethod.POST, UserController.URL_WHO_AM_I).permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.anonymous();
|
||||
return http.userDetailsService(userService).build();
|
||||
}
|
||||
|
||||
|
||||
@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")
|
||||
.requestMatchers("/webjars/**")
|
||||
.requestMatchers("/swagger-resources/**")
|
||||
.requestMatchers("/v3/api-docs/**")
|
||||
.requestMatchers("/h2-console/**");
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
package ru.ulstu.is.sbapp.Configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
@ -0,0 +1,85 @@
|
||||
package ru.ulstu.is.sbapp.Post.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.ulstu.is.sbapp.Comment.controller.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Configuration.OpenAPI30Configuration;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/post")
|
||||
public class PostController {
|
||||
private final PostService postService;
|
||||
public PostController(PostService postService) {
|
||||
this.postService = postService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public PostDto getPost(@PathVariable Long id) {
|
||||
return new PostDto(postService.findPost(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<PostDto> getPosts() {
|
||||
return postService.findAllPosts().stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
@GetMapping("/{id}/comments")
|
||||
public List<CommentDto> getComments(@PathVariable Long id) {
|
||||
return postService.GetPostComments(id).stream()
|
||||
.map(CommentDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public PostDto createPost(@RequestBody @Valid PostDto postDto){
|
||||
return new PostDto(postService.addPost(postDto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public PostDto updatePost(@PathVariable Long id,
|
||||
@RequestBody @Valid PostDto postDto){
|
||||
return new PostDto(postService.updatePost(id,postDto));
|
||||
}
|
||||
@PostMapping("/{id}/Comment/{userId}")
|
||||
public void addComment(@PathVariable Long id,
|
||||
@PathVariable Long userId,
|
||||
@RequestParam("Text") String Text) {
|
||||
postService.addCommentToPost(id, userId,Text);
|
||||
}
|
||||
@DeleteMapping("/{id}/Comment/{commentId}/curUser/{userId}/commentUser/{userComId}")
|
||||
public void removeComment(@PathVariable Long id,
|
||||
@PathVariable Long commentId,
|
||||
@PathVariable Long userId,
|
||||
@PathVariable Long userComId)
|
||||
{
|
||||
if(Objects.equals(userComId, userId))
|
||||
{
|
||||
postService.removeCommentFromPost(id,commentId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void deletePost(@PathVariable Long id) {
|
||||
postService.deletePost(id);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void deleteall()
|
||||
{
|
||||
postService.deleteAllPosts();
|
||||
}
|
||||
|
||||
@GetMapping("/filteredposts")
|
||||
public List<PostDto> getPostsAndComments(@RequestParam("Text") String Text){
|
||||
return postService.getPostsAndComments(Text).stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
}
|
56
src/main/java/ru/ulstu/is/sbapp/Post/controller/PostDto.java
Normal file
@ -0,0 +1,56 @@
|
||||
package ru.ulstu.is.sbapp.Post.controller;
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.controller.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PostDto {
|
||||
private Long id;
|
||||
|
||||
private String heading;
|
||||
|
||||
private String content;
|
||||
|
||||
private List<CommentDto> comments = new ArrayList<>();
|
||||
private String image;
|
||||
|
||||
|
||||
public PostDto(){}
|
||||
public PostDto(Post post) {
|
||||
this.id = post.getId();
|
||||
this.heading = post.getHeading();
|
||||
this.content = post.getContent();
|
||||
this.image = new String(post.getImage(), StandardCharsets.UTF_8);
|
||||
if (post.getComments() != null) {
|
||||
comments = post.getComments().stream()
|
||||
.map(CommentDto::new).toList();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getHeading()
|
||||
{
|
||||
return heading;
|
||||
}
|
||||
public String getContent()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
public List<CommentDto> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
public String getImage() {
|
||||
return image;
|
||||
}
|
||||
}
|
110
src/main/java/ru/ulstu/is/sbapp/Post/model/Post.java
Normal file
@ -0,0 +1,110 @@
|
||||
package ru.ulstu.is.sbapp.Post.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.controller.PostDto;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
public class Post {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column
|
||||
@NotBlank(message = "heading cannot be null")
|
||||
private String heading;
|
||||
|
||||
@NotBlank(message = "content cannot be null")
|
||||
private String content;
|
||||
|
||||
@Lob
|
||||
private byte[] image;
|
||||
|
||||
@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.MERGE)
|
||||
private User user;
|
||||
|
||||
@OneToMany(mappedBy = "post",fetch = FetchType.EAGER,cascade = {CascadeType.MERGE,CascadeType.REMOVE},orphanRemoval = true)
|
||||
private List<Comment> comments=new ArrayList<>();
|
||||
|
||||
public Post(){}
|
||||
public Post(String Heading, String Content,byte[] image)
|
||||
{
|
||||
this.heading = Heading;
|
||||
this.content = Content;
|
||||
this.image=image;
|
||||
}
|
||||
public Post(PostDto postDto) {
|
||||
this.heading = postDto.getHeading();
|
||||
this.content = postDto.getContent();
|
||||
this.image = postDto.getImage().getBytes();
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
public String getHeading()
|
||||
{
|
||||
return heading;
|
||||
}
|
||||
public String getContent()
|
||||
{
|
||||
return content;
|
||||
}
|
||||
public void setHeading(String Heading){
|
||||
this.heading =Heading;
|
||||
}
|
||||
public void setContent(String Content)
|
||||
{
|
||||
this.content = Content;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public User getUser()
|
||||
{
|
||||
return user;
|
||||
}
|
||||
public byte[] getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(byte[] image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public void deleteUser() {
|
||||
this.user = null;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Post post = (Post) o;
|
||||
return Objects.equals(id, post.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Post{" +
|
||||
"id=" + id +
|
||||
", heading='" + heading + '\'' +
|
||||
", content ='" + content + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package ru.ulstu.is.sbapp.Post.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface PostRepository extends JpaRepository<Post, Long>{
|
||||
@Query("Select c from Comment c where post.id = :id")
|
||||
List<Comment> getPostComments(Long id);
|
||||
|
||||
@Query("Select p from Post p join p.comments c Where p.content Like concat('%', :text, '%') or c.Text Like concat('%', :text, '%')")
|
||||
List<Post> getPostsAndComments(String text);
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.Post.service;
|
||||
|
||||
public class PostNotFoundException extends RuntimeException{
|
||||
public PostNotFoundException(Long id) {
|
||||
super(String.format("Post with id [%s] is not found", id));
|
||||
}
|
||||
}
|
105
src/main/java/ru/ulstu/is/sbapp/Post/service/PostService.java
Normal file
@ -0,0 +1,105 @@
|
||||
package ru.ulstu.is.sbapp.Post.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Post.controller.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class PostService {
|
||||
private final PostRepository postRepository;
|
||||
private final CommentService commentService;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public PostService(PostRepository postRepository, CommentService commentService, ValidatorUtil validatorUtil, UserService userService)
|
||||
{
|
||||
this.postRepository=postRepository;
|
||||
this.commentService = commentService;
|
||||
this.validatorUtil=validatorUtil;
|
||||
this.userService = userService;
|
||||
}
|
||||
@Transactional
|
||||
public Post addPost(PostDto postDto) {
|
||||
final Post post = new Post(postDto);
|
||||
validatorUtil.validate(post);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void savePost(Post post) {
|
||||
postRepository.save(post);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Post findPost(Long id) {
|
||||
final Optional<Post> post = postRepository.findById(id);
|
||||
return post.orElseThrow(() -> new PostNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Post> findAllPosts() {
|
||||
return postRepository.findAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Post updatePost(Long id, PostDto postDto) {
|
||||
final Post currentPost = findPost(id);
|
||||
currentPost.setHeading(postDto.getHeading());
|
||||
currentPost.setContent(postDto.getContent());
|
||||
currentPost.setImage(postDto.getImage().getBytes(StandardCharsets.UTF_8));
|
||||
validatorUtil.validate(currentPost);
|
||||
return postRepository.save(currentPost);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Comment> GetPostComments(Long id)
|
||||
{
|
||||
return postRepository.getPostComments(id);
|
||||
}
|
||||
@Transactional
|
||||
public void deletePost(Long id) {
|
||||
postRepository.deleteById(id);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllPosts() {
|
||||
commentService.deleteAllComments();
|
||||
postRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addCommentToPost(Long id, Long userId, String text){
|
||||
Optional<Post> optionalPost = postRepository.findById(id);
|
||||
if(optionalPost.isPresent()) {
|
||||
Comment comment = new Comment(text);
|
||||
comment.setPost(optionalPost.get(), userService.findUser(userId));
|
||||
commentService.saveComment(comment);
|
||||
}
|
||||
postRepository.save(optionalPost.get());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeCommentFromPost(Long id, Long commentId){
|
||||
Comment optionalComment = commentService.findComment(commentId);
|
||||
optionalComment.setPost(null, null);
|
||||
Optional <Post> postOptional = postRepository.findById(id);
|
||||
postOptional.get().getComments().remove(optionalComment);
|
||||
commentService.deleteComment(commentId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Post> getPostsAndComments(String text)
|
||||
{
|
||||
return postRepository.getPostsAndComments(text);
|
||||
}
|
||||
}
|
@ -2,20 +2,10 @@ package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
public class SbappApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SbappApplication.class, args);
|
||||
}
|
||||
@GetMapping("/String")
|
||||
public String Vvod(@RequestParam(value = "str", defaultValue = "none") String str) {
|
||||
return String.format("Вы ввели %s!", str);
|
||||
}
|
||||
}
|
||||
|
||||
|
19
src/main/java/ru/ulstu/is/sbapp/User/controller/Pair.java
Normal file
@ -0,0 +1,19 @@
|
||||
package ru.ulstu.is.sbapp.User.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;
|
||||
}
|
||||
}
|
@ -0,0 +1,119 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.ValidationException;
|
||||
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 ru.ulstu.is.sbapp.Configuration.OpenAPI30Configuration;
|
||||
import ru.ulstu.is.sbapp.Post.controller.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
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_SIGN_UP = "/sign_up";
|
||||
public static final String URL_WHO_AM_I = "/who_am_i";
|
||||
private final UserService userService;
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
@GetMapping("/{id}")
|
||||
public UserDto getUser(@PathVariable Long id) {
|
||||
return new UserDto(userService.findUser(id));
|
||||
}
|
||||
|
||||
@PostMapping(URL_LOGIN)
|
||||
public String login(@RequestBody @Valid UserDto userDto) {
|
||||
return userService.loginAndGetToken(userDto);
|
||||
}
|
||||
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/users")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
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(OpenAPI30Configuration.API_PREFIX + "/userList")
|
||||
public List<UserDto> getListUsers() {
|
||||
return userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
.toList();
|
||||
}
|
||||
@GetMapping(OpenAPI30Configuration.API_PREFIX +"/user/{id}/posts")
|
||||
public List<PostDto> getPosts(@PathVariable Long id) {
|
||||
return userService.GetUserPosts(id).stream()
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping(URL_SIGN_UP)
|
||||
public String signUp(@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);
|
||||
}
|
||||
|
||||
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/userId")
|
||||
public Long getUserId(@RequestParam("login") String login) {
|
||||
User user = userService.findByLogin(login);
|
||||
return user.getId();
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
@PostMapping(OpenAPI30Configuration.API_PREFIX+"/user/{id}/Post")
|
||||
public void addPost(@PathVariable Long id,
|
||||
@RequestBody @Valid PostDto postDto) {
|
||||
userService.addNewPost(id, postDto);
|
||||
}
|
||||
@DeleteMapping(OpenAPI30Configuration.API_PREFIX+"/user/{id}/Post/{postId}")
|
||||
public void removePost(@PathVariable Long id,
|
||||
@PathVariable Long postId)
|
||||
{
|
||||
userService.deletePost(id,postId);
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping(OpenAPI30Configuration.API_PREFIX + "/user/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public UserDto removeUser(@PathVariable Long id) {
|
||||
User user = userService.deleteUser(id);
|
||||
return new UserDto(user);
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
69
src/main/java/ru/ulstu/is/sbapp/User/controller/UserDto.java
Normal file
@ -0,0 +1,69 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class UserDto {
|
||||
private Long id;
|
||||
private String login;
|
||||
private String email;
|
||||
private String password;
|
||||
private UserRole role;
|
||||
|
||||
private List<Post> posts = new ArrayList<>();
|
||||
|
||||
private List<Comment> comments = new ArrayList<>();
|
||||
|
||||
public UserDto(){}
|
||||
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 String getLogin() {
|
||||
return login;
|
||||
}
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
return posts;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
public String getEmail()
|
||||
{
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package ru.ulstu.is.sbapp.User.controller;
|
||||
|
||||
public class UserSignupDto {
|
||||
private String login;
|
||||
private String email;
|
||||
private String password;
|
||||
private String passwordConfirm;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public void setPasswordConfirm(String passwordConfirm) {
|
||||
this.passwordConfirm = passwordConfirm;
|
||||
}
|
||||
}
|
||||
|
139
src/main/java/ru/ulstu/is/sbapp/User/model/User.java
Normal file
@ -0,0 +1,139 @@
|
||||
package ru.ulstu.is.sbapp.User.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserSignupDto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name="tab_user")
|
||||
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")
|
||||
private String login;
|
||||
|
||||
@NotBlank(message = "Email can't be null or empty")
|
||||
@Pattern(regexp = "^(.+)@(\\S+)$", message = "Incorrect email value")
|
||||
private String email;
|
||||
|
||||
@NotBlank(message = "Password can't be null or empty")
|
||||
@Size(min = 3, max = 64, message = "Incorrect password length")
|
||||
private String password;
|
||||
|
||||
private UserRole role;
|
||||
|
||||
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
|
||||
private List<Post> posts =new ArrayList<>();
|
||||
|
||||
@OneToMany(mappedBy ="user",cascade = {CascadeType.MERGE,CascadeType.REMOVE},fetch = FetchType.EAGER)
|
||||
private List<Comment> comments =new ArrayList<>();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String login, String email, 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;
|
||||
}
|
||||
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
return posts;
|
||||
}
|
||||
public List<Comment> getComments()
|
||||
{
|
||||
return comments;
|
||||
}
|
||||
public void addNewPost(Post post) {
|
||||
posts.add(post);
|
||||
post.setUser(this);
|
||||
}
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(UserRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getEmail()
|
||||
{
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email){
|
||||
this.email=email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
User user = (User) o;
|
||||
return Objects.equals(id, user.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Client{" +
|
||||
"id=" + id +
|
||||
", login='" + login + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", email='" + email + '\'' +
|
||||
", posts=" + posts +'\''+
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
21
src/main/java/ru/ulstu/is/sbapp/User/model/UserRole.java
Normal file
@ -0,0 +1,21 @@
|
||||
package ru.ulstu.is.sbapp.User.model;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
|
||||
public static final class AsString {
|
||||
public static final String ADMIN = PREFIX + "ADMIN";
|
||||
public static final String USER = PREFIX + "USER";
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,17 @@
|
||||
package ru.ulstu.is.sbapp.User.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
@Query("Select p from Post p where user.id = :id")
|
||||
List<Post> getUsersPosts(Long id);
|
||||
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
public class UserExistsException extends RuntimeException {
|
||||
public UserExistsException(String login) {
|
||||
super(String.format("User '%s' already exists", login));
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
165
src/main/java/ru/ulstu/is/sbapp/User/service/UserService.java
Normal file
@ -0,0 +1,165 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
import jakarta.validation.ValidationException;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Configuration.Jwt.JwtException;
|
||||
import ru.ulstu.is.sbapp.Configuration.Jwt.JwtProvider;
|
||||
import ru.ulstu.is.sbapp.Configuration.PasswordEncoderConfiguration;
|
||||
import ru.ulstu.is.sbapp.Post.controller.PostDto;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.controller.UserDto;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
|
||||
import ru.ulstu.is.sbapp.User.model.UserRole;
|
||||
import ru.ulstu.is.sbapp.User.repository.UserRepository;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
|
||||
|
||||
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 PostRepository postRepository;
|
||||
|
||||
private final CommentService commentService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final JwtProvider jwtProvider;
|
||||
|
||||
public UserService(UserRepository userRepository, ValidatorUtil validatorUtil, PostRepository postRepository, CommentService commentService, PasswordEncoder passwordEncoder, JwtProvider jwtProvider)
|
||||
{
|
||||
this.userRepository=userRepository;
|
||||
this.validatorUtil=validatorUtil;
|
||||
this.postRepository = postRepository;
|
||||
this.commentService = commentService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtProvider = jwtProvider;
|
||||
}
|
||||
@Transactional
|
||||
public User addUser(String login, String email, String password, String passwordConfirm, UserRole role) {
|
||||
if (findByLogin(login) != null) {
|
||||
throw new ValidationException(String.format("User '%s' already exists", login));
|
||||
}
|
||||
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);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
public User findByLogin(String login) {
|
||||
return userRepository.findOneByLoginIgnoreCase(login);
|
||||
}
|
||||
|
||||
public Page<User> findAllPages(int page, int size) {
|
||||
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public User findUser(Long id) {
|
||||
final Optional<User> user = userRepository.findById(id);
|
||||
return user.orElseThrow(() -> new UserNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<User> findAllUsers() {
|
||||
return userRepository.findAll();
|
||||
}
|
||||
|
||||
@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() {
|
||||
commentService.deleteAllComments();
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addNewPost(Long id, PostDto postDto)
|
||||
{
|
||||
Optional<User> currentUser = userRepository.findById(id);
|
||||
if(currentUser.isPresent())
|
||||
{
|
||||
Post post = new Post(postDto);
|
||||
post.setUser(currentUser.get());
|
||||
postRepository.save(post);
|
||||
}
|
||||
}
|
||||
@Transactional
|
||||
public List<Post> GetUserPosts(Long id)
|
||||
{
|
||||
return userRepository.getUsersPosts(id);
|
||||
}
|
||||
@Transactional
|
||||
public void deletePost(Long id, Long postId) {
|
||||
postRepository.deleteById(postId);
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
if (userEntity == null) {
|
||||
throw new UsernameNotFoundException(username);
|
||||
}
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package ru.ulstu.is.sbapp.Util.error;
|
||||
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
|
||||
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Util.validation.ValidationException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
@ExceptionHandler({
|
||||
CommentNotFoundException.class,
|
||||
UserNotFoundException.class,
|
||||
PostNotFoundException.class,
|
||||
ValidationException.class
|
||||
})
|
||||
public ResponseEntity<Object> handleException(Throwable e) {
|
||||
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
|
||||
final ValidationException validationException = new ValidationException(
|
||||
e.getBindingResult().getAllErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.collect(Collectors.toSet()));
|
||||
return handleException(validationException);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<Object> handleUnknownException(Throwable e) {
|
||||
e.printStackTrace();
|
||||
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package ru.ulstu.is.sbapp.Util.validation;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationException extends RuntimeException {
|
||||
public ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package ru.ulstu.is.sbapp.Util.validation;
|
||||
|
||||
import jakarta.validation.ConstraintViolation;
|
||||
import jakarta.validation.Validation;
|
||||
import jakarta.validation.Validator;
|
||||
import jakarta.validation.ValidatorFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class ValidatorUtil {
|
||||
private final Validator validator;
|
||||
|
||||
public ValidatorUtil() {
|
||||
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
|
||||
this.validator = factory.getValidator();
|
||||
}
|
||||
}
|
||||
|
||||
public <T> void validate(T object) {
|
||||
final Set<ConstraintViolation<T>> errors = validator.validate(object);
|
||||
if (!errors.isEmpty()) {
|
||||
throw new ValidationException(errors.stream()
|
||||
.map(ConstraintViolation::getMessage)
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
@ -1 +1,13 @@
|
||||
|
||||
spring.main.banner-mode=off
|
||||
#server.port=8080
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.settings.trace=false
|
||||
spring.h2.console.settings.web-allow-others=false
|
||||
jwt.dev-token=my-secret-jwt
|
||||
jwt.dev=true
|
||||
|
112
src/test/java/ru/ulstu/is/sbapp/JpaClientTests.java
Normal file
@ -0,0 +1,112 @@
|
||||
/*
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
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 ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.service.UserNotFoundException;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaClientTests {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaClientTests.class);
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private PostService postService;
|
||||
|
||||
@Test
|
||||
void testClientCreate() {
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
log.info("testUserCreate: " + user.toString());
|
||||
Assertions.assertNotNull(user.getId());
|
||||
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testReadClient()
|
||||
{
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
log.info("testUserRead[0]: " + user.toString());
|
||||
final User curuser=userService.findUser(user.getId());
|
||||
log.info("testUserRead[1]: " + curuser.toString());
|
||||
Assertions.assertEquals(user, curuser);
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testClientReadNotFound() {
|
||||
userService.deleteAllUsers();
|
||||
Assertions.assertThrows(UserNotFoundException.class, () -> userService.findUser(-1L));
|
||||
}
|
||||
@Test
|
||||
void testClientReadAll() {
|
||||
userService.deleteAllUsers();
|
||||
userService.addUser("Pupa","Lupa","sasdfdsf@gmail.com");
|
||||
userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final List<User> users = userService.findAllUsers();
|
||||
log.info("testUserReadAll: " + users.toString());
|
||||
Assertions.assertEquals(users.size(), 2);
|
||||
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
@Test
|
||||
void testClientReadAllEmpty() {
|
||||
userService.deleteAllUsers();
|
||||
final List<User> users = userService.findAllUsers();
|
||||
log.info("testUserReadAllEmpty: " + users.toString());
|
||||
Assertions.assertEquals(users.size(), 0);
|
||||
}
|
||||
@Test
|
||||
void testDeletePostwithcomments()
|
||||
{
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"text","tezt");
|
||||
final List<Post> post = postService.findAllPosts();
|
||||
final Post post1 = post.get(0);
|
||||
postService.addCommentToPost(post1.getId(),user12.getId(),"Da");
|
||||
userService.deleteUser(user.getId());
|
||||
}
|
||||
@Test
|
||||
void testAddAndDeletePost()
|
||||
{
|
||||
postService.deleteAllPosts();
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
final User user12 = userService.addUser("Anton","Sorokin","zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"Text1","Text2"); //post
|
||||
userService.addNewPost(user.getId(),"Привет","Да"); //post1
|
||||
final List<Post> posts =postService.findAllPosts();
|
||||
final User user1 = userService.findUser(user.getId());
|
||||
final List<Post> posts1 = user1.getPosts();
|
||||
log.info("testAddAndDeletePost :: ADD " + posts.toString() + " and " + posts1.toString());
|
||||
Assertions.assertEquals(posts.get(0).getUser(), user);
|
||||
Assertions.assertEquals(posts.toString(), posts1.toString());
|
||||
log.info("testAddAndDeletePost :: Delete ");
|
||||
userService.deletePost(user.getId(),posts.get(0).getId());
|
||||
final User us = userService.findUser(user.getId());
|
||||
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(posts.get(0).getId()));
|
||||
final List<Post> postss =postService.findAllPosts();
|
||||
log.info(us.getPosts().toString());
|
||||
log.info(postss.toString());
|
||||
userService.deleteAllUsers();
|
||||
postService.deleteAllPosts();
|
||||
}
|
||||
//посты и коментарии содержащие определенный текст
|
||||
|
||||
}
|
||||
*/
|
86
src/test/java/ru/ulstu/is/sbapp/JpaCommentTest.java
Normal file
@ -0,0 +1,86 @@
|
||||
/*
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
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 ru.ulstu.is.sbapp.Comment.controller.CommentDto;
|
||||
import ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaCommentTest {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaCommentTest.class);
|
||||
@Autowired
|
||||
private CommentService commentService;
|
||||
|
||||
@Test
|
||||
void testTidingCreate()
|
||||
{
|
||||
commentService.deleteAllComments();
|
||||
final Comment comment=commentService.addComment("Net");
|
||||
log.info("testCommentCreate: " + comment.toString());
|
||||
Assertions.assertNotNull(comment.getId());
|
||||
commentService.deleteAllComments();
|
||||
}
|
||||
@Test
|
||||
void testTidingRead()
|
||||
{
|
||||
commentService.deleteAllComments();
|
||||
final Comment comment=commentService.addComment("Net");
|
||||
log.info("testCommentRead[0]: " + comment.toString());
|
||||
final Comment findComment=commentService.findComment(comment.getId());
|
||||
log.info("testCommentRead[1]: " + findComment.toString());
|
||||
Assertions.assertEquals(comment, findComment);
|
||||
|
||||
commentService.deleteAllComments();
|
||||
}
|
||||
@Test
|
||||
void testTidingReadNotFound() {
|
||||
commentService.deleteAllComments();
|
||||
Assertions.assertThrows(CommentNotFoundException.class, () -> commentService.findComment(-1L));
|
||||
}
|
||||
@Test
|
||||
void testAllTidingRead()
|
||||
{
|
||||
commentService.deleteAllComments();
|
||||
commentService.addComment("Net");
|
||||
commentService.addComment("yep");
|
||||
final List<Comment> comments = commentService.findAllComments();
|
||||
log.info("testAllCommentRead: " + comments.toString());
|
||||
Assertions.assertEquals(comments.size(), 2);
|
||||
|
||||
commentService.deleteAllComments();
|
||||
}
|
||||
@Test
|
||||
void testTidingReadAllEmpty() {
|
||||
commentService.deleteAllComments();
|
||||
final List<Comment> comments = commentService.findAllComments();
|
||||
log.info("testCommentReadAllEmpty: " + comments.toString());
|
||||
Assertions.assertEquals(comments.size(), 0);
|
||||
}
|
||||
@Test
|
||||
void testUpdateTiding()
|
||||
{
|
||||
commentService.deleteAllComments();
|
||||
final Comment comment=commentService.addComment("Net");
|
||||
log.info("testUpdateComment: " + comment.toString());
|
||||
commentService.updateComment(comment.getId(),"Ladno");
|
||||
final Comment comment1=commentService.findComment(comment.getId());
|
||||
log.info("testUpdateComment: " + comment1.toString());
|
||||
Assertions.assertEquals(comment1.getText(), "Ladno");
|
||||
commentService.deleteAllComments();
|
||||
}
|
||||
|
||||
}
|
||||
*/
|
155
src/test/java/ru/ulstu/is/sbapp/JpaPostTests.java
Normal file
@ -0,0 +1,155 @@
|
||||
/*
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
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 ru.ulstu.is.sbapp.Comment.model.Comment;
|
||||
import ru.ulstu.is.sbapp.Comment.service.CommentService;
|
||||
import ru.ulstu.is.sbapp.Post.model.Post;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
|
||||
import ru.ulstu.is.sbapp.Post.service.PostService;
|
||||
import ru.ulstu.is.sbapp.User.model.User;
|
||||
import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaPostTests {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaPostTests.class);
|
||||
@Autowired
|
||||
private CommentService commentService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private PostService postService;
|
||||
|
||||
@Test
|
||||
void TestAddPost(){
|
||||
postService.deleteAllPosts();
|
||||
final Post post = postService.addPost("Test","Test");
|
||||
Assertions.assertNotNull(post.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestFindPost(){
|
||||
postService.deleteAllPosts();
|
||||
final Post post = postService.addPost("Test","Test");
|
||||
final Post findPost = postService.findPost(post.getId());
|
||||
Assertions.assertEquals(post, findPost);
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestPostReadNotFound(){
|
||||
postService.deleteAllPosts();
|
||||
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(-1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestFindAllPost(){
|
||||
postService.deleteAllPosts();
|
||||
final Post firstPost = postService.addPost("Test1","Test1");
|
||||
final Post secondPost = postService.addPost("Test2","Test2");
|
||||
final List<Post> posts = postService.findAllPosts();
|
||||
Assertions.assertEquals(posts.size(), 2);
|
||||
}
|
||||
@Test
|
||||
void TestPostReadAllEmpty() {
|
||||
postService.deleteAllPosts();
|
||||
final List<Post> posts = postService.findAllPosts();
|
||||
Assertions.assertEquals(posts.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestPostUpdate(){
|
||||
postService.deleteAllPosts();
|
||||
Post post = postService.addPost("Test1", "Test1");
|
||||
post = postService.updatePost(post.getId(), "Test2", "Test2");
|
||||
Assertions.assertEquals(post.getHeading(), "Test2");
|
||||
Assertions.assertEquals(post.getContent(), "Test2");
|
||||
}
|
||||
@Test
|
||||
void TestDeleteAllPosts()
|
||||
{
|
||||
log.info("Удаление всех постов");
|
||||
Post post = postService.addPost("Test1", "Test1");
|
||||
Post post2 = postService.addPost("Test1", "Test1");
|
||||
List<Post> posts1 = postService.findAllPosts();
|
||||
log.info(posts1.toString());
|
||||
postService.deleteAllPosts();
|
||||
List<Post> posts = postService.findAllPosts();
|
||||
log.info(posts.toString());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestDeletePost(){
|
||||
postService.deleteAllPosts();
|
||||
final Post post = postService.addPost("Test","Test");
|
||||
postService.deletePost(post.getId());
|
||||
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void TestAddComment()
|
||||
{
|
||||
log.info("Добавление комментария");
|
||||
postService.deleteAllPosts();
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"Text1","Text2");
|
||||
final User user2=userService.findUser(user.getId());
|
||||
log.info(user2.getPosts().toString());
|
||||
final List<Post> posts = postService.findAllPosts();
|
||||
final Post post2=postService.findPost(posts.get(0).getId());
|
||||
log.info(post2.toString());
|
||||
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Крутой пост");
|
||||
final List<Comment> comments = commentService.findAllComments();
|
||||
log.info(comments.toString());
|
||||
final User user1=userService.findUser(user.getId());
|
||||
log.info(user1.getComments().toString());
|
||||
final Post post1=postService.findPost(posts.get(0).getId());
|
||||
log.info(post1.getComments().toString());
|
||||
}
|
||||
@Test
|
||||
void TestDeleteCommentFromPost()
|
||||
{
|
||||
log.info("Удаление коммента");
|
||||
postService.deleteAllPosts();
|
||||
userService.deleteAllUsers();
|
||||
final User user = userService.addUser("Pasha","Sorokin","sorokin.zxcv@gmail.com");
|
||||
userService.addNewPost(user.getId(),"Text1","Text2");
|
||||
final User user2=userService.findUser(user.getId());
|
||||
log.info("Посты юзера (добавили)"+user2.getPosts().toString());
|
||||
final List<Post> posts = postService.findAllPosts();
|
||||
final Post post2=postService.findPost(posts.get(0).getId());
|
||||
log.info("Пост который добавили"+post2.toString());
|
||||
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Крутой пост");
|
||||
postService.addCommentToPost(posts.get(0).getId(),user.getId(),"Пост плохой");
|
||||
final List<Comment> comments = commentService.findAllComments();
|
||||
log.info("Добавили коммент"+comments.toString());
|
||||
final User user1=userService.findUser(user.getId());
|
||||
log.info("Комменты юзера"+user1.getComments().toString());
|
||||
final Post post1=postService.findPost(posts.get(0).getId());
|
||||
log.info("Комменты к посту"+post1.getComments().toString());
|
||||
Comment comment1 = commentService.findComment(comments.get(0).getId());
|
||||
log.info("Удаляем коммент");
|
||||
postService.removeCommentFromPost(posts.get(0).getId(),comment1.getId());
|
||||
final User user3=userService.findUser(user.getId());
|
||||
log.info(user3.getPosts().toString());
|
||||
log.info("Комменты юзера после удаления"+user3.getComments().toString());
|
||||
final Post post3 = postService.findPost(posts.get(0).getId());
|
||||
log.info(post3.toString());
|
||||
log.info(post3.getComments().toString());
|
||||
final List<Comment> comment4=commentService.findAllComments();
|
||||
log.info(comment4.toString());
|
||||
commentService.deleteAllComments();
|
||||
postService.deleteAllPosts();
|
||||
userService.deleteAllUsers();
|
||||
}
|
||||
}
|
||||
*/
|
@ -1,13 +0,0 @@
|
||||
package ru.ulstu.is.sbapp;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class SbappApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
6
src/test/resources/application.properties
Normal file
@ -0,0 +1,6 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|