Skip to content

Commit b23e98c

Browse files
committed
server comments
1 parent 093a8d6 commit b23e98c

File tree

7 files changed

+84
-27
lines changed

7 files changed

+84
-27
lines changed

app.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ const os = require('os')
55
const mongoose = require('mongoose')
66
require('dotenv').config()
77

8+
/**
9+
* подключение переменных среды
10+
*/
811
const devMode = process.env.NODE_ENV === "dev"
912
const PORT = process.env.PORT || 5000
1013
const mongoUri = process.env.mongoUri
@@ -14,11 +17,17 @@ const app = express()
1417

1518
app.use(express.json({ extended: true }))
1619

20+
/**
21+
* подключение роутов
22+
*/
1723
app.use('/api/auth', require('./routes/auth.routes'))
1824
app.use('/api/notes', require('./routes/notes.routes'))
1925

2026
if (httpsRedirect) app.use(httpToHttps)
2127

28+
/**
29+
* подключение статической библиотеки клиента
30+
*/
2231
if (!devMode) {
2332
app.use('/', express.static(path.join(__dirname, 'client', 'build')))
2433
app.get('*', (req, res) => {
@@ -30,6 +39,9 @@ if (!devMode) {
3039
})
3140
}
3241

42+
/**
43+
* запуск сервера
44+
*/
3345
async function start() {
3446
try {
3547
connectMongo(mongoUri)
@@ -42,6 +54,10 @@ async function start() {
4254

4355
start()
4456

57+
/**
58+
* подключение к MongoDb
59+
* @param {*} mongoUri
60+
*/
4561
async function connectMongo(mongoUri) {
4662
if (mongoUri) {
4763
await mongoose.connect(mongoUri, {
@@ -54,6 +70,9 @@ async function connectMongo(mongoUri) {
5470
}
5571
}
5672

73+
/**
74+
* Вывод информации о сервере
75+
*/
5776
function logServerStart() {
5877
dns.lookup(os.hostname(), (err, address) => {
5978
const [logName, sBef, sAft] = devMode ? ['Express server', ' ', ':'] : ['React Notes App', '-', '']
@@ -64,6 +83,9 @@ function logServerStart() {
6483
})
6584
}
6685

86+
/**
87+
* перенаправление с http на https для PWA
88+
*/
6789
function httpToHttps(req, res, next) {
6890
if (req.header('x-forwarded-proto') !== 'https') {
6991
res.redirect(`https://${req.header('host')}${req.url}`)

middleware/auth.middleware.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,29 @@
11
const jwt = require('jsonwebtoken')
22
require('dotenv').config()
33

4+
/**
5+
* Функция-Middleware для проверки авторизации пользователя
6+
* @param {*} req
7+
* @param {*} res
8+
* @param {*} next
9+
* @returns
10+
*/
411
module.exports = (req, res, next) => {
12+
//проверка работы сервера
513
if (req.method === 'OPTIONS') {
614
return next()
715
}
816

917
try {
10-
18+
/**получение токена */
1119
const token = req.headers.authorization.split(' ')[1] // "Bearer TOKEN"
1220

21+
/**проверка отсутствия токена */
1322
if (!token) {
1423
return res.status(401).json({ message: 'Нет авторизации' })
1524
}
1625

26+
/**верификация токена */
1727
const decoded = jwt.verify(token, process.env.jwtSecret)
1828
req.user = decoded
1929
next()

models/Note.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
const { Schema, model, Types } = require('mongoose')
22

3+
/**
4+
* Схема заметки для базы данных
5+
*/
36
const schema = new Schema({
4-
id: { type: String, required: true, unique: true /*, default: String(Date.now) + String(Math.random)*/ },
7+
id: { type: String, required: true, unique: true },
58
name: { type: String },
69
text: { type: String },
710
color: { type: String },
811
image: { type: String },
9-
//date: { type: Date, default: Date.now },
1012
owner: { type: Types.ObjectId, ref: 'User', required: true }
1113
})
1214

models/User.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
const {Schema, model, Types} = require('mongoose')
22

3+
/**
4+
* Схема данных пользователя
5+
*/
36
const schema = new Schema({
47
email: {type: String, required: true, unique: true},
58
password: {type: String, required: true},

routes/auth.routes.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,22 @@ const { check, validationResult } = require('express-validator')
66
const User = require('../models/User')
77
const router = Router()
88

9-
// /api/auth/register
9+
/**
10+
* Регистрация
11+
* /api/auth/register
12+
*/
1013
router.post(
1114
'/register',
1215
[
16+
/**валидация */
1317
check('email', 'Некорректный email').isEmail(),
1418
check('password', 'Минимальная длина пароля 6 символов')
1519
.isLength({ min: 6 })
1620
],
1721
async (req, res) => {
1822
try {
23+
/**проверка данных */
1924
const errors = validationResult(req)
20-
2125
if (!errors.isEmpty()) {
2226
return res.status(400).json({
2327
errors: errors.array(),
@@ -27,15 +31,15 @@ router.post(
2731

2832
const { email, password } = req.body
2933

34+
/**Проверка существования пользователя */
3035
const candidate = await User.findOne({ email })
31-
3236
if (candidate) {
3337
return res.status(400).json({ message: 'Такой пользователь уже существует' })
3438
}
3539

40+
/**Хеширование пароля и сохранение пользователя */
3641
const hashedPassword = await bcrypt.hash(password, 12)
3742
const user = new User({ email, password: hashedPassword })
38-
3943
await user.save()
4044

4145
res.status(201).json({ message: 'Пользователь создан' })
@@ -45,17 +49,21 @@ router.post(
4549
}
4650
})
4751

48-
// /api/auth/login
52+
/**
53+
* Вход
54+
* /api/auth/login
55+
*/
4956
router.post(
5057
'/login',
5158
[
59+
/**валидация */
5260
check('email', 'Введите корректный email').normalizeEmail().isEmail(),
5361
check('password', 'Введите пароль').exists()
5462
],
5563
async (req, res) => {
5664
try {
65+
/**проверка данных */
5766
const errors = validationResult(req)
58-
5967
if (!errors.isEmpty()) {
6068
return res.status(400).json({
6169
errors: errors.array(),
@@ -65,18 +73,19 @@ router.post(
6573

6674
const { email, password } = req.body
6775

76+
/**Поиск пользователя в бд */
6877
const user = await User.findOne({ email })
69-
7078
if (!user) {
7179
return res.status(400).json({ message: 'Пользователь не найден' })
7280
}
7381

82+
/**Проверка пароля */
7483
const isMatch = await bcrypt.compare(password, user.password)
75-
7684
if (!isMatch) {
7785
return res.status(400).json({ message: 'Неверный пароль, попробуйте снова' })
7886
}
7987

88+
/**Создание токена */
8089
const token = jwt.sign(
8190
{ userId: user.id },
8291
process.env.jwtSecret,

routes/notes.routes.js

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,13 @@ const router = Router()
66

77
const { checkCard } = require('../validation/CardCheck')
88

9-
9+
/**
10+
* Добавление и редактирование заметки
11+
* /api/notes/set
12+
*/
1013
router.post('/set', auth, async (req, res) => {
1114
try {
15+
/**получение данных о заметке и запись в бд */
1216
const card = tryParce(req.body.card)
1317
if (checkCard(card)) {
1418
postNote(card)
@@ -20,18 +24,20 @@ router.post('/set', auth, async (req, res) => {
2024
res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' })
2125
}
2226

27+
/**Добавление или редактирование заметки в бд */
2328
async function postNote(noteToSave) {
2429

2530
noteToSave.owner = req.user.userId
2631

32+
/**проверка существования заметки */
2733
const existing = await Note.findOne({ id: noteToSave.id })
2834

2935
if (existing) {
30-
//console.log("EXITING");
36+
/**Выполнится если такая заметка уже есть */
3137
existing.overwrite(noteToSave)
3238
existing.save()
3339
} else {
34-
//console.log("NON EXITING")
40+
/**Выполнится если нет такой заметки */
3541
const note = new Note(noteToSave)
3642
await note.save()
3743
}
@@ -40,10 +46,13 @@ router.post('/set', auth, async (req, res) => {
4046
})
4147

4248

43-
49+
/**
50+
* Удаление заметки
51+
* /api/notes/delete
52+
*/
4453
router.post('/delete', auth, async (req, res) => {
4554
try {
46-
55+
/**получение данных о заметке и удаление */
4756
const card = tryParce(req.body.card)
4857
if (checkCard(card)) {
4958
deleteNote(card)
@@ -55,32 +64,29 @@ router.post('/delete', auth, async (req, res) => {
5564
res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' })
5665
}
5766

67+
/**Удаление заметки в бд */
5868
async function deleteNote(noteToSave) {
5969
noteToSave.owner = req.user.userId
6070

6171
const existing = await Note.findOne({ id: noteToSave.id })
6272

6373
if (existing) {
64-
//console.log("EXITING");
65-
6674
existing.remove()
67-
6875
} else res.status(500).json({ message: 'уже удален' })
6976
}
7077
})
7178

72-
73-
79+
/**
80+
* Получение массива заметок
81+
* /api/notes/
82+
*/
7483
router.get('/', auth, async (req, res) => {
7584
try {
76-
//console.log(req.user.userId);
85+
/**Нахождение пользовательских заметок в бд */
7786
const notes = await Note.find({ owner: req.user.userId })
78-
//console.log(notes);
79-
res.json(notes)
87+
res.status(200).json(notes)
8088
} catch (e) {
81-
//console.log("\n\n\n GET");
82-
//console.log(e);
83-
res.status(500).json({ message: '[GET] Что-то пошло не так, попробуйте снова' })
89+
res.status(500).json({ message: 'Что-то пошло не так, попробуйте снова' })
8490
}
8591
})
8692

validation/CardCheck.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
/**
2+
* Проверка рбьекта заметки
3+
* @param {*} card
4+
* @returns
5+
*/
16
function checkCard(card) {
27
return (
38
typeof card.id === "string" &&

0 commit comments

Comments
 (0)