Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new endpoints #69

Merged
merged 4 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 16 additions & 13 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ module.exports = {
jwksUri: process.env.AZUREAD_JWK_URI,
issuer: process.env.AZUREAD_ISSUER_URI,
audience: process.env.AZUREAD_CLIENTID
},
AZUREAD_ALLOWEDGROUPS: process.env.AZUREAD_ALLOWEDGROUPS,
APIKEYS: process.env.APIKEYS,
APIKEYS_MINIMUM_LENGTH: process.env.APIKEYS_MINIMUM_LENGTH || 24,
AZURE_BLOB_CONNECTIONSTRING: process.env.AZURE_BLOB_CONNECTIONSTRING,
AZURE_BLOB_CONTAINERNAME: process.env.AZURE_BLOB_CONTAINERNAME,
BYPASS_REGISTRATION_THRESHOLD: process.env.BYPASS_REGISTRATION_THRESHOLD,
VTFK_MATRIKKELPROXY_BASEURL: process.env.VTFK_MATRIKKELPROXY_BASEURL,
VTFK_MATRIKKELPROXY_APIKEY: process.env.VTFK_MATRIKKELPROXY_APIKEY,
VTFK_PDFGENERATOR_ENDPOINT: process.env.VTFK_PDFGENERATOR_ENDPOINT,
VTFK_P360_ARCHIVE_ENDPOINT: process.env.VTFK_P360_ARCHIVE_ENDPOINT,
VTFK_P360_ARCHIVE_SUBSCRIPTION_KEY: process.env.VTFK_P360_ARCHIVE_SUBSCRIPTION_KEY
}
},
AZUREAD_ALLOWEDGROUPS: process.env.AZUREAD_ALLOWEDGROUPS,
APIKEYS: process.env.APIKEYS,
APIKEYS_MINIMUM_LENGTH: process.env.APIKEYS_MINIMUM_LENGTH || 24,
AZURE_BLOB_CONNECTIONSTRING: process.env.AZURE_BLOB_CONNECTIONSTRING,
AZURE_BLOB_CONTAINERNAME: process.env.AZURE_BLOB_CONTAINERNAME,
BYPASS_REGISTRATION_THRESHOLD: process.env.BYPASS_REGISTRATION_THRESHOLD,
VTFK_MATRIKKELPROXY_BASEURL: process.env.VTFK_MATRIKKELPROXY_BASEURL,
VTFK_MATRIKKELPROXY_APIKEY: process.env.VTFK_MATRIKKELPROXY_APIKEY,
VTFK_PDFGENERATOR_ENDPOINT: process.env.VTFK_PDFGENERATOR_ENDPOINT,
VTFK_P360_ARCHIVE_ENDPOINT: process.env.VTFK_P360_ARCHIVE_ENDPOINT,
VTFK_P360_ARCHIVE_SUBSCRIPTION_KEY: process.env.VTFK_P360_ARCHIVE_SUBSCRIPTION_KEY,
VTFK_STATISTICS_KEY: process.env.VTFK_STATISTICS_KEY,
VTFK_STATISTICS_URL: process.env.VTFK_STATISTICS_URL,
TEAMS_WEBHOOK_URL: process.env.TEAMS_WEBHOOK_URL
}
34 changes: 17 additions & 17 deletions func-completedispatch/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
const Dispatches = require('../sharedcode/models/dispatches.js')
const getDb = require('../sharedcode/connections/masseutsendelseDB.js');
const HTTPError = require('../sharedcode/vtfk-errors/httperror');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');
const getDb = require('../sharedcode/connections/masseutsendelseDB.js')
const HTTPError = require('../sharedcode/vtfk-errors/httperror')
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')

