akf-forum/routes/register.js

45 lines
1.4 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();
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: 10, standardHeaders: true, legacyHeaders: false,
handler: (_r, response, _n, options) => response.error(options.statusCode, "You are begin ratelimited")
}), async (req, res) => {
2022-08-31 14:44:28 +03:00
req.session.userID = null;
2022-03-21 23:53:22 +03:00
2022-03-13 16:16:46 +03:00
2022-08-29 19:31:59 +03:00
let { username = null, password: body_pass = null, avatar, about } = req.body;
2022-04-06 21:14:46 +03:00
2022-08-27 10:31:16 +03:00
if (!username || !body_pass) return res.error(res, 400, "You forgot entering some values");
const user = await SecretModel.findOne({ username });
2022-03-13 16:16:46 +03:00
2022-08-27 10:31:16 +03:00
if (user) return res.error(res, 400, `We have got an user named ${username}!`)
2022-03-13 16:16:46 +03:00
2022-04-06 21:14:46 +03:00
2022-08-27 10:31:16 +03:00
const user2 = new UserModel({ name: req.body.username })
2022-08-28 15:00:53 +03:00
if (avatar && /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g.test(avatar)) user2.avatar = avatar;
2022-08-29 19:31:59 +03:00
if (about) user2.about = about;
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;