Skip to content

Add refresh ability to user tokens, and expose tokens for storage #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/user_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ async fn main() {
.ok()
.or_else(|| args.next())
.map(twitch_oauth2::RefreshToken::new),
std::env::var("TWITCH_CLIENT_SECRET")
.ok()
.or_else(|| args.next())
.map(twitch_oauth2::ClientSecret::new),
)
.await
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! # let reqwest_http_client = twitch_oauth2::dummy_http_client; // This is only here to fool doc tests
//! let token = AccessToken::new("sometokenherewhichisvalidornot".to_string());
//!
//! match UserToken::from_existing(reqwest_http_client, token, None).await {
//! match UserToken::from_existing(reqwest_http_client, token, None, None).await {
//! Ok(t) => println!("user_token: {}", t.token().secret()),
//! Err(e) => panic!("got error: {}", e),
//! }
Expand Down
293 changes: 146 additions & 147 deletions src/tokens/app_access_token.rs
Original file line number Diff line number Diff line change
@@ -1,147 +1,146 @@
use super::errors::{TokenError, ValidationError};
use crate::{
id::TwitchClient,
tokens::{errors::RefreshTokenError, Scope, TwitchToken},
};
use oauth2::{AccessToken, AuthUrl, ClientId, ClientSecret, RefreshToken, TokenResponse};
use oauth2::{HttpRequest, HttpResponse};
use std::future::Future;

/// An App Access Token from the [OAuth client credentials flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow)
#[derive(Debug, Clone)]
pub struct AppAccessToken {
access_token: AccessToken,
refresh_token: Option<RefreshToken>,
expires: Option<std::time::Instant>,
client_id: ClientId,
client_secret: ClientSecret,
login: Option<String>,
scopes: Option<Vec<Scope>>,
}

#[async_trait::async_trait(?Send)]
impl TwitchToken for AppAccessToken {
fn client_id(&self) -> &ClientId { &self.client_id }

fn token(&self) -> &AccessToken { &self.access_token }

fn login(&self) -> Option<&str> { self.login.as_deref() }

async fn refresh_token<RE, C, F>(
&mut self,
http_client: C,
) -> Result<(), RefreshTokenError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: FnOnce(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let (access_token, expires, refresh_token) = if let Some(token) = self.refresh_token.take()
{
crate::refresh_token(http_client, token, &self.client_id, &self.client_secret).await?
} else {
return Err(RefreshTokenError::NoRefreshToken);
};
self.access_token = access_token;
self.expires = expires;
self.refresh_token = refresh_token;
Ok(())
}

fn expires(&self) -> Option<std::time::Instant> { self.expires }

fn scopes(&self) -> Option<&[Scope]> { self.scopes.as_deref() }
}

impl AppAccessToken {
/// Assemble token without checks.
pub fn from_existing_unchecked(
access_token: AccessToken,
client_id: impl Into<ClientId>,
client_secret: impl Into<ClientSecret>,
login: Option<String>,
scopes: Option<Vec<Scope>>,
) -> AppAccessToken
{
AppAccessToken {
access_token,
refresh_token: None,
client_id: client_id.into(),
client_secret: client_secret.into(),
login,
expires: None,
scopes,
}
}

/// Assemble token and validate it. Retrieves [`client_id`](TwitchToken::client_id) and [`scopes`](TwitchToken::scopes).
pub async fn from_existing<RE, C, F>(
http_client: C,
access_token: AccessToken,
client_secret: ClientSecret,
) -> Result<AppAccessToken, ValidationError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: FnOnce(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let token = access_token;
let validated = crate::validate_token(http_client, &token).await?;
Ok(Self::from_existing_unchecked(
token,
validated.client_id,
client_secret,
None,
validated.scopes,
))
}

/// Generate app access token via [OAuth client credentials flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow)
pub async fn get_app_access_token<RE, C, F>(
http_client: C,
client_id: ClientId,
client_secret: ClientSecret,
scopes: Vec<Scope>,
) -> Result<AppAccessToken, TokenError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: Fn(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let now = std::time::Instant::now();
let client = TwitchClient::new(
client_id.clone(),
Some(client_secret.clone()),
AuthUrl::new("https://id.twitch.tv/oauth2/authorize".to_owned())
.expect("unexpected failure to parse auth url for app_access_token"),
Some(oauth2::TokenUrl::new(
"https://id.twitch.tv/oauth2/token".to_string(),
)?),
);
let client = client.set_auth_type(oauth2::AuthType::RequestBody);
let mut client = client.exchange_client_credentials();
for scope in scopes {
client = client.add_scope(scope.as_oauth_scope());
}
let response = client
.request_async(&http_client)
.await
.map_err(TokenError::Request)?;

let app_access = AppAccessToken {
access_token: response.access_token().clone(),
refresh_token: response.refresh_token().cloned(),
expires: response.expires_in().map(|dur| now + dur),
client_id,
client_secret,
login: None,
scopes: response
.scopes()
.cloned()
.map(|s| s.into_iter().map(|s| s.into()).collect()),
};

let _ = app_access.validate_token(http_client).await?; // Sanity check
Ok(app_access)
}
}
use super::errors::{TokenError, ValidationError};
use crate::{
id::TwitchClient,
tokens::{errors::RefreshTokenError, Scope, TwitchToken},
};
use oauth2::{AccessToken, AuthUrl, ClientId, ClientSecret, RefreshToken, TokenResponse};
use oauth2::{HttpRequest, HttpResponse};
use std::future::Future;

