summaryrefslogtreecommitdiffstats
path: root/src/registration.rs
blob: 32bac61c404cf001ae9db3f69daf40c4254005fd (plain)
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
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
use std::borrow::Cow;

use reqwest::{Client, RequestBuilder, Response};
use serde::Deserialize;
use try_from::TryInto;
use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET};

use crate::{
    apps::{App, AppBuilder},
    scopes::Scopes,
    Data,
    Error,
    Mastodon,
    MastodonBuilder,
    Result,
};

const DEFAULT_REDIRECT_URI: &str = "urn:ietf:wg:oauth:2.0:oob";

/// Handles registering your mastodon app to your instance. It is recommended
/// you cache your data struct to avoid registering on every run.
#[derive(Debug, Clone)]
pub struct Registration<'a> {
    base: String,
    client: Client,
    app_builder: AppBuilder<'a>,
    force_login: bool,
}

#[derive(Deserialize)]
struct OAuth {
    client_id: String,
    client_secret: String,
    #[serde(default = "default_redirect_uri")]
    redirect_uri: String,
}

fn default_redirect_uri() -> String {
    DEFAULT_REDIRECT_URI.to_string()
}

#[derive(Deserialize)]
struct AccessToken {
    access_token: String,
}

impl<'a> Registration<'a> {
    /// Construct a new registration process to the instance of the `base` url.
    /// ```
    /// use elefren::prelude::*;
    ///
    /// let registration = Registration::new("https://mastodon.social");
    /// ```
    pub fn new<I: Into<String>>(base: I) -> Self {
        Registration {
            base: base.into(),
            client: Client::new(),
            app_builder: AppBuilder::new(),
            force_login: false,
        }
    }
}

impl<'a> Registration<'a> {
    /// Sets the name of this app
    ///
    /// This is required, and if this isn't set then the AppBuilder::build
    /// method will fail
    pub fn client_name<I: Into<Cow<'a, str>>>(&mut self, name: I) -> &mut Self {
        self.app_builder.client_name(name.into());
        self
    }

    /// Sets the redirect uris that this app uses
    pub fn redirect_uris<I: Into<Cow<'a, str>>>(&mut self, uris: I) -> &mut Self {
        self.app_builder.redirect_uris(uris);
        self
    }

    /// Sets the scopes that this app requires
    ///
    /// The default for an app is Scopes::Read
    pub fn scopes(&mut self, scopes: Scopes) -> &mut Self {
        self.app_builder.scopes(scopes);
        self
    }

    /// Sets the optional "website" to register the app with
    pub fn website<I: Into<Cow<'a, str>>>(&mut self, website: I) -> &mut Self {
        self.app_builder.website(website);
        self
    }

    /// Forces the user to re-login (useful if you need to re-auth as a
    /// different user on the same instance
    pub fn force_login(&mut self, force_login: bool) -> &mut Self {
        self.force_login = force_login;
        self
    }

    fn send(&self, req: RequestBuilder) -> Result<Response> {
        let req = req.build()?;
        Ok(self.client.execute(req)?)
    }

    /// Register the given application
    ///
    /// ```no_run
    /// # extern crate elefren;
    /// # fn main () -> elefren::Result<()> {
    /// use elefren::{apps::App, prelude::*};
    ///
    /// let mut app = App::builder();
    /// app.client_name("elefren_test");
    ///
    /// let registration = Registration::new("https://mastodon.social").register(app)?;
    /// let url = registration.authorize_url()?;
    /// // Here you now need to open the url in the browser
    /// // And handle a the redirect url coming back with the code.
    /// let code = String::from("RETURNED_FROM_BROWSER");
    /// let mastodon = registration.complete(&code)?;
    ///
    /// println!("{:?}", mastodon.get_home_timeline()?.initial_items);
    /// # Ok(())
    /// # }
    /// ```
    pub fn register<I: TryInto<App>>(&mut self, app: I) -> Result<Registered>
    where
        Error: From<<I as TryInto<App>>::Err>,
    {
        let app = app.try_into()?;
        let oauth = self.send_app(&app)?;

        Ok(Registered {
            base: self.base.clone(),
            client: self.client.clone(),
            client_id: oauth.client_id,
            client_secret: oauth.client_secret,
            redirect: oauth.redirect_uri,
            scopes: app.scopes().clone(),
            force_login: self.force_login,
        })
    }

    /// Register the application with the server from the `base` url.
    ///
    /// ```no_run
    /// # extern crate elefren;
    /// # fn main () -> elefren::Result<()> {
    /// use elefren::prelude::*;
    ///
    /// let registration = Registration::new("https://mastodon.social")
    ///     .client_name("elefren_test")
    ///     .build()?;
    /// let url = registration.authorize_url()?;
    /// // Here you now need to open the url in the browser
    /// // And handle a the redirect url coming back with the code.
    /// let code = String::from("RETURNED_FROM_BROWSER");
    /// let mastodon = registration.complete(&code)?;
    ///
    /// println!("{:?}", mastodon.get_home_timeline()?.initial_items);
    /// # Ok(())
    /// # }
    /// ```
    pub fn build(&mut self) -> Result<Registered> {
        let app: App = self.app_builder.clone().build()?;
        let oauth = self.send_app(&app)?;

        Ok(Registered {
            base: self.base.clone(),
            client: self.client.clone(),
            client_id: oauth.client_id,
            client_secret: oauth.client_secret,
            redirect: oauth.redirect_uri,
            scopes: app.scopes().clone(),
            force_login: self.force_login,
        })
    }

    fn send_app(&self, app: &App) -> Result<OAuth> {
        let url = format!("{}/api/v1/apps", self.base);
        Ok(self.send(self.client.post(&url).json(&app))?.json()?)
    }
}

