akf-forum/routes/register.js

48 lines
1.6 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-09-16 23:12:06 +03:00
const rateLimit = require('express-rate-limit');
2022-03-21 23:53:22 +03:00
const app = Router();
2022-08-29 22:33:22 +03:00
app.get("/", (req, res) => res.reply("register", { user: null }));
2022-08-29 22:33:22 +03:00
app.post("/", rateLimit({
windowMs: 24 * 60 * 60_000, max: 5, standardHeaders: true, legacyHeaders: false,
2022-08-29 22:33:22 +03:00
handler: (_r, response, _n, options) => response.error(options.statusCode, "You are begin ratelimited")
}), async (req, res) => {
2022-09-10 21:02:24 +03:00
2022-09-17 00:27:38 +03:00
req.session.userID = null;
2022-03-13 16:16:46 +03:00
2022-09-16 23:12:06 +03:00
let { username = null, password: body_pass = null, about } = req.body;
2022-04-06 21:14:46 +03:00
2022-09-17 00:27:38 +03:00
if (!username || !body_pass) return res.error(400, "You forgot entering some values");
if (username.length < 3 || username.length > 25) return res.error(400, "Username must be between 3 - 25 characters");
if (body_pass.length < 3 || body_pass.length > 25) return res.error(400, "Password must be between 3 - 25 characters");
2022-08-27 10:31:16 +03:00
const user = await SecretModel.findOne({ username });
2022-03-13 16:16:46 +03:00
2022-09-17 00:27:38 +03:00
if (user) return res.error(400, `We have got an user named ${username}!`)
2022-03-13 16:16:46 +03:00
2022-09-17 00:27:38 +03:00
const user2 = new UserModel({ name: username })
2022-08-29 19:31:59 +03:00
2022-09-17 00:27:38 +03:00
if (about) {
if (about.length > 256) return res.error(400, "about must be under 256 characters");
user2.about = about;
}
2022-08-29 19:31:59 +03:00
2022-08-27 10:31:16 +03:00
await user2.takeId()
await user2.save();
2022-04-06 21:14:46 +03:00
2022-08-27 10:31:16 +03:00
const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(body_pass, salt);
await SecretModel.create({ username, password, id: user2.id })
2022-08-31 14:44:28 +03:00
req.session.userID = user2.id;
2022-08-27 10:31:16 +03:00
res.redirect('/');
2022-04-06 21:14:46 +03:00
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;