frontend
This commit is contained in:
@@ -6,7 +6,7 @@ import { Post } from "../entity/Post";
|
||||
class PostController {
|
||||
async create(req: Request, res: Response): Promise<void> {
|
||||
const post = res.locals.post;
|
||||
AppDataSource.manager.save(post);
|
||||
await AppDataSource.manager.save(post);
|
||||
|
||||
res.status(200).send("Ok");
|
||||
}
|
||||
@@ -15,7 +15,7 @@ class PostController {
|
||||
const { postId } = req.params;
|
||||
|
||||
const post = res.locals.post;
|
||||
AppDataSource.manager.update(Post, { id: postId }, post);
|
||||
await AppDataSource.manager.update(Post, { id: postId }, post);
|
||||
|
||||
res.status(200).send("Ok");
|
||||
}
|
||||
@@ -23,10 +23,18 @@ class PostController {
|
||||
async delete(req: Request, res: Response): Promise<void> {
|
||||
const { postId } = req.params;
|
||||
|
||||
AppDataSource.manager.delete(Post, { id: postId });
|
||||
await AppDataSource.manager.delete(Post, { id: postId });
|
||||
|
||||
res.status(200).send("Ok");
|
||||
}
|
||||
|
||||
async get(req: Request, res: Response): Promise<void> {
|
||||
const { postId } = req.params;
|
||||
|
||||
const post = await AppDataSource.manager.findOneBy(Post, {id: Number.parseInt(postId)});
|
||||
|
||||
res.status(200).send(post);
|
||||
}
|
||||
}
|
||||
|
||||
export default new PostController();
|
||||
@@ -36,7 +36,15 @@ class UserController {
|
||||
async getPosts(req: Request, res: Response): Promise<void> {
|
||||
const { userId } = req.params;
|
||||
|
||||
const posts = await AppDataSource.manager.findBy(Post, { authorId: Number.parseInt(userId) });
|
||||
const posts = await AppDataSource.manager.find(Post,
|
||||
{
|
||||
where:
|
||||
{ authorId: Number.parseInt(userId) },
|
||||
order: {
|
||||
date: "DESC"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
res.status(200).send(posts);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AppDataSource } from "../data-source";
|
||||
|
||||
// Updates or creates a post and handles things like deleting old post's media
|
||||
const handlePostData = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||
try {
|
||||
const token = req.cookies.jwt;
|
||||
const user = (jwt.decode(token) as JwtPayload)
|
||||
|
||||
@@ -23,6 +24,7 @@ const handlePostData = async (req: Request, res: Response, next: NextFunction):
|
||||
fs.unlinkSync(`${process.env.UPLOAD_DESTINATION}/${filename}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (req.file) {
|
||||
const extension = path.extname(req.file.originalname).toLowerCase()
|
||||
if ([".png", ".jpg", ".jpeg", ".webp", ".mp4", ".webm"].indexOf(extension) < 0) {
|
||||
@@ -38,6 +40,10 @@ const handlePostData = async (req: Request, res: Response, next: NextFunction):
|
||||
post.message = newFilename;
|
||||
post.type = 1;
|
||||
} else {
|
||||
if (!post.message) {
|
||||
res.status(400).send("Post message is not specified");
|
||||
return;
|
||||
}
|
||||
post.type = 0;
|
||||
post.message = message;
|
||||
}
|
||||
@@ -45,6 +51,9 @@ const handlePostData = async (req: Request, res: Response, next: NextFunction):
|
||||
post.authorId = user.id;
|
||||
res.locals.post = post;
|
||||
next();
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
export default { handlePostData };
|
||||
@@ -18,6 +18,7 @@ const upload = multer({
|
||||
|
||||
PostRouter.post('/create', auth.authenticate, upload.single("file"), utils.handlePostData, PostController.create);
|
||||
PostRouter.put('/update/:postId', auth.authorizeForPost, existance.postShouldExist, upload.single("file"), utils.handlePostData, PostController.update);
|
||||
PostRouter.delete('/delete/:postId', auth.authorizeForPost, existance.postShouldExist, PostController.delete);
|
||||
PostRouter.delete('/delete/:postId', existance.postShouldExist, auth.authorizeForPost, PostController.delete);
|
||||
PostRouter.get('/:postId', existance.postShouldExist, PostController.get);
|
||||
|
||||
export default PostRouter;
|
||||
9
frontend.Dockerfile
Normal file
9
frontend.Dockerfile
Normal file
@@ -0,0 +1,9 @@
|
||||
FROM node:22-bullseye
|
||||
|
||||
WORKDIR /opt/frontend
|
||||
|
||||
COPY frontend .
|
||||
RUN npm i
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["npm", "run", "start"]
|
||||
23
frontend/.gitignore
vendored
Normal file
23
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
70
frontend/README.md
Normal file
70
frontend/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
|
||||
|
||||
The page will reload when you make changes.\
|
||||
You may also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
|
||||
|
||||
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
|
||||
|
||||
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
|
||||
### Code Splitting
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||
|
||||
### Analyzing the Bundle Size
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||
|
||||
### Making a Progressive Web App
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||
|
||||
### Advanced Configuration
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||
|
||||
### Deployment
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||
|
||||
### `npm run build` fails to minify
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
||||
17491
frontend/package-lock.json
generated
Normal file
17491
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
frontend/package.json
Normal file
43
frontend/package.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react": "^19.0.8",
|
||||
"@types/react-dom": "^19.0.3",
|
||||
"cra-template": "1.2.0",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hot-toast": "^2.5.1",
|
||||
"react-router-dom": "^7.1.3",
|
||||
"react-scripts": "^5.0.1",
|
||||
"web-vitals": "^4.2.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
BIN
frontend/public/favicon.ico
Normal file
BIN
frontend/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
43
frontend/public/index.html
Normal file
43
frontend/public/index.html
Normal file
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
BIN
frontend/public/logo192.png
Normal file
BIN
frontend/public/logo192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
BIN
frontend/public/logo512.png
Normal file
BIN
frontend/public/logo512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
25
frontend/public/manifest.json
Normal file
25
frontend/public/manifest.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
3
frontend/public/robots.txt
Normal file
3
frontend/public/robots.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
22
frontend/src/App.tsx
Normal file
22
frontend/src/App.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import React from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
|
||||
import Login from './pages/Login.tsx';
|
||||
import Index from './pages/Index.tsx';
|
||||
import Register from './pages/Register.tsx';
|
||||
import User from './pages/User.tsx';
|
||||
import PostActions from './pages/PostActions.tsx';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path='/' Component={Index} />
|
||||
<Route path='/login' Component={Login} />
|
||||
<Route path='/register' Component={Register} />
|
||||
<Route path='/user/' Component={User} />
|
||||
<Route path='/post' Component={PostActions} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
63
frontend/src/Post.tsx
Normal file
63
frontend/src/Post.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import React, { Key } from "react";
|
||||
import { jwtDecode } from 'jwt-decode';
|
||||
import Cookies from 'js-cookie';
|
||||
|
||||
class Post {
|
||||
id: Number;
|
||||
authorId: Number;
|
||||
type: Number;
|
||||
message: String;
|
||||
date: Date;
|
||||
constructor(id: Number, authorId: Number, type: Number, message: String, date: Date) {
|
||||
this.id = id;
|
||||
this.authorId = authorId;
|
||||
this.type = type;
|
||||
this.message = message;
|
||||
this.date = date;
|
||||
}
|
||||
}
|
||||
|
||||
function PostTag(post: Post) {
|
||||
|
||||
const goToUpdate = () => {
|
||||
window.location.href=`../post/?postId=${post.id}`
|
||||
}
|
||||
|
||||
const deletePost = async () => {
|
||||
await fetch(`/api/v1/post/delete/${post.id}`, {
|
||||
method: "DELETE"
|
||||
}).then(response => console.log(response));
|
||||
}
|
||||
|
||||
|
||||
const amIAnAuthor = jwtDecode(Cookies.get("jwt")!).id == post.authorId;
|
||||
|
||||
let content;
|
||||
if (post.type == 1) {
|
||||
if ([".mp4", ".webm"].indexOf(post.message.slice(-4).toLowerCase()) > -1) {
|
||||
content = <video>
|
||||
<source src={`/media/${post.message}`} />
|
||||
</video>
|
||||
} else {
|
||||
content = <img width="50%" height="50%" src={`/media/${post.message}`} />
|
||||
}
|
||||
} else {
|
||||
content = post.message;
|
||||
}
|
||||
return (
|
||||
<div className="post" key={post.id as Key}>
|
||||
{content}
|
||||
{amIAnAuthor ? (
|
||||
<div>
|
||||
<button onClick={goToUpdate} >изменить</button>
|
||||
<br></br>
|
||||
<button onClick={deletePost}>удалить</button></div>
|
||||
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default { Post, PostTag };
|
||||
0
frontend/src/css/Login.css
Normal file
0
frontend/src/css/Login.css
Normal file
0
frontend/src/css/Register.css
Normal file
0
frontend/src/css/Register.css
Normal file
101
frontend/src/css/index.css
Normal file
101
frontend/src/css/index.css
Normal file
@@ -0,0 +1,101 @@
|
||||
html,
|
||||
body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
background-color: #3d2b53;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: block;
|
||||
width: 40%;
|
||||
height: 650px;
|
||||
margin-top: 10%;
|
||||
margin-bottom: auto;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
background-color: #875dba;
|
||||
box-shadow: 0px 0px 120px #000f;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
h1 {
|
||||
display: block;
|
||||
text-align: center;
|
||||
padding-top: 180px;
|
||||
color: white;
|
||||
-webkit-text-stroke: 1px #777;
|
||||
}
|
||||
|
||||
.beautiful_input {
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-bottom: 1px solid #9bfaa9;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
letter-spacing: 2px;
|
||||
margin-bottom: 30px;
|
||||
margin-left: 33%;
|
||||
margin-right: 33%;
|
||||
outline: none;
|
||||
padding: 10px 0;
|
||||
width: 33%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #9bfaa9;
|
||||
font-size: 14px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
color: #655b5b;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
padding: 10px 20px;
|
||||
letter-spacing: 2px;
|
||||
text-transform: uppercase;
|
||||
position: relative;
|
||||
animation: cubic-bezier();
|
||||
box-shadow: 0 6px #777;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #95efa3
|
||||
}
|
||||
|
||||
button:active {
|
||||
background-color: #75bd80;
|
||||
box-shadow: 0 5px #777;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
|
||||
.post {
|
||||
background-color: #875dba;
|
||||
margin-top: 20px;
|
||||
margin-left: 20%;
|
||||
margin-right: 20%;
|
||||
padding: 20px;
|
||||
box-shadow: 0px 0px 40px #000f;
|
||||
}
|
||||
|
||||
.users {
|
||||
background-color: #875dba;
|
||||
margin-top: 20px;
|
||||
margin-left: 20%;
|
||||
margin-right: 20%;
|
||||
padding: 20px;
|
||||
box-shadow: 0px 0px 40px #000f;
|
||||
}
|
||||
|
||||
.userEntry {
|
||||
background-color: #75bd80;
|
||||
padding: 5px;
|
||||
box-shadow: 0px 0px 6px #463061;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
.backButton {
|
||||
margin-left: 20%;
|
||||
/* margin-top: 20% */
|
||||
}
|
||||
12
frontend/src/index.tsx
Normal file
12
frontend/src/index.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import './css/index.css';
|
||||
import App from './App.tsx';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root')!);
|
||||
root.render(
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
);
|
||||
44
frontend/src/pages/Index.tsx
Normal file
44
frontend/src/pages/Index.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import Cookies from 'js-cookie';
|
||||
import Login from './Login.tsx';
|
||||
|
||||
function Index() {
|
||||
const [users, setUsers] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAllUsers = async () => {
|
||||
await fetch(`/api/v1/user/all`, {method: "GET"})
|
||||
.then(response => response.json())
|
||||
.then(usersJSON => setUsers(usersJSON));
|
||||
}
|
||||
|
||||
fetchAllUsers()
|
||||
}, []);
|
||||
|
||||
const gotToUser = (event) => {
|
||||
window.location.href = `/user/?userId=${event.target.id}`;
|
||||
}
|
||||
|
||||
const newPost = () => {
|
||||
window.location.href = `/post`;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{Cookies.get("jwt")? (
|
||||
<>
|
||||
<center><button onClick={newPost}>Новый пост</button></center>
|
||||
<div className="users">
|
||||
{users.map((user: any) => {
|
||||
return <div className="userEntry" key={user.id} id={user.id} onClick={gotToUser}>{user.username}</div>
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Login />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Index;
|
||||
65
frontend/src/pages/Login.tsx
Normal file
65
frontend/src/pages/Login.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import toast, { Toaster } from 'react-hot-toast';
|
||||
import React from 'react';
|
||||
import '../css/Login.css';
|
||||
import '../css/index.css';
|
||||
|
||||
function Login() {
|
||||
async function sendData(event) {
|
||||
event.preventDefault();
|
||||
const username = event.target![0].value;
|
||||
const password = event.target![1].value;
|
||||
|
||||
if (!username) {
|
||||
toast("Необходимо указать имя пользователя", {icon: '⚠️'})
|
||||
return;
|
||||
}
|
||||
if (!password) {
|
||||
toast("Необходимо указать пароль", {icon: '⚠️'});
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/v1/user/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
switch (response.status) {
|
||||
case 404:
|
||||
toast("Такой пользователь не существует!", {icon: '❌️'});
|
||||
break;
|
||||
case 401:
|
||||
toast("Неверный пароль!", {icon:'❌️'});
|
||||
break;
|
||||
case 200:
|
||||
document.location.href = "/";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function goToLoginPage () {
|
||||
window.location.href="/register"
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='container'>
|
||||
<h1>
|
||||
Вход
|
||||
</h1>
|
||||
<iframe name="invisible" style={{display: "none"}}></iframe>
|
||||
<form onSubmit={sendData}>
|
||||
<input className='beautiful_input' id='login' name='login' type='text' placeholder='Имя пользователя'></input>
|
||||
<input className='beautiful_input' id='password' name='password' type='password' placeholder='Пароль'></input>
|
||||
<button type="submit">Войти</button>
|
||||
</form>
|
||||
<button style={{marginTop: "25px"}} onClick={goToLoginPage}>Нет аккаунта</button>
|
||||
<Toaster />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Login;
|
||||
93
frontend/src/pages/PostActions.tsx
Normal file
93
frontend/src/pages/PostActions.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import React, { useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import post from '../Post.tsx';
|
||||
import toast, { Toaster } from "react-hot-toast";
|
||||
|
||||
function PostActions() {
|
||||
const [isMedia, setIsMedia] = useState(false);
|
||||
const [oldPost, setOldPost] = useState({ id: 0, type: 0, message: "", authorId: 0, date: new Date(0) });
|
||||
|
||||
const search = useLocation().search
|
||||
const searchParams = new URLSearchParams(search)
|
||||
const toUpdate = searchParams.get("postId")
|
||||
const isUpdating = toUpdate ? true : false;
|
||||
|
||||
const fetchOldData = async () => {
|
||||
if (isUpdating) {
|
||||
const oldPostContent = await fetch(`/api/v1/post/${toUpdate}`).then(response => response.json())
|
||||
if (oldPostContent.type == 1) {
|
||||
setIsMedia(true)
|
||||
}
|
||||
setOldPost(oldPostContent);
|
||||
}
|
||||
}
|
||||
window.onload =
|
||||
fetchOldData;
|
||||
|
||||
const getFormData = () => {
|
||||
const formData = new FormData();
|
||||
const fileUploader = (document.getElementById("fileUploader") as HTMLInputElement);
|
||||
if (!fileUploader.files) {
|
||||
toast("Выберите файл для загрузки")
|
||||
return
|
||||
}
|
||||
formData.append('file', fileUploader.files![0]);
|
||||
return formData
|
||||
}
|
||||
|
||||
|
||||
const postNewPost = async (event) => {
|
||||
event.preventDefault();
|
||||
let headers = {};
|
||||
if (!isMedia) {
|
||||
headers = { "Content-Type": "application/json" }
|
||||
}
|
||||
await fetch(`/api/v1/post/${isUpdating ? `update/${toUpdate}` : "create"}`, {
|
||||
method: isUpdating ? "PUT" : "POST",
|
||||
headers,
|
||||
body: isMedia ? getFormData() : JSON.stringify({
|
||||
message: (document.getElementById("textInput") as HTMLInputElement).value
|
||||
})
|
||||
}).then(() => window.location.href = `..`);
|
||||
}
|
||||
|
||||
const changePostType = (event) => {
|
||||
setIsMedia(event.target.value == "media")
|
||||
}
|
||||
return (
|
||||
<div className="container">
|
||||
<iframe style={{ display: "none" }}></iframe>
|
||||
<form onSubmit={postNewPost}>
|
||||
<div>
|
||||
<input type="radio" id="plaintext" value="plaintext" name="isMedia" onChange={changePostType}></input>
|
||||
<label htmlFor="plaintext">Текст</label>
|
||||
<input type="radio" id="media" value="media" name="isMedia" onChange={changePostType}></input>
|
||||
<label htmlFor="media">Медиа</label>
|
||||
</div>
|
||||
<div>
|
||||
{oldPost.type == 1 ? (
|
||||
post.PostTag(oldPost)
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
{isMedia ? (
|
||||
<input type="file" className="beautiful_input" name="file" id="fileUploader" style={isMedia ? ({ display: "block" }) : ({ display: "none" })}></input>
|
||||
|
||||
) : (
|
||||
<input placeholder="Текст поста" type="text" className="beautiful_input" id="textInput" value={oldPost.message} style={isMedia ? ({ display: "none" }) : ({ display: "block" })}></input>
|
||||
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
|
||||
</div>
|
||||
<button type="submit" >{isUpdating ? "Обновить" : "Загрузить"}</button>
|
||||
</form>
|
||||
<Toaster />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PostActions;
|
||||
65
frontend/src/pages/Register.tsx
Normal file
65
frontend/src/pages/Register.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import toast, { Toaster } from 'react-hot-toast';
|
||||
import React from 'react';
|
||||
import '../css/Register.css';
|
||||
|
||||
function Register() {
|
||||
async function sendData(event) {
|
||||
event.preventDefault();
|
||||
const username = event.target![0].value;
|
||||
const password = event.target![1].value;
|
||||
const passwordConfirm = event.target![2].value;
|
||||
if (!username) {
|
||||
toast("Необходимо указать имя пользователя!", {icon: '⚠️'});
|
||||
return;
|
||||
}
|
||||
if (!password) {
|
||||
toast("Необходимо придумать пароль!", {icon: '⚠️'});
|
||||
return;
|
||||
}
|
||||
if (password != passwordConfirm) {
|
||||
toast("Пароли не совпадают!", { icon: '⚠️' });
|
||||
return;
|
||||
}
|
||||
const response = await fetch('/api/v1/user/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
});
|
||||
switch (response.status) {
|
||||
case 409:
|
||||
toast("Такой пользователь уже существует!", {icon: '❌️'});
|
||||
break;
|
||||
case 200:
|
||||
document.location.href = "/";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function goToRegisterPage() {
|
||||
window.location.href = "/login"
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='container'>
|
||||
<h1>
|
||||
Регистрация
|
||||
</h1>
|
||||
<iframe style={{ display: "none" }}></iframe>
|
||||
<form onSubmit={sendData}>
|
||||
<input className="beautiful_input" id='login' name='login' type='text' placeholder='Имя пользователя'></input>
|
||||
<input className="beautiful_input" id='password' name='password' type='password' placeholder='Пароль'></input>
|
||||
<input className="beautiful_input" id='passwordConfirm' name='passwordConfirm' type='password' placeholder='Повтор пароля'></input>
|
||||
<button type="submit" >Зарегистрироваться</button>
|
||||
</form>
|
||||
<button style={{marginTop: "25px"}} onClick={goToRegisterPage}>Уже есть аккаунт</button>
|
||||
<Toaster />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Register;
|
||||
56
frontend/src/pages/User.tsx
Normal file
56
frontend/src/pages/User.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import Post from '../Post.tsx';
|
||||
import toast, { Toaster } from 'react-hot-toast';
|
||||
|
||||
function User() {
|
||||
const search = useLocation().search
|
||||
const searchParams = new URLSearchParams(search)
|
||||
const userId = searchParams.get("userId")
|
||||
const [username, setUsername] = useState("Loading");
|
||||
const [postsData, setPostsData]: any = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPosts = async () => {
|
||||
await fetch(`/api/v1/user/posts/${userId}`, {
|
||||
method: "GET"
|
||||
}).then(response => response.json())
|
||||
.then(posts => setPostsData(posts));
|
||||
}
|
||||
|
||||
fetchPosts();
|
||||
}, [username]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUsername = async () => {
|
||||
await fetch(`/api/v1/user/by-id/${userId}`, {
|
||||
method: "GET"
|
||||
}).then(async response => {
|
||||
if (response.status == 404) {
|
||||
toast("Такой пользователь не существует!", { icon: '❌️' });
|
||||
window.location.href = ".."
|
||||
return;
|
||||
}
|
||||
return response.json()
|
||||
}).then(user => setUsername(user.username))
|
||||
}
|
||||
fetchUsername();
|
||||
}, [userId]);
|
||||
|
||||
const goBack = () => {
|
||||
window.location.href=".."
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{username}</h1>
|
||||
<button className="backButton" onClick={goBack}>Назад</button>
|
||||
{postsData.map((post) => {
|
||||
return Post.PostTag(new Post.Post(post.id, post.authorId, post.type, post.message, post.date));
|
||||
})}
|
||||
<Toaster />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default User;
|
||||
Reference in New Issue
Block a user