impl Registered {
    /// Skip having to retrieve the client id and secret from the server by
    /// creating a `Registered` struct directly
    ///
    /// # Example
    ///
    /// ```no_run
    /// # extern crate elefren;
    /// # fn main() -> elefren::Result<()> {
    /// use elefren::{prelude::*, registration::Registered};
    ///
    /// let registration = Registered::from_parts(
    ///     "https://example.com",
    ///     "the-client-id",
    ///     "the-client-secret",
    ///     "https://example.com/redirect",
    ///     Scopes::read_all(),
    ///     false,
    /// );
    /// let url = registration.authorize_url()?;
    /// // Here you now need to open the url in the browser
    /// // And handle a the redirect url coming back with the code.
    /// let code = String::from("RETURNED_FROM_BROWSER");
    /// let mastodon = registration.complete(&code)?;
    ///
    /// println!("{:?}", mastodon.get_home_timeline()?.initial_items);
    /// #   Ok(())
    /// # }
    /// ```
    pub fn from_parts(
        base: &str,
        client_id: &str,
        client_secret: &str,
        redirect: &str,
        scopes: Scopes,
        force_login: bool,
    ) -> Registered {
        Registered {
            base: base.to_string(),
            client: Client::new(),
            client_id: client_id.to_string(),
            client_secret: client_secret.to_string(),
            redirect: redirect.to_string(),
            scopes,
            force_login,
        }
    }
}

impl Registered {
    fn send(&self, req: RequestBuilder) -> Result<Response> {
        let req = req.build()?;
        Ok(self.client.execute(req)?)
    }

    /// Returns the parts of the `Registered` struct that can be used to
    /// recreate another `Registered` struct
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate elefren;
    /// use elefren::{prelude::*, registration::Registered};
    /// # fn main() -> Result<(), Box<std::error::Error>> {
    ///
    /// let origbase = "https://example.social";
    /// let origclient_id = "some-client_id";
    /// let origclient_secret = "some-client-secret";
    /// let origredirect = "https://example.social/redirect";
    /// let origscopes = Scopes::all();
    /// let origforce_login = false;
    ///
    /// let registered = Registered::from_parts(
    ///     origbase,
    ///     origclient_id,
    ///     origclient_secret,
    ///     origredirect,
    ///     origscopes.clone(),
    ///     origforce_login,
    /// );
    ///
    /// let (base, client_id, client_secret, redirect, scopes, force_login) = registered.into_parts();
    ///
    /// assert_eq!(origbase, &base);
    /// assert_eq!(origclient_id, &client_id);
    /// assert_eq!(origclient_secret, &client_secret);
    /// assert_eq!(origredirect, &redirect);
    /// assert_eq!(origscopes, scopes);
    /// assert_eq!(origforce_login, force_login);
    /// #   Ok(())
    /// # }
    /// ```
    pub fn into_parts(self) -> (String, String, String, String, Scopes, bool) {
        (
            self.base,
            self.client_id,
            self.client_secret,
            self.redirect,
            self.scopes,
            self.force_login,
        )
    }

    /// Returns the full url needed for authorisation. This needs to be opened
    /// in a browser.
    pub fn authorize_url(&self) -> Result<String> {
        let scopes = format!("{}", self.scopes);
        let scopes: String = utf8_percent_encode(&scopes, DEFAULT_ENCODE_SET).collect();
        let url = if self.force_login {
            format!(
                "{}/oauth/authorize?client_id={}&redirect_uri={}&scope={}&force_login=true&\
                 response_type=code",
                self.base, self.client_id, self.redirect, scopes,
            )
        } else {
            format!(
                "{}/oauth/authorize?client_id={}&redirect_uri={}&scope={}&response_type=code",
                self.base, self.client_id, self.redirect, scopes,
            )
        };

        Ok(url)
    }

    /// Create an access token from the client id, client secret, and code
    /// provided by the authorisation url.
    pub fn complete(&self, code: &str) -> Result<Mastodon> {