multy-stub/server/routers/todo/auth.js

75 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2025-01-18 15:44:14 +03:00
const { Router } = require("express");
const hash = require("pbkdf2-password")();
const { promisify } = require("node:util");
const jwt = require('jsonwebtoken')
const { getAnswer } = require("../../utils/common");
2025-01-18 16:50:58 +03:00
const { AuthModel } = require("./model/todo/auth");
const { TOKEN_KEY } = require('./const')
const { UserModel } = require("./model/todo/user");
2025-01-18 15:44:14 +03:00
2025-01-18 16:50:58 +03:00
const { requiredValidate } = require('./utils')
2025-01-18 15:44:14 +03:00
2025-01-18 16:50:58 +03:00
const router = Router();
2025-01-18 15:44:14 +03:00
router.post(
"/signup",
requiredValidate("login", "password", "email"),
async (req, res, next) => {
2025-01-18 16:50:58 +03:00
const { login, password, email } = req.body
2025-01-18 15:44:14 +03:00
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 });
2025-01-18 16:50:58 +03:00
res.json(getAnswer(null, { ok: true }))
})
2025-01-18 15:44:14 +03:00
}
2025-01-18 16:50:58 +03:00
)
2025-01-18 15:44:14 +03:00
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)
})
})
}
2025-01-18 16:50:58 +03:00
const auth = promisify(authenticate)
2025-01-18 15:44:14 +03:00
2025-01-18 16:50:58 +03:00
router.post('/signin', requiredValidate('login', 'password'), async (req, res) => {
const { login, password } = req.body
2025-01-18 15:44:14 +03:00
const user = await auth(login, password)
if (!user) {
throw new Error("Неверный логин или пароль")
}
const accessToken = jwt.sign({
2025-01-18 16:50:58 +03:00
...JSON.parse(JSON.stringify(user.userId)),
2025-01-18 15:44:14 +03:00
}, TOKEN_KEY, {
expiresIn: '12h'
})
res.json(getAnswer(null, {
user: user.userId,
2025-01-18 16:50:58 +03:00
token: accessToken,
2025-01-18 15:44:14 +03:00
}))
})
module.exports = router