diff --git a/src/controller/account.ts b/src/controller/account.ts new file mode 100644 index 0000000..8b1d34d --- /dev/null +++ b/src/controller/account.ts @@ -0,0 +1,49 @@ +import { Account } from "../models/Account"; +import { genSalt, hash } from "bcrypt"; +import { sendMail } from "@utils/email"; +import { Types } from "mongoose"; +import { encryptClearField } from "@utils/decryption"; + +export const sendVerificationEmail = async (email: string, code: number, id: string) => { + sendMail({ + to: email, + subject: "LicenseAPI Verifizierungscode", + text: `Dein LicenseAPI Code: ${code}. Deine User-ID: ${id}`, + }); +}; + +export const createAccount = async (configuration: { username: string, email: string, password: string }) => { + const account = await Account.findOne().or([{ username: encryptClearField(configuration.username) }, { + email: encryptClearField(configuration.email), + verified: true, + }]); + + if (account !== null) return { code: 1001, message: "This account already exists" }; + + // Hash the password + const salt = await genSalt(10); + const password = await hash(configuration.password, salt); + + // Create the account + const created = await Account.create({ ...configuration, password }); + + // Send the email + await sendVerificationEmail(configuration.email, created.verificationSecret || 0, created._id.toString()); +}; + +export const verifyAccount = async (configuration: { id: string, code: number }) => { + if (!Types.ObjectId.isValid(configuration.id)) return { code: 3, message: "Invalid object id provided" }; + + const account = await Account.findById(configuration.id); + + if (account === null) return { code: 1002, message: "The provided account does not exist" }; + + if (account.verified) return { code: 1003, message: "The provided account is already verified" } + + if (account.verificationSecret !== configuration.code) return { + code: 1003, + message: "The provided verification secret is wrong", + }; + + await Account.findByIdAndUpdate(configuration.id, {verified: true, $unset: {verificationSecret: 1}}); +}; \ No newline at end of file