1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
233
234
235
236
237
238
239
240
241
242
243
use std::borrow::Cow;
use std::fmt;

use rocket::figment::{self, Error, Figment};

/// Holds configuration for an OAuth application. This consists of the [Provider]
/// details, a `client_id` and `client_secret`, and an optional `redirect_uri`.
pub struct OAuthConfig {
    provider: Box<dyn Provider>,
    client_id: String,
    client_secret: String,
    redirect_uri: Option<String>,
}

impl OAuthConfig {
    /// Construct an OAuthConfig specifying all parameters manually.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket_oauth2::{OAuthConfig, StaticProvider};
    ///
    /// let provider = StaticProvider::GitHub;
    /// let client_id = "...".to_string();
    /// let client_secret = "...".to_string();
    /// let redirect_uri = Some("http://localhost:8000/auth/github".to_string());
    ///
    /// let config = OAuthConfig::new(provider, client_id, client_secret, redirect_uri);
    /// ```
    pub fn new(
        provider: impl Provider,
        client_id: String,
        client_secret: String,
        redirect_uri: Option<String>,
    ) -> OAuthConfig {
        OAuthConfig {
            provider: Box::new(provider),
            client_id,
            client_secret,
            redirect_uri,
        }
    }

    /// Construct an OAuthConfig from Rocket configuration.
    ///
    /// # Example
    ///
    /// ## Rocket.toml
    ///
    /// ```toml
    /// [default.oauth.github]
    /// provider = "GitHub"
    /// client_id = "..."
    /// client_secret = "..."
    /// redirect_uri = "http://localhost:8000/auth/github"
    /// ```
    ///
    /// ## main.rs
    /// ```rust,no_run
    /// use rocket::fairing::AdHoc;
    /// use rocket_oauth2::{HyperRustlsAdapter, OAuth2, OAuthConfig};
    ///
    /// struct GitHub;
    ///
    /// #[rocket::launch]
    /// fn rocket() -> _ {
    ///     rocket::build()
    ///         .attach(AdHoc::on_ignite("OAuth Config", |mut rocket| async {
    ///             let config = OAuthConfig::from_figment(rocket.figment(), "github").unwrap();
    ///             rocket.attach(OAuth2::<GitHub>::custom(HyperRustlsAdapter::default(), config))
    ///         }))
    /// }
    /// ```
    pub fn from_figment(figment: &Figment, name: &str) -> Result<Self, Error> {
        #[derive(serde::Deserialize)]
        struct Config {
            provider: Option<String>,
            auth_uri: Option<String>,
            token_uri: Option<String>,
            client_id: String,
            client_secret: String,
            redirect_uri: Option<String>,
        }

        let conf: Config = figment.extract_inner(&format!("oauth.{}", name))?;

        let provider = match (conf.provider, conf.auth_uri, conf.token_uri) {
            (Some(provider_name), None, None) => StaticProvider::from_known_name(&provider_name)
                .ok_or_else(|| {
                    figment::error::Kind::InvalidValue(
                        figment::error::Actual::Str(provider_name),
                        "one of the predefined 'provider' names".into(),
                    )
                })?,
            (None, Some(auth_uri), Some(token_uri)) => StaticProvider {
                auth_uri: auth_uri.into(),
                token_uri: token_uri.into(),
            },
            _ => {
                return Err("either 'provider' or 'auth_uri'+'token_uri' should be specified, but not both".to_string().into());
            }
        };

        Ok(OAuthConfig::new(
            provider,
            conf.client_id,
            conf.client_secret,
            conf.redirect_uri,
        ))
    }

    /// Get the [`Provider`] for this configuration.
    pub fn provider(&self) -> &dyn Provider {
        &*self.provider
    }

    /// Get the client id for this configuration.
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// Get the client secret for this configuration.
    pub fn client_secret(&self) -> &str {
        &self.client_secret
    }

    /// Get the redirect URI for this configuration.
    pub fn redirect_uri(&self) -> Option<&str> {
        self.redirect_uri.as_deref()
    }
}

