From 645df1d00f953524c6da22103d26c38ae4331cd6 Mon Sep 17 00:00:00 2001 From: Skitty1238 <157652284+Skitty1238@users.noreply.github.com> Date: Wed, 4 Jun 2025 13:59:34 -0400 Subject: partial google calendar task integration + fix with dark mode colors for task nodes so that text is still visible --- src/server/apis/google/GoogleApiServerUtils.ts | 39 +++++++++++++++++--------- 1 file changed, 25 insertions(+), 14 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 7373df473..75f904331 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -6,6 +6,7 @@ import * as request from 'request-promise'; import { Opt } from '../../../fields/Doc'; import { Database } from '../../database'; import { GoogleCredentialsLoader } from './CredentialsLoader'; +import { DashUserModel } from '../../authentication/DashUserModel'; /** * Scopes give Google users fine granularity of control @@ -13,7 +14,7 @@ import { GoogleCredentialsLoader } from './CredentialsLoader'; * This is the somewhat overkill list of what Dash requests * from the user. */ -const scope = ['documents.readonly', 'documents', 'presentations', 'presentations.readonly', 'drive', 'drive.file', 'photoslibrary', 'photoslibrary.appendonly', 'photoslibrary.sharing', 'userinfo.profile'].map( +const scope = ['tasks', 'documents.readonly', 'documents', 'presentations', 'presentations.readonly', 'drive', 'drive.file', 'photoslibrary', 'photoslibrary.appendonly', 'photoslibrary.sharing', 'userinfo.profile'].map( relative => `https://www.googleapis.com/auth/${relative}` ); @@ -118,8 +119,9 @@ export namespace GoogleApiServerUtils { * @param userId the id of the Dash user making the request to the API * @returns the relevant 'googleapis' wrapper, if any */ - export async function GetEndpoint(sector: string, userId: string): Promise { - const auth = await retrieveOAuthClient(userId); + export async function GetEndpoint(sector: string, user: DashUserModel): Promise { + if (!user.googleToken) await retrieveOAuthClient(user); + const auth = user.googleToken; // await retrieveOAuthClient(user); if (!auth) { return; } @@ -145,14 +147,14 @@ export namespace GoogleApiServerUtils { * npm-installed API wrappers that use authenticated client instances rather than access codes for * security. */ - export async function retrieveOAuthClient(userId: string): Promise { - const { credentials, refreshed } = await retrieveCredentials(userId); + export async function retrieveOAuthClient(user: DashUserModel): Promise { + const { credentials, refreshed } = await retrieveCredentials(user); if (!credentials) { return; } - let client = authenticationClients.get(userId); + let client = authenticationClients.get(user.id); if (!client) { - authenticationClients.set(userId, (client = generateClient(credentials))); + authenticationClients.set(user.id, (client = generateClient(credentials))); } else if (refreshed) { client.setCredentials(credentials); } @@ -181,7 +183,16 @@ export namespace GoogleApiServerUtils { * @returns the newly generated url to the authentication landing page */ export function generateAuthenticationUrl(): string { - return worker.generateAuthUrl({ scope, access_type: 'offline' }); + const oauth2Client = new google.auth.OAuth2( + '838617994486-a28072lirm8uk8cm78t7ic4krp0rgkgv.apps.googleusercontent.com', + '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', + 'http://localhost:1050/refreshGoogle' // Ensure this matches the redirect URI in Google Cloud Console + ); + + return oauth2Client.generateAuthUrl({ + access_type: 'offline', + scope: ['https://www.googleapis.com/auth/tasks'], + }); } /** @@ -267,15 +278,15 @@ export namespace GoogleApiServerUtils { * @returns the credentials, or undefined if the user has no stored associated credentials, * and a flag indicating whether or not they were refreshed during retrieval */ - export async function retrieveCredentials(userId: string): Promise<{ credentials: Opt; refreshed: boolean }> { - let credentials = await Database.Auxiliary.GoogleAccessToken.Fetch(userId); + export async function retrieveCredentials(user: DashUserModel): Promise<{ credentials: Opt; refreshed: boolean }> { + let credentials = await Database.Auxiliary.GoogleAccessToken.Fetch(user.id); let refreshed = false; if (!credentials) { return { credentials: undefined, refreshed }; } // check for token expiry if (credentials.expiry_date! <= new Date().getTime()) { - credentials = { ...credentials, ...(await refreshAccessToken(credentials, userId)) }; + credentials = { ...credentials, ...(await refreshAccessToken(credentials, user)) }; refreshed = true; } return { credentials, refreshed }; @@ -291,11 +302,11 @@ export namespace GoogleApiServerUtils { * his/her credentials be refreshed * @returns the updated credentials */ - async function refreshAccessToken(credentials: Credentials, userId: string): Promise { + async function refreshAccessToken(credentials: Credentials, user: DashUserModel): Promise { const headerParameters = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; const { client_id, client_secret } = GoogleCredentialsLoader.ProjectCredentials; const params = new URLSearchParams({ - refresh_token: credentials.refresh_token!, + refresh_token: credentials.refresh_token!, // AARAV use user.googleToken client_id, client_secret, grant_type: 'refresh_token', @@ -306,7 +317,7 @@ export namespace GoogleApiServerUtils { }); // expires_in is in seconds, but we're building the new expiry date in milliseconds const expiry_date = new Date().getTime() + expires_in * 1000; - await Database.Auxiliary.GoogleAccessToken.Update(userId, access_token, expiry_date); + await Database.Auxiliary.GoogleAccessToken.Update(user.id, access_token, expiry_date); // update the relevant properties credentials.access_token = access_token; credentials.expiry_date = expiry_date; -- cgit v1.2.3-70-g09d2 From 09be9002b5aa8f5ad7c602bcef6b53bbe0398cd3 Mon Sep 17 00:00:00 2001 From: Skitty1238 <157652284+Skitty1238@users.noreply.github.com> Date: Wed, 4 Jun 2025 18:28:35 -0400 Subject: fixed google authentication + linking and task creation via GT button --- src/client/apis/GoogleAuthenticationManager.tsx | 98 ++++++++++++++-------- src/client/views/nodes/TaskBox.tsx | 57 ++++++++++++- src/server/ApiManagers/GeneralGoogleManager.ts | 50 +++++++---- src/server/apis/google/GoogleApiServerUtils.ts | 10 ++- .../apis/google/google_project_credentials.json | 2 +- 5 files changed, 161 insertions(+), 56 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/client/apis/GoogleAuthenticationManager.tsx b/src/client/apis/GoogleAuthenticationManager.tsx index 1b1d6f734..a93e03e60 100644 --- a/src/client/apis/GoogleAuthenticationManager.tsx +++ b/src/client/apis/GoogleAuthenticationManager.tsx @@ -42,46 +42,72 @@ export class GoogleAuthenticationManager extends ObservableReactComponent { - const response = await Networking.FetchFromServer('/readGoogleAccessToken'); - // if this is an authentication url, activate the UI to register the new access token - if (new RegExp(AuthenticationUrl).test(response)) { - this.isOpen = true; - this.authenticationLink = response; - - // GETS STUCK AT THIS PROMISE!! - return new Promise(resolve => { - this.disposer?.(); - this.disposer = reaction( - () => this.authenticationCode, - async authenticationCode => { - if (authenticationCode && /\d{1}\/[\w-]{55}/.test(authenticationCode)) { - resolve(authenticationCode); - this.disposer?.(); - // const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); - // runInAction(() => { - // this.success = true; - // this.credentials = response2 as { user_info: { name: string; picture: string }; access_token: string }; - // }); - // resolve((response2 as { access_token: string }).access_token); - this.resetState(); - } - } - ); - }); - } + // public fetchOrGenerateAccessToken = async (displayIfFound = false) => { + // const response = await Networking.FetchFromServer('/readGoogleAccessToken'); + // // if this is an authentication url, activate the UI to register the new access token + + // if (new RegExp(AuthenticationUrl).test(response)) { + // this.isOpen = true; + // this.authenticationLink = response; - // otherwise, we already have a valid, stored access token and user info - const response2 = JSON.parse(response) as { user_info: { name: string; picture: string }; access_token: string }; - if (displayIfFound) { + // // GETS STUCK AT THIS PROMISE!! + // return new Promise(resolve => { + // this.disposer?.(); + // this.disposer = reaction( + // () => this.authenticationCode, + // async authenticationCode => { + // if (authenticationCode && /\d{1}\/[\w-]{55}/.test(authenticationCode)) { + // resolve(authenticationCode); + // this.disposer?.(); + // // const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); + // // runInAction(() => { + // // this.success = true; + // // this.credentials = response2 as { user_info: { name: string; picture: string }; access_token: string }; + // // }); + // // resolve((response2 as { access_token: string }).access_token); + // this.resetState(); + // } + // } + // ); + // }); + // } + + // // otherwise, we already have a valid, stored access token and user info + // const response2 = JSON.parse(response) as { user_info: { name: string; picture: string }; access_token: string }; + // if (displayIfFound) { + // runInAction(() => { + // this.success = true; + // this.credentials = response2; + // }); + // this.resetState(-1, -1); + // this.isOpen = true; + // } + // return (response2 as { access_token: string }).access_token; + // }; + + public fetchOrGenerateAccessToken = async (): Promise => { + const response = await Networking.FetchFromServer('/readGoogleAccessToken'); + + // This will return a JSON object with { access_token, user_info } if already linked + try { + const parsed = JSON.parse(response) as { access_token: string; user_info: { name: string; picture: string } }; + runInAction(() => { this.success = true; - this.credentials = response2; + this.credentials = parsed; }); - this.resetState(-1, -1); - this.isOpen = true; + + return parsed.access_token; + } catch (err) { + console.warn('Not linked yet or invalid JSON. Redirecting to auth...'); + // This is an auth URL β€” redirect the user to /refreshGoogle + if (typeof response === 'string' && response.startsWith('http')) { + window.location.href = response; + return ''; // Won’t be used β€” this page will reload anyway + } + + throw new Error('Unable to fetch Google access token.'); } - return (response2 as { access_token: string }).access_token; }; resetState = action((visibleForMS: number = 3000, fadesOutInMS: number = 500) => { @@ -132,7 +158,7 @@ export class GoogleAuthenticationManager extends ObservableReactComponent ) : null} {this.showPasteTargetState ? (this.authenticationCode = e.currentTarget.value))} placeholder={prompt} /> : null} - {this.credentials ? ( + {this.credentials?.user_info?.picture ? ( <> Welcome to Dash, {this.credentials.user_info.name} diff --git a/src/client/views/nodes/TaskBox.tsx b/src/client/views/nodes/TaskBox.tsx index 3990356b9..8855e43c8 100644 --- a/src/client/views/nodes/TaskBox.tsx +++ b/src/client/views/nodes/TaskBox.tsx @@ -6,6 +6,7 @@ import { DocumentType } from '../../documents/DocumentTypes'; import { FieldView } from './FieldView'; import { DateField } from '../../../fields/DateField'; import { Doc } from '../../../fields/Doc'; +import { Networking } from '../../Network'; import './TaskBox.scss'; import { GoogleAuthenticationManager } from '../../apis/GoogleAuthenticationManager'; @@ -270,7 +271,7 @@ export class TaskBox extends React.Component { )} {/** test button */} - */} + + {/* */} + + ); diff --git a/src/server/ApiManagers/GeneralGoogleManager.ts b/src/server/ApiManagers/GeneralGoogleManager.ts index e8debfc12..25589ccb5 100644 --- a/src/server/ApiManagers/GeneralGoogleManager.ts +++ b/src/server/ApiManagers/GeneralGoogleManager.ts @@ -71,24 +71,20 @@ export default class GeneralGoogleManager extends ApiManager { subscription: new RouteSubscriber('googleTasks').add('create'), secureHandler: async ({ req, res, user }) => { try { - const { credentials } = await GoogleApiServerUtils.retrieveCredentials(user.id); - const access_token = user.googleToken || credentials?.access_token; // if googleToken expires, we need to renew it. - - if (!access_token) { - return res.status(401).send('Google access token not found.'); + const auth = await GoogleApiServerUtils.retrieveOAuthClient(user); + + if (!auth) { + return res.status(401).send('Google credentials missing or invalid.'); } - - const auth = new google.auth.OAuth2(); - auth.setCredentials({ access_token: access_token }); - + const tasks = google.tasks({ version: 'v1', auth }); - - const { title, notes, due } = req.body; + + const { title, notes, due, status, completed } = req.body; const result = await tasks.tasks.insert({ tasklist: '@default', - requestBody: { title, notes, due }, + requestBody: { title, notes, due, status, completed}, }); - + res.status(200).send(result.data); } catch (err) { console.error('Google Tasks error:', err); @@ -102,9 +98,31 @@ export default class GeneralGoogleManager extends ApiManager { subscription: '/refreshGoogle', secureHandler: async ({ user, req, res }) => { const code = req.query.code as string; - _success(res, code); - user.googleToken = code; - user.save(); + console.log('/refreshGoogle hit with code:', code); + + try { + const enriched = await GoogleApiServerUtils.processNewUser(user.id, code); + + if (enriched.refresh_token) { + console.log('Enriched credentials:', enriched); + + if (enriched.refresh_token) { + user.googleToken = enriched.refresh_token; + await user.save(); + console.log('Saved refresh token to user model'); + } else { + console.warn('No refresh token returned'); + } + } + + // await user.save(); + // _success(res, 'Google account successfully linked!'); + res.redirect('/home'); + + } catch (err) { + console.error('Failed to process Google code:', err); + res.status(500).send('Error linking Google account'); + } // const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); // runInAction(() => { diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 75f904331..56bc79119 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -59,6 +59,7 @@ export namespace GoogleApiServerUtils { */ export function processProjectCredentials(): void { const { client_secret: clientSecret, client_id: clientId, redirect_uris: redirectUris } = GoogleCredentialsLoader.ProjectCredentials; + console.log('Loaded Google redirect URIs:', redirectUris); // initialize the global authorization client oAuthOptions = { clientId, @@ -191,7 +192,12 @@ export namespace GoogleApiServerUtils { return oauth2Client.generateAuthUrl({ access_type: 'offline', - scope: ['https://www.googleapis.com/auth/tasks'], + scope: [ + 'https://www.googleapis.com/auth/tasks', + 'openid', + 'profile' + ], + prompt: 'consent', // This ensures we get a refresh token }); } @@ -306,7 +312,7 @@ export namespace GoogleApiServerUtils { const headerParameters = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; const { client_id, client_secret } = GoogleCredentialsLoader.ProjectCredentials; const params = new URLSearchParams({ - refresh_token: credentials.refresh_token!, // AARAV use user.googleToken + refresh_token: credentials.refresh_token!, // AARAV use user.googleToken client_id, client_secret, grant_type: 'refresh_token', diff --git a/src/server/apis/google/google_project_credentials.json b/src/server/apis/google/google_project_credentials.json index 738e13647..010f9a626 100644 --- a/src/server/apis/google/google_project_credentials.json +++ b/src/server/apis/google/google_project_credentials.json @@ -6,6 +6,6 @@ "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_secret": "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", - "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"] + "redirect_uris": ["http://localhost:1050/refreshGoogle"] } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 8d424c8cb4d178d5fb92b6543d63fa409eb6430b Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 4 Jun 2025 21:05:03 -0400 Subject: changed google authentication to not reload the page. --- src/client/apis/GoogleAuthenticationManager.tsx | 23 +++++++++--------- src/client/util/SettingsManager.tsx | 2 +- src/client/views/nodes/TaskBox.tsx | 11 ++++++++- src/server/ApiManagers/GeneralGoogleManager.ts | 27 +++++----------------- src/server/apis/google/GoogleApiServerUtils.ts | 16 +++++-------- .../apis/google/google_project_credentials.json | 8 +++---- 6 files changed, 39 insertions(+), 48 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/client/apis/GoogleAuthenticationManager.tsx b/src/client/apis/GoogleAuthenticationManager.tsx index a93e03e60..ffec07512 100644 --- a/src/client/apis/GoogleAuthenticationManager.tsx +++ b/src/client/apis/GoogleAuthenticationManager.tsx @@ -1,4 +1,4 @@ -import { action, IReactionDisposer, makeObservable, observable, reaction, runInAction } from 'mobx'; +import { action, IReactionDisposer, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { Opt } from '../../fields/Doc'; @@ -8,7 +8,6 @@ import { MainViewModal } from '../views/MainViewModal'; import './GoogleAuthenticationManager.scss'; import { ObservableReactComponent } from '../views/ObservableReactComponent'; -const AuthenticationUrl = 'https://accounts.google.com/o/oauth2/v2/auth'; const prompt = 'Paste authorization code here...'; @observer @@ -85,27 +84,29 @@ export class GoogleAuthenticationManager extends ObservableReactComponent => { + public fetchOrGenerateAccessToken = async (): Promise => { const response = await Networking.FetchFromServer('/readGoogleAccessToken'); - + // This will return a JSON object with { access_token, user_info } if already linked try { const parsed = JSON.parse(response) as { access_token: string; user_info: { name: string; picture: string } }; - + runInAction(() => { this.success = true; this.credentials = parsed; }); - + return parsed.access_token; - } catch (err) { - console.warn('Not linked yet or invalid JSON. Redirecting to auth...'); + } catch { + console.warn('Not linked yet or invalid JSON. open auth...'); // This is an auth URL β€” redirect the user to /refreshGoogle if (typeof response === 'string' && response.startsWith('http')) { - window.location.href = response; - return ''; // Won’t be used β€” this page will reload anyway + if (window.confirm('Authorize Dash to access your Google tasks?')) { + window.open(response)?.focus(); + return undefined; + } } - + throw new Error('Unable to fetch Google access token.'); } }; diff --git a/src/client/util/SettingsManager.tsx b/src/client/util/SettingsManager.tsx index 9e79fd870..f54dea90c 100644 --- a/src/client/util/SettingsManager.tsx +++ b/src/client/util/SettingsManager.tsx @@ -40,7 +40,7 @@ export class SettingsManager extends React.Component { @observable private _activeTab = 'Accounts'; @observable private _isOpen = false; - private googleAuthorize = action(() => GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken(true)); + private googleAuthorize = action(() => GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken()); public closeMgr = action(() => { this._isOpen = false; diff --git a/src/client/views/nodes/TaskBox.tsx b/src/client/views/nodes/TaskBox.tsx index 8855e43c8..df81d9c69 100644 --- a/src/client/views/nodes/TaskBox.tsx +++ b/src/client/views/nodes/TaskBox.tsx @@ -6,7 +6,6 @@ import { DocumentType } from '../../documents/DocumentTypes'; import { FieldView } from './FieldView'; import { DateField } from '../../../fields/DateField'; import { Doc } from '../../../fields/Doc'; -import { Networking } from '../../Network'; import './TaskBox.scss'; import { GoogleAuthenticationManager } from '../../apis/GoogleAuthenticationManager'; @@ -324,6 +323,16 @@ export class TaskBox extends React.Component { console.log('GT button clicked'); try { const token = await GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken(); + if (token === undefined) { + const listener = () => { + if (confirm('βœ… Try again?')) { + // refactor this click function and call it again + } + window.removeEventListener('focusin', listener); + }; + setTimeout(() => window.addEventListener('focusin', listener), 100); + return; + } console.log('Got token', token); const response = await fetch('/googleTasks/create', { diff --git a/src/server/ApiManagers/GeneralGoogleManager.ts b/src/server/ApiManagers/GeneralGoogleManager.ts index 25589ccb5..59d066934 100644 --- a/src/server/ApiManagers/GeneralGoogleManager.ts +++ b/src/server/ApiManagers/GeneralGoogleManager.ts @@ -1,5 +1,5 @@ import ApiManager, { Registration } from './ApiManager'; -import { Method, _success } from '../RouteManager'; +import { Method } from '../RouteManager'; import { GoogleApiServerUtils } from '../apis/google/GoogleApiServerUtils'; import RouteSubscriber from '../RouteSubscriber'; import { Database } from '../database'; @@ -72,19 +72,19 @@ export default class GeneralGoogleManager extends ApiManager { secureHandler: async ({ req, res, user }) => { try { const auth = await GoogleApiServerUtils.retrieveOAuthClient(user); - + if (!auth) { return res.status(401).send('Google credentials missing or invalid.'); } - + const tasks = google.tasks({ version: 'v1', auth }); - + const { title, notes, due, status, completed } = req.body; const result = await tasks.tasks.insert({ tasklist: '@default', - requestBody: { title, notes, due, status, completed}, + requestBody: { title, notes, due, status, completed }, }); - + res.status(200).send(result.data); } catch (err) { console.error('Google Tasks error:', err); @@ -98,37 +98,22 @@ export default class GeneralGoogleManager extends ApiManager { subscription: '/refreshGoogle', secureHandler: async ({ user, req, res }) => { const code = req.query.code as string; - console.log('/refreshGoogle hit with code:', code); try { const enriched = await GoogleApiServerUtils.processNewUser(user.id, code); if (enriched.refresh_token) { - console.log('Enriched credentials:', enriched); - if (enriched.refresh_token) { user.googleToken = enriched.refresh_token; await user.save(); - console.log('Saved refresh token to user model'); } else { console.warn('No refresh token returned'); } } - - // await user.save(); - // _success(res, 'Google account successfully linked!'); - res.redirect('/home'); - } catch (err) { console.error('Failed to process Google code:', err); res.status(500).send('Error linking Google account'); } - - // const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); - // runInAction(() => { - // this.success = true; - // this.credentials = response2 as { user_info: { name: string; picture: string }; access_token: string }; - // }); }, }); } diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 56bc79119..2f7ef473c 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -185,18 +185,14 @@ export namespace GoogleApiServerUtils { */ export function generateAuthenticationUrl(): string { const oauth2Client = new google.auth.OAuth2( - '838617994486-a28072lirm8uk8cm78t7ic4krp0rgkgv.apps.googleusercontent.com', - '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', + '740987818053-dtflji3hfkn5r9t8ad6jb8740pls8moh.apps.googleusercontent.com', + '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', 'http://localhost:1050/refreshGoogle' // Ensure this matches the redirect URI in Google Cloud Console ); return oauth2Client.generateAuthUrl({ access_type: 'offline', - scope: [ - 'https://www.googleapis.com/auth/tasks', - 'openid', - 'profile' - ], + scope: ['https://www.googleapis.com/auth/tasks', 'openid', 'profile'], prompt: 'consent', // This ensures we get a refresh token }); } @@ -220,12 +216,12 @@ export namespace GoogleApiServerUtils { */ export async function processNewUser(userId: string, authenticationCode: string): Promise { const credentials = await new Promise((resolve, reject) => { - worker.getToken(authenticationCode, (err, credentials) => { - if (err || !credentials) { + worker.getToken(authenticationCode, (err, creds) => { + if (err || !creds) { reject(err); return; } - resolve(credentials); + resolve(creds); }); }); const enriched = injectUserInfo(credentials); diff --git a/src/server/apis/google/google_project_credentials.json b/src/server/apis/google/google_project_credentials.json index 010f9a626..8abc13b80 100644 --- a/src/server/apis/google/google_project_credentials.json +++ b/src/server/apis/google/google_project_credentials.json @@ -1,11 +1,11 @@ { "installed": { - "client_id": "838617994486-a28072lirm8uk8cm78t7ic4krp0rgkgv.apps.googleusercontent.com", - "project_id": "gtasks-test-dash", + "client_id": "740987818053-dtflji3hfkn5r9t8ad6jb8740pls8moh.apps.googleusercontent.com", + "project_id": "dash-web-461920", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "client_secret": "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", + "client_secret": "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", "redirect_uris": ["http://localhost:1050/refreshGoogle"] } -} \ No newline at end of file +} -- cgit v1.2.3-70-g09d2 From f7cb0dcebb0514cf38f8a7e635ec9959c196145a Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 4 Jun 2025 21:32:34 -0400 Subject: cleaned up getting client id/secret for google. fixed final message after going through authentication process. --- src/server/ApiManagers/GeneralGoogleManager.ts | 39 +++++++++++++------------- src/server/apis/google/GoogleApiServerUtils.ts | 13 ++------- 2 files changed, 22 insertions(+), 30 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/server/ApiManagers/GeneralGoogleManager.ts b/src/server/ApiManagers/GeneralGoogleManager.ts index 59d066934..693b17779 100644 --- a/src/server/ApiManagers/GeneralGoogleManager.ts +++ b/src/server/ApiManagers/GeneralGoogleManager.ts @@ -96,25 +96,26 @@ export default class GeneralGoogleManager extends ApiManager { register({ method: Method.GET, subscription: '/refreshGoogle', - secureHandler: async ({ user, req, res }) => { - const code = req.query.code as string; - - try { - const enriched = await GoogleApiServerUtils.processNewUser(user.id, code); - - if (enriched.refresh_token) { - if (enriched.refresh_token) { - user.googleToken = enriched.refresh_token; - await user.save(); - } else { - console.warn('No refresh token returned'); - } - } - } catch (err) { - console.error('Failed to process Google code:', err); - res.status(500).send('Error linking Google account'); - } - }, + secureHandler: async ({ user, req, res }) => + new Promise(resolve => + GoogleApiServerUtils.processNewUser(user.id, req.query.code as string) + .then(enriched => { + if (enriched.refresh_token) { + if (enriched.refresh_token) { + user.googleToken = enriched.refresh_token; + user.save(); + } else { + console.warn('No refresh token returned'); + } + } + res.status(200).send('Google account linked successfully!'); + }) + .catch(err => { + console.error('Failed to process Google code:', err); + res.status(500).send('Error linking Google account'); + }) + .finally(resolve) + ), }); } } diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 2f7ef473c..45c661730 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -14,6 +14,7 @@ import { DashUserModel } from '../../authentication/DashUserModel'; * This is the somewhat overkill list of what Dash requests * from the user. */ +// 'https://www.googleapis.com/auth/tasks', 'openid', 'profile' const scope = ['tasks', 'documents.readonly', 'documents', 'presentations', 'presentations.readonly', 'drive', 'drive.file', 'photoslibrary', 'photoslibrary.appendonly', 'photoslibrary.sharing', 'userinfo.profile'].map( relative => `https://www.googleapis.com/auth/${relative}` ); @@ -184,17 +185,7 @@ export namespace GoogleApiServerUtils { * @returns the newly generated url to the authentication landing page */ export function generateAuthenticationUrl(): string { - const oauth2Client = new google.auth.OAuth2( - '740987818053-dtflji3hfkn5r9t8ad6jb8740pls8moh.apps.googleusercontent.com', - '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', - 'http://localhost:1050/refreshGoogle' // Ensure this matches the redirect URI in Google Cloud Console - ); - - return oauth2Client.generateAuthUrl({ - access_type: 'offline', - scope: ['https://www.googleapis.com/auth/tasks', 'openid', 'profile'], - prompt: 'consent', // This ensures we get a refresh token - }); + return worker.generateAuthUrl({ scope, access_type: 'offline', prompt: 'consent' }); } /** -- cgit v1.2.3-70-g09d2 From 59689fe94c27986674dd6ecb7f0e6073861a98a6 Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 4 Jun 2025 22:07:36 -0400 Subject: more cleanup of google authorization --- src/server/ApiManagers/GeneralGoogleManager.ts | 12 +----------- src/server/apis/google/GoogleApiServerUtils.ts | 7 +++---- src/server/authentication/DashUserModel.ts | 6 ------ 3 files changed, 4 insertions(+), 21 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/server/ApiManagers/GeneralGoogleManager.ts b/src/server/ApiManagers/GeneralGoogleManager.ts index 693b17779..7581eec13 100644 --- a/src/server/ApiManagers/GeneralGoogleManager.ts +++ b/src/server/ApiManagers/GeneralGoogleManager.ts @@ -99,17 +99,7 @@ export default class GeneralGoogleManager extends ApiManager { secureHandler: async ({ user, req, res }) => new Promise(resolve => GoogleApiServerUtils.processNewUser(user.id, req.query.code as string) - .then(enriched => { - if (enriched.refresh_token) { - if (enriched.refresh_token) { - user.googleToken = enriched.refresh_token; - user.save(); - } else { - console.warn('No refresh token returned'); - } - } - res.status(200).send('Google account linked successfully!'); - }) + .then(() => res.status(200).send('Google account linked successfully!')) .catch(err => { console.error('Failed to process Google code:', err); res.status(500).send('Error linking Google account'); diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 45c661730..24905896d 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -14,7 +14,6 @@ import { DashUserModel } from '../../authentication/DashUserModel'; * This is the somewhat overkill list of what Dash requests * from the user. */ -// 'https://www.googleapis.com/auth/tasks', 'openid', 'profile' const scope = ['tasks', 'documents.readonly', 'documents', 'presentations', 'presentations.readonly', 'drive', 'drive.file', 'photoslibrary', 'photoslibrary.appendonly', 'photoslibrary.sharing', 'userinfo.profile'].map( relative => `https://www.googleapis.com/auth/${relative}` ); @@ -122,8 +121,7 @@ export namespace GoogleApiServerUtils { * @returns the relevant 'googleapis' wrapper, if any */ export async function GetEndpoint(sector: string, user: DashUserModel): Promise { - if (!user.googleToken) await retrieveOAuthClient(user); - const auth = user.googleToken; // await retrieveOAuthClient(user); + const auth = await retrieveOAuthClient(user); if (!auth) { return; } @@ -299,7 +297,7 @@ export namespace GoogleApiServerUtils { const headerParameters = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; const { client_id, client_secret } = GoogleCredentialsLoader.ProjectCredentials; const params = new URLSearchParams({ - refresh_token: credentials.refresh_token!, // AARAV use user.googleToken + refresh_token: credentials.refresh_token!, client_id, client_secret, grant_type: 'refresh_token', @@ -308,6 +306,7 @@ export namespace GoogleApiServerUtils { const { access_token, expires_in } = await new Promise<{ access_token: string; expires_in: number }>(resolve => { request.post(url, headerParameters).then(response => resolve(JSON.parse(response))); }); + // expires_in is in seconds, but we're building the new expiry date in milliseconds const expiry_date = new Date().getTime() + expires_in * 1000; await Database.Auxiliary.GoogleAccessToken.Update(user.id, access_token, expiry_date); diff --git a/src/server/authentication/DashUserModel.ts b/src/server/authentication/DashUserModel.ts index 4397e2bd4..debeef60c 100644 --- a/src/server/authentication/DashUserModel.ts +++ b/src/server/authentication/DashUserModel.ts @@ -9,14 +9,9 @@ export type DashUserModel = mongoose.Document & { passwordResetToken?: string; passwordResetExpires?: Date; - - // AARAV ADD - googleToken?: string; - dropboxRefresh?: string; dropboxToken?: string; - userDocumentId: string; sharingDocumentId: string; linkDatabaseId: string; @@ -45,7 +40,6 @@ const userSchema = new mongoose.Schema( passwordResetToken: String, passwordResetExpires: Date, - googleToken: String, dropboxRefresh: String, dropboxToken: String, userDocumentId: String, // id that identifies a document which hosts all of a user's account data -- cgit v1.2.3-70-g09d2 From d917449cb195fd151f6c3558a476a95e6675e2f3 Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 4 Jun 2025 22:30:58 -0400 Subject: more typing/cleanup for google authentication and dashUserModel --- src/server/ApiManagers/GeneralGoogleManager.ts | 6 +++--- src/server/apis/google/GoogleApiServerUtils.ts | 24 +++++++++++------------- src/server/authentication/DashUserModel.ts | 14 ++++++++------ src/server/authentication/Passport.ts | 6 +++--- 4 files changed, 25 insertions(+), 25 deletions(-) (limited to 'src/server/apis/google/GoogleApiServerUtils.ts') diff --git a/src/server/ApiManagers/GeneralGoogleManager.ts b/src/server/ApiManagers/GeneralGoogleManager.ts index 7581eec13..81efc3eb5 100644 --- a/src/server/ApiManagers/GeneralGoogleManager.ts +++ b/src/server/ApiManagers/GeneralGoogleManager.ts @@ -17,7 +17,7 @@ export default class GeneralGoogleManager extends ApiManager { method: Method.GET, subscription: '/readGoogleAccessToken', secureHandler: async ({ user, res }) => { - const { credentials } = await GoogleApiServerUtils.retrieveCredentials(user); + const { credentials } = await GoogleApiServerUtils.retrieveCredentials(user.id as string); if (!credentials?.access_token) { const url = GoogleApiServerUtils.generateAuthenticationUrl(); return res.send(url); @@ -49,7 +49,7 @@ export default class GeneralGoogleManager extends ApiManager { secureHandler: async ({ req, res, user }) => { const sector: GoogleApiServerUtils.Service = req.params.sector as GoogleApiServerUtils.Service; const action: GoogleApiServerUtils.Action = req.params.action as GoogleApiServerUtils.Action; - const endpoint = await GoogleApiServerUtils.GetEndpoint(GoogleApiServerUtils.Service[sector], user); + const endpoint = await GoogleApiServerUtils.GetEndpoint(GoogleApiServerUtils.Service[sector], user.id); const handler = EndpointHandlerMap.get(action); if (endpoint && handler) { try { @@ -71,7 +71,7 @@ export default class GeneralGoogleManager extends ApiManager { subscription: new RouteSubscriber('googleTasks').add('create'), secureHandler: async ({ req, res, user }) => { try { - const auth = await GoogleApiServerUtils.retrieveOAuthClient(user); + const auth = await GoogleApiServerUtils.retrieveOAuthClient(user.id); if (!auth) { return res.status(401).send('Google credentials missing or invalid.'); diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 24905896d..ad0f0e580 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -6,7 +6,6 @@ import * as request from 'request-promise'; import { Opt } from '../../../fields/Doc'; import { Database } from '../../database'; import { GoogleCredentialsLoader } from './CredentialsLoader'; -import { DashUserModel } from '../../authentication/DashUserModel'; /** * Scopes give Google users fine granularity of control @@ -59,7 +58,6 @@ export namespace GoogleApiServerUtils { */ export function processProjectCredentials(): void { const { client_secret: clientSecret, client_id: clientId, redirect_uris: redirectUris } = GoogleCredentialsLoader.ProjectCredentials; - console.log('Loaded Google redirect URIs:', redirectUris); // initialize the global authorization client oAuthOptions = { clientId, @@ -120,8 +118,8 @@ export namespace GoogleApiServerUtils { * @param userId the id of the Dash user making the request to the API * @returns the relevant 'googleapis' wrapper, if any */ - export async function GetEndpoint(sector: string, user: DashUserModel): Promise { - const auth = await retrieveOAuthClient(user); + export async function GetEndpoint(sector: string, userId: string): Promise { + const auth = await retrieveOAuthClient(userId); if (!auth) { return; } @@ -147,14 +145,14 @@ export namespace GoogleApiServerUtils { * npm-installed API wrappers that use authenticated client instances rather than access codes for * security. */ - export async function retrieveOAuthClient(user: DashUserModel): Promise { - const { credentials, refreshed } = await retrieveCredentials(user); + export async function retrieveOAuthClient(userId: string): Promise { + const { credentials, refreshed } = await retrieveCredentials(userId); if (!credentials) { return; } - let client = authenticationClients.get(user.id); + let client = authenticationClients.get(userId); if (!client) { - authenticationClients.set(user.id, (client = generateClient(credentials))); + authenticationClients.set(userId, (client = generateClient(credentials))); } else if (refreshed) { client.setCredentials(credentials); } @@ -269,15 +267,15 @@ export namespace GoogleApiServerUtils { * @returns the credentials, or undefined if the user has no stored associated credentials, * and a flag indicating whether or not they were refreshed during retrieval */ - export async function retrieveCredentials(user: DashUserModel): Promise<{ credentials: Opt; refreshed: boolean }> { - let credentials = await Database.Auxiliary.GoogleAccessToken.Fetch(user.id); + export async function retrieveCredentials(userId: string): Promise<{ credentials: Opt; refreshed: boolean }> { + let credentials = await Database.Auxiliary.GoogleAccessToken.Fetch(userId); let refreshed = false; if (!credentials) { return { credentials: undefined, refreshed }; } // check for token expiry if (credentials.expiry_date! <= new Date().getTime()) { - credentials = { ...credentials, ...(await refreshAccessToken(credentials, user)) }; + credentials = { ...credentials, ...(await refreshAccessToken(credentials, userId)) }; refreshed = true; } return { credentials, refreshed }; @@ -293,7 +291,7 @@ export namespace GoogleApiServerUtils { * his/her credentials be refreshed * @returns the updated credentials */ - async function refreshAccessToken(credentials: Credentials, user: DashUserModel): Promise { + async function refreshAccessToken(credentials: Credentials, userId: string): Promise { const headerParameters = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; const { client_id, client_secret } = GoogleCredentialsLoader.ProjectCredentials; const params = new URLSearchParams({ @@ -309,7 +307,7 @@ export namespace GoogleApiServerUtils { // expires_in is in seconds, but we're building the new expiry date in milliseconds const expiry_date = new Date().getTime() + expires_in * 1000; - await Database.Auxiliary.GoogleAccessToken.Update(user.id, access_token, expiry_date); + await Database.Auxiliary.GoogleAccessToken.Update(userId, access_token, expiry_date); // update the relevant properties credentials.access_token = access_token; credentials.expiry_date = expiry_date; diff --git a/src/server/authentication/DashUserModel.ts b/src/server/authentication/DashUserModel.ts index debeef60c..6fd8dd593 100644 --- a/src/server/authentication/DashUserModel.ts +++ b/src/server/authentication/DashUserModel.ts @@ -2,9 +2,10 @@ import * as bcrypt from 'bcrypt-nodejs'; import * as mongoose from 'mongoose'; import { Utils } from '../../Utils'; -type comparePasswordFunction = (candidatePassword: string, cb: (err: any, isMatch: any) => void) => void; -export type DashUserModel = mongoose.Document & { - email: String; +type comparePasswordFunction = (candidatePassword: string, cb: (err: Error, isMatch: boolean) => void) => void; +type mongooseDocument = { id: string }; // & mongoose.Document; +export type DashUserModel = mongooseDocument & { + email: string; password: string; passwordResetToken?: string; passwordResetExpires?: Date; @@ -65,12 +66,13 @@ const userSchema = new mongoose.Schema( /** * Password hash middleware. */ -userSchema.pre('save', function save(next) { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +userSchema.pre('save', function save(next: any) { const user = this; if (!user.isModified('password')) { return next(); } - bcrypt.genSalt(10, (err: any, salt: string) => { + bcrypt.genSalt(10, (err: Error, salt: string) => { if (err) { return next(err); } @@ -102,7 +104,7 @@ const comparePassword: comparePasswordFunction = function (this: DashUserModel, userSchema.methods.comparePassword = comparePassword; -const User: any = mongoose.model('User', userSchema); +const User = mongoose.model('User', userSchema); export function initializeGuest() { new User({ email: 'guest', diff --git a/src/server/authentication/Passport.ts b/src/server/authentication/Passport.ts index ca9e3058e..a62d38e3e 100644 --- a/src/server/authentication/Passport.ts +++ b/src/server/authentication/Passport.ts @@ -5,13 +5,13 @@ import User, { DashUserModel } from './DashUserModel'; const LocalStrategy = passportLocal.Strategy; passport.serializeUser((req, user, done) => { - done(undefined, (user as any)?.id); + done(undefined, (user as DashUserModel)?.id); }); passport.deserializeUser((id, done) => { User.findById(id) .exec() - .then((user: any) => done(undefined, user)); + .then((user: DashUserModel) => done(undefined, user)); }); // AUTHENTICATE JUST WITH EMAIL AND PASSWORD @@ -30,6 +30,6 @@ passport.use( }); } }) - .catch((error: any) => done(error)); + .catch((error: Error) => done(error)); }) ); -- cgit v1.2.3-70-g09d2