-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-google-api-keys.js
More file actions
executable file
·303 lines (249 loc) · 11.1 KB
/
test-google-api-keys.js
File metadata and controls
executable file
·303 lines (249 loc) · 11.1 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env node
/**
* Google API Key Validation Script
* Tests Google Maps and Places API functionality for the AIO app
*/
const https = require('https');
const fs = require('fs');
// Simple .env file parser
function loadEnvFile() {
try {
const envContent = fs.readFileSync('.env', 'utf8');
const envVars = {};
envContent.split('\n').forEach(line => {
line = line.trim();
if (line && !line.startsWith('#')) {
const [key, ...valueParts] = line.split('=');
if (key && valueParts.length > 0) {
envVars[key.trim()] = valueParts.join('=').trim();
}
}
});
// Set environment variables
Object.keys(envVars).forEach(key => {
if (!process.env[key]) {
process.env[key] = envVars[key];
}
});
} catch (error) {
console.log('No .env file found or error reading it, using system environment variables only');
}
}
// Load environment variables
loadEnvFile();
// Color codes for console output
const colors = {
green: '\x1b[32m',
red: '\x1b[31m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
reset: '\x1b[0m',
bold: '\x1b[1m'
};
class GoogleAPITester {
constructor() {
// Try to get API key from various environment variables
this.apiKey = process.env.GOOGLE_MAPS_API_KEY ||
process.env.VITE_GOOGLE_MAPS_API_KEY ||
process.env.GOOGLE_API_KEY;
this.testResults = [];
}
log(message, color = colors.reset) {
console.log(`${color}${message}${colors.reset}`);
}
logResult(test, status, details = '') {
const statusColor = status === 'PASS' ? colors.green :
status === 'FAIL' ? colors.red : colors.yellow;
this.log(`${statusColor}[${status}]${colors.reset} ${test}${details ? ': ' + details : ''}`);
this.testResults.push({ test, status, details });
}
async makeRequest(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
resolve({
statusCode: res.statusCode,
data: JSON.parse(data)
});
} catch (e) {
resolve({
statusCode: res.statusCode,
data: data
});
}
});
}).on('error', reject);
});
}
async testAPIKeyBasic() {
this.log(`\n${colors.bold}=== Testing API Key Configuration ===${colors.reset}`);
if (!this.apiKey) {
this.logResult('API Key Configuration', 'FAIL', 'No Google Maps API key found in environment variables');
return false;
}
if (this.apiKey === 'your_google_maps_api_key_here' ||
this.apiKey === 'test_key_for_development') {
this.logResult('API Key Configuration', 'FAIL', 'Using placeholder/test API key');
return false;
}
this.logResult('API Key Configuration', 'PASS', `Key found: ${this.apiKey.substring(0, 10)}...`);
return true;
}
async testGeocodingAPI() {
this.log(`\n${colors.bold}=== Testing Geocoding API ===${colors.reset}`);
const testAddress = 'Times Square, New York, NY';
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(testAddress)}&key=${this.apiKey}`;
try {
const response = await this.makeRequest(url);
if (response.statusCode !== 200) {
this.logResult('Geocoding API', 'FAIL', `HTTP ${response.statusCode}`);
return false;
}
const data = response.data;
if (data.status === 'OK' && data.results && data.results.length > 0) {
const location = data.results[0].geometry.location;
this.logResult('Geocoding API', 'PASS', `Found coordinates: ${location.lat}, ${location.lng}`);
return true;
} else {
this.logResult('Geocoding API', 'FAIL', `API Error: ${data.status} - ${data.error_message || 'Unknown error'}`);
return false;
}
} catch (error) {
this.logResult('Geocoding API', 'FAIL', `Network error: ${error.message}`);
return false;
}
}
async testPlacesAPI() {
this.log(`\n${colors.bold}=== Testing Places API ===${colors.reset}`);
// Test Places Nearby Search (commonly used for finding Subway locations)
const location = '40.7580,-73.9855'; // Times Square coordinates
const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location}&radius=1000&type=restaurant&keyword=subway&key=${this.apiKey}`;
try {
const response = await this.makeRequest(url);
if (response.statusCode !== 200) {
this.logResult('Places API (Nearby Search)', 'FAIL', `HTTP ${response.statusCode}`);
return false;
}
const data = response.data;
if (data.status === 'OK') {
this.logResult('Places API (Nearby Search)', 'PASS', `Found ${data.results.length} places`);
return true;
} else {
this.logResult('Places API (Nearby Search)', 'FAIL', `API Error: ${data.status} - ${data.error_message || 'Unknown error'}`);
return false;
}
} catch (error) {
this.logResult('Places API (Nearby Search)', 'FAIL', `Network error: ${error.message}`);
return false;
}
}
async testPlacesTextSearch() {
this.log(`\n${colors.bold}=== Testing Places Text Search ===${colors.reset}`);
const query = 'Subway restaurant near Times Square New York';
const url = `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${encodeURIComponent(query)}&key=${this.apiKey}`;
try {
const response = await this.makeRequest(url);
if (response.statusCode !== 200) {
this.logResult('Places API (Text Search)', 'FAIL', `HTTP ${response.statusCode}`);
return false;
}
const data = response.data;
if (data.status === 'OK') {
this.logResult('Places API (Text Search)', 'PASS', `Found ${data.results.length} places`);
return true;
} else {
this.logResult('Places API (Text Search)', 'FAIL', `API Error: ${data.status} - ${data.error_message || 'Unknown error'}`);
return false;
}
} catch (error) {
this.logResult('Places API (Text Search)', 'FAIL', `Network error: ${error.message}`);
return false;
}
}
async testMapsJavaScriptAPI() {
this.log(`\n${colors.bold}=== Testing Maps JavaScript API ===${colors.reset}`);
// Test if the API key works with Maps JavaScript API by checking a simple request
const url = `https://maps.googleapis.com/maps/api/js?key=${this.apiKey}&libraries=places`;
try {
const response = await this.makeRequest(url);
if (response.statusCode === 200) {
this.logResult('Maps JavaScript API', 'PASS', 'API key accepted');
return true;
} else {
this.logResult('Maps JavaScript API', 'FAIL', `HTTP ${response.statusCode}`);
return false;
}
} catch (error) {
this.logResult('Maps JavaScript API', 'FAIL', `Network error: ${error.message}`);
return false;
}
}
checkAPIPermissions() {
this.log(`\n${colors.bold}=== API Permissions Recommendations ===${colors.reset}`);
const requiredAPIs = [
'Maps JavaScript API',
'Places API',
'Geocoding API',
'Maps Static API (optional)'
];
this.log(`${colors.yellow}Ensure these APIs are enabled in Google Cloud Console:${colors.reset}`);
requiredAPIs.forEach(api => {
this.log(` • ${api}`);
});
this.log(`\n${colors.yellow}API Key Restrictions (recommended):${colors.reset}`);
this.log(` • HTTP referrers: Add your domain(s)`);
this.log(` • API restrictions: Enable only the APIs listed above`);
}
generateReport() {
this.log(`\n${colors.bold}=== Test Summary ===${colors.reset}`);
const passed = this.testResults.filter(r => r.status === 'PASS').length;
const failed = this.testResults.filter(r => r.status === 'FAIL').length;
const warnings = this.testResults.filter(r => r.status === 'WARN').length;
this.log(`${colors.green}Passed: ${passed}${colors.reset}`);
this.log(`${colors.red}Failed: ${failed}${colors.reset}`);
if (warnings > 0) {
this.log(`${colors.yellow}Warnings: ${warnings}${colors.reset}`);
}
if (failed === 0) {
this.log(`\n${colors.green}${colors.bold}✓ All tests passed! Your Google API key is working correctly.${colors.reset}`);
} else {
this.log(`\n${colors.red}${colors.bold}✗ Some tests failed. Check your API key and enabled services.${colors.reset}`);
}
// Save detailed report
const report = {
timestamp: new Date().toISOString(),
apiKey: this.apiKey ? `${this.apiKey.substring(0, 10)}...` : 'Not found',
results: this.testResults,
summary: { passed, failed, warnings }
};
fs.writeFileSync('google-api-test-report.json', JSON.stringify(report, null, 2));
this.log(`\n${colors.blue}Detailed report saved to: google-api-test-report.json${colors.reset}`);
}
async runAllTests() {
this.log(`${colors.bold}${colors.blue}Google Maps API Key Validation${colors.reset}`);
this.log(`${colors.blue}================================${colors.reset}`);
const hasValidKey = await this.testAPIKeyBasic();
if (!hasValidKey) {
this.log(`\n${colors.red}Cannot proceed with API tests - invalid or missing API key${colors.reset}`);
this.checkAPIPermissions();
this.generateReport();
return;
}
// Run all API tests
await this.testGeocodingAPI();
await this.testPlacesAPI();
await this.testPlacesTextSearch();
await this.testMapsJavaScriptAPI();
this.checkAPIPermissions();
this.generateReport();
}
}
// Run the tests
const tester = new GoogleAPITester();
tester.runAllTests().catch(error => {
console.error(`${colors.red}Test runner error: ${error.message}${colors.reset}`);
process.exit(1);
});