From 078ed46ec2c065e7bea869737ddb8d8644a723cb Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Thu, 3 Aug 2023 23:36:34 +0200 Subject: [PATCH] Created the validation.ts controller --- src/controller/validation.ts | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/controller/validation.ts diff --git a/src/controller/validation.ts b/src/controller/validation.ts new file mode 100644 index 0000000..5f264f6 --- /dev/null +++ b/src/controller/validation.ts @@ -0,0 +1,43 @@ +import { Project } from "@models/Project"; +import { encryptClearField } from "@utils/decryption"; +import { License } from "@models/License"; +import { mapLicense } from "@controller/license"; +import { Group } from "@models/Group"; +import { Permission } from "@models/Permission"; + +enum ResponseStatus { + VALID = "VALID", + EXPIRED = "EXPIRED", + INVALID = "INVALID", + INVALID_KEY = "INVALID_KEY", + MAX_USES_REACHED = "MAX_USES_REACHED" +} + +export const validateLicense = async (validationKey: string, licenseKey: string) => { + const project = await Project.findOne({ validationKey: encryptClearField(validationKey) }); + if (project === null) return { status: ResponseStatus.INVALID_KEY, message: "The provided validation key is invalid" }; + + const license = await License.findOne({ projectId: encryptClearField(String(project.id)), key: encryptClearField(licenseKey) }); + if (license === null) return { status: ResponseStatus.INVALID, message: "The provided license key is invalid" }; + + if (license.expirationDate && license.expirationDate < new Date()) + return { status: ResponseStatus.EXPIRED, message: "The provided license key has expired" }; + + if (license.maxUses && license.maxUses !== -1 && license.maxUses <= license.currentUses) + return { status: ResponseStatus.MAX_USES_REACHED, message: "The provided license key has reached its maximum uses" }; + + const licenseData = await mapLicense(String(project.id), license, true); + + if (license.groups) { + const groups = await Group.find({ _id: { $in: license.groups }}); + + for (const group of groups) { + const permissions = await Permission.find({ _id: { $in: group.permissions }}); + licenseData.permissions.push(...permissions.map(permission => permission.permission)); + } + } + + await License.updateOne({ _id: license.id }, { currentUses: license.currentUses + 1 }); + + return { status: ResponseStatus.VALID, license: licenseData }; +} \ No newline at end of file