Skip to content

Commit

Permalink
fixed bug related to chrome extension: not able to save token in cache
Browse files Browse the repository at this point in the history
  • Loading branch information
ali-ahnaf committed Sep 17, 2024
1 parent ec39918 commit 867b874
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 14 deletions.
Binary file added client/public/favicon-16x16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added client/public/favicon-32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions client/public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"default_popup": "index.html",
"default_title": "Bookify"
},
"icons": {
"16": "favicon-16x16.png",
"32": "favicon-32x32.png"
},
"permissions": [
"identity",
"storage"
Expand Down
15 changes: 10 additions & 5 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Route, Routes, useNavigate } from 'react-router-dom';
import Home from './pages/Home';
import Login from './pages/Login';
import AppTheme from './theme/AppTheme';
import toast, { Toaster } from 'react-hot-toast';
import { Toaster } from 'react-hot-toast';
import { FONT_PRIMARY } from './theme/primitives/typography';
import { useEffect } from 'react';
import { handleOAuthCallback } from './helpers/api';
Expand All @@ -17,20 +17,25 @@ function OAuth() {
useEffect(() => {
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');

if (error) {
navigate(ROUTES.signIn, { state: { errorMessage: error } });
return;
}

if (code) {
handleOAuthCallback(code).then(async ({ data, status }) => {
if (status !== 200) {
toast.error(data.message || 'Something went wrong');
navigate(ROUTES.home);

if (status !== 201 && status !== 200) {
navigate(ROUTES.signIn, { state: { errorMessage: data.message || 'Something went wrong' } });
return;
}

console.log('Access Token:', data.accessToken);
if (data?.accessToken) {
const cacheService: CacheService = CacheServiceFactory.getCacheService();
await cacheService.saveToCache('access_token', data.accessToken);
navigate(ROUTES.home);
}
});
}
Expand Down
31 changes: 26 additions & 5 deletions client/src/helpers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export async function logout() {
export async function loginChrome() {
const scopes = SCOPES.join(' ').trim();
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${secrets.clientId}&redirect_uri=${secrets.oAuthRedirectUrl}&response_type=code&scope=${scopes}&access_type=offline`;
console.log('secrets.oAuthRedirectUrl', secrets.oAuthRedirectUrl);

return handleChromeOauthFlow(authUrl);
}
Expand All @@ -103,7 +104,7 @@ export async function login() {
}

async function handleChromeOauthFlow(authUrl: string) {
const redirectUrl = await new Promise<boolean>((resolve, _) => {
const res = await new Promise<IResponse>((resolve, _) => {
chrome.identity.launchWebAuthFlow(
{
url: authUrl,
Expand All @@ -122,17 +123,37 @@ async function handleChromeOauthFlow(authUrl: string) {

try {
if (code) {
await handleOAuthCallback(code);
resolve(true);
const { data, status, errorMessage } = await handleOAuthCallback(code);
if (status !== 201 && status !== 200) {
resolve({
errorMessage: errorMessage || data?.message || 'Something went wrong',
redirect: true,
});
return;
}

console.log('Access Token:', data.accessToken);
resolve({
status,
data: data?.accessToken,
});
}
} catch (error: any) {
console.error(error);
resolve(false);
resolve({
redirect: true,
errorMessage: error.message,
});
}

resolve({
redirect: true,
errorMessage: 'Something went wrong',
});
}
},
);
});

return redirectUrl;
return res;
}
20 changes: 16 additions & 4 deletions client/src/pages/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Box, Button, Stack, styled, Typography } from '@mui/material';
import MuiCard from '@mui/material/Card';
import { useEffect } from 'react';
import { GoogleIcon } from '../../components/CustomIcons';
import { useNavigate } from 'react-router-dom';
import { useLocation, useNavigate } from 'react-router-dom';
import { login, loginChrome } from '../../helpers/api';
import { CacheService, CacheServiceFactory } from '../../helpers/cache';
import { secrets } from '../../config/secrets';
Expand Down Expand Up @@ -59,6 +59,13 @@ const RootContainer = styled(Stack)(({ theme }) => ({

const Login = () => {
const navigate = useNavigate();
const { state } = useLocation();
const errorMessage = state?.errorMessage;
console.log(secrets);
console.log(chrome.identity.getRedirectURL());
if (errorMessage) {
toast.error(errorMessage);
}

useEffect(() => {
cacheService.getFromCache('access_token').then((token) => {
Expand All @@ -70,11 +77,16 @@ const Login = () => {

async function onSignInClick(): Promise<void> {
if (secrets.appEnvironment === 'chrome') {
const res = await loginChrome();
if (res) {
const { redirect, data, errorMessage } = await loginChrome();

if (data) {
const cacheService: CacheService = CacheServiceFactory.getCacheService();
await cacheService.saveToCache('access_token', data.accessToken);
navigate(ROUTES.home);
} else {
toast.error("Coudn't sign in user.");
if (redirect) {
navigate(ROUTES.signIn, { state: { errorMessage: errorMessage || "Couldn't sign in user" } });
}
}
} else {
await login();
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
"scripts": {
"build": "nest build",
"build:chrome": "cd client && npm run build:chrome",
"build:web": "cd client && npm run build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "node dist/main",
"start:prod": "node dist/main",
"start:dev": "(cd client && npm run build) && (cross-env NODE_ENV=development nest start --watch)",
"start:server": "cross-env NODE_ENV=development nest start --watch",
"start:client": "cd client && npm run start",
"typeorm": "ts-node ./node_modules/typeorm/cli",
"migration:run": "npm run build && (npm run typeorm migration:run -- -d ./src/config/orm.config.ts)",
Expand Down

0 comments on commit 867b874

Please sign in to comment.