Skip to content

feat: add config file #740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 27 commits into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
8a8517c
add config file possibility
m-mattia-m Jan 10, 2025
7982084
revert port in docker compose
m-mattia-m Jan 10, 2025
78d4ee5
Update docker-compose.yml
m-mattia-m Jan 14, 2025
b1c384c
Update docker-compose.yml
m-mattia-m Jan 14, 2025
4188069
add attribute description to config file
m-mattia-m Jan 17, 2025
c175efc
remove email message config
m-mattia-m Jan 17, 2025
7870c27
add package to resolve errors
m-mattia-m Jan 17, 2025
70056f8
remove email messages from config
m-mattia-m Jan 17, 2025
4a0ee97
move config initialization to config module
m-mattia-m Feb 21, 2025
ea83c6a
revert unnecessary change
m-mattia-m Feb 21, 2025
cc61a0c
add order
m-mattia-m Feb 24, 2025
7ef11de
improve alert
stonith404 Feb 26, 2025
bc1b5f9
run formatter
stonith404 Feb 26, 2025
55fd774
remove unnecessary packages
stonith404 Feb 26, 2025
cd3748f
remove unnecessary types
stonith404 Feb 26, 2025
f81a152
use logger
stonith404 Feb 26, 2025
a485435
don't save yaml config to db
stonith404 Feb 26, 2025
2a2d042
allowEdit if no yaml config is set
stonith404 Feb 26, 2025
d10e36a
improve docs
stonith404 Feb 26, 2025
56f4635
fix allow edit state
m-mattia-m Feb 26, 2025
f474eba
remove unnecessary check and refactor code
m-mattia-m Feb 26, 2025
78cc841
restore old config file
stonith404 Feb 27, 2025
fb8fde0
add script that generates `config.example.yaml` automatically
stonith404 Feb 27, 2025
7dbdb67
allow config variables to be changed if they are not set in the `conf…
stonith404 Feb 27, 2025
31ede39
add back init user
stonith404 Feb 28, 2025
61278e4
Revert "allow config variables to be changed if they are not set in t…
stonith404 Feb 28, 2025
c866807
improve info box text
stonith404 Feb 28, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ yarn-error.log*
/docs/build/
/docs/.docusaurus
/docs/.cache-loader
/config.yaml

# Jetbrains specific (webstorm)
.idea/**/**
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Pingvin Share is a self-hosted file sharing platform and an alternative for WeTr
- Reverse shares
- OIDC and LDAP authentication
- Integration with ClamAV for security scans
- Different file providers: local storage and S3

## 🐧 Get to know Pingvin Share

Expand Down
4,093 changes: 2,025 additions & 2,068 deletions backend/package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@
"rimraf": "^6.0.1",
"rxjs": "^7.8.1",
"sharp": "^0.33.5",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"yaml": "^2.7.0"
},
"devDependencies": {
"@nestjs/cli": "^10.4.5",
Expand Down
33 changes: 24 additions & 9 deletions backend/prisma/seed/config.seed.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Prisma, PrismaClient } from "@prisma/client";
import * as crypto from "crypto";

const configVariables: ConfigVariables = {
export const configVariables = {
internal: {
jwtSecret: {
type: "string",
Expand Down Expand Up @@ -181,12 +181,12 @@ const configVariables: ConfigVariables = {
},
searchQuery: {
type: "string",
defaultValue: ""
defaultValue: "",
},

adminGroups: {
type: "string",
defaultValue: ""
defaultValue: "",
},

fieldNameMemberOf: {
Expand All @@ -196,18 +196,18 @@ const configVariables: ConfigVariables = {
fieldNameEmail: {
type: "string",
defaultValue: "userPrincipalName",
}
},
},
oauth: {
"allowRegistration": {
allowRegistration: {
type: "boolean",
defaultValue: "true",
},
"ignoreTotp": {
ignoreTotp: {
type: "boolean",
defaultValue: "true",
},
"disablePassword": {
disablePassword: {
type: "boolean",
defaultValue: "false",
secret: false,
Expand Down Expand Up @@ -376,7 +376,22 @@ const configVariables: ConfigVariables = {
defaultValue: "",
secret: false,
},
}
},
} satisfies ConfigVariables;

export type YamlConfig = {
[Category in keyof typeof configVariables]: {
[Key in keyof (typeof configVariables)[Category]]: string;
};
} & {
initUser: {
enabled: string;
username: string;
email: string;
password: string;
isAdmin: boolean;
ldapDN: string;
};
};

type ConfigVariables = {
Expand Down Expand Up @@ -433,7 +448,7 @@ async function migrateConfigVariables() {
for (const existingConfigVariable of existingConfigVariables) {
const configVariable =
configVariables[existingConfigVariable.category]?.[
existingConfigVariable.name
existingConfigVariable.name
];

// Delete the config variable if it doesn't exist in the seed
Expand Down
95 changes: 87 additions & 8 deletions backend/src/config/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,93 @@ import {
BadRequestException,
Inject,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { Config } from "@prisma/client";
import * as argon from "argon2";
import { EventEmitter } from "events";
import * as fs from "fs";
import { PrismaService } from "src/prisma/prisma.service";
import { stringToTimespan } from "src/utils/date.util";
import { parse as yamlParse } from "yaml";
import { YamlConfig } from "../../prisma/seed/config.seed";

/**
* ConfigService extends EventEmitter to allow listening for config updates,
* now only `update` event will be emitted.
*/
@Injectable()
export class ConfigService extends EventEmitter {
yamlConfig?: YamlConfig;
logger = new Logger(ConfigService.name);

constructor(
@Inject("CONFIG_VARIABLES") private configVariables: Config[],
private prisma: PrismaService,
) {
super();
}

async onModuleInit() {
await this.loadYamlConfig();

if (this.yamlConfig) {
await this.migrateInitUser();
}
}

private async loadYamlConfig() {
let configFile: string = "";
try {
configFile = fs.readFileSync("../config.yaml", "utf8");
} catch (e) {
this.logger.log(
"Config.yaml is not set. Falling back to UI configuration.",
);
}
try {
this.yamlConfig = yamlParse(configFile);
if (this.yamlConfig) {
for (const configVariable of this.configVariables) {
const category = this.yamlConfig[configVariable.category];
if (!category) continue;

configVariable.value = category[configVariable.name];
}
}
} catch (e) {
this.logger.error(
"Failed to parse config.yaml. Falling back to UI configuration: ",
e,
);
}
}

private async migrateInitUser(): Promise<void> {
if (!this.yamlConfig.initUser.enabled) return;

const userCount = await this.prisma.user.count({
where: { isAdmin: true },
});
if (userCount === 1) {
this.logger.log(
"Skip initial user creation. Admin user is already existent.",
);
return;
}
await this.prisma.user.create({
data: {
email: this.yamlConfig.initUser.email,
username: this.yamlConfig.initUser.username,
password: this.yamlConfig.initUser.password
? await argon.hash(this.yamlConfig.initUser.password)
: null,
isAdmin: this.yamlConfig.initUser.isAdmin,
},
});
}

get(key: `${string}.${string}`): any {
const configVariable = this.configVariables.filter(
(variable) => `${variable.category}.${variable.name}` == key,
Expand All @@ -40,24 +107,22 @@ export class ConfigService extends EventEmitter {
}

async getByCategory(category: string) {
const configVariables = await this.prisma.config.findMany({
orderBy: { order: "asc" },
where: { category, locked: { equals: false } },
});
const configVariables = this.configVariables
.filter((c) => !c.locked && category == c.category)
.sort((c) => c.order);

return configVariables.map((variable) => {
return {
...variable,
key: `${variable.category}.${variable.name}`,
value: variable.value ?? variable.defaultValue,
allowEdit: this.isEditAllowed(),
};
});
}

async list() {
const configVariables = await this.prisma.config.findMany({
where: { secret: { equals: false } },
});
const configVariables = this.configVariables.filter((c) => !c.secret);

return configVariables.map((variable) => {
return {
Expand All @@ -69,16 +134,26 @@ export class ConfigService extends EventEmitter {
}

async updateMany(data: { key: string; value: string | number | boolean }[]) {
if (!this.isEditAllowed())
throw new BadRequestException(
"You are only allowed to update config variables via the config.yaml file",
);

const response: Config[] = [];

for (const variable of data) {
response.push(await this.update(variable.key, variable.value));
response.push(await this.update(variable.key, variable.value));
}

return response;
}

async update(key: string, value: string | number | boolean) {
if (!this.isEditAllowed())
throw new BadRequestException(
"You are only allowed to update config variables via the config.yaml file",
);

const configVariable = await this.prisma.config.findUnique({
where: {
name_category: {
Expand Down Expand Up @@ -143,4 +218,8 @@ export class ConfigService extends EventEmitter {
throw new BadRequestException(validation.message);
}
}

isEditAllowed(): boolean {
return this.yamlConfig === undefined || this.yamlConfig === null;
}
}
3 changes: 3 additions & 0 deletions backend/src/config/dto/adminConfig.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export class AdminConfigDTO extends ConfigDTO {
@Expose()
obscured: boolean;

@Expose()
allowEdit: boolean;

from(partial: Partial<AdminConfigDTO>) {
return plainToClass(AdminConfigDTO, partial, {
excludeExtraneousValues: true,
Expand Down
Loading