Spaces:
Paused
Paused
Update lib/services/api-key-service.ts
Browse files- lib/services/api-key-service.ts +196 -196
lib/services/api-key-service.ts
CHANGED
|
@@ -1,196 +1,196 @@
|
|
| 1 |
-
import { db } from '@/lib/db';
|
| 2 |
-
|
| 3 |
-
import {
|
| 4 |
-
import { sql } from 'drizzle-orm
|
| 5 |
-
import { generateApiKey } from '@/lib/utils/api-key-generator';
|
| 6 |
-
|
| 7 |
-
export class ApiKeyService {
|
| 8 |
-
static async createApiKey(userId: string, keyName: string) {
|
| 9 |
-
try {
|
| 10 |
-
const keyValue = generateApiKey();
|
| 11 |
-
|
| 12 |
-
const newApiKey = {
|
| 13 |
-
userId,
|
| 14 |
-
keyName,
|
| 15 |
-
keyValue,
|
| 16 |
-
isActive: true,
|
| 17 |
-
createdAt: new Date(),
|
| 18 |
-
updatedAt: new Date(),
|
| 19 |
-
};
|
| 20 |
-
|
| 21 |
-
const [createdApiKey] = await db
|
| 22 |
-
.insert(apiKeysTable)
|
| 23 |
-
.values(newApiKey)
|
| 24 |
-
.returning();
|
| 25 |
-
|
| 26 |
-
return createdApiKey;
|
| 27 |
-
} catch (error) {
|
| 28 |
-
console.error('Error creating API key:', error);
|
| 29 |
-
throw new Error('Failed to create API key');
|
| 30 |
-
}
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
static async getUserApiKeys(userId: string) {
|
| 34 |
-
try {
|
| 35 |
-
const apiKeys = await db
|
| 36 |
-
.select()
|
| 37 |
-
.from(apiKeysTable)
|
| 38 |
-
.where(eq(apiKeysTable.userId, userId));
|
| 39 |
-
|
| 40 |
-
return apiKeys;
|
| 41 |
-
} catch (error) {
|
| 42 |
-
console.error('Error fetching API keys:', error);
|
| 43 |
-
return [];
|
| 44 |
-
}
|
| 45 |
-
}
|
| 46 |
-
|
| 47 |
-
static async deleteApiKey(userId: string, keyId: string) {
|
| 48 |
-
try {
|
| 49 |
-
await db
|
| 50 |
-
.delete(apiKeysTable)
|
| 51 |
-
.where(
|
| 52 |
-
and(
|
| 53 |
-
eq(apiKeysTable.id, keyId),
|
| 54 |
-
eq(apiKeysTable.userId, userId)
|
| 55 |
-
)
|
| 56 |
-
);
|
| 57 |
-
|
| 58 |
-
return true;
|
| 59 |
-
} catch (error) {
|
| 60 |
-
console.error('Error deleting API key:', error);
|
| 61 |
-
throw new Error('Failed to delete API key');
|
| 62 |
-
}
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
static async toggleApiKeyStatus(userId: string, keyId: string, isActive: boolean) {
|
| 66 |
-
try {
|
| 67 |
-
const [updatedApiKey] = await db
|
| 68 |
-
.update(apiKeysTable)
|
| 69 |
-
.set({
|
| 70 |
-
isActive,
|
| 71 |
-
updatedAt: new Date(),
|
| 72 |
-
})
|
| 73 |
-
.where(
|
| 74 |
-
and(
|
| 75 |
-
eq(apiKeysTable.id, keyId),
|
| 76 |
-
eq(apiKeysTable.userId, userId)
|
| 77 |
-
)
|
| 78 |
-
)
|
| 79 |
-
.returning();
|
| 80 |
-
|
| 81 |
-
return updatedApiKey;
|
| 82 |
-
} catch (error) {
|
| 83 |
-
console.error('Error updating API key status:', error);
|
| 84 |
-
throw new Error('Failed to update API key status');
|
| 85 |
-
}
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
-
static async validateAndIncrementUsage(keyValue: string) {
|
| 89 |
-
try {
|
| 90 |
-
// Find the API key and get user info
|
| 91 |
-
const [apiKey] = await db
|
| 92 |
-
.select({
|
| 93 |
-
id: apiKeysTable.id,
|
| 94 |
-
userId: apiKeysTable.userId,
|
| 95 |
-
keyName: apiKeysTable.keyName,
|
| 96 |
-
isActive: apiKeysTable.isActive,
|
| 97 |
-
userRequestsUsed: usersTable.requestsUsed,
|
| 98 |
-
userRequestsLimit: usersTable.requestsLimit,
|
| 99 |
-
})
|
| 100 |
-
.from(apiKeysTable)
|
| 101 |
-
.leftJoin(usersTable, eq(apiKeysTable.userId, usersTable.uid))
|
| 102 |
-
.where(eq(apiKeysTable.keyValue, keyValue))
|
| 103 |
-
.limit(1);
|
| 104 |
-
|
| 105 |
-
if (!apiKey) {
|
| 106 |
-
console.log('API key not found:', keyValue.slice(0, 8) + '...');
|
| 107 |
-
return null;
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
// Check if key is active
|
| 111 |
-
if (!apiKey.isActive) {
|
| 112 |
-
console.log('API key is inactive:', keyValue.slice(0, 8) + '...');
|
| 113 |
-
return null;
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
// Check if user usage limit is exceeded
|
| 117 |
-
const requestsUsed = Number(apiKey.userRequestsUsed) || 0;
|
| 118 |
-
const requestsLimit = Number(apiKey.userRequestsLimit) || 1000;
|
| 119 |
-
|
| 120 |
-
if (requestsUsed >= requestsLimit) {
|
| 121 |
-
console.log('Request limit exceeded:', { requestsUsed, requestsLimit });
|
| 122 |
-
return null;
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
-
// Increment user's usage count
|
| 126 |
-
console.log('Incrementing usage count for user:', apiKey.userId);
|
| 127 |
-
await db
|
| 128 |
-
.update(usersTable)
|
| 129 |
-
.set({
|
| 130 |
-
requestsUsed: sql`COALESCE(${usersTable.requestsUsed}, 0) + 1`,
|
| 131 |
-
})
|
| 132 |
-
.where(eq(usersTable.uid, apiKey.userId));
|
| 133 |
-
|
| 134 |
-
const newRequestsUsed = requestsUsed + 1;
|
| 135 |
-
|
| 136 |
-
console.log('Usage incremented successfully:', {
|
| 137 |
-
userId: apiKey.userId,
|
| 138 |
-
oldCount: requestsUsed,
|
| 139 |
-
newCount: newRequestsUsed,
|
| 140 |
-
});
|
| 141 |
-
|
| 142 |
-
return {
|
| 143 |
-
id: apiKey.id,
|
| 144 |
-
userId: apiKey.userId,
|
| 145 |
-
keyName: apiKey.keyName,
|
| 146 |
-
isActive: apiKey.isActive,
|
| 147 |
-
requestsUsed: newRequestsUsed,
|
| 148 |
-
requestsLimit: requestsLimit,
|
| 149 |
-
};
|
| 150 |
-
} catch (error) {
|
| 151 |
-
console.error('Error in validateAndIncrementUsage:', error);
|
| 152 |
-
throw error;
|
| 153 |
-
}
|
| 154 |
-
}
|
| 155 |
-
|
| 156 |
-
static async validateApiKey(keyValue: string) {
|
| 157 |
-
try {
|
| 158 |
-
const [apiKey] = await db
|
| 159 |
-
.select({
|
| 160 |
-
id: apiKeysTable.id,
|
| 161 |
-
userId: apiKeysTable.userId,
|
| 162 |
-
keyName: apiKeysTable.keyName,
|
| 163 |
-
isActive: apiKeysTable.isActive,
|
| 164 |
-
userRequestsUsed: usersTable.requestsUsed,
|
| 165 |
-
userRequestsLimit: usersTable.requestsLimit,
|
| 166 |
-
})
|
| 167 |
-
.from(apiKeysTable)
|
| 168 |
-
.leftJoin(usersTable, eq(apiKeysTable.userId, usersTable.uid))
|
| 169 |
-
.where(eq(apiKeysTable.keyValue, keyValue))
|
| 170 |
-
.limit(1);
|
| 171 |
-
|
| 172 |
-
if (!apiKey) {
|
| 173 |
-
return null;
|
| 174 |
-
}
|
| 175 |
-
|
| 176 |
-
const requestsUsed = Number(apiKey.userRequestsUsed) || 0;
|
| 177 |
-
const requestsLimit = Number(apiKey.userRequestsLimit) || 1000;
|
| 178 |
-
|
| 179 |
-
if (!apiKey.isActive || requestsUsed >= requestsLimit) {
|
| 180 |
-
return null;
|
| 181 |
-
}
|
| 182 |
-
|
| 183 |
-
return {
|
| 184 |
-
id: apiKey.id,
|
| 185 |
-
userId: apiKey.userId,
|
| 186 |
-
keyName: apiKey.keyName,
|
| 187 |
-
isActive: apiKey.isActive,
|
| 188 |
-
requestsUsed: requestsUsed,
|
| 189 |
-
requestsLimit: requestsLimit,
|
| 190 |
-
};
|
| 191 |
-
} catch (error) {
|
| 192 |
-
console.error('Error validating API key:', error);
|
| 193 |
-
throw error;
|
| 194 |
-
}
|
| 195 |
-
}
|
| 196 |
-
}
|
|
|
|
| 1 |
+
import { db } from '@/lib/db';
|
| 2 |
+
// Assuming these are the correct named exports from your schema file based on your snippet
|
| 3 |
+
import { apiKeysTable, usersTable } from '@/lib/db/schema';
|
| 4 |
+
import { eq, and, sql } from 'drizzle-orm';
|
| 5 |
+
import { generateApiKey } from '@/lib/utils/api-key-generator';
|
| 6 |
+
|
| 7 |
+
export class ApiKeyService {
|
| 8 |
+
static async createApiKey(userId: string, keyName: string) {
|
| 9 |
+
try {
|
| 10 |
+
const keyValue = generateApiKey();
|
| 11 |
+
|
| 12 |
+
const newApiKey = {
|
| 13 |
+
userId,
|
| 14 |
+
keyName,
|
| 15 |
+
keyValue,
|
| 16 |
+
isActive: true,
|
| 17 |
+
createdAt: new Date(),
|
| 18 |
+
updatedAt: new Date(),
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
const [createdApiKey] = await db
|
| 22 |
+
.insert(apiKeysTable)
|
| 23 |
+
.values(newApiKey)
|
| 24 |
+
.returning();
|
| 25 |
+
|
| 26 |
+
return createdApiKey;
|
| 27 |
+
} catch (error) {
|
| 28 |
+
console.error('Error creating API key:', error);
|
| 29 |
+
throw new Error('Failed to create API key');
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
static async getUserApiKeys(userId: string) {
|
| 34 |
+
try {
|
| 35 |
+
const apiKeys = await db
|
| 36 |
+
.select()
|
| 37 |
+
.from(apiKeysTable)
|
| 38 |
+
.where(eq(apiKeysTable.userId, userId));
|
| 39 |
+
|
| 40 |
+
return apiKeys;
|
| 41 |
+
} catch (error) {
|
| 42 |
+
console.error('Error fetching API keys:', error);
|
| 43 |
+
return [];
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
static async deleteApiKey(userId: string, keyId: string) {
|
| 48 |
+
try {
|
| 49 |
+
await db
|
| 50 |
+
.delete(apiKeysTable)
|
| 51 |
+
.where(
|
| 52 |
+
and(
|
| 53 |
+
eq(apiKeysTable.id, keyId),
|
| 54 |
+
eq(apiKeysTable.userId, userId)
|
| 55 |
+
)
|
| 56 |
+
);
|
| 57 |
+
|
| 58 |
+
return true;
|
| 59 |
+
} catch (error) {
|
| 60 |
+
console.error('Error deleting API key:', error);
|
| 61 |
+
throw new Error('Failed to delete API key');
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
static async toggleApiKeyStatus(userId: string, keyId: string, isActive: boolean) {
|
| 66 |
+
try {
|
| 67 |
+
const [updatedApiKey] = await db
|
| 68 |
+
.update(apiKeysTable)
|
| 69 |
+
.set({
|
| 70 |
+
isActive,
|
| 71 |
+
updatedAt: new Date(),
|
| 72 |
+
})
|
| 73 |
+
.where(
|
| 74 |
+
and(
|
| 75 |
+
eq(apiKeysTable.id, keyId),
|
| 76 |
+
eq(apiKeysTable.userId, userId)
|
| 77 |
+
)
|
| 78 |
+
)
|
| 79 |
+
.returning();
|
| 80 |
+
|
| 81 |
+
return updatedApiKey;
|
| 82 |
+
} catch (error) {
|
| 83 |
+
console.error('Error updating API key status:', error);
|
| 84 |
+
throw new Error('Failed to update API key status');
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
static async validateAndIncrementUsage(keyValue: string) {
|
| 89 |
+
try {
|
| 90 |
+
// Find the API key and get user info
|
| 91 |
+
const [apiKey] = await db
|
| 92 |
+
.select({
|
| 93 |
+
id: apiKeysTable.id,
|
| 94 |
+
userId: apiKeysTable.userId,
|
| 95 |
+
keyName: apiKeysTable.keyName,
|
| 96 |
+
isActive: apiKeysTable.isActive,
|
| 97 |
+
userRequestsUsed: usersTable.requestsUsed,
|
| 98 |
+
userRequestsLimit: usersTable.requestsLimit,
|
| 99 |
+
})
|
| 100 |
+
.from(apiKeysTable)
|
| 101 |
+
.leftJoin(usersTable, eq(apiKeysTable.userId, usersTable.uid))
|
| 102 |
+
.where(eq(apiKeysTable.keyValue, keyValue))
|
| 103 |
+
.limit(1);
|
| 104 |
+
|
| 105 |
+
if (!apiKey) {
|
| 106 |
+
console.log('API key not found:', keyValue.slice(0, 8) + '...');
|
| 107 |
+
return null;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
// Check if key is active
|
| 111 |
+
if (!apiKey.isActive) {
|
| 112 |
+
console.log('API key is inactive:', keyValue.slice(0, 8) + '...');
|
| 113 |
+
return null;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Check if user usage limit is exceeded
|
| 117 |
+
const requestsUsed = Number(apiKey.userRequestsUsed) || 0;
|
| 118 |
+
const requestsLimit = Number(apiKey.userRequestsLimit) || 1000;
|
| 119 |
+
|
| 120 |
+
if (requestsUsed >= requestsLimit) {
|
| 121 |
+
console.log('Request limit exceeded:', { requestsUsed, requestsLimit });
|
| 122 |
+
return null;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// Increment user's usage count
|
| 126 |
+
console.log('Incrementing usage count for user:', apiKey.userId);
|
| 127 |
+
await db
|
| 128 |
+
.update(usersTable)
|
| 129 |
+
.set({
|
| 130 |
+
requestsUsed: sql`COALESCE(${usersTable.requestsUsed}, 0) + 1`,
|
| 131 |
+
})
|
| 132 |
+
.where(eq(usersTable.uid, apiKey.userId));
|
| 133 |
+
|
| 134 |
+
const newRequestsUsed = requestsUsed + 1;
|
| 135 |
+
|
| 136 |
+
console.log('Usage incremented successfully:', {
|
| 137 |
+
userId: apiKey.userId,
|
| 138 |
+
oldCount: requestsUsed,
|
| 139 |
+
newCount: newRequestsUsed,
|
| 140 |
+
});
|
| 141 |
+
|
| 142 |
+
return {
|
| 143 |
+
id: apiKey.id,
|
| 144 |
+
userId: apiKey.userId,
|
| 145 |
+
keyName: apiKey.keyName,
|
| 146 |
+
isActive: apiKey.isActive,
|
| 147 |
+
requestsUsed: newRequestsUsed,
|
| 148 |
+
requestsLimit: requestsLimit,
|
| 149 |
+
};
|
| 150 |
+
} catch (error) {
|
| 151 |
+
console.error('Error in validateAndIncrementUsage:', error);
|
| 152 |
+
throw error;
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
static async validateApiKey(keyValue: string) {
|
| 157 |
+
try {
|
| 158 |
+
const [apiKey] = await db
|
| 159 |
+
.select({
|
| 160 |
+
id: apiKeysTable.id,
|
| 161 |
+
userId: apiKeysTable.userId,
|
| 162 |
+
keyName: apiKeysTable.keyName,
|
| 163 |
+
isActive: apiKeysTable.isActive,
|
| 164 |
+
userRequestsUsed: usersTable.requestsUsed,
|
| 165 |
+
userRequestsLimit: usersTable.requestsLimit,
|
| 166 |
+
})
|
| 167 |
+
.from(apiKeysTable)
|
| 168 |
+
.leftJoin(usersTable, eq(apiKeysTable.userId, usersTable.uid))
|
| 169 |
+
.where(eq(apiKeysTable.keyValue, keyValue))
|
| 170 |
+
.limit(1);
|
| 171 |
+
|
| 172 |
+
if (!apiKey) {
|
| 173 |
+
return null;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
const requestsUsed = Number(apiKey.userRequestsUsed) || 0;
|
| 177 |
+
const requestsLimit = Number(apiKey.userRequestsLimit) || 1000;
|
| 178 |
+
|
| 179 |
+
if (!apiKey.isActive || requestsUsed >= requestsLimit) {
|
| 180 |
+
return null;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
return {
|
| 184 |
+
id: apiKey.id,
|
| 185 |
+
userId: apiKey.userId,
|
| 186 |
+
keyName: apiKey.keyName,
|
| 187 |
+
isActive: apiKey.isActive,
|
| 188 |
+
requestsUsed: requestsUsed,
|
| 189 |
+
requestsLimit: requestsLimit,
|
| 190 |
+
};
|
| 191 |
+
} catch (error) {
|
| 192 |
+
console.error('Error validating API key:', error);
|
| 193 |
+
throw error;
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
}
|