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-09-03 00:07:45 +03:00
|
|
|
/*
|
2020-06-19 06:57:57 +03:00
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
2020-07-17 13:24:20 +03:00
|
|
|
|
2020-02-19 09:30:47 +03:00
|
|
|
res.header(
|
2020-06-19 06:57:57 +03:00
|
|
|
"Access-Control-Allow-Methods",
|
|
|
|
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
|
2020-02-19 09:30:47 +03:00
|
|
|
);
|
2020-07-17 13:24:20 +03:00
|
|
|
|
2020-02-19 09:30:47 +03:00
|
|
|
res.header(
|
2020-06-19 06:57:57 +03:00
|
|
|
"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();
|
|
|
|
}
|
2020-09-03 00:07:45 +03:00
|
|
|
*/
|
2020-02-19 09:30:47 +03:00
|
|
|
|
|
|
|
next();
|
|
|
|
};
|
2020-07-21 14:36:50 +03:00
|
|
|
|
|
|
|
export const RequireCookieAuthentication = async (req, res, next) => {
|
|
|
|
if (Strings.isEmpty(req.headers.cookie)) {
|
|
|
|
return res
|
|
|
|
.status(403)
|
|
|
|
.json({ decorator: "SERVER_AUTH_USER_NO_TOKEN", error: true });
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
|
|
|
return res
|
|
|
|
.status(403)
|
|
|
|
.json({ decorator: "SERVER_AUTH_USER_NOT_FOUND", error: true });
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.log(err);
|
|
|
|
return res
|
|
|
|
.status(403)
|
|
|
|
.json({ decorator: "SERVER_AUTH_USER_ERROR", error: true });
|
|
|
|
}
|
|
|
|
|
|
|
|
next();
|
|
|
|
};
|