Compare commits

..

No commits in common. "master" and "dsf-fix" have entirely different histories.

10 changed files with 1755 additions and 1881 deletions

View File

@ -0,0 +1,74 @@
const { Router } = require("express");
const hash = require("pbkdf2-password")();
const { promisify } = require("node:util");
const jwt = require('jsonwebtoken')
const { getAnswer } = require("../../utils/common");
const { AuthModel } = require("./model/todo/auth");
const { TOKEN_KEY } = require('./const')
const { UserModel } = require("./model/todo/user");
const { requiredValidate } = require('./utils')
const router = Router();
router.post(
"/signup",
requiredValidate("login", "password", "email"),
async (req, res, next) => {
const { login, password, email } = req.body
const user = await AuthModel.findOne({ login });
if (user) {
throw new Error("Пользователь с таким логином уже существует");
}
hash({ password }, async function (err, pass, salt, hash) {
if (err) return next(err);
const user = await UserModel.create({ login, email });
await AuthModel.create({ login, hash, salt, userId: user.id });
res.json(getAnswer(null, { ok: true }))
})
}
)
function authenticate(login, pass, cb) {
AuthModel.findOne({ login }).populate('userId').exec().then((user) => {
if (!user) return cb(null, null)
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return cb(err)
if (hash === user.hash) return cb(null, user)
cb(null, null)
})
})
}
const auth = promisify(authenticate)
router.post('/signin', requiredValidate('login', 'password'), async (req, res) => {
const { login, password } = req.body
const user = await auth(login, password)
if (!user) {
throw new Error("Неверный логин или пароль")
}
const accessToken = jwt.sign({
...JSON.parse(JSON.stringify(user.userId)),
}, TOKEN_KEY, {
expiresIn: '12h'
})
res.json(getAnswer(null, {
user: user.userId,
token: accessToken,
}))
})
module.exports = router

View File

@ -1,2 +1,3 @@
exports.DSF_AUTH_PASSWD_MODEL_NAME = 'DSF_AUTH_PASSWD'
exports.DSF_AUTH_USER_MODEL_NAME = 'DSF_AUTH_USER'
exports.DSF_INTERACTION_MODEL_NAME = 'DSF_INTERACTION'

View File

@ -67,162 +67,3 @@ router.get("/auth/session", (request, response) => {
return response.status(403).json({ error: "Invalid token" });
}
});
// Проверка взаимодействия между пользователем и догситтером
router.get("/interactions/check", (req, res) => {
const { owner_id, dogsitter_id } = req.query;
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
delete require.cache[require.resolve(usersFilePath)];
const usersFile = require(usersFilePath);
const interactions = usersFile.interactions || [];
const exists = interactions.some(
(interaction) =>
interaction.owner_id === Number(owner_id) &&
interaction.dogsitter_id === Number(dogsitter_id)
);
res.json({ exists });
});
// Добавление нового взаимодействия
router.post("/interactions", (req, res) => {
const { owner_id, dogsitter_id, interaction_type } = req.body;
if (!owner_id || !dogsitter_id || !interaction_type) {
return res.status(400).json({ error: "Missing required fields" });
}
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
delete require.cache[require.resolve(usersFilePath)];
const usersFile = require(usersFilePath);
if (!usersFile.interactions) {
usersFile.interactions = [];
}
// Проверяем, существует ли уже такое взаимодействие
const exists = usersFile.interactions.some(
(interaction) =>
interaction.owner_id === Number(owner_id) &&
interaction.dogsitter_id === Number(dogsitter_id)
);
if (!exists) {
usersFile.interactions.push({
owner_id: Number(owner_id),
dogsitter_id: Number(dogsitter_id),
interaction_type,
});
fs.writeFileSync(
usersFilePath,
JSON.stringify(usersFile, null, 2),
"utf8"
);
console.log(
`Добавлено взаимодействие: owner_id=${owner_id}, dogsitter_id=${dogsitter_id}`
);
}
res.json({ success: true });
});
router.get("/dogsitter-viewing", (req, res) => {
const { id } = req.query;
console.log(`Получен запрос для dogsitter с ID: ${id}`);
const usersFile = require("./json/users/users.json");
const users = usersFile.data; // Извлекаем массив из свойства "data"
const user = users.find((user) => user.id === Number(id));
if (user) {
res.json(user); // Возвращаем найденного пользователя
} else {
res.status(404).json({ error: "User not found" }); // Если пользователь не найден
}
});
const fs = require('fs');
const path = require('path');
router.post('/dogsitter-viewing/rating/:id', (req, res) => {
const { id } = req.params;
const { rating } = req.body;
if (!rating || rating < 1 || rating > 5) {
return res.status(400).json({ error: 'Некорректная оценка' });
}
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
delete require.cache[require.resolve(usersFilePath)];
const usersFile = require(usersFilePath);
const users = usersFile.data;
const userIndex = users.findIndex(user => user.id === Number(id));
if (userIndex === -1) {
return res.status(404).json({ error: 'Догситтер не найден' });
}
if (!users[userIndex].ratings) {
users[userIndex].ratings = [];
}
users[userIndex].ratings.push(rating);
if (users[userIndex].ratings.length > 100) {
users[userIndex].ratings.shift();
}
const total = users[userIndex].ratings.reduce((sum, r) => sum + r, 0);
users[userIndex].rating = parseFloat((total / users[userIndex].ratings.length).toFixed(2));
fs.writeFileSync(usersFilePath, JSON.stringify({ data: users }, null, 2), 'utf8');
console.log(`Обновлен рейтинг догситтера ${id}: ${users[userIndex].rating}`);
res.json({ rating: users[userIndex].rating, ratings: users[userIndex].ratings });
});
router.patch('/users/:id', (req, res) => {
const { id } = req.params;
const updateData = req.body;
console.log('Полученные данные для обновления:', updateData);
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
delete require.cache[require.resolve(usersFilePath)];
const usersFile = require(usersFilePath);
const users = usersFile.data;
const userIndex = users.findIndex((user) => user.id === Number(id));
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found' });
}
users[userIndex] = { ...users[userIndex], ...updateData };
fs.writeFileSync(
usersFilePath,
JSON.stringify({ data: users }, null, 2),
'utf8'
);
console.log('Обновлённые данные пользователя:', users[userIndex]);
res.json(users[userIndex]);
});
module.exports = router

