Lab 6 react (сделал все с пользователем (ну кроме обновления)) (вообщем регистрация и логин работает, и по правам нормально ссылки распределяет (работаем дальше))
This commit is contained in:
parent
c61553b284
commit
814cc54767
@ -1,48 +1,45 @@
|
||||
|
||||
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
|
||||
import Header from './components/common/Header';
|
||||
import Catalogs from './components/catalogs/MainPage';
|
||||
import CatalogGroups from './components/catalogs/Autorize';
|
||||
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 Reports from './components/catalogs/RezhimRaboty';
|
||||
import ReportGroupStudents from './components/catalogs/Raspisanie';
|
||||
import Footer from './components/common/Footer';
|
||||
|
||||
function Router(props) {
|
||||
return useRoutes(props.rootRoute);
|
||||
}
|
||||
import LoginPage from "./components/catalogs/LoginPage";
|
||||
import SignupPage from "./components/catalogs/SignupPage";
|
||||
import NavBar from "./components/common/NavBar";
|
||||
|
||||
export default function App() {
|
||||
const routes = [
|
||||
{ index: true, element: <Catalogs /> },
|
||||
{ path: 'Main_page', element: <Catalogs />, label: 'Главная' },
|
||||
{ path: 'News', element: <CatalogStudents/>, label:'Новости' },
|
||||
{ path: 'Autorize', element: <CatalogGroups />, label:'Авторизация'},
|
||||
{ path: 'RezhimRaboty', element: <Reports />, label: 'Режим работы' },
|
||||
{ path: 'Raspisanie', element: <ReportGroupStudents />,label:'Расписание' },
|
||||
{ path: 'Post', element: <Post/>}
|
||||
];
|
||||
const links = routes.filter(route => route.hasOwnProperty('label'));
|
||||
const rootRoute = [
|
||||
{ path: '/', element: render(links), children: routes }
|
||||
];
|
||||
const links = [
|
||||
{ path: 'main', label: "Main", userGroup: "AUTH" },
|
||||
{ path: 'news', label: "News", userGroup: "AUTH" },
|
||||
{ path: 'users', label: "Users", userGroup: "ADMIN" },
|
||||
];
|
||||
return(
|
||||
<>
|
||||
<BrowserRouter>
|
||||
<div className='body_app'>
|
||||
<NavBar links={links}></NavBar>
|
||||
<div className="d-flex 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="*" />
|
||||
</Route>
|
||||
<Route element={<PrivateRoutes userGroup="ADMIN" />}>
|
||||
<Route element={<UsersPage />} path="/users" />
|
||||
</Route>
|
||||
</Routes>
|
||||
</div>
|
||||
<Footer className="border-top">
|
||||
Footer
|
||||
</Footer >
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
</>
|
||||
);
|
||||
|
||||
function render(links) {
|
||||
return (
|
||||
<div className='body_app'>
|
||||
<Header links={links} />
|
||||
<div className="d-flex text-white bg-info bg-gradient fw-bold">
|
||||
<Outlet />
|
||||
</div>
|
||||
<Footer links={links}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Router rootRoute={ rootRoute } />
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
@ -1,146 +0,0 @@
|
||||
import React from "react";
|
||||
import { useState } from 'react';
|
||||
import {useEffect} from 'react';
|
||||
import UserDto from '../../models/UserDto';
|
||||
export default function CatalogGroups(props) {
|
||||
const formRef = React.createRef();
|
||||
const [output, setOutput] = useState([]);
|
||||
const FirstInput = document.getElementById("validationCustom01");
|
||||
const LastInput = document.getElementById("validationCustom02");
|
||||
const emailInput = document.getElementById("validationCustomMail");
|
||||
const getAll = async function () {
|
||||
const requestUrl = "http://localhost:8080/user";
|
||||
const response = await fetch(requestUrl);
|
||||
const users = await response.json();
|
||||
setOutput(users);
|
||||
}
|
||||
useEffect(() => {
|
||||
getAll();
|
||||
}, []);
|
||||
const remove = async function(id){
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const requestUrl = "http://localhost:8080" + "/user/" + id;
|
||||
const response=await fetch(requestUrl,requestParams);
|
||||
return await response.json;
|
||||
};
|
||||
const create = async function (firstName, lastName,Email) {
|
||||
const requestParams = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
};
|
||||
const response = await fetch("http://localhost:8080" + `/user?firstName=${firstName}&lastName=${lastName}&email=${Email}`, requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
const refresh = async function(id,firstName, lastName,Email)
|
||||
{
|
||||
const requestParams={
|
||||
method:"PUT",
|
||||
headers:{
|
||||
"Content-Type":"application/json",
|
||||
}
|
||||
};
|
||||
const response=await fetch(`http://localhost:8080/user/${id}?firstName=${firstName}&lastName=${lastName}&email=${Email}`,requestParams);
|
||||
return await response.json();
|
||||
}
|
||||
const add_but = function(event)
|
||||
{
|
||||
event.preventDefault();
|
||||
create(FirstInput.value, LastInput.value,emailInput.value).then((result) => {
|
||||
getAll();
|
||||
FirstInput.value = "";
|
||||
LastInput.value = "";
|
||||
emailInput.value="";
|
||||
alert(`User[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName},email=${result.email}]`);
|
||||
});
|
||||
}
|
||||
const edit_btn = function(id,event)
|
||||
{
|
||||
console.log("Обновление")
|
||||
refresh(id,FirstInput.value, LastInput.value,emailInput.value).then((result)=>{
|
||||
getAll();
|
||||
FirstInput.value = "";
|
||||
LastInput.value = "";
|
||||
emailInput.value="";
|
||||
});
|
||||
}
|
||||
const rem_but = function(id,event)
|
||||
{
|
||||
console.log("Удаление")
|
||||
remove(id).then((result)=>{
|
||||
getAll();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
<form className="row g-3 needs-validation">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustom01">Имя</label>
|
||||
<input className="form-control" id="validationCustom01" type="text" defaultValue="" required/>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите имя!</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustom02">Фамилия</label>
|
||||
<input className="form-control" id="validationCustom02" type="text" defaultValue="" required/>
|
||||
<div className="valid-feedback">Отлично! </div>
|
||||
<div className="invalid-feedback">Введите Фамилию!</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="validationCustomMail">Почта</label>
|
||||
<div className="input-group has-validation">
|
||||
<input className="form-control" id="validationCustomMail" type="email" aria-describedby="inputGroupPrepend" required/>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите почту!</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12">
|
||||
<div className="form=check">
|
||||
<input className="form-check-input" id="invalidCheck" type="checkbox" defaultValue="" required/>
|
||||
<label className="form-check-label" htmlFor="invalidCheck">Согласие на обработку персональных данных</label>
|
||||
<div className="valid-feedback">Отлично!</div>
|
||||
<div className="invalid-feedback">Введите пароль!</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 d-flex">
|
||||
<div className="d-grid col-sm-4 mx-auto">
|
||||
<button type="button" id="add_btn" className="btn btn-outline-light btn-lg float-end" onClick={add_but}>Add</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<div className="row table-responsive mx-2">
|
||||
<table className="table mt-3">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Last Name</th>
|
||||
<th scope="col">First Name</th>
|
||||
<th scope="col">Email</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody">
|
||||
{output.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<th scope="row">{user.id}</th>
|
||||
<td>{user.firstName}</td>
|
||||
<td>{user.lastName}</td>
|
||||
<td>{user.email}</td>
|
||||
<td><button type="button" className="btn btn-outline-light text-center mx-2" onClick={(e) => edit_btn(user.id, 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) => rem_but(user.id, e)}><i className="fa-sharp fa-solid fa-trash"></i></button></td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
90
FrontEnd/src/components/catalogs/LoginPage.jsx
Normal file
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;
|
@ -1,13 +0,0 @@
|
||||
|
||||
|
||||
export default function ReportGroupStudents(props) {
|
||||
return (
|
||||
<div className="container-fluid justify-content-center align-items-center d-flex flex-column my-2">
|
||||
<div>
|
||||
<h6>Расписание<img className="pdf-size " src="img/Rasp.png" alt="Rasp"/></h6>
|
||||
</div>
|
||||
<div> <a href="Rasp(1-4).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(1-4).pdf" target="_blank">Расписание 1 - 4 кл. (.pdf)</a></div><br/><br/>
|
||||
<div> <a href="Rasp(5-11).pdf" target="_blank"><img className="pdf-size" src="img/6666.png"/></a><a href="Rasp(5-11).pdf" target="_blank">Расписание 5 - 11 кл. (.pdf)</a></div>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -1,135 +0,0 @@
|
||||
|
||||
|
||||
export default function Reports(props) {
|
||||
return (
|
||||
<div className="container-fluid my-2">
|
||||
<div className="float-start me-5">
|
||||
<h3 className="text-wrap">Расписание звонков</h3>
|
||||
<table className="Vnov1 float-start table-bordered">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th colSpan="2">1 смена</th>
|
||||
<th colSpan="2">2 смена</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1 урок</td>
|
||||
<td>8.00-8.45</td>
|
||||
<td>0 урок</td>
|
||||
<td>12.55-13.40</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2 урок </td>
|
||||
<td>8.55-9.40 </td>
|
||||
<td>1 урок </td>
|
||||
<td>13.50-14.35</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>3 урок </td>
|
||||
<td>10.00-10.45</td>
|
||||
<td>2 урок</td>
|
||||
<td>14.50-15.35</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>4 урок</td>
|
||||
<td>11.05-11.50</td>
|
||||
<td>3 урок</td>
|
||||
<td>12.00-12.45</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>5 урок</td>
|
||||
<td>12.00-12.45</td>
|
||||
<td>4 урок</td>
|
||||
<td>16.45-17.30</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>6 урок</td>
|
||||
<td>12.55-13.40 </td>
|
||||
<td>5 урок</td>
|
||||
<td>17.40-18.25 </td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>7 урок</td>class
|
||||
<td>13.50-14.35</td>
|
||||
<td> </td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Режим работы ОУ:
|
||||
<div className="align-items-justify text-wrap fs-5">Учебный год в МБОУ средняя общеобразовательная школа №10 начинается 2 сентября, состоит из 3-х триместров, включает каникулы по графику. МБОУ средняя общеобразовательная школа №10 работает в две смены. Школа работает в течение 5 дней в неделю с понедельника по пятницу, выходной день – суббота и воскресенье — в 1-11 классах. Продолжительность учебного года – 33 учебных недели для учащихся 1-х классов, 34 учебных недель для учащихся 2-11 классов. Для учащихся, обучающихся на дому, продолжительность учебного года составляет 34 недели. Начало учебных занятий в 8-00.
|
||||
<table className="table-bordered">
|
||||
|
||||
<tbody>
|
||||
<th>Триместр</th>
|
||||
<th>Дата начала/дата окончания</th>
|
||||
<th colSpan="2">Каникулы</th>
|
||||
<tr>
|
||||
<td>I</td>
|
||||
<td>02.09.2022 - 19.11.2022</td>
|
||||
<td>08.10.2022 - 13.10.2022</td>
|
||||
<td>20.11.2022 - 25.11.2022</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>II</td>
|
||||
<td>26.11.2022 - 19.02.2023</td>
|
||||
<td>28.12.2022 - 07.01.2023 </td>
|
||||
<td>20.02.2023 - 25.02.2023</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>III</td>
|
||||
<td>26.02.2023 - 29.05.2023</td>
|
||||
<td>10.04.2023 - 15.04.2023</td>
|
||||
<td>30.05.2023 - 31.08.2023</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
86
FrontEnd/src/components/catalogs/SignupPage.jsx
Normal file
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
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 UsersPage = function () {
|
||||
|
||||
const [users, setUsers] = useState([]);
|
||||
const [pageNumbers, setPageNumbers] = useState([]);
|
||||
const [pageNumber, setPageNumber] = useState();
|
||||
|
||||
useEffect(() => {
|
||||
getUsers(1);
|
||||
}, []);
|
||||
|
||||
const getTokenForHeader = function () {
|
||||
return "Bearer " + localStorage.getItem("token");
|
||||
}
|
||||
|
||||
const getUsers = async function (page) {
|
||||
const requestParams = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = host + `/users?page=${page}`;
|
||||
const response = await fetch(requestUrl, requestParams);
|
||||
const data = await response.json();
|
||||
setUsers(data.first.content);
|
||||
setPageNumber(data.first.number);
|
||||
setPageNumbers(data.second);
|
||||
}
|
||||
|
||||
const removeUser = async function (id) {
|
||||
const requestParams = {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": getTokenForHeader(),
|
||||
}
|
||||
};
|
||||
const requestUrl = host + `/user/${id}`;
|
||||
await fetch(requestUrl, requestParams);
|
||||
}
|
||||
|
||||
const pageButtonOnClick = function (page) {
|
||||
getUsers(page);
|
||||
}
|
||||
|
||||
const removeButtonOnClick = function (id) {
|
||||
const confirmResult = confirm("Are you sure you want to remove " +
|
||||
"the selected user?");
|
||||
if (confirmResult === false) {
|
||||
return;
|
||||
}
|
||||
removeUser(id).then(() => getUsers(pageNumber + 1));
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="table-shell mb-3">
|
||||
<table className="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: "10%" }} scope="col">#</th>
|
||||
<th style={{ width: "15%" }} scope="col">ID</th>
|
||||
<th style={{ width: "30%" }} scope="col">Login</th>
|
||||
<th style={{ width: "30%" }} scope="col">Email</th>
|
||||
<th style={{ width: "15%" }} scope="col">Role</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user, index) => (
|
||||
<tr>
|
||||
<th style={{ width: "10%" }} scope="row">{index}</th>
|
||||
<td style={{ width: "15%" }}>{user.id}</td>
|
||||
<td style={{ width: "30%" }}>{user.login}</td>
|
||||
<td style={{ width: "30%" }}>{user.email}</td>
|
||||
<td style={{ width: "15%" }}>{user.role}</td>
|
||||
{user.login !== localStorage.getItem("user") ?
|
||||
<td style={{ width: "1%" }}>
|
||||
<button className="btn btn-secondary btn-sm"
|
||||
onClick={() => removeButtonOnClick(user.id)}>
|
||||
del
|
||||
</button>
|
||||
</td> : null}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div>
|
||||
<p>
|
||||
Pages:
|
||||
</p>
|
||||
<nav>
|
||||
<ul className="pagination">
|
||||
{pageNumbers.map((number) => (
|
||||
<li className={`page-item ${number === pageNumber + 1 ? "active" : ""}`}
|
||||
onClick={() => pageButtonOnClick(number)}>
|
||||
<a className="page-link" href="#">{number}</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default UsersPage;
|
@ -1,30 +0,0 @@
|
||||
import { NavLink } from 'react-router-dom';
|
||||
|
||||
export default function Header(props) {
|
||||
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 =>
|
||||
<button key={route.path}
|
||||
className="btn btn-outline-light mx-1">
|
||||
<NavLink className="nav-link" to={route.path}>
|
||||
{route.label}
|
||||
</NavLink>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
);
|
||||
}
|
56
FrontEnd/src/components/common/NavBar.jsx
Normal file
56
FrontEnd/src/components/common/NavBar.jsx
Normal file
@ -0,0 +1,56 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
const NavBar = function (props) {
|
||||
|
||||
const [userRole, setUserRole] = useState("NONE");
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("storage", () => {
|
||||
getUserRole();
|
||||
});
|
||||
getUserRole();
|
||||
}, [])
|
||||
|
||||
const getUserRole = function () {
|
||||
const role = localStorage.getItem("role") || "NONE";
|
||||
setUserRole(role);
|
||||
}
|
||||
|
||||
const validate = function (userGroup) {
|
||||
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;
|
47
FrontEnd/src/components/common/PrivateRoutes.jsx
Normal file
47
FrontEnd/src/components/common/PrivateRoutes.jsx
Normal file
@ -0,0 +1,47 @@
|
||||
import { Outlet, Navigate, useNavigate } from 'react-router-dom';
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const PrivateRoutes = (props) => {
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener("storage", () => {
|
||||
let token = localStorage.getItem("token");
|
||||
if (token) {
|
||||
getRole(token).then((role) => {
|
||||
if (localStorage.getItem("role") != role) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user");
|
||||
localStorage.removeItem("role");
|
||||
window.dispatchEvent(new Event("storage"));
|
||||
navigate("/main");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [])
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
@ -4,7 +4,5 @@ import App from './App'
|
||||
import './style.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('app')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
||||
|
@ -1,8 +0,0 @@
|
||||
export default class BuyerDto {
|
||||
constructor(args) {
|
||||
this.id = args.id || null;
|
||||
this.firstName = args.firstName;
|
||||
this.lastName = args.lastName;
|
||||
this.email = args.email;
|
||||
}
|
||||
}
|
8
FrontEnd/src/models/user-signup-dto.js
Normal file
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;
|
||||
}
|
||||
}
|
12
build.gradle
12
build.gradle
@ -18,12 +18,20 @@ jar {
|
||||
|
||||
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 group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
|
@ -2,11 +2,12 @@ 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;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/comment")
|
||||
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/comment")
|
||||
public class CommentController {
|
||||
private final CommentService commentService;
|
||||
public CommentController(CommentService commentService) {
|
||||
|
@ -13,7 +13,7 @@ public class CommentDto {
|
||||
{
|
||||
this.id= comment.getId();
|
||||
this.Text=comment.getText();
|
||||
this.userName=comment.getUser().getFirstName() + " " + comment.getUser().getLastName();
|
||||
this.userName=comment.getUser().getLogin();
|
||||
}
|
||||
public Long getId()
|
||||
{
|
||||
|
@ -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,91 @@
|
||||
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.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
|
||||
AuthenticationManagerBuilder authenticationManagerBuilder = http
|
||||
.getSharedObject(AuthenticationManagerBuilder.class);
|
||||
authenticationManagerBuilder.userDetailsService(userService);
|
||||
return authenticationManagerBuilder.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.ignoring()
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.requestMatchers("/*.js")
|
||||
.requestMatchers("/*.html")
|
||||
.requestMatchers("/*.css")
|
||||
.requestMatchers("/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;
|
@ -3,6 +3,7 @@ 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;
|
||||
@ -11,7 +12,7 @@ import ru.ulstu.is.sbapp.User.service.UserService;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/post")
|
||||
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/post")
|
||||
public class PostController {
|
||||
private final PostService postService;
|
||||
public PostController(PostService postService) {
|
||||
|
19
src/main/java/ru/ulstu/is/sbapp/User/controller/Pair.java
Normal file
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;
|
||||
}
|
||||
}
|
@ -1,16 +1,27 @@
|
||||
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
|
||||
@RequestMapping("/user")
|
||||
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;
|
||||
@ -19,11 +30,22 @@ public class UserController {
|
||||
public UserDto getUser(@PathVariable Long id) {
|
||||
return new UserDto(userService.findUser(id));
|
||||
}
|
||||
@GetMapping
|
||||
public List<UserDto> getUsers() {
|
||||
return userService.findAllUsers().stream()
|
||||
.map(UserDto::new)
|
||||
|
||||
@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("/{id}/posts")
|
||||
public List<PostDto> getPosts(@PathVariable Long id) {
|
||||
@ -31,26 +53,37 @@ public class UserController {
|
||||
.map(PostDto::new)
|
||||
.toList();
|
||||
}
|
||||
@PostMapping
|
||||
public UserDto createUser(@RequestParam("firstName") String firstName,
|
||||
@RequestParam("lastName") String lastname,
|
||||
@RequestParam("email") String email) {
|
||||
return new UserDto(userService.addUser(firstName, lastname,email));
|
||||
@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);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto updateClient(@PathVariable Long id,
|
||||
@RequestParam("firstName") String firstName,
|
||||
@RequestParam("lastName") String lastname,
|
||||
@RequestParam("email") String email){
|
||||
return new UserDto(userService.updateUser(id, firstName, lastname,email));
|
||||
@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("/{id}/Post")
|
||||
@PostMapping("/user/{id}/Post")
|
||||
public void addPost(@PathVariable Long id,
|
||||
@RequestBody @Valid PostDto postDto) {
|
||||
userService.addNewPost(id, postDto);
|
||||
}
|
||||
@DeleteMapping("/{id}/Post/{postId}")
|
||||
@DeleteMapping("/user/{id}/Post/{postId}")
|
||||
public void removePost(@PathVariable Long id,
|
||||
@PathVariable Long postId)
|
||||
{
|
||||
@ -58,8 +91,17 @@ public class UserController {
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void deleteUser(@PathVariable Long id) {
|
||||
userService.deleteUser(id);
|
||||
@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();
|
||||
}
|
||||
}
|
||||
|
@ -3,18 +3,17 @@ 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 firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String login;
|
||||
private String email;
|
||||
private String password;
|
||||
private UserRole role;
|
||||
|
||||
private List<Post> posts = new ArrayList<>();
|
||||
|
||||
@ -22,21 +21,31 @@ public class UserDto {
|
||||
|
||||
public UserDto(){}
|
||||
public UserDto(User user) {
|
||||
this.id=user.getId();
|
||||
this.firstName = user.getFirstName();
|
||||
this.lastName = user.getLastName();
|
||||
this.email= user.getEmail();
|
||||
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 getFirstName() {
|
||||
return firstName;
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
@ -47,9 +56,14 @@ public class UserDto {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -2,8 +2,12 @@ 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;
|
||||
@ -15,15 +19,21 @@ public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column()
|
||||
@NotBlank(message = "firstName cannot be null")
|
||||
private String firstName;
|
||||
@NotBlank(message = "lastName cannot be null")
|
||||
private String lastName;
|
||||
|
||||
@NotBlank(message = "email cannot be null")
|
||||
@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<>();
|
||||
|
||||
@ -33,10 +43,25 @@ public class User {
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String firstName, String lastName, String email) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.email=email;
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@ -44,20 +69,20 @@ public class User {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public List<Post> getPosts()
|
||||
{
|
||||
@ -71,6 +96,13 @@ public class User {
|
||||
posts.add(post);
|
||||
post.setUser(this);
|
||||
}
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(UserRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getEmail()
|
||||
{
|
||||
@ -97,8 +129,8 @@ public class User {
|
||||
public String toString() {
|
||||
return "Client{" +
|
||||
"id=" + id +
|
||||
", firstName='" + firstName + '\'' +
|
||||
", lastName='" + lastName + '\'' +
|
||||
", login='" + login + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", email='" + email + '\'' +
|
||||
", posts=" + posts +'\''+
|
||||
'}';
|
||||
|
21
src/main/java/ru/ulstu/is/sbapp/User/model/UserRole.java
Normal file
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";
|
||||
}
|
||||
}
|
||||
|
@ -12,4 +12,6 @@ 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));
|
||||
}
|
||||
}
|
@ -1,7 +1,10 @@
|
||||
package ru.ulstu.is.sbapp.User.service;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException{
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,37 @@
|
||||
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 {
|
||||
public class UserService implements UserDetailsService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@ -25,20 +40,38 @@ public class UserService {
|
||||
private final CommentService commentService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public UserService(UserRepository userRepository, ValidatorUtil validatorUtil, PostRepository postRepository, CommentService commentService)
|
||||
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 firstName, String lastName, String email) {
|
||||
final User user = new User(firstName, lastName, email);
|
||||
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);
|
||||
@ -51,24 +84,31 @@ public class UserService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User updateUser(Long id, String firstName, String lastName, String email) {
|
||||
final User currentUser = findUser(id);
|
||||
currentUser.setFirstName(firstName);
|
||||
currentUser.setLastName(lastName);
|
||||
currentUser.setEmail(email);
|
||||
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 void deleteUser(Long id) {
|
||||
userRepository.deleteById(id);
|
||||
public User deleteUser(Long id) {
|
||||
final User currentUser = findUser(id);
|
||||
userRepository.delete(currentUser);
|
||||
return currentUser;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllUsers() {
|
||||
commentService.deleteAllComments();
|
||||
postRepository.deleteAll();
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
@ -92,4 +132,34 @@ public class UserService {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
@ -9,3 +9,5 @@ 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
|
||||
|
Loading…
x
Reference in New Issue
Block a user