Fully implemented the register flow
This commit is contained in:
48
src/pages/api/register.ts
Normal file
48
src/pages/api/register.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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, getDoc, doc, setDoc} from "firebase/firestore";
|
||||
|
||||
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} = req.body as {email: string; password: string};
|
||||
|
||||
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: true};
|
||||
|
||||
await setDoc(doc(db, "users", userId), user);
|
||||
|
||||
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});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user