73 lines
2.2 KiB
TypeScript
73 lines
2.2 KiB
TypeScript
import {NextApiRequest, NextApiResponse} from "next";
|
|
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";
|
|
import {app} from "@/firebase";
|
|
import {sessionOptions} from "@/lib/session";
|
|
import {withIronSessionApiRoute} from "iron-session/next";
|
|
import {getFirestore, doc, setDoc, query, collection, where, getDocs} from "firebase/firestore";
|
|
import {DemographicInformation, Type} from "@/interfaces/user";
|
|
import {addUserToGroupOnCreation} from "@/utils/registration";
|
|
|
|
const auth = getAuth(app);
|
|
const db = getFirestore(app);
|
|
|
|
export default withIronSessionApiRoute(login, sessionOptions);
|
|
|
|
const DEFAULT_DESIRED_LEVELS = {
|
|
reading: 9,
|
|
listening: 9,
|
|
writing: 9,
|
|
speaking: 9,
|
|
};
|
|
|
|
const DEFAULT_LEVELS = {
|
|
reading: 0,
|
|
listening: 0,
|
|
writing: 0,
|
|
speaking: 0,
|
|
};
|
|
|
|
async function login(req: NextApiRequest, res: NextApiResponse) {
|
|
const {email, password, code} = req.body as {email: string; password: string; code: string; demographicInformation: DemographicInformation};
|
|
|
|
const codeQuery = query(collection(db, "codes"), where("code", "==", code));
|
|
const codeDocs = (await getDocs(codeQuery)).docs.filter((x) => !Object.keys(x.data()).includes("userId"));
|
|
|
|
if (codeDocs.length === 0) {
|
|
res.status(400).json({error: "Invalid Code!"});
|
|
return;
|
|
}
|
|
|
|
const codeData = codeDocs[0].data() as {code: string; type: Type; creator?: string; expiryDate: Date | null};
|
|
|
|
createUserWithEmailAndPassword(auth, email, password)
|
|
.then(async (userCredentials) => {
|
|
const userId = userCredentials.user.uid;
|
|
delete req.body.password;
|
|
|
|
const user = {
|
|
...req.body,
|
|
desiredLevels: DEFAULT_DESIRED_LEVELS,
|
|
levels: DEFAULT_LEVELS,
|
|
bio: "",
|
|
isFirstLogin: codeData.type === "student",
|
|
focus: "academic",
|
|
type: codeData.type,
|
|
subscriptionExpirationDate: codeData.expiryDate,
|
|
registrationDate: new Date(),
|
|
};
|
|
|
|
await setDoc(doc(db, "users", userId), user);
|
|
await setDoc(codeDocs[0].ref, {userId: userId}, {merge: true});
|
|
if (codeData.creator) await addUserToGroupOnCreation(userId, codeData.type, codeData.creator);
|
|
|
|
req.session.user = {...user, id: userId};
|
|
await req.session.save();
|
|
|
|
res.status(200).json({user: {...user, id: userId}});
|
|
})
|
|
.catch((error) => {
|
|
console.log(error);
|
|
res.status(401).json({error});
|
|
});
|
|
}
|