/// An App Access Token from the [OAuth client credentials flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow)
#[derive(Debug, Clone)]
pub struct AppAccessToken {
access_token: AccessToken,
refresh_token: Option<RefreshToken>,
expires: Option<std::time::Instant>,
client_id: ClientId,
client_secret: ClientSecret,
login: Option<String>,
scopes: Option<Vec<Scope>>,
}

#[async_trait::async_trait(?Send)]
impl TwitchToken for AppAccessToken {
fn client_id(&self) -> &ClientId { &self.client_id }

fn token(&self) -> &AccessToken { &self.access_token }

fn login(&self) -> Option<&str> { self.login.as_deref() }

async fn refresh_token<RE, C, F>(
&mut self,
http_client: C,
) -> Result<(), RefreshTokenError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: FnOnce(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let (access_token, expires, refresh_token) = if let Some(token) = self.refresh_token.take()
{
crate::refresh_token(http_client, token, &self.client_id, &self.client_secret).await?
} else {
return Err(RefreshTokenError::NoRefreshToken);
};
self.access_token = access_token;
self.expires = expires;
self.refresh_token = refresh_token;
Ok(())
}

fn expires(&self) -> Option<std::time::Instant> { self.expires }

fn scopes(&self) -> Option<&[Scope]> { self.scopes.as_deref() }
}

impl AppAccessToken {
/// Assemble token without checks.
pub fn from_existing_unchecked(
access_token: AccessToken,
client_id: impl Into<ClientId>,
client_secret: impl Into<ClientSecret>,
login: Option<String>,
scopes: Option<Vec<Scope>>,
) -> AppAccessToken {
AppAccessToken {
access_token,
refresh_token: None,
client_id: client_id.into(),
client_secret: client_secret.into(),
login,
expires: None,
scopes,
}
}

/// Assemble token and validate it. Retrieves [`client_id`](TwitchToken::client_id) and [`scopes`](TwitchToken::scopes).
pub async fn from_existing<RE, C, F>(
http_client: C,
access_token: AccessToken,
client_secret: ClientSecret,
) -> Result<AppAccessToken, ValidationError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: FnOnce(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let token = access_token;
let validated = crate::validate_token(http_client, &token).await?;
Ok(Self::from_existing_unchecked(
token,
validated.client_id,
client_secret,
None,
validated.scopes,
))
}

/// Generate app access token via [OAuth client credentials flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow)
pub async fn get_app_access_token<RE, C, F>(
http_client: C,
client_id: ClientId,
client_secret: ClientSecret,
scopes: Vec<Scope>,
) -> Result<AppAccessToken, TokenError<RE>>
where
RE: std::error::Error + Send + Sync + 'static,
C: Fn(HttpRequest) -> F,
F: Future<Output = Result<HttpResponse, RE>>,
{
let now = std::time::Instant::now();
let client = TwitchClient::new(
client_id.clone(),
Some(client_secret.clone()),
AuthUrl::new("https://id.twitch.tv/oauth2/authorize".to_owned())
.expect("unexpected failure to parse auth url for app_access_token"),
Some(oauth2::TokenUrl::new(
"https://id.twitch.tv/oauth2/token".to_string(),
)?),
);
let client = client.set_auth_type(oauth2::AuthType::RequestBody);
let mut client = client.exchange_client_credentials();
for scope in scopes {
client = client.add_scope(scope.as_oauth_scope());
}
let response = client
.request_async(&http_client)
.await
.map_err(TokenError::Request)?;

let app_access = AppAccessToken {
access_token: response.access_token().clone(),
refresh_token: response.refresh_token().cloned(),
expires: response.expires_in().map(|dur| now + dur),
client_id,
client_secret,
login: None,
scopes: response
.scopes()
.cloned()
.map(|s| s.into_iter().map(|s| s.into()).collect()),
};

let _ = app_access.validate_token(http_client).await?; // Sanity check
Ok(app_access)
}
}
Loading