2022-09-23 23:10:13 +03:00
|
|
|
const { Router } = require("express");
|
2022-03-21 23:53:22 +03:00
|
|
|
const app = Router();
|
2022-09-16 22:40:43 +03:00
|
|
|
const fs = require("fs");
|
2022-08-10 02:08:18 +03:00
|
|
|
const bcrypt = require("bcrypt");
|
2022-09-23 23:10:13 +03:00
|
|
|
const { UserModel } = require("../../models");
|
2022-08-10 02:08:18 +03:00
|
|
|
|
|
|
|
|
2022-04-06 21:14:46 +03:00
|
|
|
app.use(async (req, res, next) => {
|
2022-08-27 14:08:28 +03:00
|
|
|
res.error = (status, error) => res.status(status).json({ error });
|
2022-08-24 22:09:21 +03:00
|
|
|
res.complate = result => res.status(200).json(result);
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-08-11 00:38:44 +03:00
|
|
|
if (req.user) return next();
|
2022-09-21 22:42:08 +03:00
|
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader) return res.error(401, "No authorization header");
|
2022-09-23 23:10:13 +03:00
|
|
|
const [name, password] = Buffer.from(authHeader.split(' ')[1], "base64").toString().split(":");
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-09-23 23:10:13 +03:00
|
|
|
if (!name || !password)
|
|
|
|
return res.error(400, "Authorise headers are not well formed");
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-09-23 23:10:13 +03:00
|
|
|
const user = await UserModel.findOne({ name });
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-09-23 23:10:13 +03:00
|
|
|
if (!user || user.deleted) return res.error(401, `We don't have any user with name ${name}.`)
|
2022-09-24 01:39:06 +03:00
|
|
|
if (!user.approved) return res.error(401, "Your account is not approved yet.");
|
2022-08-10 02:08:18 +03:00
|
|
|
|
2022-08-28 21:14:02 +03:00
|
|
|
if (!await bcrypt.compare(password, user.password)) return res.error(401, 'Incorrect Password!');
|
2022-08-27 14:08:28 +03:00
|
|
|
|
2022-09-23 23:10:13 +03:00
|
|
|
req.user = user;
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-04-03 21:22:06 +03:00
|
|
|
next();
|
2022-04-06 21:14:46 +03:00
|
|
|
});
|
2022-03-21 23:53:22 +03:00
|
|
|
|
2022-09-09 21:40:02 +03:00
|
|
|
app.get("/me", (req, res) => res.complate(req.user))
|
2022-09-09 21:36:55 +03:00
|
|
|
|
2022-09-16 22:40:43 +03:00
|
|
|
for (const file of fs.readdirSync("./routes/api/routes"))
|
2022-08-29 21:32:57 +03:00
|
|
|
app.use("/" + file.replace(".js", ""), require(`./routes/${file}`));
|
2022-09-16 22:40:43 +03:00
|
|
|
|
2022-08-10 02:08:18 +03:00
|
|
|
app.all("*", (req, res) => res.error(400, "Bad request"));
|
2022-03-21 23:53:22 +03:00
|
|
|
|
|
|
|
module.exports = app;
|