View File

@ -1,20 +1,13 @@
{
"data": [
[
{
"id": 1,
"phone_number": "89999999999",
"phone_number": 89283244141,
"first_name": "Вася",
"second_name": "Пупкин",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, Пушкина, 12",
"price": "1500",
"about_me": "Я люблю собак!",
"rating": 5,
"ratings": [
5,
5
],
"tg": "jullllllie"
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
"price": 1500,
"about_me": "Я люблю собак"
},
{
"id": 2,
@ -23,18 +16,12 @@
"second_name": "Пуськин",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, улица Абсалямова, 19",
"price": 2000,
"about_me": "Я не люблю собак. И вообще я котоман.",
"rating": 4,
"ratings": [
4,
4
],
"tg": "vanya006"
"price": 1000000,
"about_me": "Я не люблю собак. И вообще я котоман."
},
{
"id": 3,
"phone_number": 89559999999,
"phone_number": 89872855893,
"first_name": "Гадий",
"second_name": "Петрович",
"role": "owner"
@ -46,24 +33,7 @@
"second_name": "Максим",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, проспект Ямашева, 83",
"price": 1750,
"about_me": "Миллион алых роз",
"rating": 4.5,
"ratings": [
4,
5
],
"tg": "maks100500"
"price": 1000000,
"about_me": "Миллион алых роз"
}
],
"interactions": [
{
"owner_id": 3,
"dogsitter_id": 4
},
{
"owner_id": 1,
"dogsitter_id": 2
}
]
}
]

View File

@ -0,0 +1,44 @@
const { Schema, model } = require("mongoose");
const {
DSF_AUTH_PASSWD_MODEL_NAME,
DSF_AUTH_USER_MODEL_NAME,
} = require("../../const");
const schema = new Schema({
login: {
type: String,
required: true,
unique: true
},
hash: {
type: String,
required: true
},
salt: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: DSF_AUTH_USER_MODEL_NAME
},
created: {
type: Date,
default: () => new Date().toISOString(),
},
});
schema.set("toJSON", {
virtuals: true,
versionKey: false,
transform: function (doc, ret) {
delete ret._id;
},
});
schema.virtual("id").get(function () {
return this._id.toHexString();
});
exports.AuthModel = model(DSF_AUTH_PASSWD_MODEL_NAME, schema);

File diff suppressed because it is too large Load Diff

View File

@ -607,7 +607,8 @@ function createGigachat(options = {}) {
}
var gigachat = createGigachat();
// Annotate the CommonJS export names for ESM import in node:
module.exports = {
0 && (module.exports = {
createGigachat,
gigachat
}
});
//# sourceMappingURL=index.js.map

View File

@ -84,7 +84,7 @@ router.use(async (req, res, next) => {
process.env.GIGACHAT_ACCESS_TOKEN = json.access_token;
process.env.GIGACHAT_EXPIRES_AT = json.expires_at;
console.log(JSON.stringify(response.data));
} catch (error) {
} catch {
console.log(error);
}
}

View File

@ -5,11 +5,9 @@ const router = Router()
const todoRouter = require('./routes')
const authRouter = require('./auth')
const commentRouter = require('./comment')
const navRouter = require('./nav')
router.use('/auth', authRouter)
router.use('/comment', commentRouter)
router.use('/nav', navRouter)
router.use(todoRouter)

View File

@ -1,51 +0,0 @@
const router = require("express").Router();
router.get("/users", (req, res) => {
res.send({
success: false,
body: [
{
id: "some-user-id",
name: "alexandr",
age: 38,
surname: null,
email: null,
rated: 4,
avatar:
"https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash",
friends: [
{
id: "2",
name: "not alexandr",
surname: null,
email: null,
rated: 2,
avatar: "https://www.gravatar.com/avatar/6e?d=robohash",
},
],
},
{
id: "2",
name: "not alexandr",
surname: null,
email: null,
age: 24,
rated: 5,
avatar: "https://www.gravatar.com/avatar/6e?d=robohash",
friends: [
{
id: "some-user-id",
name: "alexandr",
surname: null,
email: null,
rated: 3,
avatar:
"https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash",
},
],
},
],
})
})
module.exports = router