mirror of
https://github.com/unraid/api.git
synced 2026-05-03 05:31:19 -05:00
58 lines
1.2 KiB
TypeScript
58 lines
1.2 KiB
TypeScript
/*!
|
|
* Copyright 2019-2020 Lime Technology Inc. All rights reserved.
|
|
* Written by: Alexis Tyler
|
|
*/
|
|
|
|
import { v4 as uuid } from 'uuid';
|
|
import uuidApiKey from 'uuid-apikey';
|
|
import { CoreContext, CoreResult } from '../types';
|
|
import { ensurePermission } from '../utils';
|
|
import { apiManager, CacheItem } from '../api-manager';
|
|
|
|
interface Context extends CoreContext {
|
|
data: {
|
|
name?: string;
|
|
key?: string;
|
|
userId?: string;
|
|
expiration?: string;
|
|
};
|
|
}
|
|
|
|
interface Result extends CoreResult {
|
|
json: CacheItem;
|
|
}
|
|
|
|
/**
|
|
* Register an api key.
|
|
*
|
|
* NOTE: If the name or key is missing they'll be generated.
|
|
*/
|
|
export const addApikey = async (context: Context): Promise<Result | void> => {
|
|
ensurePermission(context.user, {
|
|
resource: 'apikey',
|
|
action: 'create',
|
|
possession: 'any'
|
|
});
|
|
|
|
const name = context.data?.name ?? uuid();
|
|
const key = context.data?.key ?? uuidApiKey.create().apiKey;
|
|
const userId = context.data?.userId ?? context.user.id;
|
|
const expiration = context.data?.expiration;
|
|
|
|
if (name && key) {
|
|
apiManager.add(name, key, {
|
|
userId,
|
|
expiration
|
|
});
|
|
|
|
const result = apiManager.getKey(name);
|
|
|
|
if (result) {
|
|
return {
|
|
json: result
|
|
};
|
|
}
|
|
}
|
|
};
|
|
|