Initial Commit
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import { env } from "elysia";
|
||||
|
||||
const keys = {
|
||||
[env.PRIVATE_API_KEY]: ["card"],
|
||||
[env.PUBLIC_API_KEY]: ["card"],
|
||||
} as const;
|
||||
|
||||
declare module "bun" {
|
||||
interface Env {
|
||||
PUBLIC_API_KEY: string;
|
||||
PRIVATE_API_KEY: string;
|
||||
}
|
||||
}
|
||||
|
||||
function validateKeyList(
|
||||
keys: unknown,
|
||||
): asserts keys is Record<string, string[]> {
|
||||
if (typeof keys !== "object" || !keys) throw "key list is not an object";
|
||||
for (const [i, [key, perms]] of Object.entries(Object.entries(keys))) {
|
||||
if (!(typeof key === "string") || !key) throw `key ${i} is invalid`;
|
||||
if (!Array.isArray(perms))
|
||||
throw `key ${i} doesn't have valid permission list`;
|
||||
if (perms.some((p) => !(typeof p === "string")))
|
||||
throw `key ${i} has invalid permission`;
|
||||
}
|
||||
}
|
||||
|
||||
validateKeyList(keys);
|
||||
|
||||
type Permission = (typeof keys)[string][number];
|
||||
|
||||
class Key {
|
||||
readonly valid = true;
|
||||
readonly permissions: Permission[];
|
||||
|
||||
constructor(permissions: Permission[]) {
|
||||
this.permissions = permissions;
|
||||
}
|
||||
|
||||
has(permission: Permission) {
|
||||
return this.permissions.includes(permission);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return { valid: this.valid, permissions: this.permissions };
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidKey {
|
||||
readonly valid = false;
|
||||
|
||||
has() {
|
||||
return false;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return { valid: false };
|
||||
}
|
||||
}
|
||||
|
||||
class PermissionManager {
|
||||
readonly invalid = new InvalidKey();
|
||||
validate(key: string) {
|
||||
if (!Object.keys(keys).includes(key)) return this.invalid;
|
||||
return new Key([...keys[key]]);
|
||||
}
|
||||
}
|
||||
|
||||
export const pm = new PermissionManager();
|
||||
+2241
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user