1
0
mirror of https://github.com/spacebarchat/server.git synced 2024-11-11 05:02:37 +01:00

Config: Refactor config method, so we have a new get all option, fix issues in configurations

This commit is contained in:
Diego Magdaleno 2021-05-21 18:18:58 -05:00
parent 8872f806f7
commit 05057b922a
11 changed files with 26 additions and 24 deletions

View File

@ -44,8 +44,7 @@ export async function GlobalRateLimit(req: Request, res: Response, next: NextFun
}
export function getIpAdress(req: Request): string {
const rateLimitProperties = Config.apiConfig.get('security', {jwtSecret: crypto.randomBytes(256).toString("base64"), forwadedFor: null, captcha: {enabled:false, service: null, sitekey: null, secret: null}}) as Config.DefaultOptions;
const { forwadedFor } = rateLimitProperties.security;
const { forwadedFor } = Config.apiConfig.getAll().security;
const ip = forwadedFor ? <string>req.headers[forwadedFor] : req.ip;
return ip.replaceAll(".", "_").replaceAll(":", "_");
}

View File

@ -27,7 +27,7 @@ router.post(
// TODO: Rewrite this to have the proper config syntax on the new method
const config = Config.apiConfig.store as unknown as Config.DefaultOptions;
const config = Config.apiConfig.getAll();
if (config.login.requireCaptcha && config.security.captcha.enabled) {
if (!captcha_key) {
@ -69,10 +69,9 @@ export async function generateToken(id: string) {
const algorithm = "HS256";
return new Promise((res, rej) => {
const securityPropertiesSecret = Config.apiConfig.get('security.jwtSecret') as Config.DefaultOptions;
jwt.sign(
{ id: id, iat },
securityPropertiesSecret.security.jwtSecret,
Config.apiConfig.getAll().security.jwtSecret,
{
algorithm,
},

View File

@ -52,8 +52,7 @@ router.post(
let discriminator = "";
// get register Config
const securityProperties = Config.apiConfig.store as unknown as Config.DefaultOptions;
const { register, security } = securityProperties;
const { register, security } = Config.apiConfig.getAll();
// check if registration is allowed
if (!register.allowNewRegistration) {

View File

@ -20,8 +20,7 @@ router.post("/", check({ messages: [String] }), async (req, res) => {
const permission = await getPermission(req.user_id, channel?.guild_id, channel_id, { channel });
permission.hasThrow("MANAGE_MESSAGES");
const limitsProperties = Config.apiConfig.get('limits.message') as Config.DefaultOptions;
const { maxBulkDelete } = limitsProperties.limits.message;
const { maxBulkDelete } = Config.apiConfig.getAll().limits.message;
const { messages } = req.body as { messages: string[] };
if (messages.length < 2) throw new HTTPError("You must at least specify 2 messages to bulk delete");

View File

@ -18,8 +18,7 @@ router.put("/:message_id", async (req: Request, res: Response) => {
if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES");
const pinned_count = await MessageModel.count({ channel_id, pinned: true }).exec();
const limitsProperties = Config.apiConfig.get('limits.channel') as Config.DefaultOptions;
const { maxPins } = limitsProperties.limits.channel;
const { maxPins } = Config.apiConfig.getAll().limits.channel;
if (pinned_count >= maxPins) throw new HTTPError("Max pin count reached: " + maxPins);
await MessageModel.updateOne({ id: message_id }, { pinned: true }).exec();

View File

@ -4,8 +4,7 @@ import * as Config from "../util/Config"
const router = Router();
router.get("/", (req, res) => {
const generalConfig = Config.apiConfig.get('gateway', 'ws://localhost:3002') as Config.DefaultOptions;
const { gateway } = generalConfig;
const { gateway } = Config.apiConfig.getAll();
res.send({ url: gateway || "ws://localhost:3002" });
});

View File

@ -14,8 +14,7 @@ const router: Router = Router();
router.post("/", check(GuildCreateSchema), async (req: Request, res: Response) => {
const body = req.body as GuildCreateSchema;
const limitsProperties = Config.apiConfig.get('limits.user') as Config.DefaultOptions;
const { maxGuilds } = limitsProperties.limits.user;
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
const user = await getPublicUser(req.user_id, { guilds: true });
if (user.guilds.length >= maxGuilds) {

View File

@ -21,8 +21,7 @@ router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res
const { code } = req.params;
const body = req.body as GuildTemplateCreateSchema;
const limitsProperties = Config.apiConfig.get('limits.user') as Config.DefaultOptions;
const { maxGuilds } = limitsProperties.limits.user;
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
const user = await getPublicUser(req.user_id, { guilds: true });
if (user.guilds.length >= maxGuilds) {

View File

@ -1,5 +1,4 @@
import Ajv, { JSONSchemaType } from "ajv"
import { ValidateFunction } from 'ajv'
import Ajv, { JSONSchemaType, ValidateFunction } from "ajv"
import ajvFormats from 'ajv-formats';
import dotProp from "dot-prop";
import envPaths from "env-paths";
@ -101,6 +100,7 @@ export interface DefaultOptions {
};
}
const schema: JSONSchemaType<DefaultOptions> & {
definitions: {
rateLimitOptions: JSONSchemaType<RateLimitOptions>
@ -398,6 +398,10 @@ class Config<T extends Record<string, any> = Record<string, unknown>> implements
}
}
private _has<Key extends keyof T>(key: Key | string): boolean {
return dotProp.has(this.store, key as string);
}
private _validate(data: T | unknown): void {
if (!this.#validator) {
return;
@ -432,7 +436,7 @@ class Config<T extends Record<string, any> = Record<string, unknown>> implements
private _ensureDirectory(): void {
fs.mkdirSync(path.dirname(this.path), { recursive: true })
}
set store(value: T) {
this._validate(value);
@ -449,9 +453,17 @@ class Config<T extends Record<string, any> = Record<string, unknown>> implements
return this._get(key, defaultValue);
}
public getAll(): DefaultOptions {
return this.store as unknown as DefaultOptions
}
private _get<Key extends keyof T>(key: Key): T[Key] | undefined;
private _get<Key extends keyof T, Default = unknown>(key: Key, defaultValue: Default): T[Key] | Default;
private _get<Key extends keyof T, Default = unknown>(key: Key | string, defaultValue?: Default): Default | undefined {
if (!this._has(key)) {
throw new Error("Tried to acess a non existant property in the config");
}
return dotProp.get<T[Key] | undefined>(this.store, key as string, defaultValue as T[Key]);
}

View File

@ -39,8 +39,7 @@ export async function isMember(user_id: string, guild_id: string) {
export async function addMember(user_id: string, guild_id: string, cache?: { guild?: GuildDocument }) {
const user = await getPublicUser(user_id, { guilds: true });
const limitsUserProperties = Config.apiConfig.get('limits.user', {maxGuilds: 100, masxUsername: 32, maxFriends: 1000}) as Config.DefaultOptions;
const { maxGuilds } = limitsUserProperties.limits.user;
const { maxGuilds } = Config.apiConfig.getAll().limits.user;
if (user.guilds.length >= maxGuilds) {
throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403);
}

View File

@ -17,14 +17,13 @@ const blocklist: string[] = []; // TODO: update ones passwordblocklist is stored
* Returns: 0 > pw > 1
*/
export function check(password: string): number {
const passwordProperties = Config.apiConfig.get('register.password', { minLength: 8, minNumbers: 2, minUpperCase: 2, minSymbols: 0, blockInsecureCommonPasswords: false }) as Config.DefaultOptions;
const {
minLength,
minNumbers,
minUpperCase,
minSymbols,
blockInsecureCommonPasswords,
} = passwordProperties.register.password;
} = Config.apiConfig.getAll().register.password;
var strength = 0;
// checks for total password len