djs_rest/endpoints/oauth2.rs
1//! [OAuth2 endpoints](https://docs.discord.com/developers/topics/oauth2): the application and
2//! authorization behind a token, and the token endpoints (D-131, D-132).
3//!
4//! The token endpoints take the application's [`OAuth2Credentials`] in an
5//! `application/x-www-form-urlencoded` body and are sent without the client's own token, so
6//! any [`Rest`] works for them — also one built without a token.
7
8use djs_model::{
9 application::Application,
10 oauth2::{AccessTokenResponse, CurrentAuthorizationInformation, Scope},
11};
12
13use crate::client::boxed;
14use crate::{
15 Error, Request, Rest, Route,
16 oauth2::{OAuth2Credentials, TokenForm, TokenTypeHint},
17};
18
19impl Rest {
20 /// [Get Current Bot Application Information](https://docs.discord.com/developers/topics/oauth2#get-current-bot-application-information):
21 /// returns the bot's application, like
22 /// [`get_current_application`](Self::get_current_application).
23 ///
24 /// discord.js counterpart: `ClientApplication#fetch`.
25 ///
26 /// # Errors
27 ///
28 /// See [`Rest::request`].
29 pub fn get_current_bot_application_information(
30 &self,
31 ) -> impl Future<Output = Result<Application, Error>> + Send + '_ {
32 boxed(async move {
33 self.call(Request::new(Route::GetCurrentBotApplicationInformation))
34 .await
35 })
36 }
37
38 /// [Get Current Authorization Information](https://docs.discord.com/developers/topics/oauth2#get-current-authorization-information):
39 /// returns what the client's access token is authorized for, when it expires and — with
40 /// the `identify` scope — who authorized it. Needs a client built with
41 /// [`bearer_token`](crate::RestBuilder::bearer_token).
42 ///
43 /// discord.js counterpart: none.
44 ///
45 /// # Errors
46 ///
47 /// See [`Rest::request`]; `401` for a bot token or an invalid access token.
48 pub fn get_current_authorization_information(
49 &self,
50 ) -> impl Future<Output = Result<CurrentAuthorizationInformation, Error>> + Send + '_ {
51 boxed(async move {
52 self.call(Request::new(Route::GetCurrentAuthorizationInformation))
53 .await
54 })
55 }
56
57 /// Exchanges the `code` of an [authorization code grant](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant)
58 /// redirect for the user's access token. `redirect_uri` must be the one of the
59 /// authorization URL.
60 ///
61 /// discord.js counterpart: none.
62 ///
63 /// # Examples
64 ///
65 /// See the [`oauth2`](crate::oauth2) module.
66 ///
67 /// # Errors
68 ///
69 /// See [`Rest::request`]; `400` for an invalid, expired or already used code or a
70 /// mismatched redirect URI, `401` for wrong credentials. Discord's `OAuth2` error bodies
71 /// (`{"error": "invalid_grant", …}`) are not parsed into an
72 /// [`ApiError`](crate::ApiError).
73 pub fn exchange_code<'a>(
74 &'a self,
75 credentials: &'a OAuth2Credentials,
76 code: &'a str,
77 redirect_uri: &'a str,
78 ) -> impl Future<Output = Result<AccessTokenResponse, Error>> + Send + 'a {
79 boxed(async move {
80 let form = TokenForm::new("grant_type", "authorization_code")
81 .field("code", code)
82 .field("redirect_uri", redirect_uri)
83 .finish(credentials);
84 self.call(Request::new(Route::OAuth2TokenExchange).form_urlencoded(form))
85 .await
86 })
87 }
88
89 /// [Refreshes](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant-refresh-token-exchange-example)
90 /// an access token: returns a new access token and a new refresh token.
91 ///
92 /// discord.js counterpart: none.
93 ///
94 /// # Errors
95 ///
96 /// See [`Rest::request`]; `400` for an invalid or revoked refresh token.
97 pub fn refresh_access_token<'a>(
98 &'a self,
99 credentials: &'a OAuth2Credentials,
100 refresh_token: &'a str,
101 ) -> impl Future<Output = Result<AccessTokenResponse, Error>> + Send + 'a {
102 boxed(async move {
103 let form = TokenForm::new("grant_type", "refresh_token")
104 .field("refresh_token", refresh_token)
105 .finish(credentials);
106 self.call(Request::new(Route::OAuth2TokenExchange).form_urlencoded(form))
107 .await
108 })
109 }
110
111 /// The [client credentials grant](https://docs.discord.com/developers/topics/oauth2#client-credentials-grant):
112 /// an access token of the application's owner for `scopes`, without a refresh token —
113 /// mostly for testing. Team applications may only request `identify` and
114 /// `applications.commands.update`.
115 ///
116 /// discord.js counterpart: none.
117 ///
118 /// # Errors
119 ///
120 /// See [`Rest::request`]; `400` for a scope that is not allowed.
121 pub fn client_credentials_grant<'a>(
122 &'a self,
123 credentials: &'a OAuth2Credentials,
124 scopes: &'a [Scope],
125 ) -> impl Future<Output = Result<AccessTokenResponse, Error>> + Send + 'a {
126 boxed(async move {
127 let scope = scopes
128 .iter()
129 .map(Scope::as_str)
130 .collect::<Vec<_>>()
131 .join(" ");
132 let form = TokenForm::new("grant_type", "client_credentials")
133 .field("scope", &scope)
134 .finish(credentials);
135 self.call(Request::new(Route::OAuth2TokenExchange).form_urlencoded(form))
136 .await
137 })
138 }
139
140 /// [Revokes](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant-token-revocation-example)
141 /// an access or refresh token. Discord revokes every token of the authorization, whichever
142 /// is passed.
143 ///
144 /// discord.js counterpart: none.
145 ///
146 /// # Errors
147 ///
148 /// See [`Rest::request`].
149 pub fn revoke_token<'a>(
150 &'a self,
151 credentials: &'a OAuth2Credentials,
152 token: &'a str,
153 hint: Option<TokenTypeHint>,
154 ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
155 boxed(async move {
156 let mut form = TokenForm::new("token", token);
157 if let Some(hint) = hint {
158 form = form.field("token_type_hint", hint.as_str());
159 }
160 self.request_ignoring_body(
161 Request::new(Route::OAuth2TokenRevocation)
162 .form_urlencoded(form.finish(credentials)),
163 )
164 .await
165 })
166 }
167}