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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
#![warn(missing_docs)]
//!
//! A simple implementation of the OAuth2 flow, trying to adhere as much as possible to
//! [RFC 6749](https://tools.ietf.org/html/rfc6749).
//!
//! # Getting started: Authorization Code Grant
//!
//! This is the most common OAuth2 flow.
//!
//! ## Example
//!
//! ```
//! extern crate base64;
//! extern crate oauth2;
//! extern crate rand;
//! extern crate url;
//!
//! use oauth2::prelude::*;
//! use oauth2::{
//!     AuthorizationCode,
//!     AuthUrl,
//!     ClientId,
//!     ClientSecret,
//!     CsrfToken,
//!     RedirectUrl,
//!     Scope,
//!     TokenUrl
//! };
//! use oauth2::basic::BasicClient;
//! use url::Url;
//!
//! # fn err_wrapper() -> Result<(), Box<std::error::Error>> {
//! // Create an OAuth2 client by specifying the client ID, client secret, authorization URL and
//! // token URL.
//! let client =
//!     BasicClient::new(
//!         ClientId::new("client_id".to_string()),
//!         Some(ClientSecret::new("client_secret".to_string())),
//!         AuthUrl::new(Url::parse("http://authorize")?),
//!         Some(TokenUrl::new(Url::parse("http://token")?))
//!     )
//!         // Set the desired scopes.
//!         .add_scope(Scope::new("read".to_string()))
//!         .add_scope(Scope::new("write".to_string()))
//!
//!         // Set the URL the user will be redirected to after the authorization process.
//!         .set_redirect_url(RedirectUrl::new(Url::parse("http://redirect")?));
//!
//! // Generate the full authorization URL.
//! let (auth_url, csrf_token) = client.authorize_url(CsrfToken::new_random);
//!
//! // This is the URL you should redirect the user to, in order to trigger the authorization
//! // process.
//! println!("Browse to: {}", auth_url);
//!
//! // Once the user has been redirected to the redirect URL, you'll have access to the
//! // authorization code. For security reasons, your code should verify that the `state`
//! // parameter returned by the server matches `csrf_state`.
//!
//! // Now you can trade it for an access token.
//! let token_result =
//!     client.exchange_code(AuthorizationCode::new("some authorization code".to_string()));
//!
//! // Unwrapping token_result will either produce a Token or a RequestTokenError.
//! # Ok(())
//! # }
//! # fn main() {}
//! ```
//!
//! # Implicit Grant
//!
//! This flow fetches an access token directly from the authorization endpoint. Be sure to
//! understand the security implications of this flow before using it. In most cases, the
//! Authorization Code Grant flow is preferable to the Implicit Grant flow.
//!
//! ## Example:
//!
//! ```
//! extern crate base64;
//! extern crate oauth2;
//! extern crate rand;
//! extern crate url;
//!
//! use oauth2::prelude::*;
//! use oauth2::{
//!     AuthUrl,
//!     ClientId,
//!     ClientSecret,
//!     CsrfToken,
//!     RedirectUrl,
//!     Scope
//! };
//! use oauth2::basic::BasicClient;
//! use url::Url;
//!
//! # fn err_wrapper() -> Result<(), Box<std::error::Error>> {
//! let client =
//!     BasicClient::new(
//!         ClientId::new("client_id".to_string()),
//!         Some(ClientSecret::new("client_secret".to_string())),
//!         AuthUrl::new(Url::parse("http://authorize")?),
//!         None
//!     );
//!
//! // Generate the full authorization URL.
//! let (auth_url, csrf_token) = client.authorize_url_implicit(CsrfToken::new_random);
//!
//! // This is the URL you should redirect the user to, in order to trigger the authorization
//! // process.
//! println!("Browse to: {}", auth_url);
//!
//! // Once the user has been redirected to the redirect URL, you'll have the access code.
//! // For security reasons, your code should verify that the `state` parameter returned by the
//! // server matches `csrf_state`.
//!
//! # Ok(())
//! # }
//! # fn main() {}
//! ```
//!
//! # Resource Owner Password Credentials Grant
//!
//! You can ask for a *password* access token by calling the `Client::exchange_password` method,
//! while including the username and password.
//!
//! ## Example
//!
//! ```
//! extern crate base64;
//! extern crate oauth2;
//! extern crate rand;
//! extern crate url;
//!
//! use oauth2::prelude::*;
//! use oauth2::{
//!     AuthUrl,
//!     ClientId,
//!     ClientSecret,
//!     ResourceOwnerPassword,
//!     ResourceOwnerUsername,
//!     Scope,
//!     TokenUrl
//! };
//! use oauth2::basic::BasicClient;
//! use url::Url;
//!
//! # fn err_wrapper() -> Result<(), Box<std::error::Error>> {
//! let client =
//!     BasicClient::new(
//!         ClientId::new("client_id".to_string()),
//!         Some(ClientSecret::new("client_secret".to_string())),
//!         AuthUrl::new(Url::parse("http://authorize")?),
//!         Some(TokenUrl::new(Url::parse("http://token")?))
//!     )
//!         .add_scope(Scope::new("read".to_string()));
//!
//! let token_result =
//!     client.exchange_password(
//!         &ResourceOwnerUsername::new("user".to_string()),
//!         &ResourceOwnerPassword::new("pass".to_string())
//!     );
//! # Ok(())
//! # }
//! # fn main() {}
//! ```
//!
//! # Client Credentials Grant
//!
//! You can ask for a *client credentials* access token by calling the
//! `Client::exchange_client_credentials` method.
//!
//! ## Example:
//!
//! ```
//! extern crate oauth2;
//! extern crate url;
//!
//! use oauth2::prelude::*;
//! use oauth2::{
//!     AuthUrl,
//!     ClientId,
//!     ClientSecret,
//!     Scope,
//!     TokenUrl
//! };
//! use oauth2::basic::BasicClient;
//! use url::Url;
//!
//! # fn err_wrapper() -> Result<(), Box<std::error::Error>> {
//! let client =
//!     BasicClient::new(
//!         ClientId::new("client_id".to_string()),
//!         Some(ClientSecret::new("client_secret".to_string())),
//!         AuthUrl::new(Url::parse("http://authorize")?),
//!         Some(TokenUrl::new(Url::parse("http://token")?))
//!     )
//!         .add_scope(Scope::new("read".to_string()));
//!
//! let token_result = client.exchange_client_credentials();
//! # Ok(())
//! # }
//! # fn main() {}
//! ```
//!
//! # Other examples
//!
//! More specific implementations are available as part of the examples:
//!
//! - [Google](https://github.com/ramosbugs/oauth2-rs/blob/master/examples/google.rs)
//! - [Github](https://github.com/ramosbugs/oauth2-rs/blob/master/examples/github.rs)
//!

extern crate base64;
extern crate curl;
extern crate failure;
extern crate rand;
extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate serde_json;
extern crate sha2;
extern crate url;

use std::convert::Into;
use std::io::Read;
use std::fmt::{Debug, Display, Error as FormatterError, Formatter};
use std::marker::{Send, Sync, PhantomData};
use std::ops::Deref;
use std::time::Duration;

