|
- // Copyright (c) 2020 Jan Kaßel
- // Copyright (c) 2022 Gerben
- //
- // SPDX-License-Identifier: MIT
-
- import express, { NextFunction, Request, Response } from 'express';
- import basicAuth from 'express-basic-auth';
- import users from '../config/users.json';
- import {
- createCollection,
- getCollection,
- deleteCollection,
- } from './handlers/collection.js';
- import {
- createAnnotation,
- getAnnotation,
- updateAnnotation,
- deleteAnnotation,
- } from './handlers/annotation.js';
- import { getUser } from './handlers/user.js';
-
- var router = express.Router();
-
- const authHandler = basicAuth({
- users,
- challenge: true,
- });
-
- // Require authentication only for write methods
- router.use((req, res, next) => {
- if (['POST', 'PUT', 'DELETE'].includes(req.method.toUpperCase()))
- authHandler(req, res, next);
- else next();
- });
-
- declare global {
- namespace Express {
- interface Request {
- auth?: {
- user: string;
- password: string;
- };
- }
- }
- }
-
- function checkIfAuthorised(req: Request, res: Response, next: NextFunction) {
- if (req.auth?.user === req.params.user) {
- next();
- } else {
- res.status(403).send('Forbidden');
- }
- }
-
- function ensureTrailingSlash(req: Request, res: Response, next: NextFunction) {
- const [originalPath, query] = req.originalUrl.split('?');
- if (originalPath.endsWith('/')) {
- next();
- } else {
- const newPath = `${originalPath}/${query ? `?${query}` : ''}`;
- res.redirect(301, newPath);
- }
- }
-
- router.get('/', ensureTrailingSlash, (req, res, next) => {
- res.render('index', {
- title: `Annonation server`,
- users: Object.keys(users),
- });
- });
- router.get('/login', authHandler, (req, res, next) => {
- if (req.auth?.user) {
- res.redirect(`${req.baseUrl}/${req.auth?.user}`);
- } else {
- res.status(500).send('Something wrong2.');
- }
- });
- router.get('/logout', (req, res, next) => {
- basicAuth({
- users: {},
- challenge: true,
- })(req, res, next);
- });
- router.get('/:user/', ensureTrailingSlash, getUser);
- router.post('/:user/', checkIfAuthorised, createCollection);
- router.get('/:user/:collection/', ensureTrailingSlash, getCollection);
- router.delete('/:user/:collection/', checkIfAuthorised, deleteCollection);
- router.post('/:user/:collection/', checkIfAuthorised, createAnnotation);
- router.get('/:user/:collection/:annotation', getAnnotation);
- router.put(
- '/:user/:collection/:annotation',
- checkIfAuthorised,
- updateAnnotation,
- );
- router.delete(
- '/:user/:collection/:annotation',
- checkIfAuthorised,
- deleteAnnotation,
- );
-
- export default router;
|