Compare commits

...

12 Commits

Author SHA1 Message Date
312cc229d8 Изменены запросы и добавлены новые
Some checks failed
platform/multy-stub/pipeline/head There was a failure building this commit
2025-02-08 02:23:22 +03:00
11b1d670d0 Merge pull request 'small fixes in kfu-m-24-1/eng-it-lean' (#88) from kfu-m-24-1/eng-it-lean into master
Reviewed-on: #88
2025-02-07 12:26:56 +03:00
Ruslan Zagitov
522ea36bb9 fix: delete broken dicitonary
Some checks failed
platform/multy-stub/pipeline/head There was a failure building this commit
2025-02-07 00:32:53 +03:00
Ruslan Zagitov
8be391c8e1 fix: /units 2025-02-07 00:30:46 +03:00
Ruslan Zagitov
ea80304c21 fix: /users 2025-02-07 00:08:03 +03:00
aa
771f75ef08 Merge pull request 'add new game, add link' (#87) from gamehub into master
Reviewed-on: #87
2025-02-05 22:26:15 +03:00
aaeii
edf9b2c82b add new game, add link 2025-02-05 22:24:05 +03:00
Ruslan Zagitov
8c3bf8a8ed fix 2025-02-05 19:34:45 +03:00
a88d3657bf Merge pull request 'kfu-m-24-1/eng-it-lean quick fix' (#86) from kfu-m-24-1/eng-it-lean into master
Reviewed-on: #86
2025-02-05 19:33:51 +03:00
Ruslan Zagitov
1656ce8690 Merge branch 'master' into kfu-m-24-1/eng-it-lean 2025-02-05 19:25:39 +03:00
Ruslan Zagitov
7cdbec53ee fix 2025-02-05 18:55:22 +03:00
Ruslan Zagitov
33845b743d feat: add /users endpoint; update /units 2025-02-05 13:53:11 +03:00
20 changed files with 136 additions and 150 deletions

View File

@@ -7,33 +7,64 @@ router.get("/users", (request, response) => {
router.post("/auth", (request, response) => {
const { phoneNumber, password } = request.body;
console.log(phoneNumber, password);
if (phoneNumber === "89999999999") {
response.send(require("./json/auth/dogsitter.success.json"));
} else if (phoneNumber === "89555555555") {
response.status(400).send(require("./json/auth/error.json"));
if (phoneNumber === "89999999999" || phoneNumber === "89559999999") {
response.send(require("../json/auth/success.json"));
} else {
response.send(require("./json/auth/owner.success.json"));
response.status(401).send(require("../json/auth/error.json"));
}
});
router.post("/auth/2fa", (request, response) => {
const { code } = request.body;
if (code === "0000") {
response.send(require("./json/2fa/success.json"));
const { phoneNumber, code } = request.body;
if (code === "0000" && phoneNumber === "89999999999") {
response.send(require("../json/2fa/dogsitter.success.json"));
} else if (code === "0000" && phoneNumber === "89559999999") {
response.send(require("../json/2fa/owner.success.json"));
} else {
response.status(400).send(require("./json/2fa/error.json"));
response.status(401).send(require("../json/2fa/error.json"));
}
});
router.post("/register", (request, response) => {
const { firstName, secondName, phoneNumber, password, role } = request.body;
console.log(phoneNumber, password, role);
if (phoneNumber === "89283244141" || phoneNumber === "89872855893") {
response.status(400).send(require("./json/register/error.json"));
if (phoneNumber === "89999999999" || phoneNumber === "89559999999") {
response.status(401).send(require("../json/register/error.json"));
} else if (role === "dogsitter") {
response.send(require("./json/register/dogsitter.success.json"));
response.send(require("../json/register/dogsitter.success.json"));
} else {
response.send(require("./json/register/owner.success.json"));
response.send(require("../json/register/owner.success.json"));
}
});
router.get("/auth/session", (request, response) => {
const authHeader = request.headers.authorization;
if (!authHeader) {
return response.status(401).json({ error: "Authorization header missing" });
}
// Берём сам токен из заголовка
const token = authHeader.split(" ")[1];
if (!token) {
return response.status(401).json({ error: "Bearer token missing" });
}
const jwt = require("jsonwebtoken");
const secretKey = "secret";
try {
const decoded = jwt.verify(token, secretKey);
if (decoded.role === "dogsitter") {
response.send(require("../json/role/dogsitter.success.json"));
} else {
response.send(require("../json/role/owner.success.json"));
}
} catch (e) {
console.log("token e:", e);
return response.status(403).json({ error: "Invalid token" });
}
});

View File

@@ -0,0 +1,3 @@
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwicm9sZSI6ImRvZ3NpdHRlciIsImlhdCI6MTUxNjIzOTAyMn0.7q66wTNyLZp3TGFYF_JdU-yhlWViJulTxP_PCQzO4OI"
}

View File

@@ -1,4 +1,5 @@
{
"status": "error",
"message": "Invalid code."
"message": "Invalid code",
"statusCode": 401
}

View File

@@ -0,0 +1,3 @@
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mywicm9sZSI6Im93bmVyIiwiaWF0IjoxNTE2MjM5MDIyfQ.sI9839YXveTpEWhdpr5QbCYllt6hHYO7NsrQDcrXZIQ"
}

View File

@@ -1,4 +0,0 @@
{
"status": "success",
"message": "Two-factor authentication passed."
}

View File

@@ -1,12 +0,0 @@
{
"data": {
"id": 1,
"phoneNumber": 89283244141,
"firstName": "Вася",
"secondName": "Пупкин",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
"price": 1500,
"aboutMe": "Я люблю собак"
}
}

View File

@@ -1,3 +1,5 @@
{
"error": "Пользователь не найден"
}
"message": "Неверный логин или пароль",
"error": "Unauthorized",
"statusCode": 401
}

View File

@@ -1,9 +0,0 @@
{
"data": {
"id": 3,
"phoneNumber": 89872855893,
"firstName": "Гадий",
"secondName": "Петрович",
"role": "owner"
}
}

View File

@@ -0,0 +1,5 @@
{
"status": "success",
"message": "Первый фактор аутентификации пройден",
"statusCode": 200
}

View File

@@ -1,12 +1,3 @@
{
"data": {
"id": 5,
"phoneNumber": 89555555555,
"firstName": "Масяня",
"secondName": "Карлова",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
"price": 100,
"aboutMe": "Все на свете - собаки"
}
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NSwicm9sZSI6ImRvZ3NpdHRlciIsImlhdCI6MTUxNjIzOTAyMn0.T9V3-f3rD1deA5a2J-tYNw0cACEpzKHbhMPkc7gh8c0"
}

View File

@@ -1,3 +1,5 @@
{
"error": "Пользователь с таким номером телефона уже существует"
"message": "Такой пользователь уже был зарегистрирован",
"error": "Unauthorized",
"statusCode": 401
}

View File

@@ -1,9 +1,3 @@
{
"data": {
"id": 6,
"phoneNumber": 89888888888,
"firstName": "Генадий",
"secondName": "Паровозов",
"role": "owner"
}
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Niwicm9sZSI6Im93bmVyIiwiaWF0IjoxNTE2MjM5MDIyfQ.qgOhk9tNcaMRbarRWISTgvGx5Eq_X8fcA5lhdVs2tQI"
}

View File

@@ -0,0 +1,4 @@
{
"id": 1,
"role": "dogsitter"
}

View File

@@ -0,0 +1,5 @@
{
"message": "Неверный jwt token",
"error": "Forbidden",
"statusCode": 403
}

View File

@@ -0,0 +1,4 @@
{
"id": 3,
"role": "owner"
}

View File

@@ -12,6 +12,10 @@ router.get("/categories", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
router.get("/favourites", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
router.get("/shopping-cart", (request, response) => {
response.send(require("./json/shopping-cart/success.json"));
});

View File

@@ -3,41 +3,43 @@
"data": [
{
"id": 1,
"title": "Elden Ring",
"image": "game17",
"price": 3295,
"old_price": 3599,
"imgPath": "img_top_17",
"description": "Крупномасштабная RPG, действие которой происходит в обширном открытом мире c богатой мифологией и множеством опасных врагов.",
"category": "RPG"
},
{
"id": 2,
"title": "The Witcher 3: Wild Hunt",
"image": "game1",
"price": 990,
"old_price": 1200,
"os": "windows",
"imgPath": "img_top_1",
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
"category": "RPG"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 2,
"id": 17,
"title": "Red Dead Redemption 2",
"image": "game2",
"price": 980,
"old_price": 3800,
"os": "windows",
"imgPath": "img_top_2",
"description": "Приключенческая игра с открытым миром на Диком Западе, рассказывающая историю Артура Моргана.",
"category": "Adventures"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 3,
"title": "Forza Horizon 5",
"image": "game3",
"price": 1900,
"os": "windows",
"imgPath": "img_top_3",
"description": "Гоночная игра с огромным открытым миром, действие которой происходит в Мексике.",
"category": "Race"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 4,
@@ -45,72 +47,66 @@
"image": "game4",
"price": 1200,
"old_price": 2500,
"os": "windows",
"imgPath": "img_top_4",
"description": "Экшен-шутер с элементами RPG, разворачивающийся в альтернативной Советской России.",
"category": "Shooters"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 5,
"title": "Counter-Strike 2",
"image": "game5",
"price": 479,
"os": "windows",
"imgPath": "img_top_5",
"description": "Популярный онлайн-шутер с соревновательным геймплеем и тактическими элементами.",
"category": "Shooters"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 6,
"title": "Grand Theft Auto V",
"image": "game6",
"price": 700,
"os": "windows",
"imgPath": "img_top_6",
"description": "Игра с открытым миром, где можно погрузиться в криминальный мир Лос-Сантоса.",
"category": "Adventures"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 7,
"title": "Assassins Creed IV: Black Flag",
"image": "game7",
"price": 1100,
"os": "windows",
"imgPath": "img_top_7",
"description": "Приключенческая игра о пиратах и морских сражениях в эпоху золотого века пиратства.",
"category": "Adventures"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 8,
"title": "Spider-Man",
"image": "game8",
"price": 3800,
"os": "windows",
"imgPath": "img_top_8",
"description": "Игра о супергерое Человеке-пауке с захватывающими битвами и паркуром по Нью-Йорку.",
"category": "Action"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 9,
"title": "Assassins Creed Mirage",
"image": "game9",
"price": 1600,
"os": "windows",
"imgPath": "img_top_9",
"description": "Приключенческая игра с упором на скрытность, вдохновленная классическими частями серии.",
"category": "Action"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 10,
@@ -118,79 +114,72 @@
"image": "game10",
"price": 800,
"old_price": 2200,
"os": "windows",
"imgPath": "img_top_10",
"description": "RPG с открытым миром о викингах, включающая битвы, исследования и строительство поселений.",
"category": "RPG"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 11,
"title": "ARK: Survival Evolved",
"image": "game11",
"price": 790,
"os": "windows",
"imgPath": "img_top_11",
"description": "Выживание в открытом мире с динозаврами, строительством и многопользовательскими элементами.",
"category": "Simulators"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 12,
"title": "FIFA 23",
"image": "game12",
"price": 3900,
"os": "windows",
"imgPath": "img_top_12",
"description": "Популярный футбольный симулятор с улучшенной графикой и реалистичным геймплеем.",
"category": "Sports"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 13,
"title": "Dirt 5",
"image": "game13",
"price": 2300,
"os": "windows",
"imgPath": "img_top_13",
"description": "Аркадная гоночная игра с фокусом на ралли и внедорожных соревнованиях.",
"category": "Race"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 14,
"title": "Cyberpunk 2077",
"image": "game14",
"price": 3400,
"os": "windows",
"imgPath": "img_top_14",
"description": "RPG в киберпанк-сеттинге с нелинейным сюжетом и детализированным открытым миром.",
"category": "RPG"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 15,
"title": "Age of Empires IV",
"image": "game15",
"price": 3200,
"os": "windows",
"imgPath": "img_top_15",
"description": "Классическая стратегия в реальном времени с историческими кампаниями.",
"category": "Strategies"
,"fav1": "star1",
"fav2": "star2"
},
{
"id": 16,
"title": "Civilization VI",
"image": "game16",
"price": 4200,
"os": "windows",
"imgPath": "img_top_16",
"description": "Глобальная пошаговая стратегия, в которой игроки строят и развивают цивилизации.",
"category": "Strategies"

View File

@@ -1,25 +1,24 @@
[
{ "id": 1, "description": "1000 часто используемых", "imageFilename": "kart1.jpg", "words": [0, 1] },
{
"id": 2,
"id": 1,
"description": "10 слов в Data Science",
"imageFilename": "kart1.jpg",
"words": [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
},
{
"id": 3,
"id": 2,
"description": "Job Interview",
"imageFilename": "kart1.jpg",
"words": [13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
},
{
"id": 4,
"id": 3,
"description": "ReactJS",
"imageFilename": "kart1.jpg",
"words": [23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
},
{
"id": 5,
"id": 4,
"description": "NodeJS",
"imageFilename": "kart1.jpg",
"words": [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]

View File

@@ -5,15 +5,16 @@ const router = require('express').Router();
module.exports = router;
const data = require('./units.json');
const users = require('../users/users.json');
router.get('/', (req, res) => {
// for every data set author from users and save it to authoredData variable
const users = require('../users/users.json');
const authoredData = data.map((unit) => {
const user = users.find((user) => user.public_id == unit.author);
let authoredUnit = undefined;
if (user) {
unit.author = user;
authoredUnit = { ...unit, author: user };
}
return unit;
return authoredUnit;
});
res.send(authoredData);
@@ -39,9 +40,8 @@ router.post('/:id', (req, res) => {
data.splice(index, 1);
data.push(updatedUnit);
data.push({...updatedUnit, author: updatedUnit.author.public_id});
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
res.status(200).send(data);
});
@@ -61,12 +61,8 @@ router.put('/', (req, res) => {
}
const newId = data.length + 1;
// const filename = newUnit.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
// fs.writeFileSync(path.join(__dirname, 'data', `${filename}.md`), newUnit.content);
data.push({ ...newUnit, id: newId });
data.push({ ...unit, id: newId });
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
res.status(200).send(data);
});
@@ -79,11 +75,11 @@ router.delete('/:id', (req, res) => {
}
data.splice(index, 1);
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
res.send({ message: `Unit with ID ${id} deleted` });
});
router.get('/:id', (req, res) => {
const users = require('../users/users.json');
const id = parseInt(req.params.id);
const unit = data.find((unit) => unit.id === id);
@@ -91,14 +87,7 @@ router.get('/:id', (req, res) => {
return res.status(404).send('Unit not found');
}
const user = users.find((user) => {
if (user.public_id == unit.author) {
return user;
}
});
if (!user) {
return res.status(404).send('User not found');
}
const user = users.find((user) => user.public_id == unit.author);
res.send({...unit, author: user});
});

View File

@@ -3,7 +3,7 @@ const fs = require('fs');
module.exports = router;
const data = require('./users.json');
let data = require('./users.json');
const path = require('path');
router.get('/', (req, res) => {
res.send(data);
@@ -11,27 +11,15 @@ router.get('/', (req, res) => {
router.post('/', (req, res) => {
const newUser = req.body;
const updatedData = [...data, newUser];
console.log(updatedData);
fs.writeFile(path.join(__dirname, 'users.json'), JSON.stringify(updatedData), (err) => {
if (err) {
console.error('Ошибка при записи данных в файл users.json', err);
res.status(500).send('Ошибка при записи данных в файл users.json');
} else {
console.log('Данные успешно записаны в файл users.json');
res.status(200).send('Данные успешно записаны в файл users.json');
}
});
data.push(newUser);
fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));
res.send(data);
});
router.post('/login', (req, res) => {
const { email, password } = req.body;
console.log(email);
console.log(req.body);
const user = data.find((user) => user.email === email && user.password === password);
console.log(user);
if (!user) {
res.status(404).send('Пользователь не найден');
@@ -41,13 +29,11 @@ router.post('/login', (req, res) => {
router.get('/account', (req, res) => {
const { public_id } = req.query;
console.log(public_id);
const user = data.find((user) => user.public_id == public_id);
if (!user) {
res.status(404).send('Пользователь не найден');
}
console.log(user);
res.send({ ...user, id: -1 });
});
@@ -61,7 +47,6 @@ router.post('/account/save', (req, res) => {
}
data[index] = { ...data[index], ...updatedUser, id: data[index].id, password: data[index].password };
fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));
res.status(200);