Skip to content

Discord Auth Decorators

This file provides a set of decorators for adding authorization and context requirements to Discord controller methods in the @sodacore/core Discord integration. These decorators attach authentication logic and context checks as metadata, enabling fine-grained access control for Discord commands and context menu actions.


Features

  • Role-Based Authorization:
    • @HasRole and @HasRoles decorators restrict access to users with specific Discord roles.
  • Custom Authorization:
    • @UserCustom and @GuildMemberCustom allow custom callback-based authorization for users or guild members.
  • Context Checks:
    • @IsDirectMessage restricts to direct messages (DMs).
    • @IsGuildMessage restricts to guild (server) messages.
  • Metadata Management:
    • All decorators update the auth array in the method's metadata for later evaluation by the framework.

Usage

typescript
import {
	HasRole,
	HasRoles,
	UserCustom,
	GuildMemberCustom,
	IsDirectMessage,
	IsGuildMessage
} from './decorator/auth';

class MyDiscordController {
	@HasRole('1234567890')
	async adminOnly(ctx) { /* ... */ }

	@HasRoles(['123', '456'])
	async multiRole(ctx) { /* ... */ }

	@UserCustom(user => user.username === 'specialUser')
	async specialUser(ctx) { /* ... */ }

	@GuildMemberCustom(member => member.premiumSince !== null)
	async premiumOnly(ctx) { /* ... */ }

	@IsDirectMessage()
	async dmOnly(ctx) { /* ... */ }

	@IsGuildMessage()
	async guildOnly(ctx) { /* ... */ }
}

API

HasRole(roleId: string): MethodDecorator

Restricts access to users with the specified role ID.

HasRoles(roleIds: string[]): MethodDecorator

Restricts access to users who have all of the specified role IDs.

UserCustom(callback: IAuthFunctionUser): MethodDecorator

Adds a custom authorization callback for Discord users.

GuildMemberCustom(callback: IAuthFunctionGuildMember): MethodDecorator

Adds a custom authorization callback for Discord guild members.

IsDirectMessage(): MethodDecorator

Restricts access to direct messages (DMs) only.

IsGuildMessage(): MethodDecorator

Restricts access to guild (server) messages only.


How It Works

  • Each decorator retrieves or creates the method's metadata entry in the methods array.
  • The decorator pushes an auth object with a wants property (context type) and a callback function for authorization.
  • The metadata is stored using Utils.setMeta and is later used by the framework to enforce access control when the command is invoked.

Notes

  • These decorators are intended for use within Discord controller classes.
  • The framework will evaluate all auth callbacks before executing the decorated method.
  • Requires discord.js as a peer dependency.

Released under the Apache-2.0 License.