Struct twitch_oauth2::types::ClientSecret
source · #[repr(transparent)]pub struct ClientSecret(_);
Expand description
A Client Secret
Implementations§
source§impl ClientSecret
impl ClientSecret
sourcepub fn from_static(raw: &'static str) -> Self
pub fn from_static(raw: &'static str) -> Self
Constructs a new ClientSecret from a static reference
sourcepub fn into_boxed_ref(self) -> Box<ClientSecretRef>
pub fn into_boxed_ref(self) -> Box<ClientSecretRef>
Converts this ClientSecret
into a Box<ClientSecretRef>
This will drop any excess capacity.
Methods from Deref<Target = ClientSecretRef>§
sourcepub fn secret(&self) -> &str
pub fn secret(&self) -> &str
Get the secret from this string.
This function is the same as ClientSecret::as_str
, but has another name for searchability, prefer to use this function.
Examples found in repository?
src/lib.rs (line 221)
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
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 196)
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 193)
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
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![],
)
}
Trait Implementations§
source§impl AsRef<ClientSecretRef> for ClientSecret
impl AsRef<ClientSecretRef> for ClientSecret
source§fn as_ref(&self) -> &ClientSecretRef
fn as_ref(&self) -> &ClientSecretRef
Converts this type into a shared reference of the (usually inferred) input type.
source§impl AsRef<str> for ClientSecret
impl AsRef<str> for ClientSecret
source§impl Borrow<ClientSecretRef> for ClientSecret
impl Borrow<ClientSecretRef> for ClientSecret
source§fn borrow(&self) -> &ClientSecretRef
fn borrow(&self) -> &ClientSecretRef
Immutably borrows from an owned value. Read more
source§impl Borrow<str> for ClientSecret
impl Borrow<str> for ClientSecret
source§impl Clone for ClientSecret
impl Clone for ClientSecret
source§fn clone(&self) -> ClientSecret
fn clone(&self) -> ClientSecret
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl Debug for ClientSecret
impl Debug for ClientSecret
source§impl Deref for ClientSecret
impl Deref for ClientSecret
source§impl<'de> Deserialize<'de> for ClientSecret
impl<'de> Deserialize<'de> for ClientSecret
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 Display for ClientSecret
impl Display for ClientSecret
source§impl From<&ClientSecretRef> for ClientSecret
impl From<&ClientSecretRef> for ClientSecret
source§fn from(s: &ClientSecretRef) -> Self
fn from(s: &ClientSecretRef) -> Self
Converts to this type from the input type.
source§impl From<&str> for ClientSecret
impl From<&str> for ClientSecret
source§impl From<Box<ClientSecretRef, Global>> for ClientSecret
impl From<Box<ClientSecretRef, Global>> for ClientSecret
source§fn from(r: Box<ClientSecretRef>) -> Self
fn from(r: Box<ClientSecretRef>) -> Self
Converts to this type from the input type.
source§impl From<ClientSecret> for Box<ClientSecretRef>
impl From<ClientSecret> for Box<ClientSecretRef>
source§fn from(r: ClientSecret) -> Self
fn from(r: ClientSecret) -> Self
Converts to this type from the input type.
source§impl<'a> From<ClientSecret> for Cow<'a, ClientSecretRef>
impl<'a> From<ClientSecret> for Cow<'a, ClientSecretRef>
source§fn from(owned: ClientSecret) -> Self
fn from(owned: ClientSecret) -> Self
Converts to this type from the input type.
source§impl From<ClientSecret> for String
impl From<ClientSecret> for String
source§fn from(s: ClientSecret) -> Self
fn from(s: ClientSecret) -> Self
Converts to this type from the input type.
source§impl<'a> From<Cow<'a, ClientSecretRef>> for ClientSecret
impl<'a> From<Cow<'a, ClientSecretRef>> for ClientSecret
source§fn from(r: Cow<'a, ClientSecretRef>) -> Self
fn from(r: Cow<'a, ClientSecretRef>) -> Self
Converts to this type from the input type.
source§impl From<String> for ClientSecret
impl From<String> for ClientSecret
source§impl FromStr for ClientSecret
impl FromStr for ClientSecret
source§impl Hash for ClientSecret
impl Hash for ClientSecret
source§impl Ord for ClientSecret
impl Ord for ClientSecret
source§impl PartialEq<&ClientSecretRef> for ClientSecret
impl PartialEq<&ClientSecretRef> for ClientSecret
source§fn eq(&self, other: &&ClientSecretRef) -> bool
fn eq(&self, other: &&ClientSecretRef) -> bool
source§impl PartialEq<ClientSecret> for &ClientSecretRef
impl PartialEq<ClientSecret> for &ClientSecretRef
source§fn eq(&self, other: &ClientSecret) -> bool
fn eq(&self, other: &ClientSecret) -> bool
source§impl PartialEq<ClientSecret> for ClientSecret
impl PartialEq<ClientSecret> for ClientSecret
source§fn eq(&self, other: &ClientSecret) -> bool
fn eq(&self, other: &ClientSecret) -> bool
source§impl PartialEq<ClientSecret> for ClientSecretRef
impl PartialEq<ClientSecret> for ClientSecretRef
source§fn eq(&self, other: &ClientSecret) -> bool
fn eq(&self, other: &ClientSecret) -> bool
source§impl PartialEq<ClientSecretRef> for ClientSecret
impl PartialEq<ClientSecretRef> for ClientSecret
source§fn eq(&self, other: &ClientSecretRef) -> bool
fn eq(&self, other: &ClientSecretRef) -> bool
source§impl PartialOrd<ClientSecret> for ClientSecret
impl PartialOrd<ClientSecret> for ClientSecret
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 moresource§impl Serialize for ClientSecret
impl Serialize for ClientSecret
impl Eq for ClientSecret
impl StructuralEq for ClientSecret
impl StructuralPartialEq for ClientSecret
Auto Trait Implementations§
impl RefUnwindSafe for ClientSecret
impl Send for ClientSecret
impl Sync for ClientSecret
impl Unpin for ClientSecret
impl UnwindSafe for ClientSecret
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.