azalea_client/account.rs
1//! Connect to Minecraft servers.
2
3use std::sync::Arc;
4
5use azalea_auth::{
6 AccessTokenResponse,
7 certs::{Certificates, FetchCertificatesError},
8};
9use bevy_ecs::component::Component;
10use parking_lot::Mutex;
11use thiserror::Error;
12use tracing::trace;
13use uuid::Uuid;
14
15/// Something that can join Minecraft servers.
16///
17/// To join a server using this account, use [`Client::join`] or
18/// [`azalea::ClientBuilder`].
19///
20/// This is also an ECS component that is present on our client entities.
21///
22/// # Examples
23///
24/// ```rust,no_run
25/// use azalea_client::Account;
26///
27/// # #[tokio::main]
28/// # async fn main() {
29/// let account = Account::microsoft("[email protected]").await;
30/// // or Account::offline("example");
31/// # }
32/// ```
33///
34/// [`Client::join`]: crate::Client::join
35/// [`azalea::ClientBuilder`]: https://docs.rs/azalea/latest/azalea/struct.ClientBuilder.html
36#[derive(Clone, Debug, Component)]
37pub struct Account {
38 /// The Minecraft username of the account.
39 pub username: String,
40 /// The access token for authentication. You can obtain one of these
41 /// manually from azalea-auth.
42 ///
43 /// This is an `Arc<Mutex>` so it can be modified by [`Self::refresh`].
44 pub access_token: Option<Arc<Mutex<String>>>,
45 /// Only required for online-mode accounts.
46 pub uuid: Option<Uuid>,
47
48 /// The parameters (i.e. email) that were passed for creating this
49 /// [`Account`]. This is used for automatic reauthentication when we get
50 /// "Invalid Session" errors. If you don't need that feature (like in
51 /// offline mode), then you can set this to `AuthOpts::default()`.
52 pub account_opts: AccountOpts,
53
54 /// The certificates used for chat signing.
55 ///
56 /// This is set when you call [`Self::request_certs`], but you only
57 /// need to if the servers you're joining require it.
58 pub certs: Arc<Mutex<Option<Certificates>>>,
59}
60
61/// The parameters that were passed for creating the associated [`Account`].
62#[derive(Clone, Debug)]
63pub enum AccountOpts {
64 Offline {
65 username: String,
66 },
67 Microsoft {
68 email: String,
69 },
70 MicrosoftWithAccessToken {
71 msa: Arc<Mutex<azalea_auth::cache::ExpiringValue<AccessTokenResponse>>>,
72 },
73}
74
75impl Account {
76 /// An offline account does not authenticate with Microsoft's servers, and
77 /// as such can only join offline mode servers. This is useful for testing
78 /// in LAN worlds.
79 pub fn offline(username: &str) -> Self {
80 Self {
81 username: username.to_string(),
82 access_token: None,
83 uuid: None,
84 account_opts: AccountOpts::Offline {
85 username: username.to_string(),
86 },
87 certs: Arc::new(Mutex::new(None)),
88 }
89 }
90
91 /// This will create an online-mode account by authenticating with
92 /// Microsoft's servers. Note that the email given is actually only used as
93 /// a key for the cache, but it's recommended to use the real email to
94 /// avoid confusion.
95 pub async fn microsoft(email: &str) -> Result<Self, azalea_auth::AuthError> {
96 Self::microsoft_with_custom_client_id_and_scope(email, None, None).await
97 }
98
99 /// Similar to [`Account::microsoft`] but you can use your
100 /// own `client_id` and `scope`.
101 ///
102 /// Pass `None` if you want to use default ones.
103 pub async fn microsoft_with_custom_client_id_and_scope(
104 email: &str,
105 client_id: Option<&str>,
106 scope: Option<&str>,
107 ) -> Result<Self, azalea_auth::AuthError> {
108 let minecraft_dir = minecraft_folder_path::minecraft_dir().unwrap_or_else(|| {
109 panic!(
110 "No {} environment variable found",
111 minecraft_folder_path::home_env_var()
112 )
113 });
114 let auth_result = azalea_auth::auth(
115 email,
116 azalea_auth::AuthOpts {
117 cache_file: Some(minecraft_dir.join("azalea-auth.json")),
118 client_id,
119 scope,
120 ..Default::default()
121 },
122 )
123 .await?;
124 Ok(Self {
125 username: auth_result.profile.name,
126 access_token: Some(Arc::new(Mutex::new(auth_result.access_token))),
127 uuid: Some(auth_result.profile.id),
128 account_opts: AccountOpts::Microsoft {
129 email: email.to_string(),
130 },
131 // we don't do chat signing by default unless the user asks for it
132 certs: Arc::new(Mutex::new(None)),
133 })
134 }
135
136 /// This will create an online-mode account through
137 /// [`azalea_auth::get_minecraft_token`] so you can have more control over
138 /// the authentication process (like doing your own caching or
139 /// displaying the Microsoft user code to the user in a different way).
140 ///
141 /// This will refresh the given token if it's expired.
142 ///
143 /// ```
144 /// # use azalea_client::Account;
145 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
146 /// let client = reqwest::Client::new();
147 ///
148 /// let res = azalea_auth::get_ms_link_code(&client, None, None).await?;
149 /// // Or, `azalea_auth::get_ms_link_code(&client, Some(client_id), None).await?`
150 /// // if you want to use your own client_id
151 /// println!(
152 /// "Go to {} and enter the code {}",
153 /// res.verification_uri, res.user_code
154 /// );
155 /// let msa = azalea_auth::get_ms_auth_token(&client, res, None).await?;
156 /// Account::with_microsoft_access_token(msa).await?;
157 /// # Ok(())
158 /// # }
159 /// ```
160 pub async fn with_microsoft_access_token(
161 msa: azalea_auth::cache::ExpiringValue<AccessTokenResponse>,
162 ) -> Result<Self, azalea_auth::AuthError> {
163 Self::with_microsoft_access_token_and_custom_client_id_and_scope(msa, None, None).await
164 }
165
166 /// Similar to [`Account::with_microsoft_access_token`] but you can use
167 /// custom `client_id` and `scope`.
168 pub async fn with_microsoft_access_token_and_custom_client_id_and_scope(
169 mut msa: azalea_auth::cache::ExpiringValue<AccessTokenResponse>,
170 client_id: Option<&str>,
171 scope: Option<&str>,
172 ) -> Result<Self, azalea_auth::AuthError> {
173 let client = reqwest::Client::new();
174
175 if msa.is_expired() {
176 trace!("refreshing Microsoft auth token");
177 msa = azalea_auth::refresh_ms_auth_token(
178 &client,
179 &msa.data.refresh_token,
180 client_id,
181 scope,
182 )
183 .await?;
184 }
185
186 let msa_token = &msa.data.access_token;
187
188 let res = azalea_auth::get_minecraft_token(&client, msa_token).await?;
189
190 let profile = azalea_auth::get_profile(&client, &res.minecraft_access_token).await?;
191
192 Ok(Self {
193 username: profile.name,
194 access_token: Some(Arc::new(Mutex::new(res.minecraft_access_token))),
195 uuid: Some(profile.id),
196 account_opts: AccountOpts::MicrosoftWithAccessToken {
197 msa: Arc::new(Mutex::new(msa)),
198 },
199 certs: Arc::new(Mutex::new(None)),
200 })
201 }
202 /// Refresh the access_token for this account to be valid again.
203 ///
204 /// This requires the `auth_opts` field to be set correctly (which is done
205 /// by default if you used the constructor functions). Note that if the
206 /// Account is offline-mode then this function won't do anything.
207 pub async fn refresh(&self) -> Result<(), azalea_auth::AuthError> {
208 match &self.account_opts {
209 // offline mode doesn't need to refresh so just don't do anything lol
210 AccountOpts::Offline { .. } => Ok(()),
211 AccountOpts::Microsoft { email } => {
212 let new_account = Account::microsoft(email).await?;
213 let access_token_mutex = self.access_token.as_ref().unwrap();
214 let new_access_token = new_account.access_token.unwrap().lock().clone();
215 *access_token_mutex.lock() = new_access_token;
216 Ok(())
217 }
218 AccountOpts::MicrosoftWithAccessToken { msa } => {
219 let msa_value = msa.lock().clone();
220 let new_account = Account::with_microsoft_access_token(msa_value).await?;
221
222 let access_token_mutex = self.access_token.as_ref().unwrap();
223 let new_access_token = new_account.access_token.unwrap().lock().clone();
224
225 *access_token_mutex.lock() = new_access_token;
226 let AccountOpts::MicrosoftWithAccessToken { msa: new_msa } =
227 new_account.account_opts
228 else {
229 unreachable!()
230 };
231 *msa.lock() = new_msa.lock().clone();
232
233 Ok(())
234 }
235 }
236 }
237
238 /// Get the UUID of this account. This will generate an offline-mode UUID
239 /// by making a hash with the username if the `uuid` field is None.
240 pub fn uuid_or_offline(&self) -> Uuid {
241 self.uuid
242 .unwrap_or_else(|| azalea_auth::offline::generate_uuid(&self.username))
243 }
244}
245
246#[derive(Error, Debug)]
247pub enum RequestCertError {
248 #[error("Failed to fetch certificates")]
249 FetchCertificates(#[from] FetchCertificatesError),
250 #[error("You can't request certificates for an offline account")]
251 NoAccessToken,
252}
253
254impl Account {
255 /// Request the certificates used for chat signing and set it in
256 /// [`Self::certs`].
257 pub async fn request_certs(&mut self) -> Result<(), RequestCertError> {
258 let access_token = self
259 .access_token
260 .as_ref()
261 .ok_or(RequestCertError::NoAccessToken)?
262 .lock()
263 .clone();
264 let certs = azalea_auth::certs::fetch_certificates(&access_token).await?;
265 *self.certs.lock() = Some(certs);
266
267 Ok(())
268 }
269}