# OAuthClient

`class` in `plugin-oauth` · v0.1.0

<https://seedcord.org/docs/packages/plugin-oauth/0.1.0/classes/oauth-client>

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`.

```ts
class OAuthClient<
    TScopes extends OAuthScope = never,
    TExtra extends OAuthScope = never
>
```

## Examples

```ts
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
```

## Constructors

### constructor

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

Constructs a new instance of the `OAuthClient` class

## Properties

### redirectUri

```ts
public readonly redirectUri: string
```

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

## Methods

### as

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

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.

### authorizeUrl

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

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

### exchange

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

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.

### fetch

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

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`.

### forget

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

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`](/docs/packages/plugin-oauth/0.1.0/classes/oauth-client#revoke) when the login has to end for certain.

### loginUrl

```ts
public loginUrl(link?: LoginLink<TScopes, TExtra>): string
```

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

### revoke

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

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`](/docs/packages/plugin-oauth/0.1.0/classes/oauth-client#forget) to log someone out of one place.

### scopesOf

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

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