use curl::easy::Easy;
use failure::{Backtrace, Fail};
use rand::{thread_rng, Rng};
use serde::Serialize;
use serde::de::DeserializeOwned;
use sha2::{Digest, Sha256};
use url::Url;

use prelude::*;

const CONTENT_TYPE_JSON: &str = "application/json";

///
/// Indicates whether requests to the authorization server should use basic authentication or
/// include the parameters in the request body for requests in which either is valid.
///
/// The default AuthType is *BasicAuth*, following the recommendation of
/// [Section 2.3.1 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-2.3.1).
///
#[derive(Clone, Debug)]
pub enum AuthType {
    /// The client_id and client_secret will be included as part of the request body.
    RequestBody,
    /// The client_id and client_secret will be included using the basic auth authentication scheme.
    BasicAuth,
}

///
/// Crate prelude that should be wildcard-imported by crate users.
///
pub mod prelude {
    use std::fmt::Debug;
    use std::ops::Deref;

    ///
    /// New type to wrap a more primitive type in a more typesafe manner.
    ///
    pub trait NewType<T> : Clone + Debug + Deref + PartialEq {
        ///
        /// Create a new instance to wrap the given `val`.
        ///
        fn new(val: T) -> Self;
    }

    ///
    /// New type representing a secret value to wrap a more primitive type in a more typesafe
    /// manner.
    ///
    pub trait SecretNewType<T> : Debug {
        ///
        /// Create a new instance to wrap the given `val`.
        ///
        fn new(val: T) -> Self where Self: Sized;
        ///
        /// Get the secret contained within this type.
        ///
        /// # Security Warning
        ///
        /// Leaking this value may compromise the security of the OAuth2 flow.
        ///
        fn secret(&self) -> &T;
    }
}

