139 lines
4.7 KiB
TypeScript
139 lines
4.7 KiB
TypeScript
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
|
import type {NextApiRequest, NextApiResponse} from "next";
|
|
import {app} from "@/firebase";
|
|
import {getFirestore, collection, getDocs, getDoc, doc, setDoc, query, where} from "firebase/firestore";
|
|
import {withIronSessionApiRoute} from "iron-session/next";
|
|
import {sessionOptions} from "@/lib/session";
|
|
import {User} from "@/interfaces/user";
|
|
import {getDownloadURL, getStorage, ref, uploadBytes} from "firebase/storage";
|
|
import {getAuth, signInWithEmailAndPassword, updateEmail, updatePassword} from "firebase/auth";
|
|
import {errorMessages} from "@/constants/errors";
|
|
import moment from "moment";
|
|
import ShortUniqueId from "short-unique-id";
|
|
import {Payment} from "@/interfaces/paypal";
|
|
|
|
const db = getFirestore(app);
|
|
const storage = getStorage(app);
|
|
const auth = getAuth(app);
|
|
|
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
|
|
|
const addPaymentRecord = async (data: Payment) => {
|
|
const shortUID = new ShortUniqueId();
|
|
await setDoc(doc(db, "payments", shortUID.randomUUID(8)), data);
|
|
}
|
|
const managePaymentRecords = async (user: User, userId: string | undefined): Promise<boolean> => {
|
|
try {
|
|
if(user.type === 'corporate' && userId) {
|
|
const data = {
|
|
corporate: userId,
|
|
agent: user.corporateInformation.referralAgent,
|
|
agentCommission: user.corporateInformation.payment!.commission,
|
|
agentValue: (user.corporateInformation.payment!.commission / 100) * user.corporateInformation.payment!.value,
|
|
currency: user.corporateInformation.payment!.currency,
|
|
value: user.corporateInformation.payment!.value,
|
|
isPaid: false,
|
|
date: new Date(),
|
|
} as Payment;
|
|
|
|
const corporatePayments = await getDocs(query(collection(db, "payments"), where("corporate", "==", userId)));
|
|
if(corporatePayments.docs.length === 0) {
|
|
await addPaymentRecord(data);
|
|
return true;
|
|
}
|
|
|
|
const hasPaymentPaidAndExpiring = corporatePayments.docs.filter((doc) => {
|
|
const data = doc.data();
|
|
return data.isPaid
|
|
&& moment().isAfter(moment(user.subscriptionExpirationDate).subtract(30, "days"))
|
|
&& moment().isBefore(moment(user.subscriptionExpirationDate));
|
|
});
|
|
|
|
if(hasPaymentPaidAndExpiring.length > 0) {
|
|
await addPaymentRecord(data);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
} catch(e) {
|
|
// if this process fails it should not stop the rest of the process
|
|
console.log(e);
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
res.status(401).json({ok: false});
|
|
return;
|
|
}
|
|
|
|
const userRef = doc(db, "users", req.query.id ? (req.query.id as string) : req.session.user.id);
|
|
const updatedUser = req.body as User & {password?: string; newPassword?: string};
|
|
|
|
if (!!req.query.id) {
|
|
const user = await setDoc(userRef, updatedUser, {merge: true});
|
|
await managePaymentRecords(updatedUser, updatedUser.id);
|
|
res.status(200).json({ok: true});
|
|
return;
|
|
}
|
|
|
|
if (updatedUser.profilePicture && updatedUser.profilePicture !== req.session.user.profilePicture) {
|
|
const profilePictureFiletype = updatedUser.profilePicture.split(";")[0].split("/")[1];
|
|
const profilePictureRef = ref(storage, `profile_pictures/${req.session.user.id}.${profilePictureFiletype}`);
|
|
|
|
const pictureBytes = Buffer.from(updatedUser.profilePicture.split(";base64,")[1], "base64url");
|
|
const pictureSnapshot = await uploadBytes(profilePictureRef, pictureBytes);
|
|
|
|
const pictureReference = ref(storage, pictureSnapshot.metadata.fullPath);
|
|
updatedUser.profilePicture = await getDownloadURL(pictureReference);
|
|
}
|
|
|
|
if (updatedUser.newPassword && updatedUser.password) {
|
|
try {
|
|
const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
|
|
await updatePassword(credential.user, updatedUser.newPassword);
|
|
} catch {
|
|
res.status(400).json({error: "E001", message: errorMessages.E001});
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (updatedUser.email !== req.session.user.email && updatedUser.password) {
|
|
try {
|
|
const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
|
|
await updateEmail(credential.user, updatedUser.email);
|
|
} catch {
|
|
res.status(400).json({error: "E002", message: errorMessages.E002});
|
|
return;
|
|
}
|
|
}
|
|
|
|
delete updatedUser.password;
|
|
delete updatedUser.newPassword;
|
|
|
|
await setDoc(userRef, updatedUser, {merge: true});
|
|
|
|
const docUser = await getDoc(doc(db, "users", req.session.user.id));
|
|
const user = docUser.data() as User;
|
|
|
|
if (!req.query.id) {
|
|
req.session.user = {...user, id: req.session.user.id};
|
|
await req.session.save();
|
|
}
|
|
|
|
await managePaymentRecords(user, req.query.id);
|
|
|
|
res.status(200).json({user});
|
|
}
|
|
|
|
export const config = {
|
|
api: {
|
|
bodyParser: {
|
|
sizeLimit: "20mb",
|
|
},
|
|
},
|
|
};
|