|
| 1 | +use super::Authorization; |
| 2 | +use crate::error::{Error, Result}; |
| 3 | +use oauth2::basic::{BasicClient, BasicRequestTokenError}; |
| 4 | +use oauth2::{ |
| 5 | + AccessToken, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, |
| 6 | + PkceCodeVerifier, RedirectUrl, RefreshToken, RevocationUrl, TokenResponse, TokenUrl, |
| 7 | +}; |
| 8 | +use std::time::SystemTime; |
| 9 | +use strum::{Display, EnumString}; |
| 10 | +use url::Url; |
| 11 | + |
| 12 | +#[derive(Copy, Clone, Debug, EnumString, Display)] |
| 13 | +#[strum(serialize_all = "snake_case")] |
| 14 | +pub enum Scope { |
| 15 | + #[strum(serialize = "tweet.read")] |
| 16 | + TweetRead, |
| 17 | + #[strum(serialize = "tweet.write")] |
| 18 | + TweetWrite, |
| 19 | + #[strum(serialize = "tweet.moderate.write")] |
| 20 | + TweetModerateWrite, |
| 21 | + #[strum(serialize = "users.read")] |
| 22 | + UsersRead, |
| 23 | + #[strum(serialize = "follows.read")] |
| 24 | + FollowsRead, |
| 25 | + #[strum(serialize = "follows.write")] |
| 26 | + FollowsWrite, |
| 27 | + #[strum(serialize = "offline.access")] |
| 28 | + OfflineAccess, |
| 29 | + #[strum(serialize = "space.read")] |
| 30 | + SpaceRead, |
| 31 | + #[strum(serialize = "mute.read")] |
| 32 | + MuteRead, |
| 33 | + #[strum(serialize = "mute.write")] |
| 34 | + MuteWrite, |
| 35 | + #[strum(serialize = "like.read")] |
| 36 | + LikeRead, |
| 37 | + #[strum(serialize = "like.write")] |
| 38 | + LikeWrite, |
| 39 | + #[strum(serialize = "list.read")] |
| 40 | + ListRead, |
| 41 | + #[strum(serialize = "list.write")] |
| 42 | + ListWrite, |
| 43 | + #[strum(serialize = "block.read")] |
| 44 | + BlockRead, |
| 45 | + #[strum(serialize = "block.write")] |
| 46 | + BlockWrite, |
| 47 | +} |
| 48 | + |
| 49 | +impl From<Scope> for oauth2::Scope { |
| 50 | + fn from(scope: Scope) -> Self { |
| 51 | + oauth2::Scope::new(scope.to_string()) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[derive(Clone, Debug)] |
| 56 | +pub struct Oauth2Client(BasicClient); |
| 57 | + |
| 58 | +impl Oauth2Client { |
| 59 | + pub fn new(client_id: impl ToString, client_secret: impl ToString, callback_url: Url) -> Self { |
| 60 | + Self( |
| 61 | + BasicClient::new( |
| 62 | + ClientId::new(client_id.to_string()), |
| 63 | + Some(ClientSecret::new(client_secret.to_string())), |
| 64 | + AuthUrl::from_url("https://twitter.com/i/oauth2/authorize".parse().unwrap()), |
| 65 | + Some(TokenUrl::from_url( |
| 66 | + "https://api.twitter.com/2/oauth2/token".parse().unwrap(), |
| 67 | + )), |
| 68 | + ) |
| 69 | + .set_revocation_uri(RevocationUrl::from_url( |
| 70 | + "https://api.twitter.com/2/oauth2/revoke".parse().unwrap(), |
| 71 | + )) |
| 72 | + .set_redirect_uri(RedirectUrl::from_url(callback_url)), |
| 73 | + ) |
| 74 | + } |
| 75 | + |
| 76 | + pub fn auth_url( |
| 77 | + &self, |
| 78 | + challenge: PkceCodeChallenge, |
| 79 | + scopes: impl IntoIterator<Item = Scope>, |
| 80 | + ) -> (Url, CsrfToken) { |
| 81 | + self.0 |
| 82 | + .authorize_url(CsrfToken::new_random) |
| 83 | + .set_pkce_challenge(challenge) |
| 84 | + .add_scopes(scopes.into_iter().map(|s| s.into())) |
| 85 | + .url() |
| 86 | + } |
| 87 | + |
| 88 | + pub async fn request_token( |
| 89 | + &self, |
| 90 | + code: AuthorizationCode, |
| 91 | + verifier: PkceCodeVerifier, |
| 92 | + ) -> Result<Oauth2Token> { |
| 93 | + let res = self |
| 94 | + .0 |
| 95 | + .exchange_code(code) |
| 96 | + .set_pkce_verifier(verifier) |
| 97 | + .request_async(oauth2::reqwest::async_http_client) |
| 98 | + .await |
| 99 | + .map_err(|err| { |
| 100 | + println!("{:?}", err); |
| 101 | + Error::from(err) |
| 102 | + })?; |
| 103 | + Ok(Oauth2Token { |
| 104 | + oauth_client: self.clone(), |
| 105 | + access_token: res.access_token().clone(), |
| 106 | + refresh_token: res.refresh_token().cloned(), |
| 107 | + expires: SystemTime::now() |
| 108 | + + res.expires_in().ok_or_else(|| { |
| 109 | + Error::Oauth2TokenError(BasicRequestTokenError::Other( |
| 110 | + "Missing expiration".to_string(), |
| 111 | + )) |
| 112 | + })?, |
| 113 | + scopes: res |
| 114 | + .scopes() |
| 115 | + .ok_or_else(|| { |
| 116 | + Error::Oauth2TokenError(BasicRequestTokenError::Other( |
| 117 | + "Missing scopes".to_string(), |
| 118 | + )) |
| 119 | + })? |
| 120 | + .iter() |
| 121 | + .map(|s| { |
| 122 | + s.parse().map_err(|err| { |
| 123 | + Error::Oauth2TokenError(BasicRequestTokenError::Other(format!( |
| 124 | + "Invalid scope: {}", |
| 125 | + err |
| 126 | + ))) |
| 127 | + }) |
| 128 | + }) |
| 129 | + .collect::<Result<Vec<_>>>()?, |
| 130 | + }) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +#[derive(Clone, Debug)] |
| 135 | +pub struct Oauth2Token { |
| 136 | + oauth_client: Oauth2Client, |
| 137 | + access_token: AccessToken, |
| 138 | + refresh_token: Option<RefreshToken>, |
| 139 | + expires: SystemTime, |
| 140 | + scopes: Vec<Scope>, |
| 141 | +} |
| 142 | + |
| 143 | +impl Oauth2Token { |
| 144 | + pub fn access_token(&self) -> &AccessToken { |
| 145 | + &self.access_token |
| 146 | + } |
| 147 | + pub fn refresh_token(&self) -> Option<&RefreshToken> { |
| 148 | + self.refresh_token.as_ref() |
| 149 | + } |
| 150 | + pub fn expires(&self) -> SystemTime { |
| 151 | + self.expires |
| 152 | + } |
| 153 | + pub fn is_expired(&self) -> bool { |
| 154 | + self.expires < SystemTime::now() |
| 155 | + } |
| 156 | + pub fn scopes(&self) -> &[Scope] { |
| 157 | + &self.scopes |
| 158 | + } |
| 159 | +} |
0 commit comments