Implement a more robust Config (#60)

* Implement a more robust Config

This moves the configuration variables from the `.env` file to a new `bewcloud.config.ts` file. Note that DB connection and secrets are still in the `.env` file.

This will allow for more reliable and easier personalized configurations, and was a requirement to start working on adding SSO (#13).

For now, `.env`-based config will still be allowed and respected (overriden by `bewcloud.config.ts`), but in the future I'll probably remove it (some major upgrade).

* Update deploy script to also copy the new config file
This commit is contained in:
Bruno Bernardino
2025-05-25 15:48:53 +01:00
committed by GitHub
parent 69142973d8
commit e337859a22
30 changed files with 443 additions and 198 deletions

View File

@@ -1,12 +1,19 @@
import { PageProps } from 'fresh/server.ts';
import { FreshContextState } from '/lib/types.ts';
import { defaultDescription, defaultTitle } from '/lib/utils/misc.ts';
import { AppConfig } from '/lib/config.ts';
import Header from '/components/Header.tsx';
interface Data {}
export default function App({ route, Component, state }: PageProps<Data, FreshContextState>) {
export default async function App(_request: Request, { route, Component, state }: PageProps<Data, FreshContextState>) {
const config = await AppConfig.getConfig();
const defaultTitle = config.visuals.title || 'bewCloud is a modern and simpler alternative to Nextcloud and ownCloud';
const defaultDescription = config.visuals.description || `Have your files under your own control.`;
const enabledApps = config.core.enabledApps;
return (
<html class='h-full bg-slate-800'>
<head>
@@ -22,7 +29,7 @@ export default function App({ route, Component, state }: PageProps<Data, FreshCo
<link rel='manifest' href='/manifest.json' />
</head>
<body class='h-full'>
<Header route={route} user={state.user} />
<Header route={route} user={state.user} enabledApps={enabledApps} />
<Component />
</body>
</html>

View File

@@ -3,7 +3,7 @@ import { join } from 'std/path/join.ts';
import { parse, stringify } from 'xml';
import { FreshContextState } from '/lib/types.ts';
import { getFilesRootPath } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import Locker from '/lib/interfaces/locker.ts';
import {
addDavPrefixToKeys,
@@ -37,7 +37,7 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
const userId = context.state.user.id;
const rootPath = join(getFilesRootPath(), userId);
const rootPath = join(await AppConfig.getFilesRootPath(), userId);
if (request.method === 'OPTIONS') {
const headers = new Headers({
@@ -76,7 +76,7 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
if (request.method === 'DELETE') {
try {
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await Deno.remove(join(rootPath, filePath));
@@ -94,7 +94,7 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
const body = contentLength === 0 ? new Blob([new Uint8Array([0])]).stream() : request.clone().body;
try {
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
const newFile = await Deno.open(join(rootPath, filePath), {
create: true,
@@ -116,8 +116,8 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
const newFilePath = request.headers.get('destination');
if (newFilePath) {
try {
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
ensureUserPathIsValidAndSecurelyAccessible(userId, getProperDestinationPath(newFilePath));
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, getProperDestinationPath(newFilePath));
await Deno.copyFile(join(rootPath, filePath), join(rootPath, getProperDestinationPath(newFilePath)));
return new Response('Created', { status: 201 });
@@ -133,8 +133,8 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
const newFilePath = request.headers.get('destination');
if (newFilePath) {
try {
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
ensureUserPathIsValidAndSecurelyAccessible(userId, getProperDestinationPath(newFilePath));
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, getProperDestinationPath(newFilePath));
await Deno.rename(join(rootPath, filePath), join(rootPath, getProperDestinationPath(newFilePath)));
return new Response('Created', { status: 201 });
@@ -146,7 +146,7 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
if (request.method === 'MKCOL') {
try {
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await Deno.mkdir(join(rootPath, filePath), { recursive: true });
return new Response('Created', { status: 201 });
} catch (error) {
@@ -223,7 +223,7 @@ export const handler: Handler<Data, FreshContextState> = async (request, context
const properties = getPropertyNames(parsedXml);
ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
await ensureUserPathIsValidAndSecurelyAccessible(userId, filePath);
const responseXml = await buildPropFindResponse(properties, rootPath, filePath, depth);

View File

@@ -1,7 +1,7 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { Budget, Expense, FreshContextState, SupportedCurrencySymbol } from '/lib/types.ts';
import { isAppEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import { BudgetModel, ExpenseModel, generateMonthlyBudgetsAndExpenses } from '/lib/models/expenses.ts';
import ExpensesWrapper from '/islands/expenses/ExpensesWrapper.tsx';
@@ -18,7 +18,7 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
if (!isAppEnabled('expenses')) {
if (!(await AppConfig.isAppEnabled('expenses'))) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/files` } });
}

View File

@@ -2,12 +2,14 @@ import { Handlers, PageProps } from 'fresh/server.ts';
import { Directory, DirectoryFile, FreshContextState } from '/lib/types.ts';
import { DirectoryModel, FileModel } from '/lib/models/files.ts';
import { AppConfig } from '/lib/config.ts';
import FilesWrapper from '/islands/files/FilesWrapper.tsx';
interface Data {
userDirectories: Directory[];
userFiles: DirectoryFile[];
currentPath: string;
baseUrl: string;
}
export const handler: Handlers<Data, FreshContextState> = {
@@ -16,6 +18,8 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
const baseUrl = (await AppConfig.getConfig()).auth.baseUrl;
const searchParams = new URL(request.url).searchParams;
let currentPath = searchParams.get('path') || '/';
@@ -34,7 +38,7 @@ export const handler: Handlers<Data, FreshContextState> = {
const userFiles = await FileModel.list(context.state.user.id, currentPath);
return await context.render({ userDirectories, userFiles, currentPath });
return await context.render({ userDirectories, userFiles, currentPath, baseUrl });
},
};
@@ -45,6 +49,7 @@ export default function FilesPage({ data }: PageProps<Data, FreshContextState>)
initialDirectories={data.userDirectories}
initialFiles={data.userFiles}
initialPath={data.currentPath}
baseUrl={data.baseUrl}
/>
</main>
);

View File

@@ -1,18 +1,20 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { generateHash, helpEmail, validateEmail } from '/lib/utils/misc.ts';
import { generateHash, validateEmail } from '/lib/utils/misc.ts';
import { createSessionResponse, PASSWORD_SALT } from '/lib/auth.ts';
import { FormField, generateFieldHtml, getFormDataField } from '/lib/form-utils.tsx';
import { UserModel, VerificationCodeModel } from '/lib/models/user.ts';
import { sendVerifyEmailEmail } from '/lib/providers/brevo.ts';
import { FreshContextState } from '/lib/types.ts';
import { isEmailEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
interface Data {
error?: string;
notice?: string;
email?: string;
formData?: FormData;
isEmailVerificationEnabled: boolean;
helpEmail: string;
}
export const handler: Handlers<Data, FreshContextState> = {
@@ -21,6 +23,9 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/` } });
}
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
const searchParams = new URL(request.url).searchParams;
const formData = new FormData();
@@ -31,20 +36,23 @@ export const handler: Handlers<Data, FreshContextState> = {
email = searchParams.get('email') || '';
formData.set('email', email);
if (isEmailEnabled()) {
if (await AppConfig.isEmailVerificationEnabled()) {
notice = `You have received a code in your email. Use it to verify your email and login.`;
} else {
notice = `Your account was created successfully. Login below.`;
}
}
return await context.render({ notice, email, formData });
return await context.render({ notice, email, formData, isEmailVerificationEnabled, helpEmail });
},
async POST(request, context) {
if (context.state.user) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/` } });
}
const isEmailVerificationEnabled = await AppConfig.isEmailVerificationEnabled();
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
const formData = await request.clone().formData();
const email = getFormDataField(formData, 'email');
@@ -67,7 +75,7 @@ export const handler: Handlers<Data, FreshContextState> = {
throw new Error('Email not found or invalid password.');
}
if (!isEmailEnabled() && !user.extra.is_email_verified) {
if (!(await AppConfig.isEmailVerificationEnabled()) && !user.extra.is_email_verified) {
user.extra.is_email_verified = true;
await UserModel.update(user);
@@ -94,7 +102,13 @@ export const handler: Handlers<Data, FreshContextState> = {
return createSessionResponse(request, user, { urlToRedirectTo: `/` });
} catch (error) {
console.error(error);
return await context.render({ error: (error as Error).toString(), email, formData });
return await context.render({
error: (error as Error).toString(),
email,
formData,
isEmailVerificationEnabled,
helpEmail,
});
}
},
};
@@ -150,16 +164,17 @@ export default function Login({ data }: PageProps<Data, FreshContextState>) {
{data?.notice
? (
<section class='notification-success'>
<h3>{isEmailEnabled() ? 'Verify your email!' : 'Account created!'}</h3>
<h3>{data?.isEmailVerificationEnabled ? 'Verify your email!' : 'Account created!'}</h3>
<p>{data?.notice}</p>
</section>
)
: null}
<form method='POST' class='mb-12'>
{formFields(data?.email, data?.notice?.includes('verify your email') && isEmailEnabled()).map((field) =>
generateFieldHtml(field, data?.formData || new FormData())
)}
{formFields(
data?.email,
data?.notice?.includes('verify your email') && data?.isEmailVerificationEnabled,
).map((field) => generateFieldHtml(field, data?.formData || new FormData()))}
<section class='flex justify-center mt-8 mb-4'>
<button class='button' type='submit'>Login</button>
</section>
@@ -173,14 +188,14 @@ export default function Login({ data }: PageProps<Data, FreshContextState>) {
</strong>.
</p>
{helpEmail !== ''
{data?.helpEmail !== ''
? (
<>
<h2 class='text-2xl mb-4 text-center'>Need help?</h2>
<p class='text-center mt-2 mb-6'>
If you're having any issues or have any questions,{' '}
<strong>
<a href={`mailto:${helpEmail}`}>please reach out</a>
<a href={`mailto:${data?.helpEmail}`}>please reach out</a>
</strong>.
</p>
</>

View File

@@ -1,7 +1,7 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { FreshContextState, NewsFeedArticle } from '/lib/types.ts';
import { isAppEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import { ArticleModel } from '/lib/models/news.ts';
import Articles from '/islands/news/Articles.tsx';
@@ -15,7 +15,7 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
if (!isAppEnabled('news')) {
if (!(await AppConfig.isAppEnabled('news'))) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/dashboard` } });
}

View File

@@ -1,7 +1,7 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { Directory, DirectoryFile, FreshContextState } from '/lib/types.ts';
import { isAppEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import { DirectoryModel, FileModel } from '/lib/models/files.ts';
import NotesWrapper from '/islands/notes/NotesWrapper.tsx';
@@ -17,7 +17,7 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
if (!isAppEnabled('notes')) {
if (!(await AppConfig.isAppEnabled('notes'))) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/files` } });
}

View File

@@ -1,7 +1,7 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { Directory, DirectoryFile, FreshContextState } from '/lib/types.ts';
import { isAppEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import { DirectoryModel, FileModel } from '/lib/models/files.ts';
import { PHOTO_EXTENSIONS } from '/lib/utils/photos.ts';
import PhotosWrapper from '/islands/photos/PhotosWrapper.tsx';
@@ -18,7 +18,7 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
if (!isAppEnabled('photos')) {
if (!(await AppConfig.isAppEnabled('photos'))) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/files` } });
}

View File

@@ -6,7 +6,7 @@ import { UserModel, VerificationCodeModel } from '/lib/models/user.ts';
import { convertFormDataToObject, generateHash, validateEmail } from '/lib/utils/misc.ts';
import { getFormDataField } from '/lib/form-utils.tsx';
import { sendVerifyEmailEmail } from '/lib/providers/brevo.ts';
import { isEmailEnabled } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import Settings, { Action, actionWords } from '/islands/Settings.tsx';
interface Data {
@@ -20,6 +20,8 @@ interface Data {
};
formData: Record<string, any>;
currency?: SupportedCurrencySymbol;
isExpensesAppEnabled: boolean;
helpEmail: string;
}
export const handler: Handlers<Data, FreshContextState> = {
@@ -28,9 +30,14 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
const isExpensesAppEnabled = await AppConfig.isAppEnabled('expenses');
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
return await context.render({
formData: {},
currency: context.state.user.extra.expenses_currency,
isExpensesAppEnabled,
helpEmail,
});
},
async POST(request, context) {
@@ -38,6 +45,9 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/login` } });
}
const isExpensesAppEnabled = await AppConfig.isAppEnabled('expenses');
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
let action: Action = 'change-email';
let errorTitle = '';
let errorMessage = '';
@@ -72,7 +82,7 @@ export const handler: Handlers<Data, FreshContextState> = {
throw new Error('Email is already in use.');
}
if (action === 'change-email' && isEmailEnabled()) {
if (action === 'change-email' && (await AppConfig.isEmailVerificationEnabled())) {
const verificationCode = await VerificationCodeModel.create(user, email, 'email');
await sendVerifyEmailEmail(email, verificationCode);
@@ -80,7 +90,7 @@ export const handler: Handlers<Data, FreshContextState> = {
successTitle = 'Verify your email!';
successMessage = 'You have received a code in your new email. Use it to verify it here.';
} else {
if (isEmailEnabled()) {
if (await AppConfig.isEmailVerificationEnabled()) {
const code = getFormDataField(formData, 'verification-code');
await VerificationCodeModel.validate(user, email, code, 'email');
@@ -178,6 +188,8 @@ export const handler: Handlers<Data, FreshContextState> = {
notice,
formData: convertFormDataToObject(formData),
currency: user.extra.expenses_currency,
isExpensesAppEnabled,
helpEmail,
});
} catch (error) {
console.error(error);
@@ -188,6 +200,8 @@ export const handler: Handlers<Data, FreshContextState> = {
error: { title: errorTitle, message: errorMessage },
formData: convertFormDataToObject(formData),
currency: user.extra.expenses_currency,
isExpensesAppEnabled,
helpEmail,
});
}
},
@@ -196,7 +210,14 @@ export const handler: Handlers<Data, FreshContextState> = {
export default function SettingsPage({ data }: PageProps<Data, FreshContextState>) {
return (
<main>
<Settings formData={data?.formData} error={data?.error} notice={data?.notice} currency={data?.currency} />
<Settings
formData={data?.formData}
error={data?.error}
notice={data?.notice}
currency={data?.currency}
isExpensesAppEnabled={data?.isExpensesAppEnabled}
helpEmail={data?.helpEmail}
/>
</main>
);
}

View File

@@ -1,11 +1,11 @@
import { Handlers, PageProps } from 'fresh/server.ts';
import { generateHash, helpEmail, validateEmail } from '/lib/utils/misc.ts';
import { generateHash, validateEmail } from '/lib/utils/misc.ts';
import { PASSWORD_SALT } from '/lib/auth.ts';
import { FormField, generateFieldHtml, getFormDataField } from '/lib/form-utils.tsx';
import { UserModel, VerificationCodeModel } from '/lib/models/user.ts';
import { sendVerifyEmailEmail } from '/lib/providers/brevo.ts';
import { isEmailEnabled, isSignupAllowed } from '/lib/config.ts';
import { AppConfig } from '/lib/config.ts';
import { FreshContextState } from '/lib/types.ts';
interface Data {
@@ -13,6 +13,7 @@ interface Data {
notice?: string;
email?: string;
formData?: FormData;
helpEmail: string;
}
export const handler: Handlers<Data, FreshContextState> = {
@@ -21,6 +22,8 @@ export const handler: Handlers<Data, FreshContextState> = {
return new Response('Redirect', { status: 303, headers: { 'Location': `/` } });
}
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
const searchParams = new URL(request.url).searchParams;
let notice = '';
@@ -29,18 +32,20 @@ export const handler: Handlers<Data, FreshContextState> = {
notice = `Your account and all its data has been deleted.`;
}
return await context.render({ notice });
return await context.render({ notice, helpEmail });
},
async POST(request, context) {
if (context.state.user) {
return new Response('Redirect', { status: 303, headers: { 'Location': `/` } });
}
const helpEmail = (await AppConfig.getConfig()).visuals.helpEmail;
const formData = await request.clone().formData();
const email = getFormDataField(formData, 'email');
try {
if (!(await isSignupAllowed())) {
if (!(await AppConfig.isSignupAllowed())) {
throw new Error(`Signups are not allowed.`);
}
@@ -64,7 +69,7 @@ export const handler: Handlers<Data, FreshContextState> = {
const user = await UserModel.create(email, hashedPassword);
if (isEmailEnabled()) {
if (await AppConfig.isEmailVerificationEnabled()) {
const verificationCode = await VerificationCodeModel.create(user, user.email, 'email');
await sendVerifyEmailEmail(user.email, verificationCode);
@@ -76,7 +81,7 @@ export const handler: Handlers<Data, FreshContextState> = {
});
} catch (error) {
console.error(error);
return await context.render({ error: (error as Error).toString(), email, formData });
return await context.render({ error: (error as Error).toString(), email, formData, helpEmail });
}
},
};
@@ -144,14 +149,14 @@ export default function Signup({ data }: PageProps<Data, FreshContextState>) {
</strong>.
</p>
{helpEmail !== ''
{data?.helpEmail !== ''
? (
<>
<h2 class='text-2xl mb-4 text-center'>Need help?</h2>
<p class='text-center mt-2 mb-6'>
If you're having any issues or have any questions,{' '}
<strong>
<a href={`mailto:${helpEmail}`}>please reach out</a>
<a href={`mailto:${data?.helpEmail}`}>please reach out</a>
</strong>.
</p>
</>