Skip to content

Commit a49f767

Browse files
authored
✨ tweak: update api key validation logic
1 parent 1ddb357 commit a49f767

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

source/utils/api.js

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,38 @@ import Conf from 'conf';
22

33
const config = new Conf({projectName: 'magicc'});
44

5-
const setOpenAIKey = (key) => {
6-
if (!key.startsWith('sk-') || key.length !== 51) {
7-
console.error('Invalid OpenAI API key. Please provide a valid key.');
8-
} else {
9-
config.set('openai', key);
5+
async function isValidOpenAIKey(apiKey) {
6+
try {
7+
const response = await fetch('https://api.openai.com/v1/models', {
8+
headers: {
9+
'Authorization': `Bearer ${apiKey}`
10+
}
11+
});
12+
13+
if (response.status === 200) {
14+
return true;
15+
} else if (response.status === 401) {
16+
console.error('Invalid API key');
17+
return false;
18+
} else {
19+
console.error('Unexpected response status:', response.status);
20+
return false;
21+
}
22+
} catch (error) {
23+
console.error('Error while validating API key:', error);
24+
return false;
1025
}
26+
}
27+
28+
const setOpenAIKey = (key) => {
29+
isValidOpenAIKey(key).then(isValid => {
30+
if (isValid) {
31+
console.log('API key is valid');
32+
config.set('openai', key);
33+
} else {
34+
console.log('API key is invalid');
35+
}
36+
});
1137
};
1238

1339
const getOpenAIKey = () => {

0 commit comments

Comments
 (0)