Add account API key management
This commit is contained in:
1 parent
98b824ce48
commit
f1c5b4f7bb
32 files changed
+1618
-15
No files matched your search
@@ -1,4 +1,11 @@
|
||||
import debug from 'debug';
|
||||
import {
|
||||
API_KEY_LAST_USED_INTERVAL,
|
||||
hashApiKey,
|
||||
isApiKey,
|
||||
isApiKeyBlockedPath,
|
||||
isApiKeyEnabled,
|
||||
} from '@/lib/api-key';
|
||||
import {
|
||||
ROLE_PERMISSIONS,
|
||||
ROLES,
|
||||
@@ -10,6 +17,7 @@ import { createAuthKey, hash, secret } from '@/lib/crypto';
|
||||
import { createSecureToken, parseSecureToken, parseToken } from '@/lib/jwt';
|
||||
import redis from '@/lib/redis';
|
||||
import { ensureArray } from '@/lib/utils';
|
||||
import { getApiKeyByHash, updateApiKeyLastUsed } from '@/queries/prisma/apiKey';
|
||||
import { getUser } from '@/queries/prisma/user';
|
||||
|
||||
const log = debug('umami:auth');
|
||||
@@ -20,8 +28,51 @@ export function getBearerToken(request: Request) {
|
||||
return auth?.split(' ')[1];
|
||||
}
|
||||
|
||||
export async function checkApiKeyAuth(request: Request, token: string) {
|
||||
const { pathname } = new URL(request.url);
|
||||
|
||||
if (isApiKeyBlockedPath(pathname)) {
|
||||
log('API key not allowed for path', pathname);
|
||||
return null;
|
||||
}
|
||||
|
||||
const apiKey = await getApiKeyByHash(hashApiKey(token));
|
||||
|
||||
if (!apiKey) {
|
||||
log('API key not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
const user: any = await getUser(apiKey.userId);
|
||||
|
||||
if (!user?.id) {
|
||||
log('API key user not found');
|
||||
return null;
|
||||
}
|
||||
|
||||
const lastUsedAt = apiKey.lastUsedAt?.getTime() ?? 0;
|
||||
|
||||
if (Date.now() - lastUsedAt > API_KEY_LAST_USED_INTERVAL) {
|
||||
updateApiKeyLastUsed(apiKey.id).catch(e => log(e));
|
||||
}
|
||||
|
||||
delete user.password;
|
||||
user.isAdmin = user.role === ROLES.admin;
|
||||
|
||||
return {
|
||||
token,
|
||||
user,
|
||||
apiKey: { id: apiKey.id, name: apiKey.name },
|
||||
};
|
||||
}
|
||||
|
||||
export async function checkAuth(request: Request) {
|
||||
const token = getBearerToken(request);
|
||||
|
||||
if (isApiKeyEnabled() && isApiKey(token)) {
|
||||
return checkApiKeyAuth(request, token);
|
||||
}
|
||||
|
||||
const payload = parseSecureToken(token, secret());
|
||||
const shareToken = await parseShareToken(request);
|
||||
|
||||
|
||||
Reference in new issue
Block a user