Commit d14b4e6d authored by dimitronic's avatar dimitronic

Initial commit

parents
.vscode
.idea
.fleet
node_modules
.DS_Store
\ No newline at end of file
.vscode
.idea
.fleet
node_modules
.DS_Store
\ No newline at end of file
npm run dev - запуск серверной части приложения
----------------------------------------------
GET /artists - получить список исполнителей.
POST /artists - создать исполнителя
GET /albums - получить все альбомы.
/albums?artist=.... - получить список альбомов конкретного исполнителя.
POST /albums - создать альбом
GET /albums/:id - получить информацию о конкретном альбоме, включая информацию о его исполнителе.
GET /tracks - получить все треки
/tracks?album=.... - получить список треков в конкретном альбоме.
POST /tracks - создать трек.
POST /users - регистрация (создание) нового пользователя.
POST /users/login - логин пользователя.
POST /track_history - принимает токен аутентификации через заголовки запроса. Также принимает один параметр через тело запроса (JSON): track - ID прослушанной композиции.
\ No newline at end of file
const path = require('path');
const rootPath = __dirname;
module.exports = {
rootPath,
port: 8003,
uploadPath: path.join(rootPath, 'public', 'uploads'),
db: {
host: 'mongodb://127.0.0.1',
database: 'chat'
}
};
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
</form>
</body>
</html>
\ No newline at end of file
const cors = require('cors');
const express = require('express');
const app = express();
const nanoid = require('fix-esm').require('nanoid').nanoid;
require('express-ws');
const message = require('./routes/messages')
const expressWs = require('express-ws')
const mongoose = require('mongoose')
const {port, db: dbConfig} = require("./config")
const userRoutes = require('./routes/users');
app.use(cors());
app.use(express.json())
app.use(express.static('public'));
app.use('/api/v1/users', userRoutes);
expressWs(app);
app.use("/api/v1/chat", message)
const run = async () => {
await mongoose.connect(
dbConfig.host + '/' + dbConfig.database,
{useNewUrlParser: true}
);
app.listen(port, () => {
console.log("Server running at http://localhost:" + port);
});
process.on('exit', () => {
mongoose.disconnect();
});
};
run().catch(e => console.error(e));
const User = require("../models/User");
const auth = async (req, res, next) => {
const token = req.get('Authorization');
if (!token) return res
.status(401)
.send({ error: 'No token present' });
const user = await User.findOne({ token });
if (!user) return res
.status(401)
.send('Token is wrong');
req.user = user;
next();
}
module.exports = auth;
\ No newline at end of file
const permit = (...roles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).send({message: 'Unauthenticated'});
}
if (!roles.includes(req.user.role)) {
return res.status(403).send({message: 'Unauthorized'});
}
next();
};
};
module.exports = permit;
\ No newline at end of file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MessageSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Пользователь обязателен']
},
message: {
type: String,
required: [true, 'Сообщение обязательно']
},
datetime: {
type: Date,
default: Date.now
}
});
const Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
\ No newline at end of file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const { nanoid } = require('fix-esm').require('nanoid');
const SALT_WORK_FACTOR = 10;
const UserSchema = new Schema({
username: {
type: String,
required: true,
validate: {
validator: async function (username) {
const user = await User.findOne({username});
return !user || user._id.toString() === this._id.toString();
},
message: "This user is already exists"
}
},
password: {
type: String,
required: true
},
token: {
type: String,
required: false,
validate: {
validator: async function (token) {
if (!token) return true;
const user = await User.findOne({token});
return !user || user._id.toString() === this._id.toString();
},
message: "Token duplicated"
}
},
role: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin']
}
});
UserSchema.pre('save', async function(next) {
if(!this.isModified('password')) return next();
const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
this.password = await bcrypt.hash(this.password, salt);
next();
});
UserSchema.set('toJSON', {
transform: (doc, ret, options) => {
delete ret.password;
return ret;
}
});
UserSchema.methods.checkPassword = function (password) {
return bcrypt.compare(password, this.password)
};
UserSchema.methods.generateToken = function () {
this.token = nanoid();
}
const User = mongoose.model('User', UserSchema);
module.exports = User;
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "homework",
"version": "1.0.0",
"description": "npm run dev - запуск серверной части приложения",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"dev": "nodemon index.js",
"fixture": "node fixtures.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.3.6",
"axios-debug-log": "^1.0.0",
"bcrypt": "^5.1.0",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"express-ws": "^5.0.2",
"fix-esm": "^1.0.1",
"mongodb": "^5.4.0",
"mongoose": "^6.11.1",
"mongoose-id-validator": "^0.6.0",
"multer": "^1.4.5-lts.1",
"nanoid": "^4.0.2",
"prop-types": "^15.8.1"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
!.gitignore
\ No newline at end of file
const express = require('express');
// const app = express();
const nanoid = require('fix-esm').require('nanoid').nanoid;
const expressWs = require('express-ws');
const router = express.Router();
expressWs(router);
const Message = require('../models/Message')
const activeConnections = {};
router.ws('/', (ws, res) => {
const id = nanoid();
console.log('client connected! id=' + id);
activeConnections[id] = ws;
ws.on('close', msg => {
console.log('client disconnected! id=' + id);
delete activeConnections[id];
});
let username = 'anonymous';
ws.on('message',async msg => {
const decodedMsg = JSON.parse(msg);
let data = '';
switch (decodedMsg.type) {
case 'SET_USERNAME':
username = decodedMsg.username;
break;
case 'CREATE_MESSAGE':
console.log(555);
data = JSON.stringify({
type: 'NEW_MESSAGE',
message: {
username,
senderId: id,
text: decodedMsg.text
}
});
console.log(decodedMsg);
const message = new Message({user: '646dfae5b8f50c0d37011198', message: decodedMsg.text, dattetime: Date.now()});
console.log(message);
await message.save();
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(data);
});
break;
case 'PERSONAL_MESSAGE':
const conn = activeConnections[decodedMsg.receiverId];
data = JSON.stringify({
type: 'NEW_MESSAGE',
message: {
username,
senderId: id,
personal: true,
text: decodedMsg.text
}
});
conn.send(data);
ws.send(data);
break;
default:
console.log('Unknown message type:' + decodedMsg.type);
}
});
});
module.exports = router
\ No newline at end of file
const router = require('express').Router();
const User = require('../models/User');
const auth = require("../middleware/auth");
router.post('/', async (req, res) => {
try {
const user = new User({
username: req.body.username,
password: req.body.password
});
console.log(user);
user.generateToken();
await user.save();
res.send(user);
} catch (e) {
res.status(400).send(e);
}
});
router.post('/login', async (req, res) => {
const user = await User.findOne({username: req.body.username});
if (!user) return res
.status(400)
.send({error: 'Username or password incorrect'});
if (!await user.checkPassword(req.body.password.toString())) return res
.status(400)
.send({error: 'Username or password incorrect'});
try {
user.generateToken();
await user.save();
res.send(user);
} catch (e) {
res
.status(400)
.send({error: e.message});
}
});
router.get('/profile', auth, async (req, res) => {
res.send({
message: "Секрет",
username: req.user.username
});
});
router.delete('/logout', auth, async (req, res) => {
req.user.token = null;
req.user.save();
res.send({message: 'Success'});
});
module.exports = router;
# 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*
.vscode
.idea
.fleet
.DS_Store
# 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)
This diff is collapsed.
{
"name": "front",
"version": "0.1.0",
"private": true,
"dependencies": {
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.11.16",
"@mui/material": "^5.12.3",
"@reduxjs/toolkit": "^1.9.5",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.4.0",
"axios-debug-log": "^1.0.0",
"bootstrap": "^5.2.3",
"react": "^18.2.0",
"react-bootstrap": "^2.7.4",
"react-dom": "^18.2.0",
"react-redux": "^8.0.5",
"react-router-dom": "^6.11.1",
"react-scripts": "5.0.1",
"react-uuid": "^2.0.0",
"web-vitals": "^2.1.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"
]
}
}
<!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>
{
"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"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
import {useSelector} from "react-redux";
import Routes from "./Routes";
const App = () => {
const user = useSelector(({usersState}) => usersState.user);
return <Routes user={user} />;
};
export default App;
\ No newline at end of file
import { Route, Routes as RoutesSwitch } from "react-router-dom";
import { LOGIN, REGISTER, MAIN } from "./constants/routes";
import Layout from "./components/Layout/Layout";
import Register from "./containers/Auth/Register/Register";
import Login from "./containers/Auth/Login/Login";
import ProtectedRoute from './components/ProtectedRoute/ProtectedRoute';
import Chat from './containers/Chat/Chat';
const Routes = ({ user }) => {
const chat = <ProtectedRoute
isAllowed={!!user}
redirectPath={!!user ? MAIN : LOGIN}
>
<Chat />
</ProtectedRoute>;
return <RoutesSwitch>
<Route element={<Layout />}>
<Route index element={chat} />
<Route path={REGISTER} element={<Register />} />
<Route path={LOGIN} element={<Login />} />
<Route path={MAIN} element={chat} />
</Route>
</RoutesSwitch>
};
export default Routes;
import axios from "axios";
import {apiUrl} from "../constants/config";
const instance = axios.create({
baseURL: apiUrl + "/api/v1"
});
export default instance;
import {Container, CssBaseline} from "@mui/material";
import AppToolbar from "../UI/AppToolbar/AppToolbar";
import {Outlet} from "react-router-dom";
const Layout = () => (
<>
<CssBaseline/>
<header>
<AppToolbar/>
</header>
<main>
<Container maxWidth="xl">
<Outlet />
</Container>
</main>
</>
);
export default Layout;
import {Navigate, Outlet} from "react-router-dom";
const ProtectedRoute = ({isAllowed, redirectPath, children}) => {
if (!isAllowed) {
return <Navigate to={redirectPath} replace />;
}
return children || <Outlet/>;
};
export default ProtectedRoute;
\ No newline at end of file
import { AppBar, Box, Toolbar, Typography } from '@mui/material';
import { useSelector } from "react-redux";
import UserMenu from './Menus/UserMenu/UserMenu';
import AnonymousMenu from './Menus/AnonymousMenu/AnonymousMenu';
const AppToolbar = () => {
const user = useSelector(({ usersState }) => usersState.user);
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
Chat
</Typography>
{
user
? <UserMenu user={user} />
: <AnonymousMenu />
}
</Toolbar>
</AppBar>
</Box>
);
};
export default AppToolbar;
import {NavLink} from "react-router-dom";
import {LOGIN, REGISTER} from "../../../../../constants/routes";
import {Button} from '@mui/material';
const AnonymousMenu = () => {
return <>
<Button color="inherit" component={NavLink} to={REGISTER}>Sign up</Button>
<Button color="inherit" component={NavLink} to={LOGIN}>Sign In</Button>
</>;
};
export default AnonymousMenu;
import { Button} from '@mui/material';
import { useDispatch } from "react-redux";
import { useNavigate, NavLink} from "react-router-dom";
import { logoutUser } from "../../../../../store/actions/usersActions";
import { MAIN, } from "../../../../../constants/routes";
const UserMenu = ({ user }) => {
const navigate = useNavigate();
const dispatch = useDispatch();
return <>
Hello, {user.username}
<Button color="inherit" component={NavLink} to={MAIN}>Home</Button>
<Button color="inherit" onClick={() => dispatch(logoutUser({ callback: () => navigate(MAIN) }))}>
Logout
</Button>
</>;
};
export default UserMenu;
import {useState, useRef} from 'react';
import {Button, Grid, TextField} from '@mui/material';
const FileInput = ({onChange, name, label}) => {
const [filename, setFilename] = useState('');
const inputRef = useRef();
const activateInput = () => {
inputRef.current.click();
};
const onChangeFile = (e) => {
const file = e.currentTarget.files[0];
setFilename(file ? file.name : '');
onChange(e);
};
return (
<>
<input
type="file"
name={name}
ref={inputRef}
onChange={onChangeFile}
accept="image/*"
style={{display: 'none'}}
/>
<Grid
container
direction="row"
spacing={2}
alignItems="center"
>
<Grid item xs>
<TextField
label={label}
disabled
variant="standard"
fullWidth
value={filename}
onClick={activateInput}
/>
</Grid>
<Grid item>
<Button
variant="contained"
onClick={activateInput}
>
Browse file
</Button>
</Grid>
</Grid>
</>
);
};
export default FileInput;
import {Grid, TextField} from "@mui/material";
import PropTypes from "prop-types";
const FormElement = ({
name,
label,
value,
onChange,
required,
error,
type,
select,
multiline,
rows,
options
}) => {
let inputChildren = null;
return <Grid item xs={12}>
<TextField
fullWidth
required={required}
id={name}
name={name}
label={label}
error={!!error}
helperText={error}
value={value}
onChange={onChange}
autoComplete={name}
type={type}
multiline={multiline}
rows={rows}
select={select}
>
{inputChildren}
</TextField>
</Grid>;
};
FormElement.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
type: PropTypes.string,
error: PropTypes.string,
required: PropTypes.bool,
onChange: PropTypes.func.isRequired,
select: PropTypes.bool,
multiline: PropTypes.bool,
rows: PropTypes.number,
options: PropTypes.arrayOf(PropTypes.object)
};
export default FormElement;
export const apiUrl = "http://localhost:8003";
export const uploadUrl = apiUrl + '/uploads';
export const MAIN = '/';
export const ARTIST_VIEW = '/artists/:id';
export const ALBUM_VIEW = '/album/:id';
export const REGISTER = '/register';
export const LOGIN = '/login';
export const TRACK_HISTORY = '/track_history';
export const ARTIST_ADD = '/artists/add';
export const ALBUM_ADD = '/albums/add';
export const TRACK_ADD = '/tracks/add';
import {useEffect, useState} from "react";
import {Avatar, Button, Container, Grid, Typography, Link, Box, CssBaseline, Alert} from "@mui/material";
import { createTheme, ThemeProvider } from '@mui/material/styles';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import {Link as RouterLink, useLocation, useNavigate} from 'react-router-dom';
import {REGISTER} from "../../../constants/routes";
import {useDispatch, useSelector} from "react-redux";
import {loginUser} from "../../../store/actions/usersActions";
import FormElement from "../../../components/UI/Form/FormElement/FormElement";
import {setLoginError} from "../../../store/services/usersSlice";
const theme = createTheme();
const Login = () => {
const error = useSelector(({usersState}) => usersState.loginError);
const dispatch = useDispatch();
const navigate = useNavigate();
const [state, setState] = useState({
username: "",
password: ""
});
const location = useLocation();
useEffect(() => {
dispatch(setLoginError(null));
}, [location]);
const inputChangeHandler = (e) => {
const {name, value} = e.currentTarget;
setState(prevState => {
return {...prevState, [name]: value};
});
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(loginUser({
data: {...state},
callback: () => navigate('/')
}));
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign In
</Typography>
{error && <Alert severity="error">{error.error}</Alert>}
<Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 3 }}>
<Grid container spacing={2}>
<FormElement
required={true}
label="Username"
name="username"
onChange={inputChangeHandler}
value={state.username}
/>
<FormElement
required={true}
name="password"
label="Password"
type="password"
onChange={inputChangeHandler}
value={state.password}
/>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign In
</Button>
<Grid container justifyContent="flex-end">
<Grid item>
<Link href="#" variant="body2" component={RouterLink} to={REGISTER}>
Sign Up
</Link>
</Grid>
</Grid>
</Box>
</Box>
</Container>
</ThemeProvider>
);
};
export default Login;
import {useEffect, useState} from "react";
import {Avatar, Button, Container, Grid, Typography, Link, Box, CssBaseline} from "@mui/material";
import { createTheme, ThemeProvider } from '@mui/material/styles';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import {Link as RouterLink, useLocation, useNavigate} from 'react-router-dom';
import {LOGIN} from "../../../constants/routes";
import {useDispatch, useSelector} from "react-redux";
import {registerUser} from "../../../store/actions/usersActions";
import FormElement from "../../../components/UI/Form/FormElement/FormElement";
import {setRegisterError} from "../../../store/services/usersSlice";
const theme = createTheme();
const Register = () => {
const error = useSelector(({usersState}) => usersState.registerError);
const dispatch = useDispatch();
const navigate = useNavigate();
const [state, setState] = useState({
username: "",
password: ""
});
const location = useLocation();
useEffect(() => {
dispatch(setRegisterError(null));
}, [location]);
const inputChangeHandler = (e) => {
const {name, value} = e.currentTarget;
setState(prevState => {
return {...prevState, [name]: value};
});
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(registerUser({
data: {...state},
callback: () => navigate('/')
}));
};
const getFieldError = (field) => {
return error?.errors[field]?.message;
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 3 }}>
<Grid container spacing={2}>
<FormElement
required={true}
label="Username"
name="username"
onChange={inputChangeHandler}
value={state.username}
error={getFieldError('username')}
/>
<FormElement
required={true}
name="password"
label="Password"
type="password"
onChange={inputChangeHandler}
value={state.password}
error={getFieldError('password')}
/>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign Up
</Button>
<Grid container justifyContent="flex-end">
<Grid item>
<Link href="#" variant="body2" component={RouterLink} to={LOGIN}>
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</Box>
</Box>
</Container>
</ThemeProvider>
);
};
export default Register;
.container {
margin: 0 auto;
display: flex;
flex-direction: row;
justify-content: space-around;
}
.onlineUsers, .chat {
display: flex;
flex-direction: column;
text-align: center;
}
.onlineUsers_item, .myMessages {
border: 1px solid black;
width: 100%;
height: 100%;
min-height: 300px;
}
.onlineUsers {
width: 30%;
min-height: 300px;
}
.chat {
width: 68%;
}
.myMessages {
padding: 20px;
display: flex;
align-items: flex-end;
justify-content: center;
text-align: center;
}
\ No newline at end of file
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import './Chat.css';
const Chat = () => {
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState('');
const [username, setUsername] = useState('');
const [receiver, setReceiver] = useState(null);
const [isLoggedIn, setLoggedIn] = useState(false);
const User = useSelector(({ usersState }) => usersState.user);
// console.log(User)
const ws = useRef(null);
useEffect(() => {
ws.current = new WebSocket('ws://localhost:8003/api/v1/chat');
ws.current.onmessage = ({ data }) => {
const decodedMsg = JSON.parse(data);
if (decodedMsg.type === 'NEW_MESSAGE') {
setMessages(messages => [...messages, decodedMsg.message]);
}
};
ws.current.onclose = e => {
console.log('connection closed!');
};
return () => ws.current.close();
}, []);
const changeMessage = ({ currentTarget }) => {
setMessage(currentTarget.value);
};
const changeUsername = ({ currentTarget }) => {
setUsername(currentTarget.value);
};
const sendData = data => {
ws.current.send(JSON.stringify(data));
};
const sendUsername = e => {
e.preventDefault();
sendData({ type: 'SET_USERNAME', username });
setLoggedIn(true);
};
const sendMessage = e => {
e.preventDefault();
if (receiver) {
sendData({
type: 'PERSONAL_MESSAGE',
text: message,
receiverId: receiver.id
});
setReceiver(null);
} else {
sendData({ type: 'CREATE_MESSAGE', text: message });
}
setMessage('');
};
let chat = (
<div>
{
messages.map((message, idx) => (
<div key={idx}>
{
message.personal && <span>Answer from </span>
}
<b onClick={() => setReceiver({
id: message.senderId,
username: message.username
})}>
{message.username}:
</b>
{message.text}
</div>
))
}
<form onSubmit={sendMessage}>
{receiver && <b>Answer for {receiver.username}</b>}
<label>Enter message</label>
<input
onChange={changeMessage}
value={message}
/>
<button>Send</button>
</form>
</div>
);
if (!isLoggedIn) {
chat = (
<form onSubmit={sendUsername}>
<label>Enter username</label>
<input
onChange={changeUsername}
value={username}
/>
<button>Send</button>
</form>
);
}
return <div className="container">
<div className="onlineUsers">
<h2> Online users</h2>
<div className="onlineUsers_item">{message.username}</div>
</div>
<div className="chat">
<h2> Chat room</h2>
<div className="myMessages">{chat}</div>
</div>
</div>
};
export default Chat;
\ No newline at end of file
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import store from './store/configureStore';
import setup from "./services/setupInterceptors";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
setup(store);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
\ No newline at end of file
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
import axiosApi from "../api/axiosApi";
const setup = ({getState}) => {
axiosApi.interceptors.request.use(
config => {
const user = getState().usersState.user;
if (user) {
config.headers.Authorization = user.token;
}
return config;
},
error => Promise.reject(error)
);
};
export default setup;
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import { createAsyncThunk } from "@reduxjs/toolkit";
import axiosApi from "../../api/axiosApi";
import { setLoginError, setRegisterError, setUser, setLogoutError } from "../services/usersSlice";
export const registerUser = createAsyncThunk(
'users/register',
async ({ data, callback }, { dispatch }) => await axiosApi
.post('/users', data)
.then(res => callback())
.catch(e => {
if (e?.response?.data) dispatch(setRegisterError(e.response.data));
else dispatch(setRegisterError(e));
throw e;
})
);
export const loginUser = createAsyncThunk(
'users/login',
async ({ data, callback }, { dispatch, getState }) => await axiosApi
.post('/users/login', data)
.then(res => {
dispatch(setUser(res.data));
callback();
})
.catch(e => {
if (e?.response?.data) dispatch(setLoginError(e.response.data));
else dispatch(setLoginError(e));
throw e;
})
);
export const logoutUser = createAsyncThunk(
'users/logout',
async (payload, {dispatch, getState}) => await axiosApi
.delete(
'/users/logout',
{headers: {Authorization: getState().usersState.user.token}}
)
.then(res => {
dispatch(setUser(null));
payload.callback();
})
.catch(e => {
if (e?.response?.data) dispatch(setLogoutError(e.response.data));
else dispatch(setLogoutError(e));
throw e;
})
);
import {configureStore} from "@reduxjs/toolkit";
import usersReducer from "./services/usersSlice";
const localStorageMiddleware = ({getState}) => next => action => {
const result = next(action);
if (getState().usersState.user) {
localStorage.setItem('user', JSON.stringify(getState().usersState.user));
} else {
localStorage.removeItem('user');
}
return result;
};
const reHydrateStore = () => {
const userLocalStorage = localStorage.getItem('user');
if (userLocalStorage !== null || userLocalStorage !== 'null' || userLocalStorage !== '') {
return {
usersState: {
user: JSON.parse(localStorage.getItem('user'))
}
};
}
return undefined;
};
const store = configureStore({
reducer: {
usersState: usersReducer
},
preloadedState: reHydrateStore(),
middleware: getDefaultMiddleware => getDefaultMiddleware().concat(localStorageMiddleware)
});
export default store;
import { createSlice } from "@reduxjs/toolkit";
import { loginUser, logoutUser, registerUser } from "../actions/usersActions";
const initialState = {
loginError: null,
logoutError: null,
registerError: null,
loading: false,
user: null
};
const usersSlice = createSlice({
name: 'users',
initialState,
reducers: {
setLoginError: (state, action) => {
state.loginError = action.payload;
},
setRegisterError: (state, action) => {
state.registerError = action.payload;
},
setLogoutError: (state, action) => {
state.logoutError = action.payload;
},
setUser: (state, action) => {
state.user = action.payload;
}
},
extraReducers: builder => {
builder
.addCase(
registerUser.pending,
state => {
state.registerError = null;
state.loading = true;
state.user = null;
}
)
.addCase(
registerUser.rejected,
state => {
state.loading = false;
}
)
.addCase(
registerUser.fulfilled,
state => {
state.loading = false;
}
);
builder
.addCase(
loginUser.pending,
state => {
state.loginError = null;
state.loading = true;
state.user = null;
}
)
.addCase(
loginUser.rejected,
state => {
state.loading = false;
}
)
.addCase(
loginUser.fulfilled,
state => {
state.loading = false;
}
);
builder
.addCase(
logoutUser.pending,
state => {
state.logoutError = null;
state.loading = true;
}
)
.addCase(
logoutUser.rejected,
state => {
state.loading = false;
}
)
.addCase(
logoutUser.fulfilled,
state => {
state.loading = false;
}
);
}
});
export const { setLoginError, setRegisterError, setUser, setLogoutError } = usersSlice.actions;
export default usersSlice.reducer;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment