2020-07-21 14:36:50 +03:00
|
|
|
import * as Environment from "~/node_common/environment";
|
|
|
|
import * as Credentials from "~/common/credentials";
|
|
|
|
import * as Strings from "~/common/strings";
|
|
|
|
import * as Data from "~/node_common/data";
|
2020-07-24 02:56:50 +03:00
|
|
|
import * as Powergate from "~/node_common/powergate";
|
2020-07-21 14:36:50 +03:00
|
|
|
|
2020-07-22 21:54:58 +03:00
|
|
|
import JWT from "jsonwebtoken";
|
|
|
|
|
2020-07-17 13:24:20 +03:00
|
|
|
export const init = (middleware) => {
|
|
|
|
return (req, res) =>
|
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
middleware(req, res, (result) => {
|
|
|
|
if (result instanceof Error) {
|
|
|
|
return reject(result);
|
|
|
|
}
|
|
|
|
return resolve(result);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2020-02-19 09:30:47 +03:00
|
|
|
export const CORS = async (req, res, next) => {
|
2020-06-19 06:57:57 +03:00
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
2020-10-23 13:34:31 +03:00
|
|
|
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
|
|
|
|
res.header("Access-Control-Allow-Headers", "Origin, Accept, Content-Type, Authorization");
|
2020-02-19 09:30:47 +03:00
|
|
|
|
2020-06-19 06:57:57 +03:00
|
|
|
if (req.method === "OPTIONS") {
|
2020-02-19 09:30:47 +03:00
|
|
|
return res.status(200).end();
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
2020-07-21 14:36:50 +03:00
|
|
|
|
|
|
|
export const RequireCookieAuthentication = async (req, res, next) => {
|
|
|
|
if (Strings.isEmpty(req.headers.cookie)) {
|
2020-10-23 13:34:31 +03:00
|
|
|
return res.status(403).json({ decorator: "SERVER_AUTH_USER_NO_TOKEN", error: true });
|
2020-07-21 14:36:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const token = req.headers.cookie.replace(
|
|
|
|
/(?:(?:^|.*;\s*)WEB_SERVICE_SESSION_KEY\s*\=\s*([^;]*).*$)|^.*$/,
|
|
|
|
"$1"
|
|
|
|
);
|
|
|
|
|
2020-07-24 02:56:50 +03:00
|
|
|
let user;
|
2020-07-21 14:36:50 +03:00
|
|
|
try {
|
|
|
|
const decoded = JWT.verify(token, Environment.JWT_SECRET);
|
2020-07-24 02:56:50 +03:00
|
|
|
user = await Data.getUserById({
|
2020-07-22 13:51:40 +03:00
|
|
|
id: decoded.id,
|
2020-07-21 14:36:50 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
if (!user || user.error) {
|
2020-10-23 13:34:31 +03:00
|
|
|
return res.status(403).json({ decorator: "SERVER_AUTH_USER_NOT_FOUND", error: true });
|
2020-07-21 14:36:50 +03:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.log(err);
|
2020-10-23 13:34:31 +03:00
|
|
|
return res.status(403).json({ decorator: "SERVER_AUTH_USER_ERROR", error: true });
|
2020-07-21 14:36:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|