Skip to content
Classplugin-oauthv0.1.0

OAuthClient

Discord's OAuth2 login for one application. It serves the login and callback routes, keeps each user's tokens encrypted in a store, and refreshes them before they expire.

@seedcord/plugin-oauth's OAuth plugin builds one for you. Build your own to use it without seedcord, in any server that has a Request and takes a Response.

class OAuthClient<
    TScopes extends OAuthScope = never,
    TExtra extends OAuthScope = never
>
const oauth = new OAuthClient({
    rest: new REST().setToken(process.env.DISCORD_BOT_TOKEN),
    store: new Map(),
    clientId: '1564002376115949650',
    clientSecret: process.env.DISCORD_CLIENT_SECRET,
    baseUrl: 'https://example.com',
    scopes: ['guilds'],
    extraScopes: ['connections']
});

// in your server's request handler
const response = await oauth.fetch(request, (outcome) =>
    outcome.kind === 'login'
        ? Response.redirect(new URL(outcome.login.returnTo ?? '/dashboard', request.url))
        : new Response('The login failed.', { status: 400 })
);

// anywhere after that
const guilds = await oauth.as(userId).guilds();
const connections = await oauth.as(userId).connections(); // undefined until they grant it

Member visibility

Filter class members by access level.

constructor

Constructs a new instance of the OAuthClient class

OAuthClient(
    {
        rest,
        store,
        clientId,
        clientSecret,
        baseUrl,
        routes,
        scopes,
        extraScopes,
        keepOpen
    },
    input: OAuthClientOptions<TScopes, TExtra>
)

Showing members with Protected visibility and higher.

TScopes

The scopes from the options. Leave it out.

TScopes extends OAuthScope = never

TExtra

The extraScopes from the options. Leave it out.

TExtra extends OAuthScope = never

redirectUri

The callback route's full address. Discord refuses logins until it's under Redirects on the OAuth2 page.

public readonly redirectUri: string

as()

Calls Discord as a user who logged in. user(), guilds(), guildMember(), and connections() return typed results. get, post, put, patch, and delete take the same arguments as your REST client's methods and reach any other route.

Each call reads the user's tokens and refreshes them first when they're about to expire. A typed call also checks that the user granted its scope before it calls Discord.

public as(userId: string): UserCalls<TScopes, TExtra>

Throws:

A SeedcordError with the code PluginOAuthLoginNeeded from any call when the user never logged in or Discord refused to refresh their tokens. A typed call also throws it when Discord refuses the access token, and when the user's login is older than a scope you added to scopes. Send them through the login again.

const guilds = await oauth.as(userId).guilds({ with_counts: true });
const authorization = await oauth.as(userId).get('/oauth2/@me');

authorizeUrl()

The link to Discord's consent screen. Call it only if your server handles state itself.

public authorizeUrl(
    options: AuthorizeUrlOptions<TScopes, TExtra>
): string

exchange()

Trades the code from Discord's redirect for the user's tokens and saves them. Call it only if your server handles state itself.

Resolves to undefined when Discord refuses the code. A reloaded callback page gets undefined because a code works once.

public async exchange(
    code: string,
    codeVerifier?: string
): Promise<OAuthLogin | undefined>
Parameter: codeVerifier

The PKCE verifier for an authorize link that had a codeChallenge.

Throws:

A SeedcordError when the authorize link didn't request identify.

fetch()

Answers a request for the login route or the callback route. Resolves to undefined for any other request, which your server should answer itself.

The login route sends the visitor to Discord. The callback route checks that this browser started the login, saves the user's tokens, and then calls respond. The login route also calls respond, with an unlisted outcome, for a link that requests a scope outside extraScopes.

public async fetch(
    request: Request,
    respond: (outcome: LoginOutcome) => Promisable<Response>
): Promise<Response | undefined>
Parameter: respond

Returns what the visitor's browser gets for that outcome, usually a redirect.

forget()

Deletes a user's saved tokens. It doesn't call Discord, and the user's grant there keeps working.

When several processes share one store, a refresh that's running in another one can save the tokens back. Call revoke when the login has to end for certain.

public async forget(userId: string): Promise<void>

loginUrl()

The address of the login route. Send a browser there, or put it in a message.

public loginUrl(link?: LoginLink<TScopes, TExtra>): string
// requests one more scope, and ends on the page that needed it
oauth.loginUrl({ scopes: ['connections'], returnTo: '/dashboard/accounts' });

revoke()

Revokes a user's grant on Discord and deletes their saved tokens.

Discord ends every grant that the user gave your application, so tokens that another OAuthClient saved for them stop working too. Use forget to log someone out of one place.

public async revoke(userId: string): Promise<void>

scopesOf()

The scopes that a user granted, or undefined for a user without saved tokens. It doesn't call Discord.

public async scopesOf(
    userId: string
): Promise<OAuthScope[] | undefined>