djs_model/oauth2.rs
1//! [OAuth2](https://docs.discord.com/developers/topics/oauth2): scopes an application can be
2//! authorized for, access tokens and the information of an authorization.
3
4use core::fmt;
5
6use compact_str::CompactString;
7use serde::{Deserialize, Serialize};
8
9use crate::{
10 application::PartialApplication, guild::Guild, macros::str_enum, user::User, util::Timestamp,
11 webhook::Webhook,
12};
13
14str_enum! {
15 /// An [OAuth2 scope](https://docs.discord.com/developers/topics/oauth2#shared-resources-oauth2-scopes):
16 /// what an application may do on a user's behalf.
17 ///
18 /// discord.js counterpart: `OAuth2Scopes`.
19 ///
20 /// # Examples
21 ///
22 /// ```
23 /// use djs_model::oauth2::Scope;
24 ///
25 /// let scope: Scope = serde_json::from_str(r#""applications.commands""#).unwrap();
26 /// assert_eq!(scope, Scope::ApplicationsCommands);
27 /// ```
28 pub enum Scope {
29 /// Read the user's "Now Playing/Recently Played" list (not available for apps).
30 ActivitiesRead = "activities.read",
31 /// Update the user's activity (not available for apps).
32 ActivitiesWrite = "activities.write",
33 /// Read build data of the user's applications.
34 ApplicationsBuildsRead = "applications.builds.read",
35 /// Upload builds for the user's applications (approved partners only).
36 ApplicationsBuildsUpload = "applications.builds.upload",
37 /// Add application commands to a guild (included with `bot`).
38 ApplicationsCommands = "applications.commands",
39 /// Update the app's commands with a client-credentials bearer token.
40 ApplicationsCommandsUpdate = "applications.commands.update",
41 /// Update the permissions of the app's commands in a guild the user can manage.
42 ApplicationsCommandsPermissionsUpdate = "applications.commands.permissions.update",
43 /// Read entitlements of the user's applications.
44 ApplicationsEntitlements = "applications.entitlements",
45 /// Read and update store data of the user's applications.
46 ApplicationsStoreUpdate = "applications.store.update",
47 /// Add the app's bot to the guild the user selects.
48 Bot = "bot",
49 /// List the user's linked third-party accounts.
50 Connections = "connections",
51 /// See the user's DMs and group DMs (approved partners only).
52 DmChannelsRead = "dm_channels.read",
53 /// Read the user's email address.
54 Email = "email",
55 /// Add the user to group DMs.
56 GdmJoin = "gdm.join",
57 /// List the user's guilds.
58 Guilds = "guilds",
59 /// Add the user to guilds.
60 GuildsJoin = "guilds.join",
61 /// Read the user's member data in their guilds.
62 GuildsMembersRead = "guilds.members.read",
63 /// Read the user's account (without email).
64 Identify = "identify",
65 /// Read the user's Nitro subscription type.
66 IdentifyPremium = "identify.premium",
67 /// Read messages from all client channels (local RPC server).
68 MessagesRead = "messages.read",
69 /// Read the user's friends, pending requests and blocked users (Social SDK).
70 RelationshipsRead = "relationships.read",
71 /// Update the user's connection and metadata for the app (linked roles).
72 RoleConnectionsWrite = "role_connections.write",
73 /// Control the user's local Discord client (approved partners only).
74 Rpc = "rpc",
75 /// Update the user's activity over RPC (approved partners only).
76 RpcActivitiesWrite = "rpc.activities.write",
77 /// Receive notifications pushed to the user over RPC (approved partners only).
78 RpcNotificationsRead = "rpc.notifications.read",
79 /// Read the user's voice settings over RPC (approved partners only).
80 RpcVoiceRead = "rpc.voice.read",
81 /// Update the user's voice settings over RPC (approved partners only).
82 RpcVoiceWrite = "rpc.voice.write",
83 /// Connect to voice on the user's behalf (approved partners only).
84 Voice = "voice",
85 /// Create a webhook returned in the `OAuth2` token response.
86 WebhookIncoming = "webhook.incoming",
87 }
88}
89
90/// The response of the [token endpoint](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant-access-token-response):
91/// an access token for the user who authorized the application.
92///
93/// Send it with a client built with `RestBuilder::bearer_token` to act for the user. The
94/// tokens are redacted in the `Debug` output (C-011).
95///
96/// discord.js counterpart: none (discord-api-types: `RESTPostOAuth2AccessTokenResult`).
97///
98/// # Examples
99///
100/// ```
101/// use djs_model::oauth2::{AccessTokenResponse, Scope};
102///
103/// let response: AccessTokenResponse = serde_json::from_str(
104/// r#"{"access_token": "user-access-token", "token_type": "Bearer",
105/// "expires_in": 604800, "refresh_token": "user-refresh-token",
106/// "scope": "identify guilds"}"#,
107/// )?;
108/// assert_eq!(
109/// response.scopes().collect::<Vec<_>>(),
110/// [Scope::Identify, Scope::Guilds]
111/// );
112/// assert!(!format!("{response:?}").contains("user-access-token"));
113/// # Ok::<(), serde_json::Error>(())
114/// ```
115#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[non_exhaustive]
117pub struct AccessTokenResponse {
118 /// The access token.
119 pub access_token: String,
120 /// How the token is sent (`Bearer`).
121 pub token_type: CompactString,
122 /// How many seconds the access token is valid for.
123 pub expires_in: u64,
124 /// The token to get a new access token with once this one expires. Client credentials
125 /// grants do not get one.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub refresh_token: Option<String>,
128 /// The authorized scopes, separated by spaces; see [`scopes`](Self::scopes).
129 pub scope: CompactString,
130 /// For the `bot` scope with the authorization code grant: the guild the bot was added
131 /// to.
132 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub guild: Option<Box<Guild>>,
134 /// For the `webhook.incoming` scope: the webhook created in the channel the user picked,
135 /// with its token.
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub webhook: Option<Box<Webhook>>,
138}
139
140impl AccessTokenResponse {
141 /// The authorized scopes, parsed from [`scope`](Self::scope).
142 ///
143 /// discord.js counterpart: the `scope` of `RESTPostOAuth2AccessTokenResult` (discord-api-types).
144 pub fn scopes(&self) -> impl Iterator<Item = Scope> + '_ {
145 self.scope.split_ascii_whitespace().map(Scope::from)
146 }
147}
148
149impl fmt::Debug for AccessTokenResponse {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 f.debug_struct("AccessTokenResponse")
152 .field("access_token", &"<redacted>")
153 .field("token_type", &self.token_type)
154 .field("expires_in", &self.expires_in)
155 .field(
156 "refresh_token",
157 &self.refresh_token.as_ref().map(|_| "<redacted>"),
158 )
159 .field("scope", &self.scope)
160 .field("guild", &self.guild)
161 .field("webhook", &self.webhook)
162 .finish()
163 }
164}
165
166/// The response of [Get Current Authorization Information](https://docs.discord.com/developers/topics/oauth2#get-current-authorization-information):
167/// what an access token is authorized for.
168///
169/// discord.js counterpart: none (discord-api-types:
170/// `RESTGetAPIOAuth2CurrentAuthorizationResult`).
171#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
172#[non_exhaustive]
173pub struct CurrentAuthorizationInformation {
174 /// The application the token belongs to.
175 pub application: PartialApplication,
176 /// The scopes the user authorized.
177 pub scopes: Vec<Scope>,
178 /// When the access token expires.
179 pub expires: Timestamp,
180 /// The user who authorized, with the `identify` scope.
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub user: Option<Box<User>>,
183}