-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
172 lines (147 loc) · 5.05 KB
/
Copy pathauth.ts
File metadata and controls
172 lines (147 loc) · 5.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { authenticate } from "@google-cloud/local-auth";
import { google } from "googleapis";
import fs from "fs";
import path from "path";
export const SCOPES = [
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/spreadsheets",
];
// Get credentials directory from environment variable or use default
const CREDS_DIR =
process.env.GDRIVE_CREDS_DIR ||
path.join(path.dirname(new URL(import.meta.url).pathname), "../../../");
// Ensure the credentials directory exists
function ensureCredsDirectory() {
try {
fs.mkdirSync(CREDS_DIR, { recursive: true });
console.error(`Ensured credentials directory exists at: ${CREDS_DIR}`);
} catch (error) {
console.error(
`Failed to create credentials directory: ${CREDS_DIR}`,
error,
);
throw error;
}
}
const credentialsPath = path.join(CREDS_DIR, ".gdrive-server-credentials.json");
async function authenticateWithTimeout(
keyfilePath: string,
SCOPES: string[],
timeoutMs = 30000,
): Promise<any | null> {
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Authentication timed out")), timeoutMs),
);
const authPromise = authenticate({
keyfilePath,
scopes: SCOPES,
});
try {
return await Promise.race([authPromise, timeoutPromise]);
} catch (error) {
console.error(error);
return null;
}
}
async function authenticateAndSaveCredentials() {
console.error("Launching auth flow…");
console.error("Using credentials path:", credentialsPath);
const keyfilePath = path.join(CREDS_DIR, "gcp-oauth.keys.json");
console.error("Using keyfile path:", keyfilePath);
const auth = await authenticateWithTimeout(keyfilePath, SCOPES);
if (auth) {
const newAuth = new google.auth.OAuth2();
newAuth.setCredentials(auth.credentials);
}
try {
const { credentials } = await auth.refreshAccessToken();
console.error("Received new credentials with scopes:", credentials.scope);
// Ensure directory exists before saving
ensureCredsDirectory();
fs.writeFileSync(credentialsPath, JSON.stringify(credentials, null, 2));
console.error(
"Credentials saved successfully with refresh token to:",
credentialsPath,
);
auth.setCredentials(credentials);
return auth;
} catch (error) {
console.error("Error refreshing token during initial auth:", error);
return auth;
}
}
// Try to load credentials without prompting for auth
export async function loadCredentialsQuietly() {
console.error("Attempting to load credentials from:", credentialsPath);
const oauth2Client = new google.auth.OAuth2(
process.env.CLIENT_ID,
process.env.CLIENT_SECRET,
);
if (!fs.existsSync(credentialsPath)) {
console.error("No credentials file found");
return null;
}
try {
const savedCreds = JSON.parse(fs.readFileSync(credentialsPath, "utf-8"));
console.error("Loaded existing credentials with scopes:", savedCreds.scope);
oauth2Client.setCredentials(savedCreds);
const expiryDate = new Date(savedCreds.expiry_date);
const now = new Date();
const fiveMinutes = 5 * 60 * 1000;
const timeToExpiry = expiryDate.getTime() - now.getTime();
console.error("Token expiry status:", {
expiryDate: expiryDate.toISOString(),
timeToExpiryMinutes: Math.floor(timeToExpiry / (60 * 1000)),
hasRefreshToken: !!savedCreds.refresh_token,
});
if (timeToExpiry < fiveMinutes && savedCreds.refresh_token) {
console.error("Attempting to refresh token using refresh_token");
try {
const response = await oauth2Client.refreshAccessToken();
const newCreds = response.credentials;
ensureCredsDirectory();
fs.writeFileSync(credentialsPath, JSON.stringify(newCreds, null, 2));
oauth2Client.setCredentials(newCreds);
console.error("Token refreshed and saved successfully");
} catch (error) {
console.error("Failed to refresh token:", error);
return null;
}
}
return oauth2Client;
} catch (error) {
console.error("Error loading credentials:", error);
return null;
}
}
// Get valid credentials, prompting for auth if necessary
export async function getValidCredentials(forceAuth = false) {
if (!forceAuth) {
const quietAuth = await loadCredentialsQuietly();
if (quietAuth) {
return quietAuth;
}
}
return await authenticateAndSaveCredentials();
}
// Background refresh that never prompts for auth
export function setupTokenRefresh() {
console.error("Setting up automatic token refresh interval (45 minutes)");
return setInterval(
async () => {
try {
console.error("Running scheduled token refresh check");
const auth = await loadCredentialsQuietly();
if (auth) {
google.options({ auth });
console.error("Completed scheduled token refresh");
} else {
console.error("Skipping token refresh - no valid credentials");
}
} catch (error) {
console.error("Error in automatic token refresh:", error);
}
},
45 * 60 * 1000,
);
}