Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
1.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {Config} from '@app/api/Config';
import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {getRequestClientIp} from '@app/api/utils/RequestClientIp';
import {GeolocationResponse} from '@fluxer/schema/src/domains/geolocation/GeolocationSchemas';
import {resolveClientGeoip} from '@pkgs/geoip/src/ResolveClientGeoip';
import type {Hono} from 'hono';

export function GeolocationController(app: Hono<HonoEnv>): void {
	app.get(
		'/ip',
		RateLimitMiddleware(RateLimitConfigs.IP_GEO_LOOKUP),
		OpenAPI({
			operationId: 'get_client_geolocation',
			summary: 'Get client geolocation',
			responseSchema: GeolocationResponse,
			statusCode: 200,
			security: [],
			tags: ['Geolocation'],
			description:
				'Resolves the approximate location of the requesting client from its IP address, together with the locations where age restricted content is gated or unavailable.',
		}),
		async (ctx) => {
			ctx.header('Access-Control-Allow-Origin', '*');
			ctx.header('Access-Control-Allow-Headers', 'Content-Type');
			ctx.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
			const response = await resolveClientGeoip(
				getRequestClientIp(ctx),
				Config.geoip.maxmindDbPath,
				Config.instance.agePolicy,
			);
			return ctx.json(response);
		},
	);
	app.options('/ip', (ctx) => {
		ctx.header('Access-Control-Allow-Origin', '*');
		ctx.header('Access-Control-Allow-Headers', 'Content-Type');
		ctx.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
		return ctx.body(null, 204);
	});
}