Skip to content

Commit

Permalink
Log in with Google (#243)
Browse files Browse the repository at this point in the history
* finish login with google

* simplify /users/googleCreate endpoint logic

* Improve error handling

* simplify login with google

* Format

* Remove inaccessible error messages

* Rename endpoint

---------

Co-authored-by: Akinfolami Akin-Alamu <aoa9@cornell.edu>
Co-authored-by: Jason Zheng <jasonz4200@gmail.com>
  • Loading branch information
3 people authored Jun 15, 2024
1 parent 2e0dc2f commit 66ca706
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 5 deletions.
26 changes: 26 additions & 0 deletions backend/src/users/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ userRouter.post(
}
);

userRouter.post(
"/google",
NoAuth as RequestHandler,
async (req: Request, res: Response) => {
// #swagger.tags = ['Users']
socketNotify("/users");
const { ...rest } = req.body;
try {
await firebase.auth().setCustomUserClaims(rest.id, {
admin: false,
supervisor: false,
volunteer: true,
});
const user = await userController.createUser(
rest,
rest.profile,
rest.preferences,
rest.permissions
);
return res.status(200).send({ success: true, user: user });
} catch (e: any) {
return res.status(500).send({ success: false, error: e.message });
}
}
);

userRouter.delete("/:userid", useAuth, async (req: Request, res: Response) => {
// #swagger.tags = ['Users']
await admin.auth().deleteUser(req.params.userid);
Expand Down
78 changes: 73 additions & 5 deletions frontend/src/components/organisms/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import {
useSignInWithGoogle,
} from "react-firebase-hooks/auth";
import Snackbar from "../atoms/Snackbar";
import { GoogleAuthProvider, User, signInWithPopup } from "firebase/auth";
import { api } from "@/utils/api";
import { useMutation } from "@tanstack/react-query";
import Loading from "../molecules/Loading";

export type FormValues = {
email: string;
Expand Down Expand Up @@ -108,9 +112,75 @@ const LoginForm = () => {
}
}, [signInErrors]);

/** Tanstack query mutation to create a new user */
const { mutateAsync: createLocalUserFromGoogle, isPending: googleLoading } =
useMutation({
mutationFn: async (data: {
userid: string;
firstName: string;
lastName: string;
email: string;
phoneNumber: string;
}) => {
const { userid, firstName, lastName, email } = data;
const emailLowerCase = email.toLowerCase();
const post = {
id: userid,
email: emailLowerCase,
profile: {
firstName,
lastName,
},
};
const { response } = await api.post("/users/google", post, false);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error);
}

return response;
},
retry: false,
});

/** Sign in with Google */
const [signInWithGoogle, googleUser, googleLoading, googleError] =
useSignInWithGoogle(auth);
const handleGoogleLogin = async () => {
try {
const provider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, provider);
const user = result.user;

if (user) {
const email = user?.email as string;
const userid = user?.uid as string;
const phoneNumber = user?.phoneNumber as string;
const [firstName, lastName] = user?.displayName
? user?.displayName?.split(" ")
: ["", ""];

// Check if user exists in local database
const { response, data } = await api.get(`/users/${userid}`);
console.log(data);
if (!data["data"]) {
const backendUser = await createLocalUserFromGoogle({
userid,
firstName,
lastName,
email,
phoneNumber,
});
console.log(backendUser);
}
}
} catch (e) {
setNotifOpen(true);
setErrorMessage(
"Your account could not be created. Please try again later."
);
}
};

if (googleLoading) return <Loading />;

return (
<>
Expand Down Expand Up @@ -175,11 +245,9 @@ const LoginForm = () => {
</Link>
</div>
<Button
loading={googleLoading}
disabled={googleLoading}
variety="secondary"
icon={<GoogleIcon />}
// onClick={() => handleGoogleLogin()}
onClick={handleGoogleLogin}
type="submit"
>
Continue with Google
Expand Down

0 comments on commit 66ca706

Please sign in to comment.