module.exports = async function (context, req) {
try {
// Get the ID from the request
// Get the ID from the request
const id = context.bindingData.id
if(!id) throw new HTTPError(400, 'You cannot complete a dispatch without providing an id');
if (!id) throw new HTTPError(400, 'You cannot complete a dispatch without providing an id')

// Authentication / Authorization
const requestor = await require('../sharedcode/auth/auth').auth(req);
const requestor = await require('../sharedcode/auth/auth').auth(req)

// Await the DB conection
// Await the DB conection
await getDb()

// Get the existing disptach object
let existingDispatch = await Dispatches.findById(id).lean()
if(!existingDispatch) throw new HTTPError(404, `Dispatch with id ${id} could not be found`)
if(existingDispatch.status !== 'approved') throw new HTTPError(404, `Cannot complete a dispatch that is not approved`)
// Get the existing disptach object
const existingDispatch = await Dispatches.findById(id).lean()
if (!existingDispatch) throw new HTTPError(404, `Dispatch with id ${id} could not be found`)
if (existingDispatch.status !== 'approved') throw new HTTPError(404, 'Cannot complete a dispatch that is not approved')

// Set completed information
let completedData = {
const completedData = {
status: 'completed',
owners: [],
excludedOwners: [],
Expand All @@ -32,13 +32,13 @@ module.exports = async function (context, req) {
modifiedByDepartment: requestor.department,
modifiedById: requestor.id
}
if(req.body?.e18Id) completedData.e18Id = req.body.e18Id;
if (req.body?.e18Id) completedData.e18Id = req.body.e18Id

// Update the dispatch
const updatedDispatch = await Dispatches.findByIdAndUpdate(id, completedData, { new: true })

// Update the dispatch
const updatedDispatch = await Dispatches.findByIdAndUpdate(id, completedData, { new: true})

return await azfHandleResponse(updatedDispatch, context, req)
} catch (err) {
return await azfHandleError(err, context, req)
}
}
}
116 changes: 58 additions & 58 deletions func-editdispatches/index.js
Original file line number Diff line number Diff line change
@@ -1,102 +1,102 @@
const Dispatches = require('../sharedcode/models/dispatches.js')
const getDb = require('../sharedcode/connections/masseutsendelseDB.js');
const utils = require('@vtfk/utilities');
const HTTPError = require('../sharedcode/vtfk-errors/httperror');
const validate = require('../sharedcode/validators/dispatches').validate;
const blobClient = require('@vtfk/azure-blob-client');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');

module.exports = async function (context, req) {
const Dispatches = require('../sharedcode/models/dispatches.js')
const getDb = require('../sharedcode/connections/masseutsendelseDB.js')
const utils = require('@vtfk/utilities')
const HTTPError = require('../sharedcode/vtfk-errors/httperror')
const validate = require('../sharedcode/validators/dispatches').validate
const blobClient = require('@vtfk/azure-blob-client')
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')

module.exports = async function (context, req) {
try {
// Strip away som fields that should not bed set by the request.
req.body = utils.removeKeys(req.body, ['validatedArchivenumber', 'createdTimestamp', 'createdBy', 'createdById', 'createdByDepartment', 'modifiedTimestamp', 'modifiedBy', 'modifiedById', 'modifiedByDepartment']);
delete req.body._id;
req.body = utils.removeKeys(req.body, ['validatedArchivenumber', 'createdTimestamp', 'createdBy', 'createdById', 'createdByDepartment', 'modifiedTimestamp', 'modifiedBy', 'modifiedById', 'modifiedByDepartment'])
delete req.body._id

// Authentication / Authorization
const requestor = await require('../sharedcode/auth/auth').auth(req);
const requestor = await require('../sharedcode/auth/auth').auth(req)

// Update modified by
req.body.modifiedBy = requestor.name;
req.body.modifiedById = requestor.id;
req.body.modifiedTimestamp = new Date();
req.body.modifiedByEmail = requestor.email;
req.body.modifiedByDepartment = requestor.department;
req.body.modifiedBy = requestor.name
req.body.modifiedById = requestor.id
req.body.modifiedTimestamp = new Date()
req.body.modifiedByEmail = requestor.email
req.body.modifiedByDepartment = requestor.department

// Figure out if any items should be unset
let unsets = {};
if(Object.keys(req.body).length === 2 && !req.body.template) unsets.template = 1;
if(req.body.attachments && !req.body.template) unsets.template = 1;
const unsets = {}
if (Object.keys(req.body).length === 2 && !req.body.template) unsets.template = 1
if (req.body.attachments && !req.body.template) unsets.template = 1

// Get ID from request
const id = context.bindingData.id
// Await the Db conection

// Await the Db conection
await getDb()

// Get the existing disptach object
let existingDispatch = await Dispatches.findById(id).lean()
if(!existingDispatch) throw new HTTPError(404, `Dispatch with id ${id} could not be found` )
// Get the existing disptach object
const existingDispatch = await Dispatches.findById(id).lean()
if (!existingDispatch) throw new HTTPError(404, `Dispatch with id ${id} could not be found`)

// If the status is running or completed, only status is allowed to be updated
if(existingDispatch.status === 'inprogress' && req.body.status !== 'completed') throw new HTTPError(400, 'No changes can be done to a running dispatch except setting it to completed');
if(existingDispatch.status === 'inprogress' && req.body.status === 'completed') {
const result = await Dispatches.findByIdAndUpdate(id, { status: 'completed' }, { new: true});
if (existingDispatch.status === 'inprogress' && req.body.status !== 'completed') throw new HTTPError(400, 'No changes can be done to a running dispatch except setting it to completed')
if (existingDispatch.status === 'inprogress' && req.body.status === 'completed') {
const result = await Dispatches.findByIdAndUpdate(id, { status: 'completed' }, { new: true })
return context.res.status(201).send(result)
}
// Failsafe
if(existingDispatch.status === 'inprogress' || existingDispatch.status === 'completed') throw new HTTPError(400, 'No changes can be done to running or completed dispatches');
if (existingDispatch.status === 'inprogress' || existingDispatch.status === 'completed') throw new HTTPError(400, 'No changes can be done to running or completed dispatches')

// Update fields
req.body.validatedArchivenumber = existingDispatch.validatedArchivenumber;
req.body.validatedArchivenumber = existingDispatch.validatedArchivenumber

// Set approval information
if(existingDispatch.status === 'notapproved' && req.body.status === 'approved') {
req.body.approvedBy = requestor.name;
req.body.approvedById = requestor.id;
req.body.approvedByEmail = requestor.email;
req.body.approvedTimestamp = new Date();
if (existingDispatch.status === 'notapproved' && req.body.status === 'approved') {
req.body.approvedBy = requestor.name
req.body.approvedById = requestor.id
req.body.approvedByEmail = requestor.email
req.body.approvedTimestamp = new Date()
}
if(req.body.status === 'notapproved') {
req.body.approvedBy = '';
req.body.approvedById = '';
req.body.approvedTimestamp = '';
if (req.body.status === 'notapproved') {
req.body.approvedBy = ''
req.body.approvedById = ''
req.body.approvedTimestamp = ''
}

// Validate dispatch against schenarios that cannot be described by schema
// const toValidate = {...existingDispatch, ...req.body}
await validate(req.body);
req.body.validatedArchivenumber = req.body.archivenumber;
await validate(req.body)
req.body.validatedArchivenumber = req.body.archivenumber

// Validate attachments
const allowedExtensions = ['pdf', 'xlsx', 'xls', 'rtf', 'msg', 'ppt', 'pptx', 'docx', 'doc', 'png', 'jpg', 'jpeg'];
if(req.body.attachments && Array.isArray(req.body.attachments) && req.body.attachments.length > 0) {
const allowedExtensions = ['pdf', 'xlsx', 'xls', 'rtf', 'msg', 'ppt', 'pptx', 'docx', 'doc', 'png', 'jpg', 'jpeg']
if (req.body.attachments && Array.isArray(req.body.attachments) && req.body.attachments.length > 0) {
req.body.attachments.forEach((i) => {
const split = i.name.split('.');
if(split.length === 1) throw new HTTPError(400, 'All filenames must have an extension')
const extension = split[split.length - 1];
if(!allowedExtensions.includes(extension.toLowerCase())) throw new HTTPError(400, `The file extension ${extension} is not allowed`);
const split = i.name.split('.')
if (split.length === 1) throw new HTTPError(400, 'All filenames must have an extension')
const extension = split[split.length - 1]
if (!allowedExtensions.includes(extension.toLowerCase())) throw new HTTPError(400, `The file extension ${extension} is not allowed`)
blobClient.unallowedPathCharacters.forEach((char) => {
if(i.name.includes(char)) throw new HTTPError(400, `${i} cannot contain illegal character ${char}`);
if (i.name.includes(char)) throw new HTTPError(400, `${i} cannot contain illegal character ${char}`)
})
})
}

// Update the dispatch
const updatedDispatch = await Dispatches.findByIdAndUpdate(id, { ...req.body, $unset: unsets }, { new: true})
// Update the dispatch
const updatedDispatch = await Dispatches.findByIdAndUpdate(id, { ...req.body, $unset: unsets }, { new: true })

// Figure out the names of existing and requested attachments
const existingNames = existingDispatch.attachments ? existingDispatch.attachments.map((i) => i.name) : [];
const requestNames = req.body.attachments ? req.body.attachments.map((i) => i.name) : [];
const existingNames = existingDispatch.attachments ? existingDispatch.attachments.map((i) => i.name) : []
const requestNames = req.body.attachments ? req.body.attachments.map((i) => i.name) : []

// Check for attachments to add
if(req.body.attachments) {
const attachmentsToAdd = req.body.attachments.filter((i) => !existingNames.includes(i.name) || i.data);
const attachmentsToRemove = existingNames.filter((i) => !requestNames.includes(i));
if (req.body.attachments) {
const attachmentsToAdd = req.body.attachments.filter((i) => !existingNames.includes(i.name) || i.data)
const attachmentsToRemove = existingNames.filter((i) => !requestNames.includes(i))

// Upload attachments if applicable
if(process.env.NODE_ENV !== 'test') attachmentsToAdd.forEach(async (i) => { await blobClient.save(`${id}/${i.name}`, i.data); })
if (process.env.NODE_ENV !== 'test') attachmentsToAdd.forEach(async (i) => { await blobClient.save(`${id}/${i.name}`, i.data) })
// Remove attachments if applicable
if(process.env.NODE_ENV !== 'test') attachmentsToRemove.forEach(async (i) => { await blobClient.remove(`${id}/${i}`); })
if (process.env.NODE_ENV !== 'test') attachmentsToRemove.forEach(async (i) => { await blobClient.remove(`${id}/${i}`) })
}

// Return the dispatch
Expand Down
10 changes: 5 additions & 5 deletions func-getBrreg/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');
const axios = require('axios');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')
const axios = require('axios')

module.exports = async function (context, req) {
try {
// Authentication / Authorization
await require('../sharedcode/auth/auth').auth(req);
await require('../sharedcode/auth/auth').auth(req)

// Get ID from request
const id = context.bindingData.id
if(!id) throw new HTTPError(400, 'No dispatch id was provided');
if (!id) throw new HTTPError(400, 'No dispatch id was provided')

// Make the request
const response = await axios.get(`https://data.brreg.no/enhetsregisteret/api/enheter/${id}`);
const response = await axios.get(`https://data.brreg.no/enhetsregisteret/api/enheter/${id}`)

// Return the brreg info
return await azfHandleResponse(response.data, context, req)
Expand Down
20 changes: 10 additions & 10 deletions func-getblob/index.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
const HTTPError = require('../sharedcode/vtfk-errors/httperror')
const blobClient = require('@vtfk/azure-blob-client');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');
const blobClient = require('@vtfk/azure-blob-client')
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')

module.exports = async function (context, req) {
try {
// Authentication / Authorization
await require('../sharedcode/auth/auth').auth(req);
await require('../sharedcode/auth/auth').auth(req)

// Input validation
if (!context.bindingData.id) throw new HTTPError(400, 'dispatchId must be specified');
if (!context.bindingData.name) throw new HTTPError(400, 'name must be specified');
if (!context.bindingData.id) throw new HTTPError(400, 'dispatchId must be specified')
if (!context.bindingData.name) throw new HTTPError(400, 'name must be specified')

// Retreive the file
let file = ''
if(process.env.NODE_ENV !== 'test') {
if (process.env.NODE_ENV !== 'test') {
file = await blobClient.get(`${context.bindingData.id}/${context.bindingData.name}`)
if (!file || !file.data) throw new HTTPError(404, 'No files found, check if you passed the right filename and/or the right dispatchId')
} else {
file = context.bindingData.file
if(!context.bindingData.file) throw new HTTPError(400, 'No Files found')
if (!context.bindingData.file) throw new HTTPError(400, 'No Files found')
}

// Return the file
return await azfHandleResponse(file, context, req)
} catch (err) {
return await azfHandleError(err, context, req)
}
}
}
10 changes: 5 additions & 5 deletions func-getdispatches/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
const Dispatches = require('../sharedcode/models/dispatches.js')
const getDb = require('../sharedcode/connections/masseutsendelseDB.js')
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')

module.exports = async function (context, req) {
try {
// Authentication / Authorization
await require('../sharedcode/auth/auth').auth(req);
await require('../sharedcode/auth/auth').auth(req)

// Await the DB connection
// Await the DB connection
await getDb()

// Find all disptaches
let dispatches = [];
let dispatches = []
if (req.query?.full === true || req.query?.full === 'true') dispatches = await Dispatches.find({})
else dispatches = await Dispatches.find({}).select('-owners -excludedOwners -matrikkelUnitsWithoutOwners')

// If no dispatches was found
if (!dispatches) dispatches = [];
if (!dispatches) dispatches = []

// Return the disptaches
return await azfHandleResponse(dispatches, context, req)
Expand Down
19 changes: 9 additions & 10 deletions func-getdispatchesbyid/index.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
const Dispatches = require('../sharedcode/models/dispatches.js')
const getDb = require('../sharedcode/connections/masseutsendelseDB.js')
const HTTPError = require('../sharedcode/vtfk-errors/httperror');
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers');

const HTTPError = require('../sharedcode/vtfk-errors/httperror')
const { azfHandleResponse, azfHandleError } = require('@vtfk/responsehandlers')

module.exports = async function (context, req) {
try {
// Authentication / Authorization
await require('../sharedcode/auth/auth').auth(req);
await require('../sharedcode/auth/auth').auth(req)

// Get ID from request
const id = context.bindingData.id
if(!id) throw new HTTPError(400, 'No dispatch id was provided');
if (!id) throw new HTTPError(400, 'No dispatch id was provided')

// Await the database
await getDb()

//Find Dispatch by ID
let disptach = await Dispatches.findById(id)
// Find Dispatch by ID
const disptach = await Dispatches.findById(id)
if (!disptach) throw new HTTPError(404, `Disptach with id ${id} could no be found`)

//Return the dispatch object
let disptachById = await Dispatches.findById(id, req.body, { new: true })
// Return the dispatch object
const disptachById = await Dispatches.findById(id, req.body, { new: true })

return await azfHandleResponse(disptachById, context, req)
} catch (err) {
return await azfHandleError(err, context, req)
Expand Down
10 changes: 10 additions & 0 deletions func-gethandlejobs/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */10 * * * *"
}
]
}
Loading
Loading