-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
190 lines (155 loc) Β· 6.32 KB
/
Copy pathapi.js
File metadata and controls
190 lines (155 loc) Β· 6.32 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
const { ApolloServer, gql } = require('apollo-server');
const fs = require('fs');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
// Secrets for JWT verification
const JWT_SECRET = 'supersecretkey';
const ADMIN_SECRET = 'adminsecretkey';
// Utility functions to read/write files
const loadFromFile = (filename) => {
if (fs.existsSync(filename)) {
return JSON.parse(fs.readFileSync(filename));
}
return [];
};
const saveToFile = (filename, data) => {
fs.writeFileSync(filename, JSON.stringify(data, null, 2));
};
// Validate and decode the user token
const validateUserToken = (token) => {
try {
console.log('Validating user token:', token);
// Reload tokens from the file to ensure it's up to date
const userTokens = loadFromFile('tokens.json');
// Trim token to remove unnecessary whitespace
token = token.trim();
// Check if the token exists in tokens.json
if (!userTokens.includes(token)) {
console.error('Token not found in tokens.json:', token);
throw new Error('Unauthorized: Invalid user token');
}
// Decode and verify the token
const decoded = jwt.verify(token, JWT_SECRET); // Ensure JWT_SECRET matches the signing key
return decoded; // Return the decoded payload
} catch (err) {
console.error('Token validation error:', err.message);
throw new Error('Unauthorized: Invalid or expired user token');
}
};
// Validate and decode the admin token
const validateAdminToken = (adminToken) => {
try {
console.log('Validating admin token:', adminToken);
// Reload admin tokens from adtokens.json
const adminTokens = loadFromFile('adtokens.json');
// Trim the token to avoid formatting issues
adminToken = adminToken.trim();
// Check if the token exists in adtokens.json
if (!adminTokens.includes(adminToken)) {
console.error('Admin token not found in adtokens.json:', adminToken);
throw new Error('Unauthorized: Invalid admin token');
}
// Decode and verify the admin token
const decoded = jwt.verify(adminToken, ADMIN_SECRET); // Ensure ADMIN_SECRET matches the signing key
return decoded; // Return the decoded payload
} catch (err) {
console.error('Admin token validation error:', err.message);
throw new Error('Unauthorized: Invalid or expired admin token');
}
};
// Type definitions (Schema)
const typeDefs = gql`
type APIKey {
key: String!
}
type Query {
queryAPIKey(token: String!): APIKey!
}
type Mutation {
generateAPIKey(token: String!): APIKey!
revokeAPIKey(token: String!): APIKey!
createSuperKey(adminToken: String!): APIKey!
}
`;
// Resolvers
const resolvers = {
Query: {
queryAPIKey: (_, { token }) => {
// Validate and decode the token
const userData = validateUserToken(token);
// Load existing API keys
const apiKeys = loadFromFile('apikeys.json');
// Find the API key for the user by email
let userKey = apiKeys.find((key) => key.email === userData.email);
if (!userKey) {
// Create a new API key if email not found
const apiKey = crypto.randomBytes(32).toString('hex');
userKey = { email: userData.email, apiKey, userData };
apiKeys.push(userKey);
saveToFile('apikeys.json', apiKeys);
}
return { key: userKey.apiKey };
},
},
Mutation: {
generateAPIKey: (_, { token }) => {
// Validate and decode the token
const userData = validateUserToken(token);
// Load existing API keys
const apiKeys = loadFromFile('apikeys.json');
// Check if an API key already exists for the user by email
let userKey = apiKeys.find((key) => key.email === userData.email);
if (userKey) {
throw new Error('API key already exists for this user. Revoke the existing key to generate a new one.');
}
// Generate a random API key
const apiKey = crypto.randomBytes(32).toString('hex');
// Save the new API key with user email
userKey = { email: userData.email, apiKey, userData };
apiKeys.push(userKey);
saveToFile('apikeys.json', apiKeys);
return { key: apiKey };
},
revokeAPIKey: (_, { token }) => {
// Validate and decode the token
const userData = validateUserToken(token);
// Load existing API keys
const apiKeys = loadFromFile('apikeys.json');
// Find and remove the existing API key by email
const existingKeyIndex = apiKeys.findIndex((key) => key.email === userData.email);
if (existingKeyIndex === -1) {
throw new Error('No existing API key found for this user to revoke.');
}
apiKeys.splice(existingKeyIndex, 1);
// Generate a new API key
const newApiKey = crypto.randomBytes(32).toString('hex');
// Save the new API key with user email
const newUserKey = { email: userData.email, apiKey: newApiKey, userData };
apiKeys.push(newUserKey);
saveToFile('apikeys.json', apiKeys);
return { key: newApiKey };
},
createSuperKey: (_, { adminToken }) => {
// Validate and decode the admin token
const adminData = validateAdminToken(adminToken);
// Load existing super keys
const superKeys = loadFromFile('superkeys.json');
// Generate a new Super API key
const superApiKey = crypto.randomBytes(64).toString('hex');
// Save the new super key with admin email
const superKeyEntry = { email: adminData.email, superApiKey };
superKeys.push(superKeyEntry);
saveToFile('superkeys.json', superKeys);
return { key: superApiKey };
},
},
};
// Create an Apollo Server instance
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Start the server
server.listen().then(({ url }) => {
console.log(`π Server ready at ${url}`);
});