Skip to content

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

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

import type {Application} from '@app/api/models/Application';
import type {User} from '@app/api/models/User';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {
	getActiveAuthenticatorTypes,
	mapUserToPartialResponse,
	mapUserToProfileResponse,
} from '@app/api/user/UserMappers';
import type {
	ApplicationBotResponse,
	ApplicationResponse,
	BotProfileResponse,
	BotTokenResetResponse,
} from '@fluxer/schema/src/domains/oauth/OAuthSchemas';

export function findBotUser(users: Pick<UserRepository, 'findUnique'>, application: Application): Promise<User | null> {
	return application.botUserId ? users.findUnique(application.botUserId) : Promise.resolve(null);
}

export function mapBotUserToResponse(
	user: User,
	opts?: {
		token?: string;
	},
): ApplicationBotResponse {
	const partial = mapUserToPartialResponse(user);
	const profile = mapUserToProfileResponse(user);
	const authenticatorTypes = getActiveAuthenticatorTypes(user);
	return {
		id: partial.id,
		username: partial.username,
		discriminator: partial.discriminator,
		avatar: partial.avatar,
		banner: profile.banner,
		bio: profile.bio ?? null,
		token: opts?.token,
		mfa_enabled: authenticatorTypes.length > 0,
		authenticator_types: authenticatorTypes,
		flags: partial.flags,
	};
}

export function mapApplicationToResponse(
	application: Application,
	options?: {
		botUser?: User | null;
		botToken?: string;
		clientSecret?: string | null;
	},
): ApplicationResponse {
	const baseResponse: ApplicationResponse = {
		id: application.applicationId.toString(),
		name: application.name,
		redirect_uris: Array.from(application.oauth2RedirectUris),
		bot_public: application.botIsPublic,
		bot_require_code_grant: application.botRequireCodeGrant,
	};
	if (options?.botUser) {
		baseResponse.bot = mapBotUserToResponse(options.botUser, {token: options.botToken});
	}
	if (options?.clientSecret) {
		return {
			...baseResponse,
			client_secret: options.clientSecret,
		};
	}
	return baseResponse;
}

export function mapBotTokenResetResponse(user: User, token: string): BotTokenResetResponse {
	return {
		token,
		bot: mapBotUserToResponse(user),
	};
}

export function mapBotProfileToResponse(user: User): BotProfileResponse {
	const partial = mapUserToPartialResponse(user);
	const profile = mapUserToProfileResponse(user);
	return {
		id: partial.id,
		username: partial.username,
		discriminator: partial.discriminator,
		avatar: partial.avatar,
		banner: profile.banner,
		bio: profile.bio ?? null,
		flags: partial.flags,
	};
}