- Updated the colors of the application;
- Added the ability for a user to partially update their profile
This commit is contained in:
@@ -5,8 +5,13 @@ import {getFirestore, collection, getDocs, getDoc, doc, setDoc} from "firebase/f
|
||||
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";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const storage = getStorage(app);
|
||||
const auth = getAuth(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -17,7 +22,45 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
}
|
||||
|
||||
const userRef = doc(db, "users", req.session.user.id);
|
||||
await setDoc(userRef, req.body, {merge: true});
|
||||
const updatedUser = req.body as User & {password?: string; newPassword?: string};
|
||||
|
||||
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, "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});
|
||||
req.session.user = {...updatedUser, id: req.session.user.id};
|
||||
await req.session.save();
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user