Commit a6ef37e5 authored by Torstein Nicolaysen's avatar Torstein Nicolaysen Committed by Torstein
Browse files

DEICH-5952 move employee-specific endoints to /api/ansatt

parent d81a50ca
......@@ -53,7 +53,7 @@ class RegistrationStep1 extends React.Component {
async getUserDataFromKoha(ssn) {
try {
const patronRes = await fetch(
`/api/registration/getborrowerbyssn/${ssn}`,
`/api/ansatt/getborrowerbyssn/${ssn}`,
{
method: "GET",
credentials: "include",
......@@ -262,7 +262,7 @@ class RegistrationStep1 extends React.Component {
async submitFinalizeChildForm(data) {
this.setState({ isSubmitting: true });
const url = "/api/registration/child-finalize";
const url = "/api/ansatt/child-finalize";
const firstName = data.firstName;
const lastName = data.lastName;
const name = `${firstName} ${lastName}`;
......@@ -307,7 +307,7 @@ class RegistrationStep1 extends React.Component {
// Post user to Koha
async handlePostUserToKoha() {
this.setState({ isSubmitting: true });
const url = "/api/registration/initbyemployee";
const url = "/api/ansatt/initbyemployee";
try {
const { userData } = this.state;
......
class KohaError extends Error {
constructor(message, status, statusText = null) {
super(message);
this.name = "KohaError";
this.status = status;
this.statusText = statusText;
}
}
KohaError.prototype.toString = function kohaErrorToString() {
return `${this.message}: STATUS: ${this.status} - ${this.statusText}`;
};
module.exports = KohaError;
const logger = require("../../logger")(__filename);
const routes = require("express").Router();
const { verifyToken } = require("../utils/tokenChecker");
const KohaError = require("../misc/koha-error");
const CALL_ID_HEADER = "Deichman-CallID";
const kohaEndpoint = process.env.INTERNAL_URL_KOHA;
routes.post("/patronsearch/findbybirthdate", async (request, response) => {
const deichmanCallId = request.headers[CALL_ID_HEADER];
const jwtToken = request.session.jwt_token;
const { birthdate } = request.body;
try {
const kohaResponse = await fetch(
......@@ -17,7 +20,7 @@ routes.post("/patronsearch/findbybirthdate", async (request, response) => {
"Deichman-CallID": deichmanCallId,
Authorization: `Bearer ${jwtToken}`
},
body: JSON.stringify({ birthdate: birthdate })
body: JSON.stringify({ birthdate: request.body.birthdate })
}
);
......@@ -30,4 +33,202 @@ routes.post("/patronsearch/findbybirthdate", async (request, response) => {
}
});
// Initiate by superuser/librarian. Meaning that ID is verified.
routes.post("/initbyemployee", async (request, response) => {
const deichmanCallId = request.headers[CALL_ID_HEADER];
const jwtToken = request.session.jwt_token;
try {
const kohaPatron = await initPatronRegistration(
{
cardnumber: request.body.cardnumber,
categorycode: request.body.categorycode,
dateofbirth: request.body.dateofbirth,
email: request.body.email,
firstname: request.body.firstname,
guarantoremail: request.body.guarantoremail,
guarantormobile: request.body.guarantormobile,
guarantorname: request.body.guarantorname,
mobile: request.body.mobile,
ssn: request.body.ssn,
surname: request.body.surname,
useKrrDetails: request.body.useKrrDetails === "true" ? 1 : 0,
userHasNoEmail: request.body.userHasNoEmail ? 1 : 0
},
true,
jwtToken,
deichmanCallId
);
response.status(201).send(kohaPatron);
} catch (error) {
if (error instanceof KohaError) {
logger.error(
`ERROR register user from desk ${
request.body.email
}, init patron request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(error.status).json({ error: "Call to core failed." });
} else {
logger.warn(
`WARN register user from desk ${
request.body.email
}, init patron request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(500).json({ error: "Unhandled failure in middleware." });
}
}
});
// Get borrower to be able to finish registration in the skrank
routes.get("/getborrowerbyssn/:ssn", async (request, response) => {
const jwtToken = request.session.jwt_token;
const tokenCheck = await verifyToken(jwtToken);
if (!tokenCheck) {
response.status(403).send();
}
const kohaExistingUsersUrl = "http://koha:8082/api/patrons/checkexisting";
try {
const kohaRes = await fetch(kohaExistingUsersUrl, {
headers: {
"Content-type": "application/json"
},
method: "POST",
body: JSON.stringify({ ssn: request.params.ssn })
});
if (kohaRes.ok) {
const result = await kohaRes.json();
if (result.localPatron) {
const borrower = {
firstName: result.localPatron.firstname,
lastName: result.localPatron.surname,
dateOfBirth: result.localPatron.dateofbirth,
guarantorname: result.localPatron.guarantorname,
guarantoremail: result.localPatron.guarantoremail,
guarantormobile: result.localPatron.guarantormobile,
borrowernumber: result.localPatron.borrowernumber,
notFinishedSelfRegistration: !result.localPatron.password
};
response.status(200).send(borrower);
}
}
response.status(404).send();
} catch (error) {
logger.error("Unable to check if existing user", error);
response.status(404).send();
}
});
// finalize child registration
routes.post("/child-finalize", async (request, response) => {
const deichmanCallId = request.headers[CALL_ID_HEADER];
const jwtToken = request.session.jwt_token;
try {
await finalizechildfromweb(
{
borrowernumber: request.body.borrowernumber,
firstname: request.body.firstname,
surname: request.body.surname,
dateofbirth: request.body.dateofbirth,
cardnumber: request.body.cardnumber
},
jwtToken,
deichmanCallId
);
response.sendStatus(201);
} catch (error) {
if (error instanceof KohaError) {
logger.error(
`ERROR finalize child from web, request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(error.status).json({ error: "Call to core failed." });
} else {
logger.warn(
`WARN finalize child from web, request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(500).json({ error: "Unhandled failure in middleware." });
}
}
});
// NOTE: Similar function exist in registration.js
async function initPatronRegistration(
patron,
initByEmployee,
jwtToken,
deichmanCallId
) {
try {
const url = `${kohaEndpoint}/api/patrons/${
initByEmployee ? "initbyemployee" : "initchildfromweb"
}`;
const kohaResponse = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
Authorization: `Bearer ${jwtToken}`,
"Deichman-CallID": deichmanCallId
},
body: JSON.stringify(patron)
});
if (kohaResponse.status === 200 || kohaResponse.status === 201) {
const kohaPatron = await kohaResponse.json();
return { borrowernumber: kohaPatron.borrowernumber };
}
throw new KohaError(
`Could not initiate patron registration`,
kohaResponse.status,
kohaResponse.statusText
);
} catch (error) {
if (error instanceof KohaError) {
throw error;
}
throw new Error(error.message);
}
}
async function finalizechildfromweb(patron, jwtToken, deichmanCallId) {
try {
const kohaResponse = await fetch(
`${kohaEndpoint}/api/patrons/finalizechildfromweb`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
"Deichman-CallID": deichmanCallId,
Authorization: `Bearer ${jwtToken}`
},
body: JSON.stringify(patron)
}
);
if (kohaResponse.status === 200 || kohaResponse.status === 201) {
logger.info(`Child patron finalized from web complete`, {
call_id: deichmanCallId
});
return;
}
throw new KohaError(
`Could not finalize child patron registration`,
kohaResponse.status,
kohaResponse.statusText
);
} catch (error) {
if (error instanceof KohaError) {
throw error;
}
throw new Error(error.message);
}
}
module.exports = routes;
......@@ -60,6 +60,6 @@ routes.use("/resources", resources);
routes.use("/registration", registration);
routes.use("/search", search);
routes.use("/unauthenticated", unauthenticated);
routes.use("/ansatt", ansatt);
routes.use("/ansatt", ansatt); // NOTE: Secured by HAProxy to only allow requests from the intranet
module.exports = routes;
......@@ -2,6 +2,7 @@ const logger = require("../../logger")(__filename);
const routes = require("express").Router();
const jwt = require("jsonwebtoken");
const { verifyToken } = require("../utils/tokenChecker");
const KohaError = require("../misc/koha-error");
const {
refreshAccessTokenUsingRefreshToken
......@@ -10,18 +11,6 @@ const {
const CALL_ID_HEADER = "Deichman-CallID";
const kohaEndpoint = process.env.INTERNAL_URL_KOHA;
class KohaError extends Error {
constructor(message, status, statusText = null) {
super(message);
this.name = "KohaError";
this.status = status;
this.statusText = statusText;
}
}
KohaError.prototype.toString = function kohaErrorToString() {
return `${this.message}: STATUS: ${this.status} - ${this.statusText}`;
};
async function registerPatron(patron, jwtToken, deichmanCallId) {
if (patron.pincode === "") {
......@@ -67,6 +56,7 @@ async function registerPatron(patron, jwtToken, deichmanCallId) {
}
}
// NOTE: Similar function exist in ansatt.js
async function initPatronRegistration(
patron,
initByEmployee,
......@@ -140,40 +130,6 @@ async function completeSelfRegistration(patron, deichmanCallId) {
}
}
async function finalizechildfromweb(patron, jwtToken, deichmanCallId) {
try {
const kohaResponse = await fetch(
`${kohaEndpoint}/api/patrons/finalizechildfromweb`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
"Deichman-CallID": deichmanCallId,
Authorization: `Bearer ${jwtToken}`
},
body: JSON.stringify(patron)
}
);
if (kohaResponse.status === 200 || kohaResponse.status === 201) {
logger.info(`Child patron finalized from web complete`, {
call_id: deichmanCallId
});
return;
}
throw new KohaError(
`Could not finalize child patron registration`,
kohaResponse.status,
kohaResponse.statusText
);
} catch (error) {
if (error instanceof KohaError) {
throw error;
}
throw new Error(error.message);
}
}
async function setDefaultSyncStatusAndAttributes(
patron,
pincode,
......@@ -226,47 +182,6 @@ async function setDefaultSyncStatusAndAttributes(
};
}
// Get borrower to be able to finish registration in the skrank
routes.get("/getborrowerbyssn/:ssn", async (request, response) => {
const jwtToken = request.session.jwt_token;
const tokenCheck = await verifyToken(jwtToken);
if (!tokenCheck) {
response.status(403).send();
}
const kohaExistingUsersUrl = "http://koha:8082/api/patrons/checkexisting";
try {
const kohaRes = await fetch(kohaExistingUsersUrl, {
headers: {
"Content-type": "application/json"
},
method: "POST",
body: JSON.stringify({ ssn: request.params.ssn })
});
if (kohaRes.ok) {
const result = await kohaRes.json();
if (result.localPatron) {
const borrower = {
firstName: result.localPatron.firstname,
lastName: result.localPatron.surname,
dateOfBirth: result.localPatron.dateofbirth,
guarantorname: result.localPatron.guarantorname,
guarantoremail: result.localPatron.guarantoremail,
guarantormobile: result.localPatron.guarantormobile,
borrowernumber: result.localPatron.borrowernumber,
notFinishedSelfRegistration: !result.localPatron.password
};
response.status(200).send(borrower);
}
}
response.status(404).send();
} catch (error) {
logger.error("Unable to check if existing user", error);
response.status(404).send();
}
});
// Check if user exists
async function checkIfExistingUser(userId, jwtToken) {
const kohaExistingUsersUrl = "http://koha:8082/api/patrons/checkexisting";
......@@ -348,53 +263,6 @@ routes.post("/checkforexistinguser", async (request, response) => {
response.status(200).send(existingUser);
});
// Initiate by superuser/librarian. Meaning that ID is verified.
routes.post("/initbyemployee", async (request, response) => {
const deichmanCallId = request.headers[CALL_ID_HEADER];
const jwtToken = request.session.jwt_token;
try {
const kohaPatron = await initPatronRegistration(
{
cardnumber: request.body.cardnumber,
categorycode: request.body.categorycode,
dateofbirth: request.body.dateofbirth,
email: request.body.email,
firstname: request.body.firstname,
guarantoremail: request.body.guarantoremail,
guarantormobile: request.body.guarantormobile,
guarantorname: request.body.guarantorname,
mobile: request.body.mobile,
ssn: request.body.ssn,
surname: request.body.surname,
useKrrDetails: request.body.useKrrDetails === "true" ? 1 : 0,
userHasNoEmail: request.body.userHasNoEmail ? 1 : 0
},
true,
jwtToken,
deichmanCallId
);
response.status(201).send(kohaPatron);
} catch (error) {
if (error instanceof KohaError) {
logger.error(
`ERROR register user from desk ${
request.body.email
}, init patron request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(error.status).json({ error: "Call to core failed." });
} else {
logger.warn(
`WARN register user from desk ${
request.body.email
}, init patron request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(500).json({ error: "Unhandled failure in middleware." });
}
}
});
// Initiate child registration
routes.post("/child", async (request, response) => {
......@@ -430,41 +298,6 @@ routes.post("/child", async (request, response) => {
}
});
// finalize child registration
routes.post("/child-finalize", async (request, response) => {
const deichmanCallId = request.headers[CALL_ID_HEADER];
const jwtToken = request.session.jwt_token;
try {
await finalizechildfromweb(
{
borrowernumber: request.body.borrowernumber,
firstname: request.body.firstname,
surname: request.body.surname,
dateofbirth: request.body.dateofbirth,
cardnumber: request.body.cardnumber
},
jwtToken,
deichmanCallId
);
response.sendStatus(201);
} catch (error) {
if (error instanceof KohaError) {
logger.error(
`ERROR finalize child from web, request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(error.status).json({ error: "Call to core failed." });
} else {
logger.warn(
`WARN finalize child from web, request is rejected: ${error}`,
{ ...error, call_id: deichmanCallId }
);
response.status(500).json({ error: "Unhandled failure in middleware." });
}
}
});
// Get info via UUID
routes.get("/selfregister/:uuid", async (request, response) => {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment