Skip to content

Commit

Permalink
TW-1229 Add another way for Google authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
keshan3262 committed Jan 8, 2024
1 parent dd24892 commit 961fc22
Show file tree
Hide file tree
Showing 9 changed files with 114 additions and 21 deletions.
32 changes: 25 additions & 7 deletions src/app/templates/About/About.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import { FormSecondaryButton } from 'app/atoms';
import { Anchor } from 'app/atoms/Anchor';
import Logo from 'app/atoms/Logo';
import SubTitle from 'app/atoms/SubTitle';
import { getGoogleAuthToken, readGoogleDriveFile, writeGoogleDriveFile } from 'lib/apis/google';
import {
getGoogleAuthTokenWithBrowserAPI,
getGoogleAuthTokenWithProxyWebsite,
readGoogleDriveFile,
writeGoogleDriveFile
} from 'lib/apis/google';
import { EnvVars } from 'lib/env';
import { TID, T } from 'lib/i18n';
import { backupFileName, EncryptedBackupObject, getSeedPhrase, toEncryptedBackup } from 'lib/temple/backup';
Expand Down Expand Up @@ -45,15 +50,23 @@ const LINKS: {
];

// Substitute with your own password
const mockPassword = '';
const mockPassword = '123456Aa';

const About: FC = () => {
const [authToken, setAuthToken] = useState<string>();
const { revealMnemonic } = useTempleClient();

const authorize = useCallback(async () => {
const authorizeWithBrowserAPI = useCallback(async () => {
try {
setAuthToken(await getGoogleAuthToken());
setAuthToken(await getGoogleAuthTokenWithBrowserAPI());
} catch (e) {
console.error('Caught authorization error:', e);
}
}, []);

const authorizeWithProxyWebsite = useCallback(async () => {
try {
setAuthToken(await getGoogleAuthTokenWithProxyWebsite());
} catch (e) {
console.error('Caught authorization error:', e);
}
Expand Down Expand Up @@ -169,9 +182,14 @@ const About: FC = () => {
</FormSecondaryButton>
</>
) : (
<FormSecondaryButton small onClick={authorize}>
Authorize
</FormSecondaryButton>
<>
<FormSecondaryButton small onClick={authorizeWithBrowserAPI}>
Authorize with browser API
</FormSecondaryButton>
<FormSecondaryButton small onClick={authorizeWithProxyWebsite}>
Authorize with proxy website
</FormSecondaryButton>
</>
)}
</div>
</div>
Expand Down
11 changes: 2 additions & 9 deletions src/contentScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { TemplePageMessage, TemplePageMessageType } from '@temple-wallet/dapp/di
import browser from 'webextension-polyfill';

import { ContentScriptType, WEBSITES_ANALYTICS_ENABLED } from 'lib/constants';
import { IntercomClient } from 'lib/intercom/client';
import { serealizeError } from 'lib/intercom/helpers';
import { TempleMessageType, TempleResponse } from 'lib/temple/types';

import { getIntercom } from './intercom-client';

const TRACK_URL_CHANGE_INTERVAL = 5000;

enum BeaconMessageTarget {
Expand Down Expand Up @@ -182,11 +183,3 @@ function send(msg: TemplePageMessage | LegacyPageMessage | BeaconPageMessage, ta
if (!targetOrigin || targetOrigin === '*') return;
window.postMessage(msg, targetOrigin);
}

let intercom: IntercomClient;
function getIntercom() {
if (!intercom) {
intercom = new IntercomClient();
}
return intercom;
}
22 changes: 22 additions & 0 deletions src/googleAuthCommunication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { TempleMessageType } from 'lib/temple/types';

import { getIntercom } from './intercom-client';

enum AuthEventType {
AuthRequest = 'authrequest',
AuthAck = 'authack'
}

window.addEventListener('message', async (e: MessageEvent) => {
try {
if (e.data?.type === AuthEventType.AuthRequest) {
await getIntercom().request({
type: TempleMessageType.GoogleAuthTokenReceivedRequest,
authToken: e.data.content
});
window.postMessage({ type: AuthEventType.AuthAck }, '*');
}
} catch (error) {
console.error(error);
}
});
9 changes: 9 additions & 0 deletions src/intercom-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { IntercomClient } from 'lib/intercom/client';

let intercom: IntercomClient;
export function getIntercom() {
if (!intercom) {
intercom = new IntercomClient();
}
return intercom;
}
17 changes: 16 additions & 1 deletion src/lib/apis/google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { v4 } from 'uuid';
import browser from 'webextension-polyfill';

import { EnvVars } from 'lib/env';
import { intercom } from 'lib/temple/front/client';
import { TempleMessageType, TempleNotification } from 'lib/temple/types';

interface GoogleFile {
kind: string;
Expand All @@ -24,7 +26,7 @@ const googleApi = axios.create({
baseURL: 'https://www.googleapis.com'
});

export const getGoogleAuthToken = async () => {
export const getGoogleAuthTokenWithBrowserAPI = async () => {
const redirectURL = browser.identity.getRedirectURL();
const scopes = ['https://www.googleapis.com/auth/drive.appdata'];
const authURLQueryParams = new URLSearchParams({
Expand All @@ -47,6 +49,19 @@ export const getGoogleAuthToken = async () => {
throw new Error(`Failed to parse auth token, url: ${url}`);
};

export const getGoogleAuthTokenWithProxyWebsite = async () => {
await browser.tabs.create({ url: 'http://localhost:3000/google-drive-auth' });

return new Promise<string>(res => {
const unsubscribe = intercom.subscribe((msg: TempleNotification) => {
if (msg?.type === TempleMessageType.GoogleAuthTokenReceived) {
unsubscribe();
res(msg.authToken);
}
});
});
};

const getFileId = async (fileName: string, authToken: string, nextPageToken?: string): Promise<string | undefined> => {
const { data } = await googleApi.get<FilesListResponse>('/drive/v3/files', {
params: {
Expand Down
9 changes: 9 additions & 0 deletions src/lib/temple/back/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,15 @@ const processRequest = async (req: TempleRequest, port: Runtime.Port): Promise<T
}
}
break;

case TempleMessageType.GoogleAuthTokenReceivedRequest:
intercom.broadcast({
type: TempleMessageType.GoogleAuthTokenReceived,
authToken: req.authToken
});
return {
type: TempleMessageType.GoogleAuthTokenReceiveAcknowledge
};
}
};

Expand Down
26 changes: 23 additions & 3 deletions src/lib/temple/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,13 @@ export type TempleDAppPayload = TempleDAppConnectPayload | TempleDAppOperationsP
export enum TempleMessageType {
// Acknowledge
Acknowledge = 'TEMPLE_CONNECT_AKNOWLEDGE',
GoogleAuthTokenReceiveAcknowledge = 'GOOGLE_AUTH_TOKEN_RECEIVE_ACKNOWLEDGE',
// Notifications
StateUpdated = 'TEMPLE_STATE_UPDATED',
ConfirmationRequested = 'TEMPLE_CONFIRMATION_REQUESTED',
ConfirmationExpired = 'TEMPLE_CONFIRMATION_EXPIRED',
SelectedAccountChanged = 'TEMPLE_SELECTED_ACCOUNT_CHANGED',
GoogleAuthTokenReceived = 'GOOGLE_AUTH_TOKEN_RECEIVED',
// Request-Response pairs
GetStateRequest = 'TEMPLE_GET_STATE_REQUEST',
GetStateResponse = 'TEMPLE_GET_STATE_RESPONSE',
Expand Down Expand Up @@ -288,14 +290,16 @@ export enum TempleMessageType {
SendTrackEventRequest = 'SEND_TRACK_EVENT_REQUEST',
SendTrackEventResponse = 'SEND_TRACK_EVENT_RESPONSE',
SendPageEventRequest = 'SEND_PAGE_EVENT_REQUEST',
SendPageEventResponse = 'SEND_PAGE_EVENT_RESPONSE'
SendPageEventResponse = 'SEND_PAGE_EVENT_RESPONSE',
GoogleAuthTokenReceivedRequest = 'GOOGLE_AUTH_TOKEN_RECEIVED_REQUEST'
}

export type TempleNotification =
| TempleStateUpdated
| TempleConfirmationRequested
| TempleConfirmationExpired
| TempleSelectedAccountChanged;
| TempleSelectedAccountChanged
| TempleGoogleAuthTokenReceived;

export type TempleRequest =
| TempleAcknowledgeRequest
Expand Down Expand Up @@ -328,11 +332,13 @@ export type TempleRequest =
| TempleGetAllDAppSessionsRequest
| TempleRemoveDAppSessionRequest
| TempleSendTrackEventRequest
| TempleSendPageEventRequest;
| TempleSendPageEventRequest
| TempleGoogleAuthTokenReceivedRequest;

export type TempleResponse =
| TempleGetStateResponse
| TempleAcknowledgeResponse
| TempleGoogleAuthTokenReceiveAcknowledgeResponse
| TempleNewWalletResponse
| TempleUnlockResponse
| TempleLockResponse
Expand Down Expand Up @@ -388,6 +394,11 @@ interface TempleSelectedAccountChanged extends TempleMessageBase {
accountPublicKeyHash: string;
}

interface TempleGoogleAuthTokenReceived extends TempleMessageBase {
type: TempleMessageType.GoogleAuthTokenReceived;
authToken: string;
}

interface TempleGetStateRequest extends TempleMessageBase {
type: TempleMessageType.GetStateRequest;
}
Expand All @@ -403,6 +414,10 @@ interface TempleAcknowledgeResponse extends TempleMessageBase {
encrypted?: boolean;
}

interface TempleGoogleAuthTokenReceiveAcknowledgeResponse extends TempleMessageBase {
type: TempleMessageType.GoogleAuthTokenReceiveAcknowledge;
}

interface TempleNewWalletRequest extends TempleMessageBase {
type: TempleMessageType.NewWalletRequest;
password: string;
Expand Down Expand Up @@ -697,4 +712,9 @@ interface TempleRemoveDAppSessionResponse extends TempleMessageBase {
sessions: TempleDAppSessions;
}

interface TempleGoogleAuthTokenReceivedRequest extends TempleMessageBase {
type: TempleMessageType.GoogleAuthTokenReceivedRequest;
authToken: string;
}

export type OperationsPreview = any[] | { branch: string; contents: any[] };
3 changes: 2 additions & 1 deletion webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ const scriptsConfig = (() => {

config.entry = {
contentScript: Path.join(PATHS.SOURCE, 'contentScript.ts'),
replaceAds: Path.join(PATHS.SOURCE, 'replaceAds.ts')
replaceAds: Path.join(PATHS.SOURCE, 'replaceAds.ts'),
googleAuthCommunication: Path.join(PATHS.SOURCE, 'googleAuthCommunication.ts')
};

if (BACKGROUND_IS_WORKER)
Expand Down
6 changes: 6 additions & 0 deletions webpack/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,12 @@ const buildManifestCommons = (vendor: string): Omit<Manifest.WebExtensionManifes
js: ['scripts/replaceAds.js'],
run_at: 'document_start',
all_frames: false
},
{
matches: ['http://localhost/*', 'http://127.0.0.1/*', 'https://templewallet.com/*'],
js: ['scripts/googleAuthCommunication.js'],
run_at: 'document_start',
all_frames: false
}
]
};
Expand Down

0 comments on commit 961fc22

Please sign in to comment.