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

Allow users to authenticate with Google OAuth #414

Merged
merged 16 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
72 changes: 72 additions & 0 deletions functions/google.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#redirecting
export async function oauthSignIn() {
// export async function oauthSignIn(CLIENT_ID: string,REDIRECT_URI: string) {

// Google's OAuth 2.0 endpoint for requesting an access token
const oauth2Endpoint = "https://accounts.google.com/o/oauth2/v2/auth";

// Create <form> element to submit parameters to OAuth 2.0 endpoint.
const form = document.createElement("form");
WangGithub0 marked this conversation as resolved.
Show resolved Hide resolved
form.setAttribute("method", "GET"); // Send as a GET request.
form.setAttribute("action", oauth2Endpoint);

// Parameters to pass to OAuth 2.0 endpoint.
const params: { [key: string]: string } = {
client_id: "70478082635-iaa28pt6bg1h06ooeic3vo8fgtu90trh.apps.googleusercontent.com", // This is my test accout, can be used in testing on http://localhost:5173/
WangGithub0 marked this conversation as resolved.
Show resolved Hide resolved
redirect_uri: "http://localhost:5173",
WangGithub0 marked this conversation as resolved.
Show resolved Hide resolved
response_type: "token",
scope: "profile email",
include_granted_scopes: "true",
state: "pass-through value",
};

// Add form parameters as hidden input values.
for (const p in params) {
const input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", p);
input.setAttribute("value", params[p]);
form.appendChild(input);
}

// Add form to page and submit it to open the OAuth 2.0 endpoint.
document.body.appendChild(form);
WangGithub0 marked this conversation as resolved.
Show resolved Hide resolved
form.submit();
}

export async function requestUserInfo(accessToken: string) {
const xhr = new XMLHttpRequest();
const url = `https://www.googleapis.com/drive/v3/about?fields=user&access_token=${accessToken}`;
xhr.open("Get", url);

xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
const { login, name, avatar_url } = response;
const userInfo = {
username: login,
name: name ?? login,
avatarUrl: avatar_url,
};
console.log(userInfo);
} else if (xhr.readyState === 4 && xhr.status === 401) {
// Token invalid, so prompt for user permission.
oauthSignIn();
}
};

// xhr.onreadystatechange = function () {
// console.log(xhr.response);
// };
xhr.send(null);

// this will be used later to create user
// const { login, name, avatar_url } = (await res.json()) as {
// login: string;
// name: string | null;
// avatar_url: string;
// };

// return { username: login, name: name ?? login, avatarUrl: avatar_url };
}
13 changes: 13 additions & 0 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ import {
} from "@chakra-ui/react";
import { BiSun, BiMoon, BiMenu } from "react-icons/bi";
import { BsGithub } from "react-icons/bs";
// import { FcGoogle } from "react-icons/fc";
import { TbSearch } from "react-icons/tb";
import { Form } from "react-router-dom";

import PreferencesModal from "./PreferencesModal";
import DefaultSystemPromptModal from "./DefaultSystemPromptModal";
import { useUser } from "../hooks/use-user";
// import { oauthSignIn } from "../../functions/google";

type HeaderProps = {
chatId?: string;
Expand Down Expand Up @@ -136,6 +138,17 @@ function Header({ chatId, inputPromptRef, searchText, onToggleSidebar }: HeaderP
</>
)}
</MenuItem>
{/* Google login */}
{/* <MenuItem
onClick={async () => {
oauthSignIn();
console.log("google");
}}
>
<>
<FcGoogle /> <Text ml={2}>Sign in with Google</Text>
</>
</MenuItem> */}
<MenuDivider />
<MenuItem
as="a"
Expand Down
20 changes: 19 additions & 1 deletion src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@ export default createBrowserRouter([
{
path: "/",
async loader() {
// Because google will redirect_uri to "/" with accessToken
const requestedURI = location.pathname;
// Accessing anchor values
const anchor = location.hash.substring(1); // Exclude the '#' character
console.log("Requested URI:", requestedURI);
console.log("Anchor:", anchor);
const match = anchor.match(/access_token=([^&]*)/);
const accessToken = match ? match[1] : null;
console.log("accessToken:", accessToken);
const xhr = new XMLHttpRequest();
xhr.open(
"GET",
"https://www.googleapis.com/drive/v3/about?fields=user&" + "access_token=" + accessToken
);
xhr.onreadystatechange = function () {
console.log(xhr.response);
};
xhr.send(null);

try {
const recentChat = await db.chats.orderBy("date").last();
if (recentChat) {
Expand All @@ -25,7 +44,6 @@ export default createBrowserRouter([
} catch (err) {
console.warn("Error getting most recent chat", err);
}

WangGithub0 marked this conversation as resolved.
Show resolved Hide resolved
return redirect("/new");
},
errorElement: <AppError />,
Expand Down
Loading