Implemented a simple authentication scheme with Firebase and Iron Session
This commit is contained in:
38
src/pages/api/login.ts
Normal file
38
src/pages/api/login.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import {NextApiRequest, NextApiResponse} from "next";
|
||||
import {getAuth, signInWithEmailAndPassword} from "firebase/auth";
|
||||
import {app} from "@/firebase";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {User} from "@/interfaces/user";
|
||||
import {getFirestore, getDoc, doc} from "firebase/firestore";
|
||||
|
||||
const auth = getAuth(app);
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(login, sessionOptions);
|
||||
|
||||
async function login(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {email, password} = req.body as {email: string; password: string};
|
||||
|
||||
signInWithEmailAndPassword(auth, email, password)
|
||||
.then(async (userCredentials) => {
|
||||
const userId = userCredentials.user.uid;
|
||||
|
||||
const docUser = await getDoc(doc(db, "users", userId));
|
||||
if (!docUser.exists()) {
|
||||
res.status(401).json({error: 401, message: "User does not exist!"});
|
||||
return;
|
||||
}
|
||||
|
||||
const user = docUser.data() as User;
|
||||
|
||||
req.session.user = user;
|
||||
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