91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
const { Router } = require("express");
|
||
const hash = require("pbkdf2-password")();
|
||
const { promisify } = require("node:util");
|
||
const jwt = require('jsonwebtoken')
|
||
|
||
const { AuthModel } = require("./model/todo/auth");
|
||
const { UserModel } = require("./model/todo/user");
|
||
const { getAnswer } = require("../../utils/common");
|
||
|
||
const router = Router();
|
||
|
||
const TOKEN_KEY = process.env.TOKEN_KEY || "asdfhoa-podh829438132 iahda98gauj dj2i3-111"
|
||
|
||
const requiredValidate =
|
||
(...fields) =>
|
||
(req, res, next) => {
|
||
const errors = []
|
||
|
||
fields.forEach((field) => {
|
||
if (!req.body[field]) {
|
||
errors.push(field);
|
||
}
|
||
});
|
||
|
||
if (errors.length) {
|
||
throw new Error(`Не все поля заполнены: ${errors.join(", ")}`);
|
||
} else {
|
||
next();
|
||
}
|
||
};
|
||
|
||
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', async (req, res) => {
|
||
const { login, password } = req.body;
|
||
|
||
const user = await auth(login, password)
|
||
|
||
if (!user) {
|
||
throw new Error("Неверный логин или пароль")
|
||
}
|
||
|
||
const accessToken = jwt.sign({
|
||
...user.userId
|
||
}, TOKEN_KEY, {
|
||
expiresIn: '12h'
|
||
})
|
||
|
||
res.json(getAnswer(null, {
|
||
user: user.userId,
|
||
token: accessToken
|
||
}))
|
||
})
|
||
|
||
module.exports = router
|