akf-forum/routes/api/index.js

43 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-08-27 14:08:28 +03:00
const { Router, request, response } = require("express")
2022-03-21 23:53:22 +03:00
const app = Router();
2022-08-10 02:08:18 +03:00
const bcrypt = require("bcrypt");
const { SecretModel, UserModel } = require("../../models")
2022-03-21 23:53:22 +03:00
/**
2022-04-06 21:14:46 +03:00
* Auth checker
2022-03-21 23:53:22 +03:00
* @param {request} req
* @param {response} res
*/
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-10 02:08:18 +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-03-21 23:53:22 +03:00
const { username = null, password = null } = req.headers;
if (!username || !password)
2022-08-10 02:08:18 +03:00
return res.error(401, "Authorise headers are missing")
2022-03-21 23:53:22 +03:00
2022-04-06 21:14:46 +03:00
const user = await SecretModel.findOne({ username });
2022-03-21 23:53:22 +03:00
if (!user)
2022-08-10 02:08:18 +03:00
return res.error(401, "We have not got any user has got this name")
2022-08-27 14:08:28 +03:00
if (!bcrypt.compare(password, user.password)) return res.error(401, 'Incorrect Password!');
2022-08-10 02:08:18 +03:00
req.user = await UserModel.findOne({ name: req.headers.username });
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-08-10 02:08:18 +03:00
/* will add for loop */
app.use("/messages", require("./routes/messages"))
app.use("/users", require("./routes/users"))
2022-04-03 22:03:47 +03:00
app.use("/threads", require("./routes/threads"))
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;