Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log in with Google #243

Merged
merged 8 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading