mirror of
https://github.com/BradNut/TofuStack
synced 2025-09-08 17:40:26 +00:00
added rate limiter middleware
This commit is contained in:
parent
1fe545090e
commit
013ef0aa58
10 changed files with 48 additions and 54 deletions
15
src/app.d.ts
vendored
15
src/app.d.ts
vendored
|
|
@ -1,6 +1,7 @@
|
||||||
import { ApiClient } from '$lib/server/api';
|
import { ApiClient } from '$lib/server/api';
|
||||||
import type { User } from 'lucia';
|
import type { User } from 'lucia';
|
||||||
import {parseApiResponse} from '$lib/utils/api'
|
import { parseApiResponse } from '$lib/utils/api'
|
||||||
|
import type { Security } from '$lib/utils/security';
|
||||||
|
|
||||||
// See https://kit.svelte.dev/docs/types#app
|
// See https://kit.svelte.dev/docs/types#app
|
||||||
// for information about these interfaces
|
// for information about these interfaces
|
||||||
|
|
@ -18,12 +19,12 @@ declare global {
|
||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
// interface Platform {}
|
// interface Platform {}
|
||||||
namespace Superforms {
|
namespace Superforms {
|
||||||
type Message = {
|
type Message = {
|
||||||
type: 'error' | 'success',
|
type: 'error' | 'success',
|
||||||
text: string
|
text: string
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export { };
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,6 @@ const apiClient: Handle = async ({ event, resolve }) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
/* ----------------------------- Auth functions ----------------------------- */
|
/* ----------------------------- Auth functions ----------------------------- */
|
||||||
async function getAuthedUser() {
|
async function getAuthedUser() {
|
||||||
const { data } = await api.iam.user.$get().then(parseApiResponse)
|
const { data } = await api.iam.user.$get().then(parseApiResponse)
|
||||||
|
|
|
||||||
|
|
@ -5,13 +5,13 @@ import { IamService } from '../services/iam.service';
|
||||||
import { signInEmailDto } from '../../../dtos/signin-email.dto';
|
import { signInEmailDto } from '../../../dtos/signin-email.dto';
|
||||||
import { setCookie } from 'hono/cookie';
|
import { setCookie } from 'hono/cookie';
|
||||||
import { LuciaProvider } from '../providers/lucia.provider';
|
import { LuciaProvider } from '../providers/lucia.provider';
|
||||||
import { requireAuth } from '../middleware/require-auth.middleware';
|
|
||||||
import { updateEmailDto } from '../../../dtos/update-email.dto';
|
import { updateEmailDto } from '../../../dtos/update-email.dto';
|
||||||
import { verifyEmailDto } from '../../../dtos/verify-email.dto';
|
import { verifyEmailDto } from '../../../dtos/verify-email.dto';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import type { HonoTypes } from '../types';
|
import type { HonoTypes } from '../types';
|
||||||
import type { Controller } from '../interfaces/controller.interface';
|
import type { Controller } from '../interfaces/controller.interface';
|
||||||
import { limiter } from '../middleware/rate-limiter.middlware';
|
import { limiter } from '../middleware/rate-limiter.middlware';
|
||||||
|
import { requireAuth } from '../middleware/auth.middleware';
|
||||||
|
|
||||||
/* -------------------------------------------------------------------------- */
|
/* -------------------------------------------------------------------------- */
|
||||||
/* Controller */
|
/* Controller */
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ import { createMiddleware } from 'hono/factory';
|
||||||
import type { HonoTypes } from '../types';
|
import type { HonoTypes } from '../types';
|
||||||
import { lucia } from '../infrastructure/auth/lucia';
|
import { lucia } from '../infrastructure/auth/lucia';
|
||||||
import { verifyRequestOrigin } from 'lucia';
|
import { verifyRequestOrigin } from 'lucia';
|
||||||
|
import type { Session, User } from 'lucia';
|
||||||
|
import { Unauthorized } from '../common/errors';
|
||||||
|
|
||||||
export const verifyOrigin: MiddlewareHandler<HonoTypes> = createMiddleware(async (c, next) => {
|
export const verifyOrigin: MiddlewareHandler<HonoTypes> = createMiddleware(async (c, next) => {
|
||||||
if (c.req.method === "GET") {
|
if (c.req.method === "GET") {
|
||||||
|
|
@ -35,3 +37,14 @@ export const validateAuthSession: MiddlewareHandler<HonoTypes> = createMiddlewar
|
||||||
c.set("user", user);
|
c.set("user", user);
|
||||||
return next();
|
return next();
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const requireAuth: MiddlewareHandler<{
|
||||||
|
Variables: {
|
||||||
|
session: Session;
|
||||||
|
user: User;
|
||||||
|
};
|
||||||
|
}> = createMiddleware(async (c, next) => {
|
||||||
|
const user = c.var.user;
|
||||||
|
if (!user) throw Unauthorized('You must be logged in to access this resource');
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
@ -5,18 +5,16 @@ import type { HonoTypes } from "../types";
|
||||||
|
|
||||||
const client = new RedisClient()
|
const client = new RedisClient()
|
||||||
|
|
||||||
type LimiterProps = {
|
export function limiter({ limit, minutes, key = "" }: {
|
||||||
limit: number;
|
limit: number;
|
||||||
minutes: number;
|
minutes: number;
|
||||||
key?: string;
|
key?: string;
|
||||||
}
|
}) {
|
||||||
|
|
||||||
export function limiter({limit, minutes, key = ""}: LimiterProps) {
|
|
||||||
return rateLimiter({
|
return rateLimiter({
|
||||||
windowMs: minutes * 60 * 1000, // every x minutes
|
windowMs: minutes * 60 * 1000, // every x minutes
|
||||||
limit, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
|
limit, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
|
||||||
standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
|
standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
|
||||||
keyGenerator: (c) => {
|
keyGenerator: (c) => {
|
||||||
const vars = c.var as HonoTypes['Variables'];
|
const vars = c.var as HonoTypes['Variables'];
|
||||||
const clientKey = vars.user?.id || c.req.header("x-forwarded-for");
|
const clientKey = vars.user?.id || c.req.header("x-forwarded-for");
|
||||||
const pathKey = key || c.req.routePath;
|
const pathKey = key || c.req.routePath;
|
||||||
|
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
import type { MiddlewareHandler } from 'hono';
|
|
||||||
import { createMiddleware } from 'hono/factory';
|
|
||||||
import type { Session, User } from 'lucia';
|
|
||||||
import { Unauthorized } from '../common/errors';
|
|
||||||
|
|
||||||
export const requireAuth: MiddlewareHandler<{
|
|
||||||
Variables: {
|
|
||||||
session: Session;
|
|
||||||
user: User;
|
|
||||||
};
|
|
||||||
}> = createMiddleware(async (c, next) => {
|
|
||||||
const user = c.var.user;
|
|
||||||
if (!user) throw Unauthorized('You must be logged in to access this resource');
|
|
||||||
return next();
|
|
||||||
});
|
|
||||||
|
|
@ -33,7 +33,7 @@ export class IamService {
|
||||||
@inject(TokensService) private tokensService: TokensService,
|
@inject(TokensService) private tokensService: TokensService,
|
||||||
@inject(MailerService) private mailerService: MailerService,
|
@inject(MailerService) private mailerService: MailerService,
|
||||||
@inject(LuciaProvider) private lucia: LuciaProvider
|
@inject(LuciaProvider) private lucia: LuciaProvider
|
||||||
) {}
|
) { }
|
||||||
|
|
||||||
async registerEmail(data: RegisterEmailDto) {
|
async registerEmail(data: RegisterEmailDto) {
|
||||||
const existingUser = await this.usersRepository.findOneByEmail(data.email);
|
const existingUser = await this.usersRepository.findOneByEmail(data.email);
|
||||||
|
|
@ -48,16 +48,10 @@ export class IamService {
|
||||||
|
|
||||||
async signinEmail(data: SignInEmailDto) {
|
async signinEmail(data: SignInEmailDto) {
|
||||||
const user = await this.usersRepository.findOneByEmail(data.email);
|
const user = await this.usersRepository.findOneByEmail(data.email);
|
||||||
|
if (!user) throw BadRequest('Bad credentials');
|
||||||
if (!user) {
|
|
||||||
throw BadRequest('Bad credentials');
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidToken = await this.tokensService.validateToken(user.id, data.token);
|
const isValidToken = await this.tokensService.validateToken(user.id, data.token);
|
||||||
|
if (!isValidToken) throw BadRequest('Bad credentials');
|
||||||
if (!isValidToken) {
|
|
||||||
throw BadRequest('Bad credentials');
|
|
||||||
}
|
|
||||||
|
|
||||||
// if this is a new unverified user, send a welcome email and update the user
|
// if this is a new unverified user, send a welcome email and update the user
|
||||||
if (!user.verified) {
|
if (!user.verified) {
|
||||||
|
|
@ -73,16 +67,10 @@ export class IamService {
|
||||||
|
|
||||||
async verifyEmail(userId: string, token: string) {
|
async verifyEmail(userId: string, token: string) {
|
||||||
const user = await this.usersRepository.findOneById(userId);
|
const user = await this.usersRepository.findOneById(userId);
|
||||||
|
if (!user) throw BadRequest('User not found');
|
||||||
if (!user) {
|
|
||||||
throw BadRequest('User not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const validToken = await this.tokensService.validateToken(user.id, token);
|
const validToken = await this.tokensService.validateToken(user.id, token);
|
||||||
|
if (!validToken) throw BadRequest('Invalid token');
|
||||||
if (!validToken) {
|
|
||||||
throw BadRequest('Invalid token');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.usersRepository.update(user.id, { email: validToken.email });
|
await this.usersRepository.update(user.id, { email: validToken.email });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,16 +3,14 @@
|
||||||
import Menu from 'lucide-svelte/icons/menu';
|
import Menu from 'lucide-svelte/icons/menu';
|
||||||
import Package2 from 'lucide-svelte/icons/package-2';
|
import Package2 from 'lucide-svelte/icons/package-2';
|
||||||
import Search from 'lucide-svelte/icons/search';
|
import Search from 'lucide-svelte/icons/search';
|
||||||
|
|
||||||
import { Button } from '$lib/components/ui/button/index.js';
|
import { Button } from '$lib/components/ui/button/index.js';
|
||||||
import * as Card from '$lib/components/ui/card/index.js';
|
|
||||||
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
|
|
||||||
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
|
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
|
||||||
import { Input } from '$lib/components/ui/input/index.js';
|
import { Input } from '$lib/components/ui/input/index.js';
|
||||||
import * as Sheet from '$lib/components/ui/sheet/index.js';
|
import * as Sheet from '$lib/components/ui/sheet/index.js';
|
||||||
import { cn } from '$lib/utils/ui';
|
import { cn } from '$lib/utils/ui';
|
||||||
import HouseIcon from 'lucide-svelte/icons/house';
|
import HouseIcon from 'lucide-svelte/icons/house';
|
||||||
import { page } from '$app/stores';
|
import { page } from '$app/stores';
|
||||||
|
import { enhance } from '$app/forms';
|
||||||
|
|
||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
|
|
||||||
|
|
@ -98,7 +96,11 @@
|
||||||
<DropdownMenu.Content align="end">
|
<DropdownMenu.Content align="end">
|
||||||
<DropdownMenu.Item href="/settings">Settings</DropdownMenu.Item>
|
<DropdownMenu.Item href="/settings">Settings</DropdownMenu.Item>
|
||||||
<DropdownMenu.Separator />
|
<DropdownMenu.Separator />
|
||||||
<DropdownMenu.Item>Logout</DropdownMenu.Item>
|
<DropdownMenu.Item>
|
||||||
|
<form action="/?/logout" method="POST" use:enhance class="w-full">
|
||||||
|
<button class="w-full text-start cursor-default" type="submit">Logout</button>
|
||||||
|
</form></DropdownMenu.Item
|
||||||
|
>
|
||||||
</DropdownMenu.Content>
|
</DropdownMenu.Content>
|
||||||
</DropdownMenu.Root>
|
</DropdownMenu.Root>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -2,3 +2,11 @@ export const load = async ({ locals }) => {
|
||||||
const user = await locals.getAuthedUser();
|
const user = await locals.getAuthedUser();
|
||||||
return { user: user };
|
return { user: user };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
logout: async ({ locals }) => {
|
||||||
|
console.log("Logging out")
|
||||||
|
await locals.api.iam.logout.$post()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -3,8 +3,8 @@ import { verifyEmailDto } from "$lib/dtos/verify-email.dto.js";
|
||||||
import { fail, setError, superValidate } from "sveltekit-superforms";
|
import { fail, setError, superValidate } from "sveltekit-superforms";
|
||||||
import { zod } from "sveltekit-superforms/adapters";
|
import { zod } from "sveltekit-superforms/adapters";
|
||||||
|
|
||||||
export let load = async ({ locals }) => {
|
export let load = async (event) => {
|
||||||
const authedUser = await locals.getAuthedUserOrThrow();
|
const authedUser = await event.locals.getAuthedUserOrThrow()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
authedUser,
|
authedUser,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue