67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import {NextApiRequest, NextApiResponse} from "next";
|
|
import {createUserWithEmailAndPassword, getAuth, sendPasswordResetEmail} from "firebase/auth";
|
|
import {app} from "@/firebase";
|
|
import {sessionOptions} from "@/lib/session";
|
|
import {withIronSessionApiRoute} from "iron-session/next";
|
|
import {getFirestore, getDoc, doc, setDoc, deleteDoc} from "firebase/firestore";
|
|
import {DemographicInformation, Type} from "@/interfaces/user";
|
|
|
|
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 codeRef = await getDoc(doc(db, "codes", code));
|
|
if (!codeRef.exists()) {
|
|
res.status(400).json({error: "Invalid Code!"});
|
|
return;
|
|
}
|
|
|
|
const codeData = codeRef.data() as {code: string; type: Type};
|
|
|
|
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,
|
|
};
|
|
|
|
await setDoc(doc(db, "users", userId), user);
|
|
await deleteDoc(codeRef.ref);
|
|
|
|
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});
|
|
});
|
|
}
|