macro_rules! new_type {
    // Convenience pattern without an impl.
    (
        $(#[$attr:meta])*
        $name:ident(
            $(#[$type_attr:meta])*
            $type:ty
        )
    ) => {
        new_type![
            @new_type $(#[$attr])*,
            $name(
                $(#[$type_attr])*
                $type
            ),
            concat!(
                "Create a new `",
                stringify!($name),
                "` to wrap the given `",
                stringify!($type),
                "`."
            ),
            impl {}
        ];
    };
    // Main entry point with an impl.
    (
        $(#[$attr:meta])*
        $name:ident(
            $(#[$type_attr:meta])*
            $type:ty
        )
        impl {
            $($item:tt)*
        }
    ) => {
        new_type![
            @new_type $(#[$attr])*,
            $name(
                $(#[$type_attr])*
                $type
            ),
            concat!(
                "Create a new `",
                stringify!($name),
                "` to wrap the given `",
                stringify!($type),
                "`."
            ),
            impl {
                $($item)*
            }
        ];
    };
    // Actual implementation, after stringifying the #[doc] attr.
    (
        @new_type $(#[$attr:meta])*,
        $name:ident(
            $(#[$type_attr:meta])*
            $type:ty
        ),
        $new_doc:expr,
        impl {
            $($item:tt)*
        }
    ) => {
        $(#[$attr])*
        #[derive(Clone, Debug, PartialEq)]
        pub struct $name(
            $(#[$type_attr])*
            $type
        );
        impl $name {
            $($item)*
        }
        impl NewType<$type> for $name {
            #[doc = $new_doc]
            fn new(s: $type) -> Self {
                $name(s)
            }
        }
        impl Deref for $name {
            type Target = $type;
            fn deref(&self) -> &$type {
                &self.0
            }
        }
        impl Into<$type> for $name {
            fn into(self) -> $type {
                self.0
            }
        }
    }
}

macro_rules! new_secret_type {
    (
        $(#[$attr:meta])*
        $name:ident($type:ty)
    ) => {
        new_secret_type![
            $(#[$attr])*
            $name($type)
            impl {}
        ];
    };
    (
        $(#[$attr:meta])*
        $name:ident($type:ty)
        impl {
            $($item:tt)*
        }
    ) => {
        new_secret_type![
            $(#[$attr])*,
            $name($type),
            concat!(
                "Create a new `",
                stringify!($name),
                "` to wrap the given `",
                stringify!($type),
                "`."
            ),
            concat!("Get the secret contained within this `", stringify!($name), "`."),
            impl {
                $($item)*
            }
        ];
    };
    (
        $(#[$attr:meta])*,
        $name:ident($type:ty),
        $new_doc:expr,
        $secret_doc:expr,
        impl {
            $($item:tt)*
        }
    ) => {
        $(
            #[$attr]
        )*
        #[derive(Clone, PartialEq)]
        pub struct $name($type);
        impl $name {
            $($item)*
        }
        impl SecretNewType<$type> for $name {
            #[doc = $new_doc]
            fn new(s: $type) -> Self {
                $name(s)
            }
            ///
            #[doc = $secret_doc]
            ///
            /// # Security Warning
            ///
            /// Leaking this value may compromise the security of the OAuth2 flow.
            ///
            fn secret(&self) -> &$type { &self.0 }
        }
        impl Debug for $name {
            fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
                write!(f, concat!(stringify!($name), "([redacted])"))
            }
        }
    };
}

new_type![
    ///
    /// Client identifier issued to the client during the registration process described by
    /// [Section 2.2](https://tools.ietf.org/html/rfc6749#section-2.2).
    ///
    #[derive(Deserialize, Serialize)]
    ClientId(String)
];

new_type![
    #[derive(Deserialize, Serialize)]
    ///
    /// URL of the authorization server's authorization endpoint.
    ///
    AuthUrl(
        #[serde(
            deserialize_with = "helpers::deserialize_url",
            serialize_with = "helpers::serialize_url"
        )]
        Url
    )
];
new_type![
    #[derive(Deserialize, Serialize)]
    ///
    /// URL of the authorization server's token endpoint.
    ///
    TokenUrl(
        #[serde(
            deserialize_with = "helpers::deserialize_url",
            serialize_with = "helpers::serialize_url"
        )]
        Url
    )
];
new_type![
    #[derive(Deserialize, Serialize)]
    ///
    /// URL of the client's redirection endpoint.
    ///
    RedirectUrl(
        #[serde(
            deserialize_with = "helpers::deserialize_url",
            serialize_with = "helpers::serialize_url"
        )]
        Url
    )
];
new_type![
    ///
    /// Authorization endpoint response (grant) type defined in
    /// [Section 3.1.1](https://tools.ietf.org/html/rfc6749#section-3.1.1).
    ///
    #[derive(Deserialize, Serialize)]
    ResponseType(String)
];
new_type![
    ///
    /// Resource owner's username used directly as an authorization grant to obtain an access
    /// token.
    ///
    ResourceOwnerUsername(String)
];

new_type![
    ///
    /// Access token scope, as defined by the authorization server.
    ///
    #[derive(Deserialize, Serialize)]
    Scope(String)
];
impl AsRef<str> for Scope {
    fn as_ref(&self) -> &str { self }
}
new_type![
    ///
    /// Code Challenge used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection via the
    /// `code_challenge` parameter.
    ///
    #[derive(Deserialize, Serialize)]
    PkceCodeChallengeS256(String)
];
new_type![
    ///
    /// Code Challenge Method used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection
    /// via the `code_challenge_method` parameter.
    ///
    #[derive(Deserialize, Serialize)]
    PkceCodeChallengeMethod(String)
];

new_secret_type![
    ///
    /// Client password issued to the client during the registration process described by
    /// [Section 2.2](https://tools.ietf.org/html/rfc6749#section-2.2).
    ///
    #[derive(Deserialize, Serialize)]
    ClientSecret(String)
];
new_secret_type![
    ///
    /// Value used for [CSRF]((https://tools.ietf.org/html/rfc6749#section-10.12)) protection
    /// via the `state` parameter.
    ///
    #[must_use]
    CsrfToken(String)
    impl {
        ///
        /// Generate a new random, base64-encoded 128-bit CSRF token.
        ///
        pub fn new_random() -> Self {
            CsrfToken::new_random_len(16)
        }
        ///
        /// Generate a new random, base64-encoded CSRF token of the specified length.
        ///
        /// # Arguments
        ///
        /// * `num_bytes` - Number of random bytes to generate, prior to base64-encoding.
        ///
        pub fn new_random_len(num_bytes: u32) -> Self {
            let random_bytes: Vec<u8> = (0..num_bytes).map(|_| thread_rng().gen::<u8>()).collect();
            CsrfToken::new(base64::encode(&random_bytes))
        }
    }
];
new_secret_type![
    ///
    /// Code Verifier used for [PKCE]((https://tools.ietf.org/html/rfc7636)) protection via the
    /// `code_verifier` parameter. The value must have a minimum length of 43 characters and a
    /// maximum length of 128 characters.  Each character must be ASCII alphanumeric or one of
    /// the characters "-" / "." / "_" / "~".
    ///
    #[derive(Deserialize, Serialize)]
    PkceCodeVerifierS256(String)
    impl {
        ///
        /// Generate a new random, base64-encoded code verifier.
        ///
        pub fn new_random() -> Self {
            PkceCodeVerifierS256::new_random_len(32)
        }
        ///
        /// Generate a new random, base64-encoded code verifier.
        ///
        /// # Arguments
        ///
        /// * `num_bytes` - Number of random bytes to generate, prior to base64-encoding.
        ///   The value must be in the range 32 to 96 inclusive in order to generate a verifier
        ///   with a suitable length.
        ///
        pub fn new_random_len(num_bytes: u32) -> Self {
            // The RFC specifies that the code verifier must have "a minimum length of 43
            // characters and a maximum length of 128 characters".
            // This implies 32-96 octets of random data to be base64 encoded.
            assert!(num_bytes >= 32 && num_bytes <= 96);
            let random_bytes: Vec<u8> = (0..num_bytes).map(|_| thread_rng().gen::<u8>()).collect();
            let code = base64::encode_config(&random_bytes, base64::URL_SAFE_NO_PAD);
            assert!(code.len() >=43 && code.len() <= 128);
            PkceCodeVerifierS256::new(code)
        }
        ///
        /// Return the code challenge for the code verifier.
        ///
        pub fn code_challenge(&self) -> PkceCodeChallengeS256 {
            let digest = Sha256::digest(self.secret().as_bytes());
            PkceCodeChallengeS256::new(base64::encode_config(&digest, base64::URL_SAFE_NO_PAD))
        }

        ///
        /// Return the code challenge method for this code verifier.
        ///
        pub fn code_challenge_method() -> PkceCodeChallengeMethod {
            PkceCodeChallengeMethod::new("S256".to_string())
        }

        ///
        /// Return the extension params used for authorize_url.
        ///
        pub fn authorize_url_params(&self) -> Vec<(&'static str, String)> {
            vec![
                (
                    "code_challenge_method",
                    PkceCodeVerifierS256::code_challenge_method().into(),
                ),
                ("code_challenge", self.code_challenge().into()),
            ]
        }
    }
];
new_secret_type![
    ///
    /// Authorization code returned from the authorization endpoint.
    ///
    AuthorizationCode(String)
];
new_secret_type![
    ///
    /// Refresh token used to obtain a new access token (if supported by the authorization server).
    ///
    #[derive(Deserialize, Serialize)]
    RefreshToken(String)
];
new_secret_type![
    ///
    /// Access token returned by the token endpoint and used to access protected resources.
    ///
    #[derive(Deserialize, Serialize)]
    AccessToken(String)
];
new_secret_type![
    ///
    /// Resource owner's password used directly as an authorization grant to obtain an access
    /// token.
    ///
    ResourceOwnerPassword(String)
];


///
/// Stores the configuration for an OAuth2 client.
///
#[derive(Clone, Debug)]
pub struct Client<EF: ExtraTokenFields, TT: TokenType, TE: ErrorResponseType> {
    client_id: ClientId,
    client_secret: Option<ClientSecret>,
    auth_url: AuthUrl,
    auth_type: AuthType,
    token_url: Option<TokenUrl>,
    scopes: Vec<Scope>,
    redirect_url: Option<RedirectUrl>,
    phantom_ef: PhantomData<EF>,
    phantom_tt: PhantomData<TT>,
    phantom_te: PhantomData<TE>,
}

impl<EF: ExtraTokenFields, TT: TokenType, TE: ErrorResponseType> Client<EF, TT, TE> {
    ///
    /// Initializes an OAuth2 client with the fields common to most OAuth2 flows.
    ///
    /// # Arguments
    ///
    /// * `client_id` -  Client ID
    /// * `client_secret` -  Optional client secret. A client secret is generally used for private
    ///   (server-side) OAuth2 clients and omitted from public (client-side or native app) OAuth2
    ///   clients (see [RFC 8252](https://tools.ietf.org/html/rfc8252)).
    /// * `auth_url` -  Authorization endpoint: used by the client to obtain authorization from
    ///   the resource owner via user-agent redirection. This URL is used in all standard OAuth2
    ///   flows except the [Resource Owner Password Credentials
    ///   Grant](https://tools.ietf.org/html/rfc6749#section-4.3) and the
    ///   [Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4).
    /// * `token_url` - Token endpoint: used by the client to exchange an authorization grant
    ///   (code) for an access token, typically with client authentication. This URL is used in
    ///   all standard OAuth2 flows except the
    ///   [Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2). If this value is set
    ///   to `None`, the `exchange_*` methods will return `Err(RequestTokenError::Other(_))`.
    ///
    pub fn new(
        client_id: ClientId,
        client_secret: Option<ClientSecret>,
        auth_url: AuthUrl,
        token_url: Option<TokenUrl>
    ) -> Self {
        Client {
            client_id,
            client_secret,
            auth_url,
            auth_type: AuthType::BasicAuth,
            token_url,
            scopes: Vec::new(),
            redirect_url: None,
            phantom_ef: PhantomData,
            phantom_tt: PhantomData,
            phantom_te: PhantomData,
        }
    }

    ///
    /// Appends a new scope to the authorization URL.
    ///
    pub fn add_scope(mut self, scope: Scope) -> Self {
        self.scopes.push(scope);

        self
    }

    ///
    /// Configures the type of client authentication used for communicating with the authorization
    /// server.
    ///
    /// The default is to use HTTP Basic authentication, as recommended in
    /// [Section 2.3.1 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-2.3.1).
    ///
    pub fn set_auth_type(mut self, auth_type: AuthType) -> Self {
        self.auth_type = auth_type;

        self
    }

    ///
    /// Sets the the redirect URL used by the authorization endpoint.
    ///
    pub fn set_redirect_url(mut self, redirect_url: RedirectUrl) -> Self {
        self.redirect_url = Some(redirect_url);

        self
    }

    ///
    /// Produces the full authorization URL used by the
    /// [Authorization Code Grant](https://tools.ietf.org/html/rfc6749#section-4.1) flow, which
    /// is the most common OAuth2 flow.
    ///
    /// # Arguments
    ///
    /// * `state_fn` - A function that returns an opaque value used by the client to maintain state
    ///   between the request and callback. The authorization server includes this value when
    ///   redirecting the user-agent back to the client.
    ///
    /// # Security Warning
    ///
    /// Callers should use a fresh, unpredictable `state` for each authorization request and verify
    /// that this value matches the `state` parameter passed by the authorization server to the
    /// redirect URI. Doing so mitigates
    /// [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12)
    ///  attacks. To disable CSRF protections (NOT recommended), use `insecure::authorize_url`
    ///  instead.
    ///
    pub fn authorize_url<F>(&self, state_fn: F) -> (Url, CsrfToken)
    where F: FnOnce() -> CsrfToken {
        let state = state_fn();
        (self.authorize_url_impl::<&str>("code", Some(&state), None), state)
    }

    ///
    /// Produces the full authorization URL used by the
    /// [Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2) flow.
    ///
    /// # Arguments
    ///
    /// * `state_fn` - A function that returns an opaque value used by the client to maintain state
    ///   between the request and callback. The authorization server includes this value when
    ///   redirecting the user-agent back to the client.
    ///
    /// # Security Warning
    ///
    /// Callers should use a fresh, unpredictable `state` for each authorization request and verify
    /// that this value matches the `state` parameter passed by the authorization server to the
    /// redirect URI. Doing so mitigates
    /// [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12)
    ///  attacks. To disable CSRF protections (NOT recommended), use
    /// `insecure::authorize_url_implicit` instead.
    ///
    pub fn authorize_url_implicit<F>(&self, state_fn: F) -> (Url, CsrfToken)
    where F: FnOnce() -> CsrfToken {
        let state = state_fn();
        (self.authorize_url_impl::<&str>("token", Some(&state), None), state)
    }

    ///
    /// Produces the full authorization URL used by an OAuth2
    /// [extension](https://tools.ietf.org/html/rfc6749#section-8.4).
    ///
    /// # Arguments
    ///
    /// * `response_type` - The response type this client expects from the authorization endpoint.
    ///   For `"code"` or `"token"` response types, instead use the `authorize_url` or
    ///   `authorize_url_implicit` functions, respectively.
    /// * `state_fn` - A function that returns an opaque value used by the client to maintain state
    ///   between the request and callback. The authorization server includes this value when
    ///   redirecting the user-agent back to the client.
    /// * `extra_params` - Additional parameters as required by the applicable OAuth2 extension(s).
    ///   Callers should NOT specify any of the following parameters: `response_type`, `client_id`,
    ///   `redirect_uri`, or `scope`.
    ///
    /// # Security Warning
    ///
    /// Callers should use a fresh, unpredictable `state` for each authorization request and verify
    /// that this value matches the `state` parameter passed by the authorization server to the
    /// redirect URI. Doing so mitigates
    /// [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12)
    ///  attacks.
    ///
    /// Callers should follow the security recommendations for any OAuth2 extensions used with
    /// this function, which are beyond the scope of
    /// [RFC 6749](https://tools.ietf.org/html/rfc6749).
    pub fn authorize_url_extension<F, T>(
        &self,
        response_type: &ResponseType,
        state_fn: F,
        extra_params: &[(&str, T)]
    ) -> (Url, CsrfToken)
    where F: FnOnce() -> CsrfToken, T: AsRef<str> + Clone {
        let state = state_fn();
        (self.authorize_url_impl(response_type, Some(&state), Some(extra_params)), state)
    }

    fn authorize_url_impl<T>(
        &self,
        response_type: &str,
        state_opt: Option<&CsrfToken>,
        extra_params_opt: Option<&[(&str, T)]>
    ) -> Url
    where T: AsRef<str> + Clone {
        let scopes = self.scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" ");

        let mut pairs: Vec<(&str, &str)> = vec![
            ("response_type", response_type),
            ("client_id", &self.client_id),
        ];

        if let Some(ref redirect_url) = self.redirect_url {
            pairs.push(("redirect_uri", redirect_url.as_str()));
        }

        if !scopes.is_empty() {
            pairs.push(("scope", &scopes));
        }

        if let Some(state) = state_opt {
            pairs.push(("state", state.secret()));
        }

        let mut url: Url = (*self.auth_url).clone();

        url.query_pairs_mut().extend_pairs(
            pairs.iter().map(|&(k, v)| { (k, &v[..]) })
        );

        if let Some(extra_params) = extra_params_opt {
            url.query_pairs_mut().extend_pairs(
                extra_params.iter().cloned()
            );
        }

        url
    }

    ///
    /// Exchanges a code produced by a successful authorization process with an access token.
    ///
    /// Acquires ownership of the `code` because authorization codes may only be used to retrieve
    /// an access token from the authorization server.
    ///
    /// See https://tools.ietf.org/html/rfc6749#section-4.1.3
    ///
    pub fn exchange_code(
        &self,
        code: AuthorizationCode
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>> {
        self.exchange_code_extension::<&str>(code, &[])
    }

    ///
    /// Exchanges a code produced by a successful authorization process with an access token.
    ///
    /// Acquires ownership of the `code` because authorization codes may only be used to retrieve
    /// an access token from the authorization server.
    ///
    /// See https://tools.ietf.org/html/rfc6749#section-4.1.3
    ///
    pub fn exchange_code_extension<T>(
        &self,
        code: AuthorizationCode,
        extra_params: &[(&str, T)]
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>>
    where T: AsRef<str> + Clone {
        // Make Clippy happy since we're intentionally taking ownership.
        let code_owned = code;
        let mut params: Vec<(&str, &str)> = vec![
            ("grant_type", "authorization_code"),
            ("code", code_owned.secret())
        ];

        params.extend_from_slice(
            &extra_params
                .iter()
                .map(|&(k, ref v)| { (k, v.as_ref()) }).collect::<Vec<(&str, &str)>>()
        );

        self.request_token(params)
    }

    ///
    /// Requests an access token for the *password* grant type.
    ///
    /// See https://tools.ietf.org/html/rfc6749#section-4.3.2
    ///
    pub fn exchange_password(
        &self,
        username: &ResourceOwnerUsername,
        password: &ResourceOwnerPassword
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>> {
        // Generate the space-delimited scopes String before initializing params so that it has
        // a long enough lifetime.
        let scopes_opt =
            if !self.scopes.is_empty() {
                Some(self.scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" "))
            } else {
                None
            };

        let mut params = vec![
            ("grant_type", "password"),
            ("username", username),
            ("password", password.secret()),
        ];

        if let Some(ref scopes) = scopes_opt {
            params.push(("scope", scopes));
        }

        self.request_token(params)
    }

    ///
    /// Requests an access token for the *client credentials* grant type.
    ///
    /// See https://tools.ietf.org/html/rfc6749#section-4.4.2
    ///
    pub fn exchange_client_credentials(
        &self
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>> {
        // Generate the space-delimited scopes String before initializing params so that it has
        // a long enough lifetime.
        let scopes_opt =
            if !self.scopes.is_empty() {
                Some(self.scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" "))
            } else {
                None
            };

        let mut params: Vec<(&str, &str)> = vec![("grant_type", "client_credentials")];

        if let Some(ref scopes) = scopes_opt {
            params.push(("scope", scopes));
        }
        self.request_token(params)
    }

    ///
    /// Exchanges a refresh token for an access token
    ///
    /// See https://tools.ietf.org/html/rfc6749#section-6
    ///
    pub fn exchange_refresh_token(
        &self, refresh_token: &RefreshToken
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>> {
        let params: Vec<(&str, &str)> = vec![
            ("grant_type", "refresh_token"),
            ("refresh_token", refresh_token.secret()),
        ];

        self.request_token(params)
    }

    fn post_request_token<'a, 'b: 'a>(
        &'b self,
        token_url: &TokenUrl,
        mut params: Vec<(&'b str, &'a str)>
    ) -> Result<RequestTokenResponse, curl::Error> {
        let mut easy = Easy::new();

        // FIXME: add support for auth extensions? e.g., client_secret_jwt and private_key_jwt
        match self.auth_type {
            AuthType::RequestBody => {
                params.push(("client_id", &self.client_id));
                if let Some(ref client_secret) = self.client_secret {
                    params.push(("client_secret", client_secret.secret()));
                }
            }
            AuthType::BasicAuth => {
                // Section 2.3.1 of RFC 6749 requires separately url-encoding the id and secret
                // before using them as HTTP Basic auth username and password. Note that this is
                // not standard for ordinary Basic auth, so curl won't do it for us.
                let encoded_id = easy.url_encode(&self.client_id.as_bytes());
                easy.username(&encoded_id)?;

                if let Some(ref client_secret) = self.client_secret {
                    let encoded_secret = easy.url_encode(client_secret.secret().as_bytes());
                    easy.password(&encoded_secret)?;
                }
            }
        }

        if let Some(ref redirect_url) = self.redirect_url {
            params.push(("redirect_uri", redirect_url.as_str()));
        }

        let form =
            url::form_urlencoded::Serializer::new(String::new())
                .extend_pairs(params)
                .finish()
                .into_bytes();
        let mut form_slice = &form[..];

        easy.url(&token_url.to_string()[..])?;

        // Section 5.1 of RFC 6749 (https://tools.ietf.org/html/rfc6749#section-5.1) only permits
        // JSON responses for this request. Some providers such as GitHub have off-spec behavior
        // and not only support different response formats, but have non-JSON defaults. Explicitly
        // request JSON here.
        let mut headers = curl::easy::List::new();
        let accept_header = format!("Accept: {}", CONTENT_TYPE_JSON);
        headers.append(&accept_header)?;
        easy.http_headers(headers)?;

        easy.post(true)?;
        easy.post_field_size(form.len() as u64)?;

        let mut data = Vec::new();
        {
            let mut transfer = easy.transfer();

            transfer.read_function(|buf| {
                Ok(form_slice.read(buf).unwrap_or(0))
            })?;

            transfer.write_function(|new_data| {
                data.extend_from_slice(new_data);
                Ok(new_data.len())
            })?;

            transfer.perform()?;
        }

        let http_status = easy.response_code()?;
        let content_type = easy.content_type()?;

        Ok(RequestTokenResponse{
            http_status,
            content_type: content_type.map(|s| s.to_string()),
            response_body: data,
        })
    }

    fn request_token(
        &self, params: Vec<(&str, &str)>
    ) -> Result<TokenResponse<EF, TT>, RequestTokenError<TE>> {
        let token_url =
            self.token_url.as_ref().ok_or_else(||
                // Arguably, it could be better to panic in this case. However, there may be
                // situations where the library user gets the authorization server's configuration
                // dynamically. In those cases, it would be preferable to return an `Err` rather
                // than panic. An example situation where this might arise is OpenID Connect
                // discovery.
                RequestTokenError::Other("token_url must not be `None`".to_string())
            )?;
        let token_response =
            self.post_request_token(token_url, params).map_err(RequestTokenError::Request)?;
        if token_response.http_status != 200 {
            let reason = String::from_utf8_lossy(token_response.response_body.as_slice());
            if reason.is_empty() {
                return Err(
                    RequestTokenError::Other("Server returned empty error response".to_string())
                );
            } else {
                let error = match serde_json::from_str::<ErrorResponse<TE>>(&reason) {
                    Ok(error) => RequestTokenError::ServerResponse(error),
                    Err(error) => RequestTokenError::Parse(error),
                };
                return Err(error);
            }
        }

        // Validate that the response Content-Type is JSON.
        token_response
            .content_type
            .map_or(Ok(()), |content_type|
                // Section 3.1.1.1 of RFC 7231 indicates that media types are case insensitive and
                // may be followed by optional whitespace and/or a parameter (e.g., charset).
                // See https://tools.ietf.org/html/rfc7231#section-3.1.1.1.
                if !content_type.to_lowercase().starts_with(CONTENT_TYPE_JSON) {
                    Err(
                        RequestTokenError::Other(
                            format!(
                                "Unexpected response Content-Type: `{}`, should be `{}`",
                                content_type,
                                CONTENT_TYPE_JSON
                            )
                        )
                    )
                } else {
                    Ok(())
                }
            )?;

        if token_response.response_body.is_empty() {
            Err(RequestTokenError::Other("Server returned empty response body".to_string()))
        } else {
            let response_body =
                String::from_utf8(token_response.response_body)
                    .map_err(|parse_error|
                        RequestTokenError::Other(
                            format!("Couldn't parse response as UTF-8: {}", parse_error)
                        )
                    )?;

            TokenResponse::from_json(&response_body).map_err(RequestTokenError::Parse)
        }
    }
}

///
/// Private struct returned by `post_request_token`.
///
struct RequestTokenResponse {
    http_status: u32,
    content_type: Option<String>,
    response_body: Vec<u8>,
}

///
/// Trait for OAuth2 access tokens.
///
pub trait TokenType : DeserializeOwned + Debug + PartialEq + Serialize {}

///
/// Trait for adding extra fields to the `TokenResponse`.
///
pub trait ExtraTokenFields : DeserializeOwned + Debug + PartialEq + Serialize {}

///
/// Empty (default) extra token fields.
///
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct EmptyExtraTokenFields {}
impl ExtraTokenFields for EmptyExtraTokenFields {}

///
/// Common methods shared by all OAuth2 token implementations.
///
/// The methods in this struct are defined in
/// [Section 5.1 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.1).
///
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct TokenResponse<EF: ExtraTokenFields, TT: TokenType> {
    access_token: AccessToken,
    #[serde(bound = "TT: TokenType")]
    #[serde(deserialize_with = "helpers::deserialize_untagged_enum_case_insensitive")]
    token_type: TT,
    #[serde(skip_serializing_if = "Option::is_none")]
    expires_in: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    refresh_token: Option<RefreshToken>,
    #[serde(rename = "scope")]
    #[serde(deserialize_with = "helpers::deserialize_space_delimited_vec")]
    #[serde(serialize_with = "helpers::serialize_space_delimited_vec")]
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    scopes: Option<Vec<Scope>>,

    #[serde(bound = "EF: ExtraTokenFields")]
    #[serde(flatten)]
    extra_fields: EF,
}
impl<EF: ExtraTokenFields, TT: TokenType> TokenResponse<EF, TT> {
    ///
    /// REQUIRED. The access token issued by the authorization server.
    ///
    pub fn access_token(&self) -> &AccessToken { &self.access_token }
    ///
    /// REQUIRED. The type of the token issued as described in
    /// [Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1).
    /// Value is case insensitive and deserialized to the generic `TokenType` parameter.
    ///
    pub fn token_type(&self) -> &TT { &self.token_type }
    ///
    /// RECOMMENDED. The lifetime in seconds of the access token. For example, the value 3600
    /// denotes that the access token will expire in one hour from the time the response was
    /// generated. If omitted, the authorization server SHOULD provide the expiration time via
    /// other means or document the default value.
    ///
    pub fn expires_in(&self) -> Option<Duration> { self.expires_in.map(Duration::from_secs) }
    ///
    /// OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same
    /// authorization grant as described in
    /// [Section 6](https://tools.ietf.org/html/rfc6749#section-6).
    ///
    pub fn refresh_token(&self) -> Option<&RefreshToken> { self.refresh_token.as_ref() }
    ///
    /// OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. The
    /// scipe of the access token as described by
    /// [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). If included in the response,
    /// this space-delimited field is parsed into a `Vec` of individual scopes. If omitted from
    /// the response, this field is `None`.
    ///
    pub fn scopes(&self) -> Option<&Vec<Scope>> { self.scopes.as_ref() }

    ///
    /// Extra fields defined by client application.
    ///
    pub fn extra_fields(&self) -> &EF { &self.extra_fields }

    ///
    /// Factory method to deserialize a `Token` from a JSON response.
    ///
    /// # Failures
    /// If parsing fails, returns a `serde_json::error::Error` describing the parse error.
    pub fn from_json(data: &str) -> Result<Self, serde_json::error::Error> {
        serde_json::from_str(data)
    }
}


///
/// Error types enum.
///
/// NOTE: The implementation of the `Display` trait must return the `snake_case` representation of
/// this error type. This value must match the error type from the relevant OAuth 2.0 standards
/// (RFC 6749 or an extension).
///
pub trait ErrorResponseType : Debug + DeserializeOwned + Display + PartialEq + Serialize {}

///
/// Error response returned by server after requesting an access token.
///
/// The fields in this structure are defined in
/// [Section 5.2 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.2). This
/// trait is parameterized by a `ErrorResponseType` to support error types specific to future OAuth2
/// authentication schemes and extensions.
///
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct ErrorResponse<T: ErrorResponseType> {
    #[serde(bound = "T: ErrorResponseType")]
    error: T,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    error_description: Option<String>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    error_uri: Option<String>,
}

impl<T: ErrorResponseType> ErrorResponse<T> {
    ///
    /// REQUIRED. A single ASCII error code deserialized to the generic parameter
    /// `ErrorResponseType`.
    ///
    pub fn error(&self) -> &T { &self.error }
    ///
    /// OPTIONAL. Human-readable ASCII text providing additional information, used to assist
    /// the client developer in understanding the error that occurred.
    ///
    pub fn error_description(&self) -> Option<&String> { self.error_description.as_ref() }
    ///
    /// OPTIONAL. A URI identifying a human-readable web page with information about the error,
    /// used to provide the client developer with additional information about the error.
    ///
    pub fn error_uri(&self) -> Option<&String> { self.error_uri.as_ref() }
}

impl<TE: ErrorResponseType> Display for ErrorResponse<TE> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
        let mut formatted = self.error().to_string();

        if let Some(error_description) = self.error_description() {
            formatted.push_str(": ");
            formatted.push_str(error_description);
        }

        if let Some(error_uri) = self.error_uri() {
            formatted.push_str(" / See ");
            formatted.push_str(error_uri);
        }

        write!(f, "{}", formatted)
    }
}

///
/// Error encountered while requesting access token.
///
#[derive(Debug)]
pub enum RequestTokenError<T: ErrorResponseType> {
    ///
    /// Error response returned by authorization server. Contains the parsed `ErrorResponse`
    /// returned by the server.
    ///
    ServerResponse(ErrorResponse<T>),
    ///
    /// An error occurred while sending the request or receiving the response (e.g., network
    /// connectivity failed).
    ///
    Request(curl::Error),
    ///
    /// Failed to parse server response. Parse errors may occur while parsing either successful
    /// or error responses.
    ///
    Parse(serde_json::error::Error),
    ///
    /// Some other type of error occurred (e.g., an unexpected server response).
    ///
    Other(String),
}

// Due to https://github.com/rust-lang/rust/issues/26925, deriving "Fail" creates an impl that only
// applies if ErrorResponseType also implements Fail (which it shouldn't). As a workaround, we
// manually implement Fail and Display below.
impl<T> Fail for RequestTokenError<T>
where T: ErrorResponseType + Send + Sync + 'static {
    fn cause(&self) -> Option<&Fail> {
        match *self {
            RequestTokenError::ServerResponse(_) => None,
            RequestTokenError::Request(ref cause) => Some(cause),
            RequestTokenError::Parse(ref cause) => Some(cause),
            RequestTokenError::Other(_) => None,
        }
    }
    fn backtrace(&self) -> Option<&Backtrace> {
        None
    }
}
impl <T> Display for RequestTokenError<T>
where T: ErrorResponseType {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match *self {
            RequestTokenError::ServerResponse(ref err_resp) =>
                write!(f, "Server returned error response `{}`", err_resp),
            RequestTokenError::Request(_) =>
                write!(f, "Request failed"),
            RequestTokenError::Parse(_) =>
                write!(f, "Failed to parse server response"),
            RequestTokenError::Other(ref err_msg) =>
                write!(f, "Other error: {}", err_msg),
        }
    }
}

///
/// Basic OAuth2 implementation with no extensions
/// ([RFC 6749](https://tools.ietf.org/html/rfc6749)).
///
pub mod basic {
    extern crate serde_json;

    use std::fmt::Error as FormatterError;
    use std::fmt::{Debug, Display, Formatter};

    use super::{
        Client,
        EmptyExtraTokenFields,
        ErrorResponse,
        ErrorResponseType,
        RequestTokenError,
        TokenResponse,
        TokenType,
    };
    use super::helpers;

    ///
    /// Basic OAuth2 client specialization, suitable for most applications.
    ///
    pub type BasicClient = Client<EmptyExtraTokenFields, BasicTokenType, BasicErrorResponseType>;

    ///
    /// Basic OAuth2 authorization token types.
    ///
    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
    #[serde(rename_all = "lowercase")]
    pub enum BasicTokenType {
        ///
        /// Bearer token
        /// ([OAuth 2.0 Bearer Tokens - RFC 6750](https://tools.ietf.org/html/rfc6750)).
        ///
        Bearer,
        ///
        /// MAC ([OAuth 2.0 Message Authentication Code (MAC)
        /// Tokens](https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05)).
        ///
        Mac,
    }
    impl TokenType for BasicTokenType {}

    ///
    /// Basic OAuth2 token response.
    ///
    pub type BasicTokenResponse = TokenResponse<EmptyExtraTokenFields, BasicTokenType>;

    ///
    /// Basic access token error types.
    ///
    /// These error types are defined in
    /// [Section 5.2 of RFC 6749](https://tools.ietf.org/html/rfc6749#section-5.2).
    ///
    #[derive(Clone, Deserialize, PartialEq, Serialize)]
    #[serde(rename_all="snake_case")]
    pub enum BasicErrorResponseType {
        ///
        /// The request is missing a required parameter, includes an unsupported parameter value
        /// (other than grant type), repeats a parameter, includes multiple credentials, utilizes
        /// more than one mechanism for authenticating the client, or is otherwise malformed.
        ///
        InvalidRequest,
        ///
        /// Client authentication failed (e.g., unknown client, no client authentication included,
        /// or unsupported authentication method).
        ///
        InvalidClient,
        ///
        /// The provided authorization grant (e.g., authorization code, resource owner credentials)
        /// or refresh token is invalid, expired, revoked, does not match the redirection URI used
        /// in the authorization request, or was issued to another client.
        ///
        InvalidGrant,
        ///
        /// The authenticated client is not authorized to use this authorization grant type.
        ///
        UnauthorizedClient,
        ///
        /// The authorization grant type is not supported by the authorization server.
        ///
        UnsupportedGrantType,
        ///
        /// The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the
        /// resource owner.
        ///
        InvalidScope,
    }

    impl ErrorResponseType for BasicErrorResponseType {}

    impl Debug for BasicErrorResponseType {
        fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
            Display::fmt(self, f)
        }
    }

    impl Display for BasicErrorResponseType {
        fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
            write!(f, "{}", helpers::variant_name(&self))
        }
    }

    ///
    /// Error response specialization for basic OAuth2 implementation.
    ///
    pub type BasicErrorResponse = ErrorResponse<BasicErrorResponseType>;

    ///
    /// Token error specialization for basic OAuth2 implementation.
    ///
    pub type BasicRequestTokenError = RequestTokenError<BasicErrorResponseType>;
}

///
/// Insecure methods -- not recommended for most applications.
///
pub mod insecure {
    use url::Url;

    use super::{
        Client,
        ErrorResponseType,
        ExtraTokenFields,
        TokenType,
    };

    ///
    /// Produces the full authorization URL used by the
    /// [Authorization Code Grant](https://tools.ietf.org/html/rfc6749#section-4.1) flow, which
    /// is the most common OAuth2 flow.
    ///
    /// # Security Warning
    ///
    /// The URL produced by this function is vulnerable to
    /// [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12) attacks.
    /// It is highly recommended to use the `Client::authorize_url` function instead.
    ///
    pub fn authorize_url<EF, TT, TE>(client: &Client<EF, TT, TE>) -> Url
    where EF: ExtraTokenFields, TT: TokenType, TE: ErrorResponseType {
        client.authorize_url_impl::<&str>("code", None, None)
    }

    ///
    /// Produces the full authorization URL used by the
    /// [Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2) flow.
    ///
    /// # Security Warning
    ///
    /// The URL produced by this function is vulnerable to
    /// [Cross-Site Request Forgery](https://tools.ietf.org/html/rfc6749#section-10.12) attacks.
    /// It is highly recommended to use the `Client::authorize_url_implicit` function instead.
    ///
    pub fn authorize_url_implicit<EF, TT, TE>(client: &Client<EF, TT, TE>) -> Url
    where EF: ExtraTokenFields, TT: TokenType, TE: ErrorResponseType {
        client.authorize_url_impl::<&str>("token", None, None)
    }
}

///
/// Helper methods used by OAuth2 implementations/extensions.
///
pub mod helpers {
    use std;

    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use serde::ser;
    use serde::ser::{Impossible, SerializeStructVariant, SerializeTupleVariant};
    use url::Url;

    ///
    /// Serde case-insensitive deserializer for an untagged `enum`.
    ///
    /// This function converts values to lowercase before deserializing as the `enum`. Requires the
    /// `#[serde(rename_all = "lowercase")]` attribute to be set on the `enum`.
    ///
    /// # Example
    ///
    /// In example below, the following JSON values all deserialize to
    /// `GroceryBasket { fruit_item: Fruit::Banana }`:
    ///
    ///  * `{"fruit_item": "banana"}`
    ///  * `{"fruit_item": "BANANA"}`
    ///  * `{"fruit_item": "Banana"}`
    ///
    /// Note: this example does not compile automatically due to
    /// [Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).
    ///
    /// ```
    /// # /*
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// #[serde(rename_all = "lowercase")]
    /// enum Fruit {
    ///     Apple,
    ///     Banana,
    ///     Orange,
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct GroceryBasket {
    ///     #[serde(deserialize_with = "helpers::deserialize_untagged_enum_case_insensitive")]
    ///     fruit_item: Fruit,
    /// }
    /// # */
    /// ```
    ///
    pub fn deserialize_untagged_enum_case_insensitive<'de, T, D>(
        deserializer: D
    ) -> Result<T, D::Error>
    where T: Deserialize<'de>, D: Deserializer<'de> {
        use serde::de::Error;
        use serde_json::Value;
        T::deserialize(Value::String(String::deserialize(deserializer)?.to_lowercase()))
            .map_err(Error::custom)
    }

    ///
    /// Serde space-delimited string deserializer for a `Vec<String>`.
    ///
    /// This function splits a JSON string at each space character into a `Vec<String>` .
    ///
    /// # Example
    ///
    /// In example below, the JSON value `{"items": "foo bar baz"}` would deserialize to:
    ///
    /// ```
    /// # struct GroceryBasket {
    /// #     items: Vec<String>,
    /// # }
    /// # fn main() {
    /// GroceryBasket {
    ///     items: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]
    /// };
    /// # }
    /// ```
    ///
    /// Note: this example does not compile automatically due to
    /// [Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).
    ///
    /// ```
    /// # /*
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct GroceryBasket {
    ///     #[serde(deserialize_with = "helpers::deserialize_space_delimited_vec")]
    ///     items: Vec<String>,
    /// }
    /// # */
    /// ```
    ///
    pub fn deserialize_space_delimited_vec<'de, T, D>(
        deserializer: D
    ) -> Result<T, D::Error>
    where T: Default + Deserialize<'de>, D: Deserializer<'de> {
        use serde::de::Error;
        use serde_json::Value;
        if let Some(space_delimited) = Option::<String>::deserialize(deserializer)? {
            let entries =
                space_delimited
                    .split(' ')
                    .map(|s| Value::String(s.to_string()))
                    .collect();
            T::deserialize(Value::Array(entries))
                .map_err(Error::custom)
        } else {
            // If the JSON value is null, use the default value.
            Ok(T::default())
        }
    }

    ///
    /// Serde space-delimited string serializer for an `Option<Vec<String>>`.
    ///
    /// This function serializes a string vector into a single space-delimited string.
    /// If `string_vec_opt` is `None`, the function serializes it as `None` (e.g., `null`
    /// in the case of JSON serialization).
    ///
    pub fn serialize_space_delimited_vec<T, S>(
        vec_opt: &Option<Vec<T>>,
        serializer: S
    ) -> Result<S::Ok, S::Error>
    where T: AsRef<str>, S: Serializer {
        if let Some(ref vec) = *vec_opt {
            let space_delimited = vec.iter().map(|s| s.as_ref()).collect::<Vec<_>>().join(" ");

            serializer.serialize_str(&space_delimited)
        } else {
            serializer.serialize_none()
        }
    }

    ///
    /// Serde string deserializer for a `Url`.
    ///
    pub fn deserialize_url<'de, D>(
        deserializer: D
    ) -> Result<Url, D::Error>
    where D: Deserializer<'de> {
        use serde::de::Error;
        let url_str = String::deserialize(deserializer)?;
        Url::parse(url_str.as_ref()).map_err(Error::custom)
    }

    ///
    /// Serde string serializer for a `Url`.
    ///
    pub fn serialize_url<S>(
        url: &Url,
        serializer: S
    ) -> Result<S::Ok, S::Error>
    where S: Serializer {
        serializer.serialize_str(url.as_str())
    }

    ///
    /// Serde string serializer for an enum.
    ///
    /// Source:
    /// [https://github.com/serde-rs/serde/issues/553](https://github.com/serde-rs/serde/issues/553)
    ///
    pub fn variant_name<T: Serialize>(t: &T) -> &'static str {
        #[derive(Debug)]
        struct NotEnum;
        type Result<T> = std::result::Result<T, NotEnum>;
        impl std::error::Error for NotEnum {
            fn description(&self) -> &str { "not struct" }
        }
        impl std::fmt::Display for NotEnum {
            fn fmt(&self, _f: &mut std::fmt::Formatter) -> std::fmt::Result { unimplemented!() }
        }
        impl ser::Error for NotEnum {
            fn custom<T: std::fmt::Display>(_msg: T) -> Self { NotEnum }
        }

        struct VariantName;
        impl Serializer for VariantName {
            type Ok = &'static str;
            type Error = NotEnum;
            type SerializeSeq = Impossible<Self::Ok, Self::Error>;
            type SerializeTuple = Impossible<Self::Ok, Self::Error>;
            type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
            type SerializeTupleVariant = Enum;
            type SerializeMap = Impossible<Self::Ok, Self::Error>;
            type SerializeStruct = Impossible<Self::Ok, Self::Error>;
            type SerializeStructVariant = Enum;
            fn serialize_bool(self, _v: bool) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_i8(self, _v: i8) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_i16(self, _v: i16) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_i32(self, _v: i32) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_i64(self, _v: i64) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_u8(self, _v: u8) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_u16(self, _v: u16) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_u32(self, _v: u32) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_u64(self, _v: u64) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_f32(self, _v: f32) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_f64(self, _v: f64) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_char(self, _v: char) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_str(self, _v: &str) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_none(self) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<Self::Ok> {
                Err(NotEnum)
            }
            fn serialize_unit(self) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok> { Err(NotEnum) }
            fn serialize_unit_variant(
                self,
                _name: &'static str,
                _variant_index: u32,
                variant: &'static str
            ) -> Result<Self::Ok> {
                Ok(variant)
            }
            fn serialize_newtype_struct<T: ?Sized + Serialize>(
                self,
                _name: &'static str,
                _value: &T
            ) -> Result<Self::Ok> {
                Err(NotEnum)
            }
            fn serialize_newtype_variant<T: ?Sized + Serialize>(
                self,
                _name: &'static str,
                _variant_index: u32,
                variant: &'static str,
                _value: &T
            ) -> Result<Self::Ok> {
                Ok(variant)
            }
            fn serialize_seq(
                self,
                _len: Option<usize>
            ) -> Result<Self::SerializeSeq> {
                Err(NotEnum)
            }
            fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(NotEnum) }
            fn serialize_tuple_struct(
                self,
                _name: &'static str,
                _len: usize
            ) -> Result<Self::SerializeTupleStruct> {
                Err(NotEnum)
            }
            fn serialize_tuple_variant(
                self,
                _name: &'static str,
                _variant_index: u32,
                variant: &'static str,
                _len: usize
            ) -> Result<Self::SerializeTupleVariant> {
                Ok(Enum(variant))
            }
            fn serialize_map(
                self,
                _len: Option<usize>
            ) -> Result<Self::SerializeMap> {
                Err(NotEnum)
            }
            fn serialize_struct(
                self,
                _name: &'static str,
                _len: usize
            ) -> Result<Self::SerializeStruct> {
                Err(NotEnum)
            }
            fn serialize_struct_variant(
                self,
                _name: &'static str,
                _variant_index: u32,
                variant: &'static str,
                _len: usize
            ) -> Result<Self::SerializeStructVariant> {
                Ok(Enum(variant))
            }
        }

        struct Enum(&'static str);
        impl SerializeStructVariant for Enum {
            type Ok = &'static str;
            type Error = NotEnum;
            fn serialize_field<T: ?Sized + Serialize>(
                &mut self,
                _key: &'static str,
                _value: &T
            ) -> Result<()> {
                Ok(())
            }
            fn end(self) -> Result<Self::Ok> {
                Ok(self.0)
            }
        }
        impl SerializeTupleVariant for Enum {
            type Ok = &'static str;
            type Error = NotEnum;
            fn serialize_field<T: ?Sized + Serialize>(
                &mut self,
                _value: &T
            ) -> Result<()> {
                Ok(())
            }
            fn end(self) -> Result<Self::Ok> {
                Ok(self.0)
            }
        }

        t.serialize(VariantName).unwrap()
    }
}