Files
swiss-datashare/frontend/src/middleware.ts

115 lines
3.0 KiB
TypeScript
Raw Normal View History

2024-09-18 11:04:06 +02:00
import { jwtDecode } from "jwt-decode";
import { NextRequest, NextResponse } from "next/server";
import configService from "./services/config.service";
// This middleware redirects based on different conditions:
// - Authentication state
// - Setup status
// - Admin privileges
export const config = {
matcher: "/((?!api|static|.*\\..*|_next).*)",
};
export async function middleware(request: NextRequest) {
2023-02-09 18:17:53 +01:00
const routes = {
unauthenticated: new Routes(["/auth/*", "/"]),
feat(auth): add OAuth2 login (#276) * feat(auth): add OAuth2 login with GitHub and Google * chore(translations): add files for Japanese * fix(auth): fix link function for GitHub * feat(oauth): basic oidc implementation * feat(oauth): oauth guard * fix: disable image optimizations for logo to prevent caching issues with custom logos * fix: memory leak while downloading large files * chore(translations): update translations via Crowdin (#278) * New translations en-us.ts (Japanese) * New translations en-us.ts (Japanese) * New translations en-us.ts (Japanese) * release: 0.18.2 * doc(translations): Add Japanese README (#279) * Added Japanese README. * Added JAPANESE README link to README.md. * Updated Japanese README. * Updated Environment Variable Table. * updated zh-cn README. * feat(oauth): unlink account * refactor(oauth): make providers extensible * fix(oauth): fix discoveryUri error when toggle google-enabled * feat(oauth): add microsoft and discord as oauth provider * docs(oauth): update README.md * docs(oauth): update oauth2-guide.md * set password to null for new oauth users * New translations en-us.ts (Japanese) (#281) * chore(translations): add Polish files * fix(oauth): fix random username and password * feat(oauth): add totp * fix(oauth): fix totp throttle * fix(oauth): fix qrcode and remove comment * feat(oauth): add error page * fix(oauth): i18n of error page * feat(auth): add OAuth2 login * fix(auth): fix link function for GitHub * feat(oauth): basic oidc implementation * feat(oauth): oauth guard * feat(oauth): unlink account * refactor(oauth): make providers extensible * fix(oauth): fix discoveryUri error when toggle google-enabled * feat(oauth): add microsoft and discord as oauth provider * docs(oauth): update README.md * docs(oauth): update oauth2-guide.md * set password to null for new oauth users * fix(oauth): fix random username and password * feat(oauth): add totp * fix(oauth): fix totp throttle * fix(oauth): fix qrcode and remove comment * feat(oauth): add error page * fix(oauth): i18n of error page * refactor: return null instead of `false` in `getIdOfCurrentUser` functiom * feat: show original oauth error if available * refactor: run formatter * refactor(oauth): error message i18n * refactor(oauth): make OAuth token available someone may use it (to revoke token or get other info etc.) also improved the i18n message * chore(oauth): remove unused import * chore: add database migration * fix: missing python installation for nanoid --------- Co-authored-by: Elias Schneider <login@eliasschneider.com> Co-authored-by: ふうせん <10260662+fusengum@users.noreply.github.com>
2023-10-22 22:09:53 +08:00
public: new Routes(["/share/*", "/s/*", "/upload/*", "/error"]),
2023-02-09 18:17:53 +01:00
admin: new Routes(["/admin/*"]),
account: new Routes(["/account*"]),
disabled: new Routes([]),
2023-02-09 18:17:53 +01:00
};
// Get config from backend
const apiUrl = process.env.API_URL || "http://localhost:8080";
const config = await (await fetch(`${apiUrl}/api/configs`)).json();
const getConfig = (key: string) => {
return configService.get(key, config);
};
const route = request.nextUrl.pathname;
let user: { isAdmin: boolean } | null = null;
const accessToken = request.cookies.get("access_token")?.value;
try {
const claims = jwtDecode<{ exp: number; isAdmin: boolean }>(
accessToken as string,
);
if (claims.exp * 1000 > Date.now()) {
user = claims;
}
} catch {
user = null;
}
if (!getConfig("share.allowRegistration")) {
routes.disabled.routes.push("/auth/signUp");
}
if (getConfig("share.allowUnauthenticatedShares")) {
2023-02-09 18:17:53 +01:00
routes.public.routes = ["*"];
}
if (!getConfig("smtp.enabled")) {
routes.disabled.routes.push("/auth/resetPassword*");
2023-02-09 18:17:53 +01:00
}
// prettier-ignore
const rules = [
2023-02-09 18:17:53 +01:00
// Disabled routes
{
condition: routes.disabled.contains(route),
2023-02-09 18:17:53 +01:00
path: "/",
},
// Authenticated state
{
condition: user && routes.unauthenticated.contains(route) && !getConfig("share.allowUnauthenticatedShares"),
path: "/upload",
},
// Unauthenticated state
{
2023-02-09 18:17:53 +01:00
condition: !user && !routes.public.contains(route) && !routes.unauthenticated.contains(route),
path: "/auth/signIn",
},
{
2023-02-09 18:17:53 +01:00
condition: !user && routes.account.contains(route),
path: "/upload",
},
// Admin privileges
{
2023-02-09 18:17:53 +01:00
condition: routes.admin.contains(route) && !user?.isAdmin,
path: "/upload",
},
// Home page
{
condition: (!getConfig("general.showHomePage") || user) && route == "/",
path: "/upload",
},
];
for (const rule of rules) {
if (rule.condition) {
let { path } = rule;
if (path == "/auth/signIn") {
path = path + "?redirect=" + encodeURIComponent(route);
}
return NextResponse.redirect(new URL(path, request.url));
}
}
}
2023-02-09 18:17:53 +01:00
// Helper class to check if a route matches a list of routes
class Routes {
// eslint-disable-next-line no-unused-vars
constructor(public routes: string[]) {}
contains(_route: string) {
for (const route of this.routes) {
if (new RegExp("^" + route.replace(/\*/g, ".*") + "$").test(_route))
return true;
}
return false;
}
}