swaf upgrade: make code compile

This commit is contained in:
Alice Gaudon 2022-02-18 20:46:34 +01:00
parent 69b234d95c
commit b1ba6b9106
7 changed files with 97 additions and 53 deletions

View File

@ -1,4 +1,17 @@
import Application from "swaf/Application"; import Application from "swaf/Application";
import AccountController from "swaf/auth/AccountController";
import AuthComponent from "swaf/auth/AuthComponent";
import AuthController from "swaf/auth/AuthController";
import AddUsedToMagicLinksMigration from "swaf/auth/magic_link/AddUsedToMagicLinksMigration";
import CreateMagicLinksTableMigration from "swaf/auth/magic_link/CreateMagicLinksTableMigration";
import MagicLinkAuthMethod from "swaf/auth/magic_link/MagicLinkAuthMethod";
import MagicLinkController from "swaf/auth/magic_link/MagicLinkController";
import MagicLinkWebSocketListener from "swaf/auth/magic_link/MagicLinkWebSocketListener";
import MakeMagicLinksSessionNotUniqueMigration from "swaf/auth/magic_link/MakeMagicLinksSessionNotUniqueMigration";
import AddApprovedFieldToUsersTableMigration from "swaf/auth/migrations/AddApprovedFieldToUsersTableMigration";
import CreateUsersAndUserEmailsTableMigration from "swaf/auth/migrations/CreateUsersAndUserEmailsTableMigration";
import AddPasswordToUsersMigration from "swaf/auth/password/AddPasswordToUsersMigration";
import PasswordAuthMethod from "swaf/auth/password/PasswordAuthMethod";
import AutoUpdateComponent from "swaf/components/AutoUpdateComponent"; import AutoUpdateComponent from "swaf/components/AutoUpdateComponent";
import CsrfProtectionComponent from "swaf/components/CsrfProtectionComponent"; import CsrfProtectionComponent from "swaf/components/CsrfProtectionComponent";
import ExpressAppComponent from "swaf/components/ExpressAppComponent"; import ExpressAppComponent from "swaf/components/ExpressAppComponent";
@ -21,11 +34,24 @@ import NunjucksViewEngine from "swaf/frontend/NunjucksViewEngine";
import ScssAssetPreCompiler from "swaf/frontend/ScssAssetPreCompiler"; import ScssAssetPreCompiler from "swaf/frontend/ScssAssetPreCompiler";
import SvelteViewEngine from "swaf/frontend/SvelteViewEngine"; import SvelteViewEngine from "swaf/frontend/SvelteViewEngine";
import TypeScriptPreCompiler from "swaf/frontend/TypeScriptPreCompiler"; import TypeScriptPreCompiler from "swaf/frontend/TypeScriptPreCompiler";
import BackendController from "swaf/helpers/BackendController";
import MailController from "swaf/mail/MailController";
import {MAGIC_LINK_MAIL} from "swaf/Mails";
import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable"; import CreateMigrationsTable from "swaf/migrations/CreateMigrationsTable";
import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable"; import DropLegacyLogsTable from "swaf/migrations/DropLegacyLogsTable";
import DummyMigration from "swaf/migrations/DummyMigration"; import DummyMigration from "swaf/migrations/DummyMigration";
import HomeController from "./controllers/HomeController.js"; import AboutController from "./controllers/AboutController.js";
import AuthTokenController from "./controllers/AuthTokenController.js";
import FileController from "./controllers/FileController.js";
import LinkController from "./controllers/LinkController.js";
import URLRedirectController from "./controllers/URLRedirectController.js";
import DeleteOldFilesJobComponent from "./DeleteOldFilesJobComponent.js";
import CreateAuthTokensTable from "./migrations/CreateAuthTokensTable.js";
import CreateFilesTable from "./migrations/CreateFilesTable.js";
import CreateUrlRedirectsTable from "./migrations/CreateUrlRedirectsTable.js";
import IncreaseFilesSizeField from "./migrations/IncreaseFilesSizeField.js";
import ReplaceTtlWithExpiresAtFilesTable from "./migrations/ReplaceTtlWithExpiresAtFilesTable.js";
export default class App extends Application { export default class App extends Application {
public constructor( public constructor(
@ -107,7 +133,6 @@ export default class App extends Application {
this.use(new CsrfProtectionComponent()); this.use(new CsrfProtectionComponent());
// WebSocket server // WebSocket server
this.use(new WebSocketServerComponent(this, this.as(ExpressAppComponent), this.as(RedisComponent)));
this.use(new WebSocketServerComponent()); this.use(new WebSocketServerComponent());

View File

@ -1,10 +1,11 @@
import ApplicationComponent from "swaf/ApplicationComponent";
import FileModel from "./models/FileModel";
import {logger} from "swaf/Logger";
import config from "config"; import config from "config";
import {WhereTest} from "swaf/db/ModelQuery"; import ApplicationComponent from "swaf/ApplicationComponent";
import MysqlComponent from "swaf/components/MysqlComponent"; import MysqlComponent from "swaf/components/MysqlComponent";
import FileController from "./controllers/FileController"; import {WhereTest} from "swaf/db/ModelQuery";
import {logger} from "swaf/Logger";
import FileController from "./controllers/FileController.js";
import FileModel from "./models/FileModel.js";
import Timeout = NodeJS.Timeout; import Timeout = NodeJS.Timeout;
export default class DeleteOldFilesJobComponent extends ApplicationComponent { export default class DeleteOldFilesJobComponent extends ApplicationComponent {
@ -12,7 +13,7 @@ export default class DeleteOldFilesJobComponent extends ApplicationComponent {
private readonly interval: number = config.get<number>('delete_old_files_interval'); private readonly interval: number = config.get<number>('delete_old_files_interval');
public async start(): Promise<void> { public async start(): Promise<void> {
if (this.getApp().as(MysqlComponent).canServe()) { if (this.getApp().as(MysqlComponent).isReady()) {
await this.run(); await this.run();
} }
@ -33,7 +34,7 @@ export default class DeleteOldFilesJobComponent extends ApplicationComponent {
} }
this.timeout = setInterval(() => { this.timeout = setInterval(() => {
if (this.getApp().as(MysqlComponent).canServe()) { if (this.getApp().as(MysqlComponent).isReady()) {
this.run().catch(err => logger.error(err)); this.run().catch(err => logger.error(err));
} }
}, this.interval); }, this.interval);

View File

@ -1,9 +1,11 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {Request, Response} from "express";
import AuthToken from "../models/AuthToken";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
import config from "config"; import config from "config";
import {Request, Response} from "express";
import {RequireAuthMiddleware} from "swaf/auth/AuthComponent";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError} from "swaf/HttpError";
import AuthToken from "../models/AuthToken.js";
export default class AuthTokenController extends Controller { export default class AuthTokenController extends Controller {
public routes(): void { public routes(): void {
@ -30,7 +32,7 @@ export default class AuthTokenController extends Controller {
}); });
await authToken.save(); await authToken.save();
req.flash('success', 'Successfully created auth token.'); req.flash('success', 'Successfully created auth token.');
res.redirect(req.getPreviousUrl() || Controller.route('file-uploader')); res.redirect(req.getPreviousUrl() || route('file-uploader'));
} }
protected async postRevokeAuthToken(req: Request, res: Response): Promise<void> { protected async postRevokeAuthToken(req: Request, res: Response): Promise<void> {
@ -46,6 +48,6 @@ export default class AuthTokenController extends Controller {
await authToken.delete(); await authToken.delete();
req.flash('success', 'Successfully deleted auth token.'); req.flash('success', 'Successfully deleted auth token.');
res.redirect(req.getPreviousUrl() || Controller.route('file-uploader')); res.redirect(req.getPreviousUrl() || route('file-uploader'));
} }
} }

View File

@ -1,22 +1,27 @@
import Controller from "swaf/Controller";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, ForbiddenHttpError, ServerError} from "swaf/HttpError";
import FileModel from "../models/FileModel";
import config from "config"; import config from "config";
import {NextFunction, Request, Response} from "express";
import formidable from "formidable";
import * as fs from "fs"; import * as fs from "fs";
import Formidable from "formidable"; import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import generateSlug from "../SlugGenerator"; import {route} from "swaf/common/Routing";
import {logger} from "swaf/Logger"; import Controller from "swaf/Controller";
import FileUploadMiddleware from "swaf/FileUploadMiddleware"; import FileUploadMiddleware from "swaf/FileUploadMiddleware";
import {BadRequestError, ForbiddenHttpError, ServerError} from "swaf/HttpError";
import {logger} from "swaf/Logger";
import FileModel from "../models/FileModel.js";
import generateSlug from "../SlugGenerator.js";
export default class FileController extends Controller { export default class FileController extends Controller {
public routes(): void { public routes(): void {
this.get('/files/:page([0-9]+)?', this.getFileUploader, 'file-uploader', RequireAuthMiddleware); this.get('/files/:page([0-9]+)?', this.getFileUploader, 'file-uploader',
RequireAuthMiddleware);
this.get('/files/upload-script', this.downloadLinuxScript, 'file-linux-script'); this.get('/files/upload-script', this.downloadLinuxScript, 'file-linux-script');
this.post('/files/upload', this.postFileFrontend, 'post-file-frontend', RequireAuthMiddleware, FileUploadFormMiddleware); this.post('/files/upload', this.postFileFrontend, 'post-file-frontend',
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend', RequireAuthMiddleware); RequireAuthMiddleware, FileUploadFormMiddleware);
this.post('/files/delete/:slug', FileController.deleteFileRoute, 'delete-file-frontend',
RequireAuthMiddleware);
} }
protected async getFileUploader(req: Request, res: Response): Promise<void> { protected async getFileUploader(req: Request, res: Response): Promise<void> {
@ -58,7 +63,11 @@ export default class FileController extends Controller {
const upload = req.files['upload']; const upload = req.files['upload'];
if (Array.isArray(upload)) { if (Array.isArray(upload)) {
throw new BadRequestError('Uploading multiple files at once is unsupported.', 'Please only upload one file at a time.', req.url); throw new BadRequestError(
'Uploading multiple files at once is unsupported.',
'Please only upload one file at a time.',
req.url,
);
} }
// TTL // TTL
@ -72,7 +81,7 @@ export default class FileController extends Controller {
const file = FileModel.create({ const file = FileModel.create({
user_id: user.id, user_id: user.id,
slug: slug, slug: slug,
real_name: upload.name, real_name: upload.originalFilename,
storage_type: 'local', storage_type: 'local',
storage_path: 'storage/uploads/' + slug, storage_path: 'storage/uploads/' + slug,
size: upload.size, size: upload.size,
@ -80,9 +89,10 @@ export default class FileController extends Controller {
}); });
await file.save(); await file.save();
fs.renameSync(upload.path, file.getOrFail('storage_path')); fs.renameSync(upload.filepath, file.getOrFail('storage_path'));
const domain = req.body.url_domain || config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_files')]; const domain = req.body.url_domain ||
config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_files')];
res.format({ res.format({
json: () => res.json({ json: () => res.json({
url: file.getURL(domain), url: file.getURL(domain),
@ -91,7 +101,7 @@ export default class FileController extends Controller {
html: () => { html: () => {
req.flash('success', 'Upload success!'); req.flash('success', 'Upload success!');
req.flash('url', file.getURL(domain)); req.flash('url', file.getURL(domain));
res.redirect(Controller.route('file-uploader')); res.redirect(route('file-uploader'));
}, },
}); });
} }
@ -126,7 +136,7 @@ export default class FileController extends Controller {
text: () => res.send('success'), text: () => res.send('success'),
html: () => { html: () => {
req.flash('success', 'Successfully deleted file.'); req.flash('success', 'Successfully deleted file.');
res.redirect(Controller.route('file-uploader')); res.redirect(route('file-uploader'));
}, },
}); });
} }
@ -143,11 +153,11 @@ export class FileUploadFormMiddleware extends FileUploadMiddleware {
return 'upload'; return 'upload';
} }
protected makeForm(): Formidable { protected getFormidableOptions(): formidable.Options {
return new Formidable({ return {
uploadDir: 'storage/tmp', uploadDir: 'storage/tmp',
maxFileSize: config.get<number>('max_upload_size') * 1024 * 1024, maxFileSize: config.get<number>('max_upload_size') * 1024 * 1024,
}); };
} }
} }

View File

@ -1,9 +1,11 @@
import Controller from "swaf/Controller";
import {NextFunction, Request, Response} from "express";
import URLRedirect from "../models/URLRedirect";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import generateSlug from "../SlugGenerator";
import config from "config"; import config from "config";
import {NextFunction, Request, Response} from "express";
import {RequireAuthMiddleware, RequireRequestAuthMiddleware} from "swaf/auth/AuthComponent";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller";
import URLRedirect from "../models/URLRedirect.js";
import generateSlug from "../SlugGenerator.js";
export default class URLRedirectController extends Controller { export default class URLRedirectController extends Controller {
public routes(): void { public routes(): void {
@ -57,7 +59,8 @@ export default class URLRedirectController extends Controller {
await urlRedirect.save(); await urlRedirect.save();
const domain = req.body.url_domain || config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_urls')]; const domain = req.body.url_domain ||
config.get<string[]>('allowed_url_domains')[config.get<number>('default_url_domain_for_urls')];
res.format({ res.format({
json: () => res.json({ json: () => res.json({
url: urlRedirect.getURL(domain), url: urlRedirect.getURL(domain),
@ -66,7 +69,7 @@ export default class URLRedirectController extends Controller {
html: () => { html: () => {
req.flash('success', 'URL shrunk successfully!'); req.flash('success', 'URL shrunk successfully!');
req.flash('url', urlRedirect.getURL(domain)); req.flash('url', urlRedirect.getURL(domain));
res.redirect(Controller.route('url-shrinker')); res.redirect(route('url-shrinker'));
}, },
}); });
} }

View File

@ -1,9 +1,10 @@
import Model from "swaf/db/Model";
import Controller from "swaf/Controller";
import config from "config"; import config from "config";
import User from "swaf/auth/models/User";
import {Request} from "express"; import {Request} from "express";
import URLRedirect from "./URLRedirect"; import User from "swaf/auth/models/User";
import {route} from "swaf/common/Routing";
import Model from "swaf/db/Model";
import URLRedirect from "./URLRedirect.js";
export default class FileModel extends Model { export default class FileModel extends Model {
public static get table(): string { public static get table(): string {
@ -47,7 +48,7 @@ export default class FileModel extends Model {
} }
public getURL(domain: string = config.get<string>('public_url')): string { public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-file', { return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-file', {
slug: this.getOrFail('slug'), slug: this.getOrFail('slug'),
}); });
} }

View File

@ -1,9 +1,11 @@
import Model from "swaf/db/Model";
import User from "swaf/auth/models/User";
import FileModel from "./FileModel";
import {Request} from "express";
import config from "config"; import config from "config";
import {Request} from "express";
import User from "swaf/auth/models/User";
import {route} from "swaf/common/Routing";
import Controller from "swaf/Controller"; import Controller from "swaf/Controller";
import Model from "swaf/db/Model";
import FileModel from "./FileModel";
export default class URLRedirect extends Model { export default class URLRedirect extends Model {
public static get table(): string { public static get table(): string {
@ -35,7 +37,7 @@ export default class URLRedirect extends Model {
} }
public getURL(domain: string = config.get<string>('public_url')): string { public getURL(domain: string = config.get<string>('public_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-url', { return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-url', {
slug: this.getOrFail('slug'), slug: this.getOrFail('slug'),
}); });
} }