Struct twitch_oauth2::types::ClientId
source · #[repr(transparent)]pub struct ClientId(_);
Expand description
A Client Id
Implementations§
source§impl ClientId
impl ClientId
sourcepub fn from_static(raw: &'static str) -> Self
pub fn from_static(raw: &'static str) -> Self
Constructs a new ClientId from a static reference
sourcepub fn into_boxed_ref(self) -> Box<ClientIdRef>
pub fn into_boxed_ref(self) -> Box<ClientIdRef>
Converts this ClientId
into a Box<ClientIdRef>
This will drop any excess capacity.
Methods from Deref<Target = ClientIdRef>§
sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
Provides access to the underlying value as a string slice.
Examples found in repository?
src/lib.rs (line 171)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
pub fn revoke_token_request(&self, client_id: &ClientId) -> http::Request<Vec<u8>> {
use http::{HeaderMap, Method};
use std::collections::HashMap;
let mut params = HashMap::new();
params.insert("client_id", client_id.as_str());
params.insert("token", self.secret());
construct_request(
&crate::REVOKE_URL,
¶ms,
HeaderMap::new(),
Method::POST,
vec![],
)
}
/// Revoke the token.
///
/// See <https://dev.twitch.tv/docs/authentication#revoking-access-tokens>
#[cfg(feature = "client")]
pub async fn revoke_token<'a, C>(
&self,
http_client: &'a C,
client_id: &ClientId,
) -> Result<(), RevokeTokenError<<C as Client<'a>>::Error>>
where
C: Client<'a>,
{
let req = self.revoke_token_request(client_id);
let resp = http_client
.req(req)
.await
.map_err(RevokeTokenError::RequestError)?;
let _ = parse_token_response_raw(&resp)?;
Ok(())
}
}
impl RefreshTokenRef {
/// Get the request needed to refresh this token.
///
/// Parse the response from this endpoint with [TwitchTokenResponse::from_response](crate::id::TwitchTokenResponse::from_response)
pub fn refresh_token_request(
&self,
client_id: &ClientId,
client_secret: &ClientSecret,
) -> http::Request<Vec<u8>> {
use http::{HeaderMap, Method};
use std::collections::HashMap;
let mut params = HashMap::new();
params.insert("client_id", client_id.as_str());
params.insert("client_secret", client_secret.secret());
params.insert("grant_type", "refresh_token");
params.insert("refresh_token", self.secret());
construct_request(
&crate::TOKEN_URL,
¶ms,
HeaderMap::new(),
Method::POST,
vec![],
)
}
More examples
src/tokens/app_access_token.rs (line 195)
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
pub fn get_app_access_token_request(
client_id: &ClientIdRef,
client_secret: &ClientSecretRef,
scopes: Vec<Scope>,
) -> http::Request<Vec<u8>> {
use http::{HeaderMap, Method};
use std::collections::HashMap;
let scope: String = scopes
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
.join(" ");
let mut params = HashMap::new();
params.insert("client_id", client_id.as_str());
params.insert("client_secret", client_secret.secret());
params.insert("grant_type", "client_credentials");
params.insert("scope", &scope);
crate::construct_request(
&crate::TOKEN_URL,
¶ms,
HeaderMap::new(),
Method::POST,
vec![],
)
}
src/tokens/user_token.rs (line 192)
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
pub async fn mock_token<'a, C>(
http_client: &'a C,
client_id: ClientId,
client_secret: ClientSecret,
user_id: impl AsRef<str>,
scopes: Vec<Scope>,
) -> Result<UserToken, UserTokenExchangeError<<C as Client<'a>>::Error>>
where
C: Client<'a>,
{
use http::{HeaderMap, Method};
use std::collections::HashMap;
let user_id = user_id.as_ref();
let scope_str = scopes.as_slice().join(" ");
let mut params = HashMap::new();
params.insert("client_id", client_id.as_str());
params.insert("client_secret", client_secret.secret());
params.insert("grant_type", "user_token");
params.insert("scope", &scope_str);
params.insert("user_id", user_id);
let req = crate::construct_request(
&crate::AUTH_URL,
¶ms,
HeaderMap::new(),
Method::POST,
vec![],
);
let resp = http_client
.req(req)
.await
.map_err(UserTokenExchangeError::RequestError)?;
let response = crate::id::TwitchTokenResponse::from_response(&resp)?;
UserToken::from_existing(
http_client,
response.access_token,
response.refresh_token,
client_secret,
)
.await
.map_err(Into::into)
}
/// Set the client secret
pub fn set_secret(&mut self, secret: Option<ClientSecret>) { self.client_secret = secret }
}
#[cfg_attr(feature = "client", async_trait::async_trait)]
impl TwitchToken for UserToken {
fn token_type() -> super::BearerTokenType { super::BearerTokenType::UserToken }
fn client_id(&self) -> &ClientId { &self.client_id }
fn token(&self) -> &AccessToken { &self.access_token }
fn login(&self) -> Option<&UserNameRef> { Some(&self.login) }
fn user_id(&self) -> Option<&UserIdRef> { Some(&self.user_id) }
#[cfg(feature = "client")]
async fn refresh_token<'a, C>(
&mut self,
http_client: &'a C,
) -> Result<(), RefreshTokenError<<C as Client<'a>>::Error>>
where
Self: Sized,
C: Client<'a>,
{
if let Some(client_secret) = self.client_secret.clone() {
let (access_token, expires, refresh_token) =
if let Some(token) = self.refresh_token.take() {
token
.refresh_token(http_client, &self.client_id, &client_secret)
.await?
} else {
return Err(RefreshTokenError::NoRefreshToken);
};
self.access_token = access_token;
self.expires_in = expires;
self.refresh_token = refresh_token;
Ok(())
} else {
return Err(RefreshTokenError::NoClientSecretFound);
}
}
fn expires_in(&self) -> std::time::Duration {
if !self.never_expiring {
self.expires_in
.checked_sub(self.struct_created.elapsed())
.unwrap_or_default()
} else {
// We don't return an option here because it's not expected to use this if the token is known to be unexpiring.
// TODO: Use Duration::MAX
std::time::Duration::new(u64::MAX, 1_000_000_000 - 1)
}
}
fn scopes(&self) -> &[Scope] { self.scopes.as_slice() }
}
/// Builder for [OAuth authorization code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow)
///
/// See [`ImplicitUserTokenBuilder`] for the [OAuth implicit code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-implicit-code-flow) (does not require Client Secret)
pub struct UserTokenBuilder {
pub(crate) scopes: Vec<Scope>,
pub(crate) csrf: Option<crate::types::CsrfToken>,
pub(crate) force_verify: bool,
pub(crate) redirect_url: url::Url,
client_id: ClientId,
client_secret: ClientSecret,
}
impl UserTokenBuilder {
/// Create a [`UserTokenBuilder`]
///
/// # Notes
///
/// The `url` crate converts empty paths into "/" (such as `https://example.com` into `https://example.com/`),
/// which means that you'll need to add `https://example.com/` to your redirect URIs (note the "trailing" slash) if you want to use an empty path.
///
/// To avoid this, use a path such as `https://example.com/twitch/register` or similar instead, where the `url` crate would not add a trailing `/`.
pub fn new(
client_id: impl Into<ClientId>,
client_secret: impl Into<ClientSecret>,
redirect_url: url::Url,
) -> UserTokenBuilder {
UserTokenBuilder {
scopes: vec![],
csrf: None,
force_verify: false,
redirect_url,
client_id: client_id.into(),
client_secret: client_secret.into(),
}
}
/// Add scopes to the request
pub fn set_scopes(mut self, scopes: Vec<Scope>) -> Self {
self.scopes = scopes;
self
}
/// Add a single scope to request
pub fn add_scope(&mut self, scope: Scope) { self.scopes.push(scope); }
/// Enable or disable function to make the user able to switch accounts if needed.
pub fn force_verify(mut self, b: bool) -> Self {
self.force_verify = b;
self
}
/// Generate the URL to request a code.
///
/// Step 1. in the [guide](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow)
pub fn generate_url(&mut self) -> (url::Url, crate::types::CsrfToken) {
let csrf = crate::types::CsrfToken::new_random();
self.csrf = Some(csrf.clone());
let mut url = crate::AUTH_URL.clone();
let auth = vec![
("response_type", "code"),
("client_id", self.client_id.as_str()),
("redirect_uri", self.redirect_url.as_str()),
("state", csrf.as_str()),
];
url.query_pairs_mut().extend_pairs(auth);
if !self.scopes.is_empty() {
url.query_pairs_mut()
.append_pair("scope", &self.scopes.as_slice().join(" "));
}
if self.force_verify {
url.query_pairs_mut().append_pair("force_verify", "true");
};
(url, csrf)
}
/// Set the CSRF token.
///
/// Hidden because you should preferably not use this.
#[doc(hidden)]
pub fn set_csrf(&mut self, csrf: crate::types::CsrfToken) { self.csrf = Some(csrf); }
/// Check if the CSRF is valid
pub fn csrf_is_valid(&self, csrf: &str) -> bool {
if let Some(csrf2) = &self.csrf {
csrf2.secret() == csrf
} else {
false
}
}
/// Get the request for getting a [TwitchTokenResponse](crate::id::TwitchTokenResponse), to be used in [UserToken::from_response].
///
/// # Examples
///
/// ```rust
/// use twitch_oauth2::{tokens::UserTokenBuilder, id::TwitchTokenResponse};
/// use url::Url;
/// let callback_url = Url::parse("http://localhost/twitch/register")?;
/// let mut builder = UserTokenBuilder::new("myclientid", "myclientsecret", callback_url);
/// let (url, _csrf_code) = builder.generate_url();
///
/// // Direct the user to this url.
/// // Later when your server gets a response on `callback_url` with `?code=xxxxxxx&state=xxxxxxx&scope=aa%3Aaa+bb%3Abb`
///
/// // validate the state
/// # let state_in_query = _csrf_code.secret();
/// if !builder.csrf_is_valid(state_in_query) {
/// panic!("state mismatched")
/// }
/// // and then get your token
/// # let code_in_query = _csrf_code.secret();
/// let request = builder.get_user_token_request(code_in_query);
///
/// // use your favorite http client
///
/// let response: http::Response<Vec<u8>> = client_req(request);
/// let twitch_response = TwitchTokenResponse::from_response(&response)?;
///
/// // you now have a access token, do what you want with it.
/// // You're recommended to convert it into a `UserToken` via `UserToken::from_response`
///
/// // You can validate the access_token like this
/// let validated_req = twitch_response.access_token.validate_token_request();
/// # fn client_req(_: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> { http::Response::new(
/// # r#"{"access_token":"rfx2uswqe8l4g1mkagrvg5tv0ks3","expires_in":14124,"refresh_token":"5b93chm6hdve3mycz05zfzatkfdenfspp1h1ar2xxdalen01","scope":["channel:moderate","chat:edit","chat:read"],"token_type":"bearer"}"#.bytes().collect()
/// # ) }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn get_user_token_request(&self, code: &str) -> http::Request<Vec<u8>> {
use http::{HeaderMap, Method};
use std::collections::HashMap;
let mut params = HashMap::new();
params.insert("client_id", self.client_id.as_str());
params.insert("client_secret", self.client_secret.secret());
params.insert("code", code);
params.insert("grant_type", "authorization_code");
params.insert("redirect_uri", self.redirect_url.as_str());
crate::construct_request(
&crate::TOKEN_URL,
¶ms,
HeaderMap::new(),
Method::POST,
vec![],
)
}
/// Generate the code with the help of the authorization code
///
/// Step 3. and 4. in the [guide](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow)
///
/// On failure to authenticate due to wrong redirect url or other errors, twitch redirects the user to `<redirect_url or first defined url in dev console>?error=<error type>&error_description=<description of error>`
#[cfg(feature = "client")]
pub async fn get_user_token<'a, C>(
self,
http_client: &'a C,
state: &str,
// TODO: Should be either str or AuthorizationCode
code: &str,
) -> Result<UserToken, UserTokenExchangeError<<C as Client<'a>>::Error>>
where
C: Client<'a>,
{
if !self.csrf_is_valid(state) {
return Err(UserTokenExchangeError::StateMismatch);
}
let req = self.get_user_token_request(code);
let resp = http_client
.req(req)
.await
.map_err(UserTokenExchangeError::RequestError)?;
let response = crate::id::TwitchTokenResponse::from_response(&resp)?;
let validated = response.access_token.validate_token(http_client).await?;
UserToken::from_response(response, validated, self.client_secret)
.map_err(|v| v.into_other().into())
}
}
/// Builder for [OAuth implicit code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-implicit-code-flow)
///
/// See [`UserTokenBuilder`] for the [OAuth authorization code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow) (requires Client Secret, generally more secure)
pub struct ImplicitUserTokenBuilder {
pub(crate) scopes: Vec<Scope>,
pub(crate) csrf: Option<crate::types::CsrfToken>,
pub(crate) redirect_url: url::Url,
pub(crate) force_verify: bool,
client_id: ClientId,
}
impl ImplicitUserTokenBuilder {
/// Create a [`ImplicitUserTokenBuilder`]
///
/// # Notes
///
/// The `url` crate converts empty paths into "/" (such as `https://example.com` into `https://example.com/`),
/// which means that you'll need to add `https://example.com/` to your redirect URIs (note the "trailing" slash) if you want to use an empty path.
///
/// To avoid this, use a path such as `https://example.com/twitch/register` or similar instead, where the `url` crate would not add a trailing `/`.
pub fn new(client_id: ClientId, redirect_url: url::Url) -> ImplicitUserTokenBuilder {
ImplicitUserTokenBuilder {
scopes: vec![],
redirect_url,
csrf: None,
force_verify: false,
client_id,
}
}
/// Add scopes to the request
pub fn set_scopes(mut self, scopes: Vec<Scope>) -> Self {
self.scopes = scopes;
self
}
/// Add a single scope to request
pub fn add_scope(&mut self, scope: Scope) { self.scopes.push(scope); }
/// Enable or disable function to make the user able to switch accounts if needed.
pub fn force_verify(mut self, b: bool) -> Self {
self.force_verify = b;
self
}
/// Generate the URL to request a token.
///
/// Step 1. in the [guide](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#auth-implicit-code-flow)
pub fn generate_url(&mut self) -> (url::Url, crate::types::CsrfToken) {
let csrf = crate::types::CsrfToken::new_random();
self.csrf = Some(csrf.clone());
let mut url = crate::AUTH_URL.clone();
let auth = vec![
("response_type", "token"),
("client_id", self.client_id.as_str()),
("redirect_uri", self.redirect_url.as_str()),
("state", csrf.as_str()),
];
url.query_pairs_mut().extend_pairs(auth);
if !self.scopes.is_empty() {
url.query_pairs_mut()
.append_pair("scope", &self.scopes.as_slice().join(" "));
}
if self.force_verify {
url.query_pairs_mut().append_pair("force_verify", "true");
};
(url, csrf)
}
Trait Implementations§
source§impl AsRef<ClientIdRef> for ClientId
impl AsRef<ClientIdRef> for ClientId
source§fn as_ref(&self) -> &ClientIdRef
fn as_ref(&self) -> &ClientIdRef
Converts this type into a shared reference of the (usually inferred) input type.
source§impl Borrow<ClientIdRef> for ClientId
impl Borrow<ClientIdRef> for ClientId
source§fn borrow(&self) -> &ClientIdRef
fn borrow(&self) -> &ClientIdRef
Immutably borrows from an owned value. Read more
source§impl<'de> Deserialize<'de> for ClientId
impl<'de> Deserialize<'de> for ClientId
source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Deserialize this value from the given Serde deserializer. Read more
source§impl From<&ClientIdRef> for ClientId
impl From<&ClientIdRef> for ClientId
source§fn from(s: &ClientIdRef) -> Self
fn from(s: &ClientIdRef) -> Self
Converts to this type from the input type.
source§impl From<Box<ClientIdRef, Global>> for ClientId
impl From<Box<ClientIdRef, Global>> for ClientId
source§fn from(r: Box<ClientIdRef>) -> Self
fn from(r: Box<ClientIdRef>) -> Self
Converts to this type from the input type.
source§impl<'a> From<Cow<'a, ClientIdRef>> for ClientId
impl<'a> From<Cow<'a, ClientIdRef>> for ClientId
source§fn from(r: Cow<'a, ClientIdRef>) -> Self
fn from(r: Cow<'a, ClientIdRef>) -> Self
Converts to this type from the input type.
source§impl Ord for ClientId
impl Ord for ClientId
source§impl PartialEq<&ClientIdRef> for ClientId
impl PartialEq<&ClientIdRef> for ClientId
source§fn eq(&self, other: &&ClientIdRef) -> bool
fn eq(&self, other: &&ClientIdRef) -> bool
source§impl PartialEq<ClientIdRef> for ClientId
impl PartialEq<ClientIdRef> for ClientId
source§fn eq(&self, other: &ClientIdRef) -> bool
fn eq(&self, other: &ClientIdRef) -> bool
source§impl PartialOrd<ClientId> for ClientId
impl PartialOrd<ClientId> for ClientId
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read moreimpl Eq for ClientId
impl StructuralEq for ClientId
impl StructuralPartialEq for ClientId
Auto Trait Implementations§
impl RefUnwindSafe for ClientId
impl Send for ClientId
impl Sync for ClientId
impl Unpin for ClientId
impl UnwindSafe for ClientId
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key
and return true
if they are equal.