akf-forum/routes/register.js

49 lines
1.3 KiB
JavaScript
Raw Normal View History

const { UserModel, SecretModel } = require("../models");
2022-03-21 23:53:22 +03:00
const { Router } = require("express")
const bcrypt = require("bcrypt");
2022-08-24 22:39:38 +03:00
const rateLimit = require('express-rate-limit')
2022-03-21 23:53:22 +03:00
const app = Router();
app.get("/", (req, res) => res.render("register"));
app.post("/", rateLimit({
windowMs: 24*60*60_000, max: 1, standardHeaders: true, legacyHeaders: false,
handler: (request, response, next, options) =>
response.error(options.statusCode, "You are begin ratelimited")
}), async (req, res) => {
2022-03-13 16:16:46 +03:00
req.session.userid = null;
2022-03-21 23:53:22 +03:00
2022-03-13 16:16:46 +03:00
let { username = null, password = null, avatar } = req.body;
2022-04-06 21:14:46 +03:00
2022-03-13 16:16:46 +03:00
if (username && password) {
2022-04-06 21:14:46 +03:00
const user = await SecretModel.findOne({ username });
2022-03-13 16:16:46 +03:00
2022-03-21 23:53:22 +03:00
if (user)
2022-08-11 00:49:44 +03:00
res.error(res, 400, `We have got an user named ${username}!`)
2022-03-13 16:16:46 +03:00
2022-03-21 23:53:22 +03:00
else {
2022-04-06 21:14:46 +03:00
const user2 = new UserModel({ name: req.body.username, avatar })
await user2.takeId()
await user2.save();
const salt = await bcrypt.genSalt(10);
password = await bcrypt.hash(password, salt);
2022-04-06 21:14:46 +03:00
await SecretModel.create({ username, password, id: user2.id })
2022-03-13 16:16:46 +03:00
req.session.userid = user2.id;
2022-04-06 21:14:46 +03:00
2022-03-13 16:16:46 +03:00
res.redirect('/');
}
} else
2022-08-11 00:49:44 +03:00
res.error(res, 400, "You forgot entering some values")
2022-03-21 23:53:22 +03:00
})
2022-03-13 16:16:46 +03:00
2022-03-21 23:53:22 +03:00
module.exports = app;