impl fmt::Debug for OAuthConfig {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("OAuthConfig")
            .field("provider", &(..))
            .field("client_id", &self.client_id)
            .field("client_secret", &self.client_secret)
            .field("redirect_uri", &self.redirect_uri)
            .finish()
    }
}

/// A `Provider` can retrieve authorization and token exchange URIs specific to
/// an OAuth service provider.
///
/// In most cases, [`StaticProvider`] should be used instead of implementing
/// `Provider` manually. `Provider` should be implemented if the URIs will
/// change during runtime.
pub trait Provider: Send + Sync + 'static {
    /// Returns the authorization URI associated with the service provider.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket_oauth2::{Provider, StaticProvider};
    ///
    /// assert_eq!(StaticProvider::GitHub.auth_uri(), "https://github.com/login/oauth/authorize");
    /// ```
    fn auth_uri(&self) -> Cow<'_, str>;
    /// Returns the token exchange URI associated with the service provider.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket_oauth2::{Provider, StaticProvider};
    ///
    /// assert_eq!(StaticProvider::GitHub.token_uri(), "https://github.com/login/oauth/access_token");
    /// ```
    fn token_uri(&self) -> Cow<'_, str>;
}

/// A `StaticProvider` contains authorization and token exchange URIs known in
/// advance, either at compile-time or early in initialization.
///
/// If the URIs will change during runtime, implement [`Provider`] for your own
/// type instead.
///
/// # Example
///
/// ```rust
/// use rocket_oauth2::StaticProvider;
///
/// let provider = StaticProvider {
///     auth_uri: "https://example.com/oauth2/authorize".into(),
///     token_uri: "https://example.com/oauth2/token".into(),
/// };
/// ```
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct StaticProvider {
    /// The authorization URI associated with the service provider.
    pub auth_uri: Cow<'static, str>,
    /// The token exchange URI associated with the service provider.
    pub token_uri: Cow<'static, str>,
}

impl Provider for StaticProvider {
    fn auth_uri(&self) -> Cow<'_, str> {
        Cow::Borrowed(&*self.auth_uri)
    }

    fn token_uri(&self) -> Cow<'_, str> {
        Cow::Borrowed(&*self.token_uri)
    }
}

macro_rules! providers {
    (@ $(($name:ident $docstr:expr) : $auth:expr, $token:expr),*) => {
        impl StaticProvider {
            $(
                #[doc = $docstr]
                #[allow(non_upper_case_globals)]
                pub const $name: StaticProvider = StaticProvider {
                    auth_uri: Cow::Borrowed($auth),
                    token_uri: Cow::Borrowed($token),
                };
            )*

            pub(crate) fn from_known_name(name: &str) -> Option<StaticProvider> {
                $(
                    if name.eq_ignore_ascii_case(stringify!($name)) {
                        return Some(StaticProvider::$name);
                    }
                )*
                None
            }
        }
    };
    ($($name:ident : $auth:expr, $token:expr),* $(,)*) => {
        providers!(@ $(($name concat!("A `Provider` suitable for authorizing users with ", stringify!($name), ".")) : $auth, $token),*);
    };
}

providers! {
    Discord: "https://discord.com/oauth2/authorize", "https://discord.com/api/oauth2/token",
    Facebook: "https://www.facebook.com/v3.1/dialog/oauth", "https://graph.facebook.com/v3.1/oauth/access_token",
    GitHub: "https://github.com/login/oauth/authorize", "https://github.com/login/oauth/access_token",
    Google: "https://accounts.google.com/o/oauth2/v2/auth", "https://www.googleapis.com/oauth2/v4/token",
    Microsoft: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "https://login.microsoftonline.com/common/oauth2/v2.0/token",
    Reddit: "https://www.reddit.com/api/v1/authorize", "https://www.reddit.com/api/v1/access_token",
    Wikimedia: "https://meta.wikimedia.org/w/rest.php/oauth2/authorize", "https://meta.wikimedia.org/w/rest.php/oauth2/access_token",
    Yahoo: "https://api.login.yahoo.com/oauth2/request_auth", "https://api.login.yahoo.com/oauth2/get_token",
}