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
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
use crate::accesstoken::AccessToken;
use crate::grants::{GrantRequest, GrantType};
use crate::idtoken::IdToken;
use crate::oautherror::OAuthError;
use crate::strum::IntoEnumIterator;
use from_as::*;
use graph_error::GraphFailure;
use ring::rand::SecureRandom;
use std::marker::PhantomData;
use std::collections::btree_map::BTreeMap;
use std::collections::{BTreeSet, HashMap};
use std::convert::TryFrom;
use std::fmt;
use std::io::{Read, Write};
use std::process::Output;
use url::form_urlencoded::Serializer;
use url::Url;

pub type OAuthReq<T> = Result<T, GraphFailure>;

/// Fields that represent common OAuth credentials.
#[derive(
    Debug,
    Copy,
    Clone,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Hash,
    Serialize,
    Deserialize,
    EnumIter,
    AsFile,
    FromFile,
)]
pub enum OAuthCredential {
    ClientId,
    ClientSecret,
    AuthorizeURL,
    AccessTokenURL,
    RefreshTokenURL,
    RedirectURI,
    AccessCode,
    AccessToken,
    RefreshToken,
    ResponseMode,
    State,
    SessionState,
    ResponseType,
    GrantType,
    Nonce,
    Prompt,
    IdToken,
    Resource,
    DomainHint,
    Scopes,
    LoginHint,
    ClientAssertion,
    ClientAssertionType,
    CodeVerifier,
    CodeChallenge,
    CodeChallengeMethod,
    PostLogoutRedirectURI,
    LogoutURL,
    AdminConsent,
    Username,
    Password,
}

impl OAuthCredential {
    pub fn alias(self) -> &'static str {
        match self {
            OAuthCredential::ClientId => "client_id",
            OAuthCredential::ClientSecret => "client_secret",
            OAuthCredential::AuthorizeURL => "authorization_url",
            OAuthCredential::AccessTokenURL => "access_token_url",
            OAuthCredential::RefreshTokenURL => "refresh_token_url",
            OAuthCredential::RedirectURI => "redirect_uri",
            OAuthCredential::AccessCode => "code",
            OAuthCredential::AccessToken => "access_token",
            OAuthCredential::RefreshToken => "refresh_token",
            OAuthCredential::ResponseMode => "response_mode",
            OAuthCredential::ResponseType => "response_type",
            OAuthCredential::State => "state",
            OAuthCredential::SessionState => "session_state",
            OAuthCredential::GrantType => "grant_type",
            OAuthCredential::Nonce => "nonce",
            OAuthCredential::Prompt => "prompt",
            OAuthCredential::IdToken => "id_token",
            OAuthCredential::Resource => "resource",
            OAuthCredential::DomainHint => "domain_hint",
            OAuthCredential::Scopes => "scope",
            OAuthCredential::LoginHint => "login_hint",
            OAuthCredential::ClientAssertion => "client_assertion",
            OAuthCredential::ClientAssertionType => "client_assertion_type",
            OAuthCredential::CodeVerifier => "code_verifier",
            OAuthCredential::CodeChallenge => "code_challenge",
            OAuthCredential::CodeChallengeMethod => "code_challenge_method",
            OAuthCredential::LogoutURL => "logout_url",
            OAuthCredential::PostLogoutRedirectURI => "post_logout_redirect_uri",
            OAuthCredential::AdminConsent => "admin_consent",
            OAuthCredential::Username => "username",
            OAuthCredential::Password => "password",
        }
    }

    fn is_debug_redacted(&self) -> bool {
        match self {
            OAuthCredential::ClientId |
            OAuthCredential::ClientSecret |
            OAuthCredential::AccessToken |
            OAuthCredential::RefreshToken |
            OAuthCredential::IdToken |
            OAuthCredential::CodeVerifier |
            OAuthCredential::CodeChallenge |
            OAuthCredential::Password |
            OAuthCredential::AccessCode => true,
            _ => false,
        }
    }
}

impl ToString for OAuthCredential {
    fn to_string(&self) -> String {
        self.alias().to_string()
    }
}

/// # OAuth
///
/// OAuth client implementing the OAuth 2.0 and OpenID Connect protocols
/// on Microsoft identity platform. This version is specifically meant for
/// the Graph V1.0 and Beta API.
///
/// The client supports almost all OAuth 2.0 flows that Microsoft
/// implements as well as the token and code flow specific to the
/// OneDrive api.
///
/// The OAuth client is strict on what can be used for a specific OAuth
/// flow. This is to ensure that the credentials used in requests include
/// only information that is required or optional for that specific grant
/// and not any other. Even if you accidently pass a value, such as a nonce,
/// for a grant type that does not use it, any request that is made will not
/// include the nonce regardless.
///
/// # Disclaimer
/// Using this API for other resource owners besides Microsoft may work but
/// functionality will more then likely be limited.
///
/// # Example
/// ```
/// use graph_oauth::oauth::OAuth;
/// let oauth = OAuth::new();
/// ```
#[derive(Default, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct OAuth {
    access_token: Option<AccessToken>,
    scopes: BTreeSet<String>,
    credentials: BTreeMap<String, String>,
}

impl OAuth {
    /// Create a new OAuth instance.
    ///
    /// # Example
    /// ```
    /// use graph_oauth::oauth::{OAuth, GrantType};
    ///
    /// let mut oauth = OAuth::new();
    /// ```
    pub fn new() -> OAuth {
        OAuth {
            access_token: None,
            scopes: BTreeSet::new(),
            credentials: BTreeMap::new(),
        }
    }

    /// Insert oauth credentials using the OAuthCredential enum.
    /// This method is used internally for each of the setter methods.
    /// Callers can optionally use this method to set credentials instead
    /// of the individual setter methods.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// oauth.insert(OAuthCredential::AuthorizeURL, "https://example.com");
    /// assert!(oauth.contains(OAuthCredential::AuthorizeURL));
    /// println!("{:#?}", oauth.get(OAuthCredential::AuthorizeURL));
    /// ```
    pub fn insert<V: ToString>(&mut self, oac: OAuthCredential, value: V) -> &mut OAuth {
        let v = value.to_string();
        match oac {
            OAuthCredential::RefreshTokenURL |
            OAuthCredential::PostLogoutRedirectURI |
            OAuthCredential::AccessTokenURL |
            OAuthCredential::AuthorizeURL |
            OAuthCredential::LogoutURL => {
                Url::parse(v.as_ref()).unwrap();
            },
            _ => {},
        }

        self.credentials.insert(oac.to_string(), v);
        self
    }

    /// Insert and OAuth credential using the entry trait and
    /// returning the credential. This internally calls
    /// `entry.(OAuthCredential).or_insret_with(value)`.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// let entry = oauth.entry(OAuthCredential::AuthorizeURL, "https://example.com");
    /// assert_eq!(entry, "https://example.com")
    /// ```
    pub fn entry<V: ToString>(&mut self, oac: OAuthCredential, value: V) -> &mut String {
        let v = value.to_string();
        match oac {
            OAuthCredential::RefreshTokenURL |
            OAuthCredential::PostLogoutRedirectURI |
            OAuthCredential::AccessTokenURL |
            OAuthCredential::AuthorizeURL |
            OAuthCredential::LogoutURL => {
                Url::parse(v.as_ref()).unwrap();
            },
            _ => {},
        }

        self.credentials
            .entry(oac.alias().to_string())
            .or_insert_with(|| v)
    }

    /// Get a previously set credential.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// let a = oauth.get(OAuthCredential::AuthorizeURL);
    /// ```
    pub fn get(&self, oac: OAuthCredential) -> Option<String> {
        self.credentials.get(oac.alias()).cloned()
    }

    /// Check if an OAuth credential has already been set.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// println!("{:#?}", oauth.contains(OAuthCredential::Nonce));
    /// ```
    pub fn contains(&self, t: OAuthCredential) -> bool {
        if t == OAuthCredential::Scopes {
            return !self.scopes.is_empty();
        }
        self.credentials.contains_key(t.alias())
    }

    pub fn contains_key(&self, key: &str) -> bool {
        self.credentials.contains_key(key)
    }

    /// Remove a field from OAuth.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// oauth.client_id("client_id");
    ///
    /// assert_eq!(oauth.contains(OAuthCredential::ClientId), true);
    /// oauth.remove(OAuthCredential::ClientId);
    ///
    /// assert_eq!(oauth.contains(OAuthCredential::ClientId), false);
    /// ```
    pub fn remove(&mut self, oac: OAuthCredential) -> &mut OAuth {
        self.credentials.remove(oac.alias());
        self
    }

    /// Set the client id for an OAuth request.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// oauth.client_id("client_id");
    /// ```
    pub fn client_id(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ClientId, value)
    }

    /// Set the state for an OAuth request.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    /// # let mut oauth = OAuth::new();
    /// oauth.state("1234");
    /// ```
    pub fn state(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::State, value)
    }

    /// Set the client secret for an OAuth request.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.client_secret("client_secret");
    /// ```
    pub fn client_secret(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ClientSecret, value)
    }

    /// Set the authorization URL.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.authorize_url("https://example.com/authorize");
    /// ```
    pub fn authorize_url(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::AuthorizeURL, value)
    }

    /// Set the access token url of a request for OAuth
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.access_token_url("https://example.com/token");
    /// ```
    pub fn access_token_url(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::AccessTokenURL, value)
    }

    /// Set the refresh token url of a request for OAuth
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.refresh_token_url("https://example.com/token");
    /// ```
    pub fn refresh_token_url(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::RefreshTokenURL, value)
    }

    /// Set the redirect url of a request
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.redirect_uri("https://localhost:8888/redirect");
    /// ```
    pub fn redirect_uri(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::RedirectURI, value)
    }

    /// Set the access code.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.access_code("LDSF[POK43");
    /// ```
    pub fn access_code(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::AccessCode, value)
    }

    /// Set the response mode.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.response_mode("query");
    /// ```
    pub fn response_mode(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ResponseMode, value)
    }

    /// Set the response type.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.response_type("token");
    /// ```
    pub fn response_type(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ResponseType, value)
    }

    /// Set the nonce.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    ///
    /// # let mut oauth = OAuth::new();
    /// oauth.nonce("1234");
    /// ```
    pub fn nonce(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::Nonce, value)
    }

    /// Set the prompt for open id.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    ///
    /// # let mut oauth = OAuth::new();
    /// oauth.prompt("login");
    /// ```
    pub fn prompt(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::Prompt, value)
    }

    /// Set id token for open id.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::{OAuth, IdToken};
    /// # let mut oauth = OAuth::new();
    /// oauth.id_token(IdToken::new("1345", "code", "state", "session_state"));
    /// ```
    pub fn id_token(&mut self, value: IdToken) -> &mut OAuth {
        self.insert(OAuthCredential::IdToken, value.get_id_token().as_str());
        if let Some(code) = value.get_code() {
            self.access_code(code.as_str());
        }
        if let Some(state) = value.get_state() {
            let _ = self.entry(OAuthCredential::State, state.as_str());
        }
        if let Some(session_state) = value.get_session_state() {
            self.session_state(session_state.as_str());
        }
        self.insert(OAuthCredential::IdToken, value.get_id_token().as_str())
    }

    /// Set the session state.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.session_state("session-state");
    /// ```
    pub fn session_state(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::SessionState, value)
    }

    /// Set the grant_type.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.grant_type("token");
    /// ```
    pub fn grant_type(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::GrantType, value)
    }

    /// Set the resource.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.resource("resource");
    /// ```
    pub fn resource(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::Resource, value)
    }

    /// Set the code verifier.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.code_verifier("code_verifier");
    /// ```
    pub fn code_verifier(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::CodeVerifier, value)
    }

    /// Set the domain hint.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.domain_hint("domain_hint");
    /// ```
    pub fn domain_hint(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::DomainHint, value)
    }

    /// Set the code challenge.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.code_challenge("code_challenge");
    /// ```
    pub fn code_challenge(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::CodeChallenge, value)
    }

    /// Set the code challenge method.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.code_challenge_method("code_challenge_method");
    /// ```
    pub fn code_challenge_method(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::CodeChallengeMethod, value)
    }

    /// Generate a code challenge and code verifier for the
    /// authorization code grant flow using proof key for
    /// code exchange (PKCE) and SHA256.
    ///
    /// This method automatically sets the code_verifier,
    /// code_challenge, and code_challenge_method fields.
    ///
    /// For authorization, the code_challenge_method parameter in the request body
    /// is automatically set to 'S256'.
    ///
    /// Internally this method uses the Rust ring cyrpto library to
    /// generate a secure random 32-octet sequence that is base64 URL
    /// encoded (no padding). This sequence is hashed using SHA256 and
    /// base64 URL encoded (no padding) resulting in a 43-octet URL safe string.
    ///
    ///
    /// For more info on PKCE and entropy see: https://tools.ietf.org/html/rfc7636#section-7.1
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::OAuthCredential;
    ///
    /// let mut oauth = OAuth::new();
    /// oauth.generate_sha256_challenge_and_verifier();
    ///
    /// # assert!(oauth.contains(OAuthCredential::CodeChallenge));
    /// # assert!(oauth.contains(OAuthCredential::CodeVerifier));
    /// # assert!(oauth.contains(OAuthCredential::CodeChallengeMethod));
    /// println!("Code Challenge: {:#?}", oauth.get(OAuthCredential::CodeChallenge));
    /// println!("Code Verifier: {:#?}", oauth.get(OAuthCredential::CodeVerifier));
    /// println!("Code Challenge Method: {:#?}", oauth.get(OAuthCredential::CodeChallengeMethod));
    ///
    /// # let challenge = oauth.get(OAuthCredential::CodeChallenge).unwrap();
    /// # let mut context = ring::digest::Context::new(&ring::digest::SHA256);
    /// # context.update(oauth.get(OAuthCredential::CodeVerifier).unwrap().as_bytes());
    /// # let verifier = base64::encode_config(context.finish().as_ref(), base64::URL_SAFE_NO_PAD);
    /// # assert_eq!(challenge, verifier);
    ///```
    pub fn generate_sha256_challenge_and_verifier(&mut self) -> Result<(), GraphFailure> {
        let mut buf = [0; 32];
        let rng = ring::rand::SystemRandom::new();
        rng.fill(&mut buf)?;
        let verifier = base64::encode_config(&buf, base64::URL_SAFE_NO_PAD);
        let mut context = ring::digest::Context::new(&ring::digest::SHA256);
        context.update(&verifier.as_bytes());
        let code_challenge =
            base64::encode_config(context.finish().as_ref(), base64::URL_SAFE_NO_PAD);
        self.code_verifier(&verifier);
        self.code_challenge(&code_challenge);
        self.code_challenge_method("S256");
        Ok(())
    }

    /// Set the login hint.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.login_hint("login_hint");
    /// ```
    pub fn login_hint(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::LoginHint, value)
    }

    /// Set the client assertion.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.client_assertion("client_assertion");
    /// ```
    pub fn client_assertion(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ClientAssertion, value)
    }

    /// Set the client assertion type.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.client_assertion_type("client_assertion_type");
    /// ```
    pub fn client_assertion_type(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::ClientAssertionType, value)
    }

    /// Set the url to send a post request that will log out the user.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.logout_url("https://example.com/logout?");
    /// ```
    pub fn logout_url(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::LogoutURL, value)
    }

    /// Set the redirect uri that user will be redirected to after logging out.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// oauth.post_logout_redirect_uri("http://localhost:8080");
    /// ```
    pub fn post_logout_redirect_uri(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::PostLogoutRedirectURI, value)
    }

    /// Set the redirect uri that user will be redirected to after logging out.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::{OAuth, OAuthCredential};
    /// # let mut oauth = OAuth::new();
    /// oauth.username("user");
    /// assert!(oauth.contains(OAuthCredential::Username))
    /// ```
    pub fn username(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::Username, value)
    }

    /// Set the redirect uri that user will be redirected to after logging out.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::{OAuth, OAuthCredential};
    /// # let mut oauth = OAuth::new();
    /// oauth.password("user");
    /// assert!(oauth.contains(OAuthCredential::Password))
    /// ```
    pub fn password(&mut self, value: &str) -> &mut OAuth {
        self.insert(OAuthCredential::Password, value)
    }

    /// Add a scope' for the OAuth URL.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    ///
    /// oauth.add_scope("Sites.Read")
    ///     .add_scope("Sites.ReadWrite")
    ///     .add_scope("Sites.ReadWrite.All");
    /// assert_eq!(oauth.join_scopes(" "), "Sites.Read Sites.ReadWrite Sites.ReadWrite.All");
    /// ```
    pub fn add_scope<T: ToString>(&mut self, scope: T) -> &mut OAuth {
        self.scopes.insert(scope.to_string());
        self
    }

    /// Get the scopes.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// let mut oauth = OAuth::new();
    /// oauth.add_scope("Files.Read");
    /// oauth.add_scope("Files.ReadWrite");
    ///
    /// let scopes = oauth.get_scopes();
    /// assert!(scopes.contains("Files.Read"));
    /// assert!(scopes.contains("Files.ReadWrite"));
    /// ```
    pub fn get_scopes(&self) -> &BTreeSet<String> {
        &self.scopes
    }

    /// Join scopes.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    ///
    /// // the scopes take a separator just like Vec join.
    ///  let s = oauth.join_scopes(" ");
    /// println!("{:#?}", s);
    /// ```
    pub fn join_scopes(&self, sep: &str) -> String {
        self.scopes
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<&str>>()
            .join(sep)
    }

    /// Extend scopes.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use std::collections::HashSet;
    /// # let mut oauth = OAuth::new();
    ///
    /// let scopes1 = vec!["Files.Read", "Files.ReadWrite"];
    /// oauth.extend_scopes(&scopes1);
    ///
    /// assert_eq!(oauth.join_scopes(" "), "Files.Read Files.ReadWrite");
    /// ```
    pub fn extend_scopes<T: ToString, I: IntoIterator<Item = T>>(&mut self, iter: I) -> &mut Self {
        self.scopes.extend(iter.into_iter().map(|s| s.to_string()));
        self
    }

    /// Check if OAuth contains a specific scope.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    ///
    /// oauth.add_scope("Files.Read");
    /// assert_eq!(oauth.contains_scope("Files.Read"), true);
    ///
    /// // Or using static scopes
    /// oauth.add_scope("File.ReadWrite");
    /// assert!(oauth.contains_scope("File.ReadWrite"));
    /// ```
    pub fn contains_scope<T: ToString>(&self, scope: T) -> bool {
        self.scopes.contains(&scope.to_string())
    }

    /// Remove a previously added scope.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    ///
    /// oauth.add_scope("scope");
    /// # assert!(oauth.contains_scope("scope"));
    /// oauth.remove_scope("scope");
    ///# assert!(!oauth.contains_scope("scope"));
    /// ```
    pub fn remove_scope<T: AsRef<str>>(&mut self, scope: T) {
        self.scopes.remove(scope.as_ref());
    }

    /// Remove all scopes.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    ///
    /// oauth.add_scope("Files.Read").add_scope("Files.ReadWrite");
    /// assert_eq!("Files.Read Files.ReadWrite", oauth.join_scopes(" "));
    ///
    /// oauth.clear_scopes();
    /// assert!(oauth.get_scopes().is_empty());
    /// ```
    pub fn clear_scopes(&mut self) {
        self.scopes.clear();
    }

    /// Set the access token.
    ///
    /// # Example
    /// ```
    /// use graph_oauth::oauth::OAuth;
    /// use graph_oauth::oauth::AccessToken;
    /// let mut oauth = OAuth::new();
    /// let access_token = AccessToken::default();
    /// oauth.access_token(access_token);
    /// ```
    pub fn access_token(&mut self, ac: AccessToken) {
        self.access_token.replace(ac);
    }

    /// Get the access token.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::AccessToken;
    /// # let access_token = AccessToken::default();
    /// # let mut oauth = OAuth::new();
    /// # oauth.access_token(access_token);
    /// let access_token = oauth.get_access_token().unwrap();
    /// println!("{:#?}", access_token);
    /// ```
    pub fn get_access_token(&self) -> Option<AccessToken> {
        self.access_token.clone()
    }

    /// Get the refrsh token. This method returns the current refresh
    /// token stored in OAuth and does not make a request for a refresh
    /// token.
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # use graph_oauth::oauth::AccessToken;
    /// # let mut oauth = OAuth::new();
    /// let mut  access_token = AccessToken::default();
    /// access_token.set_refresh_token("refresh_token");
    /// oauth.access_token(access_token);
    ///
    /// let refresh_token = oauth.get_refresh_token().unwrap();
    /// println!("{:#?}", refresh_token);
    /// ```
    pub fn get_refresh_token(&self) -> OAuthReq<String> {
        match self.get_access_token() {
            Some(token) => match token.refresh_token() {
                Some(t) => Ok(t),
                None => OAuthError::error_from::<String>(OAuthCredential::RefreshToken),
            },
            None => OAuthError::error_from::<String>(OAuthCredential::AccessToken),
        }
    }

    pub fn build(&mut self) -> GrantSelector<AccessTokenGrant> {
        GrantSelector {
            oauth: self.clone(),
            t: PhantomData,
        }
    }

    pub fn build_async(&mut self) -> GrantSelector<AsyncAccessTokenGrant> {
        GrantSelector {
            oauth: self.clone(),
            t: PhantomData,
        }
    }

    /// Sign the user out using the OneDrive v1.0 endpoint.
    ///
    /// # Example
    /// ```rust,ignore
    /// use graph_oauth::oauth::OAuth;
    /// let mut oauth = OAuth::new();
    ///
    /// oauth.v1_logout().unwrap();
    /// ```
    pub fn v1_logout(&mut self) -> OAuthReq<Output> {
        let mut url = self.get_or_else(OAuthCredential::LogoutURL)?;
        if !url.ends_with('?') {
            url.push('?');
        }

        let mut vec = vec![
            url,
            "&client_id=".to_string(),
            self.get_or_else(OAuthCredential::ClientId)?,
            "&redirect_uri=".to_string(),
        ];

        if let Some(redirect) = self.get(OAuthCredential::PostLogoutRedirectURI) {
            vec.push(redirect)
        } else if let Some(redirect) = self.get(OAuthCredential::RedirectURI) {
            vec.push(redirect);
        }
        webbrowser::open(vec.join("").as_str()).map_err(GraphFailure::from)
    }

    /// Sign the user out using the OneDrive v2.0 endpoint.
    ///
    /// # Example
    /// ```rust,ignore
    /// use graph_oauth::oauth::OAuth;
    /// let mut oauth = OAuth::new();
    ///
    /// oauth.v2_logout().unwrap();
    /// ```
    pub fn v2_logout(&self) -> OAuthReq<Output> {
        let mut url = self.get_or_else(OAuthCredential::LogoutURL)?;
        if !url.ends_with('?') {
            url.push('?');
        }
        if let Some(redirect) = self.get(OAuthCredential::PostLogoutRedirectURI) {
            url.push_str("post_logout_redirect_uri=");
            url.push_str(redirect.as_str());
        } else {
            let redirect_uri = self.get_or_else(OAuthCredential::RedirectURI)?;
            url.push_str("post_logout_redirect_uri=");
            url.push_str(redirect_uri.as_str());
        }
        webbrowser::open(url.as_str()).map_err(GraphFailure::from)
    }
}

impl OAuth {
    fn get_or_else(&self, c: OAuthCredential) -> OAuthReq<String> {
        self.get(c).ok_or_else(|| OAuthError::credential_error(c))
    }

    fn form_encode_credentials(
        &mut self,
        pairs: Vec<OAuthCredential>,
        encoder: &mut Serializer<String>,
    ) {
        pairs
            .iter()
            .filter(|oac| self.contains_key(oac.alias()) || oac.alias().eq("scope"))
            .for_each(|oac| {
                if oac.alias().eq("scope") && !self.scopes.is_empty() {
                    encoder.append_pair("scope", self.join_scopes(" ").as_str());
                } else if let Some(val) = self.get(*oac) {
                    encoder.append_pair(oac.alias(), val.as_str());
                }
            });
    }

    pub fn params(&mut self, pairs: Vec<OAuthCredential>) -> OAuthReq<HashMap<String, String>> {
        let mut map: HashMap<String, String> = HashMap::new();
        for oac in pairs.iter() {
            if oac.eq(&OAuthCredential::RefreshToken) {
                map.insert("refresh_token".into(), self.get_refresh_token()?);
            } else if oac.alias().eq("scope") && !self.scopes.is_empty() {
                map.insert("scope".into(), self.join_scopes(" "));
            } else if let Some(val) = self.get(*oac) {
                map.insert(oac.to_string(), val);
            }
        }
        Ok(map)
    }

    pub fn encode_uri(&mut self, grant: GrantType, request_type: GrantRequest) -> OAuthReq<String> {
        let mut encoder = Serializer::new(String::new());
        match grant {
            GrantType::TokenFlow => match request_type {
                GrantRequest::Authorization => {
                    let _ = self.entry(OAuthCredential::ResponseType, "token");
                    self.form_encode_credentials(
                        GrantType::TokenFlow.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );
                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken | GrantRequest::RefreshToken => {
                    OAuthError::grant_error(
                        GrantType::TokenFlow,
                        GrantRequest::AccessToken,
                        "Grant type does not use request type. Please use OAuth::request_authorization() for browser requests"
                    )
                },
            },
            GrantType::CodeFlow => match request_type {
                GrantRequest::Authorization => {
                    let _ = self.entry(OAuthCredential::ResponseType, "code");
                    let _ = self.entry(OAuthCredential::ResponseMode, "query");
                    self.form_encode_credentials(
                        GrantType::CodeFlow.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );

                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken => {
                    let _ = self.entry(OAuthCredential::ResponseType, "token");
                    let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                    self.form_encode_credentials(
                        GrantType::CodeFlow.available_credentials(GrantRequest::AccessToken),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
                GrantRequest::RefreshToken => {
                    let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                    let refresh_token = self.get_refresh_token()?;
                    encoder.append_pair("refresh_token", &refresh_token);
                    self.form_encode_credentials(
                        GrantType::CodeFlow.available_credentials(GrantRequest::RefreshToken),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
            },
            GrantType::AuthorizationCode => match request_type {
                GrantRequest::Authorization => {
                    let _ = self.entry(OAuthCredential::ResponseType, "code");
                    let _ = self.entry(OAuthCredential::ResponseMode, "query");
                    self.form_encode_credentials(
                        GrantType::AuthorizationCode.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );
                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken | GrantRequest::RefreshToken => {
                    if request_type == GrantRequest::AccessToken {
                        let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                    } else {
                        let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                        encoder.append_pair("refresh_token", &self.get_refresh_token()?);
                    }
                    self.form_encode_credentials(
                        GrantType::AuthorizationCode.available_credentials(request_type),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
            },
            GrantType::Implicit => match request_type {
                GrantRequest::Authorization => {
                    if !self.scopes.is_empty() {
                        let _ = self.entry(OAuthCredential::ResponseType, "token");
                    }
                    self.form_encode_credentials(
                        GrantType::Implicit.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );
                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken | GrantRequest::RefreshToken => {
                    OAuthError::grant_error(
                        GrantType::Implicit,
                        GrantRequest::AccessToken,
                        "Grant type does not use request type. Please use OAuth::request_authorization() for browser requests"
                    )
                },
            },
            GrantType::OpenId => match request_type {
                GrantRequest::Authorization => {
                    self.form_encode_credentials(
                        GrantType::OpenId.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );

                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken => {
                    let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                    self.form_encode_credentials(
                        GrantType::OpenId.available_credentials(GrantRequest::AccessToken),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
                GrantRequest::RefreshToken => {
                    let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                    let refresh_token = self.get_refresh_token()?;
                    encoder.append_pair("refresh_token", &refresh_token);
                    self.form_encode_credentials(
                        GrantType::OpenId.available_credentials(GrantRequest::RefreshToken),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
            },
            GrantType::ClientCredentials => match request_type {
                GrantRequest::Authorization => {
                    self.form_encode_credentials(
                        GrantType::ClientCredentials.available_credentials(GrantRequest::Authorization),
                        &mut encoder,
                    );
                    let mut url = self.get_or_else(OAuthCredential::AuthorizeURL)?;
                    if !url.ends_with('?') {
                        url.push('?');
                    }
                    url.push_str(encoder.finish().as_str());
                    Ok(url)
                },
                GrantRequest::AccessToken | GrantRequest::RefreshToken => {
                    self.pre_request_check(GrantType::ClientCredentials, request_type);
                    self.form_encode_credentials(
                        GrantType::ClientCredentials.available_credentials(request_type),
                        &mut encoder,
                    );
                    Ok(encoder.finish())
                },
            },
            GrantType::ResourceOwnerPasswordCredentials => {
                self.pre_request_check(GrantType::ResourceOwnerPasswordCredentials, request_type);
                self.form_encode_credentials(
                    GrantType::ResourceOwnerPasswordCredentials.available_credentials(request_type),
                    &mut encoder,
                );
                Ok(encoder.finish())
            }
        }
    }

    fn pre_request_check(&mut self, grant: GrantType, request_type: GrantRequest) {
        match grant {
            GrantType::TokenFlow => {
                if request_type.eq(&GrantRequest::Authorization) {
                    let _ = self.entry(OAuthCredential::ResponseType, "token");
                }
            },
            GrantType::CodeFlow => match request_type {
                GrantRequest::Authorization => {
                    let _ = self.entry(OAuthCredential::ResponseType, "code");
                    let _ = self.entry(OAuthCredential::ResponseMode, "query");
                },
                GrantRequest::AccessToken => {
                    let _ = self.entry(OAuthCredential::ResponseType, "token");
                    let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                },
                GrantRequest::RefreshToken => {
                    let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                },
            },
            GrantType::AuthorizationCode => match request_type {
                GrantRequest::Authorization => {
                    let _ = self.entry(OAuthCredential::ResponseType, "code");
                    let _ = self.entry(OAuthCredential::ResponseMode, "query");
                },
                GrantRequest::AccessToken | GrantRequest::RefreshToken => {
                    if request_type == GrantRequest::AccessToken {
                        let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                    } else {
                        let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                    }
                },
            },
            GrantType::Implicit => {
                if request_type.eq(&GrantRequest::Authorization) && !self.scopes.is_empty() {
                    let _ = self.entry(OAuthCredential::ResponseType, "token");
                }
            },
            GrantType::OpenId => {
                if request_type.eq(&GrantRequest::AccessToken) {
                    let _ = self.entry(OAuthCredential::GrantType, "authorization_code");
                } else if request_type.eq(&GrantRequest::RefreshToken) {
                    let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                }
            },
            GrantType::ClientCredentials => {
                if request_type.eq(&GrantRequest::AccessToken) ||
                    request_type.eq(&GrantRequest::RefreshToken)
                {
                    let _ = self.entry(OAuthCredential::GrantType, "client_credentials");
                }
            },
            GrantType::ResourceOwnerPasswordCredentials => {
                if request_type.eq(&GrantRequest::RefreshToken) {
                    let _ = self.entry(OAuthCredential::GrantType, "refresh_token");
                } else {
                    let _ = self.entry(OAuthCredential::GrantType, "password");
                }
            },
        }
    }
}

/// Extend the OAuth credentials.
///
/// # Example
/// ```
/// # use graph_oauth::oauth::{OAuth, OAuthCredential};
/// # use std::collections::HashMap;
/// # let mut oauth = OAuth::new();
/// let mut map: HashMap<OAuthCredential, &str> = HashMap::new();
/// map.insert(OAuthCredential::ClientId, "client_id");
/// map.insert(OAuthCredential::ClientSecret, "client_secret");
///
/// oauth.extend(map);
/// # assert_eq!(oauth.get(OAuthCredential::ClientId), Some("client_id".to_string()));
/// # assert_eq!(oauth.get(OAuthCredential::ClientSecret), Some("client_secret".to_string()));
/// ```
impl<V: ToString> Extend<(OAuthCredential, V)> for OAuth {
    fn extend<I: IntoIterator<Item = (OAuthCredential, V)>>(&mut self, iter: I) {
        iter.into_iter().for_each(|entry| {
            self.insert(entry.0, entry.1);
        });
    }
}

pub struct GrantSelector<T> {
    oauth: OAuth,
    t: PhantomData<T>,
}

impl GrantSelector<AccessTokenGrant> {
    /// Create a new instance for token flow.
    ///
    /// # See
    /// [Microsoft Token Flow Authorizaiton](https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth?view=odsp-graph-online)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().token_flow();
    /// ```
    pub fn token_flow(self) -> ImplicitGrant {
        ImplicitGrant {
            oauth: self.oauth,
            grant: GrantType::TokenFlow,
        }
    }

    /// Create a new instance for code flow.
    ///
    /// # See
    /// [Microsoft Code Flow Authorizaiton](https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth?view=odsp-graph-online)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().code_flow();
    /// ```
    pub fn code_flow(self) -> AccessTokenGrant {
        AccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::CodeFlow,
        }
    }

    /// Create a new instance for the implicit grant.
    ///
    /// # See
    /// [Implicit Grant for OAuth 2.0](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().implicit_grant();
    /// ```
    pub fn implicit_grant(self) -> ImplicitGrant {
        ImplicitGrant {
            oauth: self.oauth,
            grant: GrantType::Implicit,
        }
    }

    /// Create a new instance for authorization code grant.
    ///
    /// # See
    /// [Authorization Code Grant for OAuth 2.0](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().authorization_code_grant();
    /// ```
    pub fn authorization_code_grant(self) -> AccessTokenGrant {
        AccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::AuthorizationCode,
        }
    }

    /// Create a new instance for the open id connect grant.
    ///
    /// # See
    /// [Microsoft Open ID Connect](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().open_id_connect();
    /// ```
    pub fn open_id_connect(self) -> AccessTokenGrant {
        AccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::OpenId,
        }
    }

    /// Create a new instance for the open id connect grant.
    ///
    /// # See
    /// [Microsoft Client Credentials](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().client_credentials();
    /// ```
    pub fn client_credentials(self) -> AccessTokenGrant {
        AccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::ClientCredentials,
        }
    }

    /// Create a new instance for the resource owner password credentials grant.
    ///
    /// # See
    /// [Microsoft Resource Owner Password Credentials](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().resource_owner_password_credentials();
    /// ```
    pub fn resource_owner_password_credentials(self) -> AccessTokenGrant {
        AccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::ResourceOwnerPasswordCredentials,
        }
    }
}

impl GrantSelector<AsyncAccessTokenGrant> {
    /// Create a new instance for token flow.
    ///
    /// # See
    /// [Microsoft Token Flow Authorizaiton](https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth?view=odsp-graph-online)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().token_flow();
    /// ```
    pub fn token_flow(self) -> ImplicitGrant {
        ImplicitGrant {
            oauth: self.oauth,
            grant: GrantType::TokenFlow,
        }
    }

    /// Create a new instance for code flow.
    ///
    /// # See
    /// [Microsoft Code Flow Authorizaiton](https://docs.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth?view=odsp-graph-online)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().code_flow();
    /// ```
    pub fn code_flow(self) -> AsyncAccessTokenGrant {
        AsyncAccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::CodeFlow,
        }
    }

    /// Create a new instance for the implicit grant.
    ///
    /// # See
    /// [Implicit Grant for OAuth 2.0](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().implicit_grant();
    /// ```
    pub fn implicit_grant(self) -> ImplicitGrant {
        ImplicitGrant {
            oauth: self.oauth,
            grant: GrantType::Implicit,
        }
    }

    /// Create a new instance for authorization code grant.
    ///
    /// # See
    /// [Authorization Code Grant for OAuth 2.0](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().authorization_code_grant();
    /// ```
    pub fn authorization_code_grant(self) -> AsyncAccessTokenGrant {
        AsyncAccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::AuthorizationCode,
        }
    }

    /// Create a new instance for the open id connect grant.
    ///
    /// # See
    /// [Microsoft Open ID Connect](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().open_id_connect();
    /// ```
    pub fn open_id_connect(self) -> AsyncAccessTokenGrant {
        AsyncAccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::OpenId,
        }
    }

    /// Create a new instance for the open id connect grant.
    ///
    /// # See
    /// [Microsoft Client Credentials](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().client_credentials();
    /// ```
    pub fn client_credentials(self) -> AsyncAccessTokenGrant {
        AsyncAccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::ClientCredentials,
        }
    }

    /// Create a new instance for the resource owner password credentials grant.
    ///
    /// # See
    /// [Microsoft Resource Owner Password Credentials](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc)
    ///
    /// # Example
    /// ```
    /// # use graph_oauth::oauth::OAuth;
    /// # let mut oauth = OAuth::new();
    /// let open_id = oauth.build().resource_owner_password_credentials();
    /// ```
    pub fn resource_owner_password_credentials(self) -> AsyncAccessTokenGrant {
        AsyncAccessTokenGrant {
            oauth: self.oauth,
            grant: GrantType::ResourceOwnerPasswordCredentials,
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AuthorizationRequest {
    uri: String,
}

impl AuthorizationRequest {
    pub fn open(&self) -> OAuthReq<Output> {
        webbrowser::open(self.uri.as_str()).map_err(GraphFailure::from)
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AccessTokenRequest {
    uri: String,
    params: HashMap<String, String>,
}

impl AccessTokenRequest {
    /// Send the request for an access token. The response body
    /// be will converted to an access token and returned.
    pub fn send(&mut self) -> OAuthReq<AccessToken> {
        let client = reqwest::blocking::Client::new();
        let builder = client.post(self.uri.as_str()).form(&self.params);
        AccessToken::try_from(builder)
    }

    /// Send the request for an access token. This method
    /// can be used to convert response bodies to custom
    /// objects using the serde crate. The object must implement
    /// serde deserialize.
    pub fn json<T>(&mut self) -> OAuthReq<T>
    where
        for<'de> T: serde::Deserialize<'de>,
    {
        let client = reqwest::blocking::Client::new();
        let builder = client.post(self.uri.as_str()).form(&self.params);
        let response = builder.send()?;
        Ok(response.json()?)
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AsyncAccessTokenRequest {
    uri: String,
    params: HashMap<String, String>,
}

impl AsyncAccessTokenRequest {
    /// Send the request for an access token. The response body
    /// be will converted to an access token and returned.
    pub async fn send(&mut self) -> OAuthReq<AccessToken> {
        let client = reqwest::Client::new();
        let builder = client.post(self.uri.as_str()).form(&self.params);
        AccessToken::try_from_async(builder).await
    }

    /// Send the request for an access token. This method
    /// can be used to convert response bodies to custom
    /// objects using the serde crate. The object must implement
    /// serde deserialize.
    pub async fn json<T>(&mut self) -> OAuthReq<T>
    where
        for<'de> T: serde::Deserialize<'de>,
    {
        let client = reqwest::Client::new();
        let builder = client.post(self.uri.as_str()).form(&self.params);
        let response = builder.send().await?;
        Ok(response.json().await?)
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct ImplicitGrant {
    oauth: OAuth,
    grant: GrantType,
}

impl ImplicitGrant {
    pub fn url(&mut self) -> Url {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::Authorization);
        Url::parse(
            self.oauth
                .get_or_else(OAuthCredential::AuthorizeURL)
                .unwrap()
                .as_str(),
        )
        .unwrap()
    }

    pub fn browser_authorization(&mut self) -> AuthorizationRequest {
        let params = self
            .oauth
            .params(
                self.grant
                    .available_credentials(GrantRequest::Authorization),
            )
            .unwrap();
        let mut url = self.url();
        url.query_pairs_mut().extend_pairs(&params);
        AuthorizationRequest {
            uri: url.to_string(),
        }
    }
}

impl From<ImplicitGrant> for OAuth {
    fn from(token_grant: ImplicitGrant) -> Self {
        token_grant.oauth
    }
}

impl AsRef<OAuth> for ImplicitGrant {
    fn as_ref(&self) -> &OAuth {
        &self.oauth
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AccessTokenGrant {
    oauth: OAuth,
    grant: GrantType,
}

impl AccessTokenGrant {
    pub fn authorization_url(&mut self) -> Url {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::Authorization);
        let params = self
            .oauth
            .params(
                self.grant
                    .available_credentials(GrantRequest::Authorization),
            )
            .unwrap();
        let mut url = Url::parse(
            self.oauth
                .get_or_else(OAuthCredential::AuthorizeURL)
                .unwrap()
                .as_str(),
        )
        .unwrap();
        url.query_pairs_mut().extend_pairs(&params);
        url
    }

    /// Make a request for authorization. The default browser for a user
    /// will be opened to the sign in page where the user will need to
    /// sign in and agree to any permissions that were set by the provided
    /// scopes.
    pub fn browser_authorization(&mut self) -> AuthorizationRequest {
        AuthorizationRequest {
            uri: self.authorization_url().to_string(),
        }
    }

    /// Make a request for an access token. The token is stored in OAuth and
    /// will be used to make for making requests for refresh tokens. The below
    /// example shows how access tokens are stored and retrieved for OAuth:
    /// # Example
    /// ```rust,ignore
    /// # use graph_oauth::oauth::{OAuth, AccessToken};
    /// let mut oauth: OAuth = OAuth::new();
    ///
    /// // As an example create a random access token.
    /// let mut access_token = AccessToken::default();
    /// access_token.access_token("12345");
    /// // Store the token in OAuth if the access token has a refresh token.
    /// // The refresh token can be later used to request more access tokens.
    /// oauth.access_token(access_token);
    /// // You can get the actual bearer token if needed:
    /// println!("{:#?}", oauth.get_access_token().unwrap().get_access_token());
    /// ```
    ///
    /// Request an access token.
    /// # Example
    /// ```rust,ignore
    /// use graph_oauth::oauth::{Grant, OAuth};
    /// let mut oauth: OAuth = OAuth::new();
    ///
    /// // This assumes the user has been authenticated and
    /// // the access_code from the request has been given:
    /// oauth.access_code("access_code");
    ///
    /// // To get an access token a access_token_url is needed and the grant_type
    /// // should be set to token.
    /// // There are other parameters that may need to be included depending on the
    /// // authorization flow chosen.
    /// // The url below is for the v1.0 drive API. You can also use the Graph URLs as well.
    /// oauth.access_token_url("https://login.live.com/oauth20_token.srf")
    ///     .response_type("token")
    ///     .grant_type("authorization_code");
    ///
    /// // Make a request for an access token.
    /// let mut request = oauth.build().authorization_code_grant();
    /// let access_token = request.access_token().send().unwrap();
    /// println!("{:#?}", access_token);
    /// ```
    pub fn access_token(&mut self) -> AccessTokenRequest {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::AccessToken);
        AccessTokenRequest {
            uri: self
                .oauth
                .get_or_else(OAuthCredential::AccessTokenURL)
                .unwrap(),
            params: self
                .oauth
                .params(self.grant.available_credentials(GrantRequest::AccessToken))
                .unwrap(),
        }
    }

    /// Request a refresh token. Assumes an access token has already
    /// been retrieved.
    pub fn refresh_token(&mut self) -> AccessTokenRequest {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::RefreshToken);
        AccessTokenRequest {
            uri: self
                .oauth
                .get_or_else(OAuthCredential::RefreshTokenURL)
                .unwrap(),
            params: self
                .oauth
                .params(self.grant.available_credentials(GrantRequest::RefreshToken))
                .unwrap(),
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, AsFile, FromFile)]
pub struct AsyncAccessTokenGrant {
    oauth: OAuth,
    grant: GrantType,
}

impl AsyncAccessTokenGrant {
    pub fn authorization_url(&mut self) -> Url {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::Authorization);
        let params = self
            .oauth
            .params(
                self.grant
                    .available_credentials(GrantRequest::Authorization),
            )
            .unwrap();
        let mut url = Url::parse(
            self.oauth
                .get_or_else(OAuthCredential::AuthorizeURL)
                .unwrap()
                .as_str(),
        )
        .unwrap();
        url.query_pairs_mut().extend_pairs(&params);
        url
    }

    /// Make a request for authorization. The default browser for a user
    /// will be opened to the sign in page where the user will need to
    /// sign in and agree to any permissions that were set by the provided
    /// scopes.
    pub fn browser_authorization(&mut self) -> AuthorizationRequest {
        AuthorizationRequest {
            uri: self.authorization_url().to_string(),
        }
    }

    /// Make a request for an access token. The token is stored in OAuth and
    /// will be used to make for making requests for refresh tokens. The below
    /// example shows how access tokens are stored and retrieved for OAuth:
    /// # Example
    /// ```rust,ignore
    /// # use graph_oauth::oauth::{OAuth, AccessToken};
    /// let mut oauth: OAuth = OAuth::new();
    ///
    /// // As an example create a random access token.
    /// let mut access_token = AccessToken::default();
    /// access_token.access_token("12345");
    /// // Store the token in OAuth if the access token has a refresh token.
    /// // The refresh token can be later used to request more access tokens.
    /// oauth.access_token(access_token);
    /// // You can get the actual bearer token if needed:
    /// println!("{:#?}", oauth.get_access_token().unwrap().get_access_token());
    /// ```
    ///
    /// Request an access token.
    /// # Example
    /// ```rust,ignore
    /// use graph_oauth::oauth::{Grant, OAuth};
    /// let mut oauth: OAuth = OAuth::new();
    ///
    /// // This assumes the user has been authenticated and
    /// // the access_code from the request has been given:
    /// oauth.access_code("access_code");
    ///
    /// // To get an access token a access_token_url is needed and the grant_type
    /// // should be set to token.
    /// // There are other parameters that may need to be included depending on the
    /// // authorization flow chosen.
    /// // The url below is for the v1.0 drive API. You can also use the Graph URLs as well.
    /// oauth.access_token_url("https://login.live.com/oauth20_token.srf")
    ///     .response_type("token")
    ///     .grant_type("authorization_code");
    ///
    /// // Make a request for an access token.
    /// let mut request = oauth.build().authorization_code_grant();
    /// let access_token = request.access_token().send().unwrap();
    /// println!("{:#?}", access_token);
    /// ```
    pub fn access_token(&mut self) -> AsyncAccessTokenRequest {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::AccessToken);
        AsyncAccessTokenRequest {
            uri: self
                .oauth
                .get_or_else(OAuthCredential::AccessTokenURL)
                .unwrap(),
            params: self
                .oauth
                .params(self.grant.available_credentials(GrantRequest::AccessToken))
                .unwrap(),
        }
    }

    /// Request a refresh token. Assumes an access token has already
    /// been retrieved.
    pub fn refresh_token(&mut self) -> AsyncAccessTokenRequest {
        self.oauth
            .pre_request_check(self.grant, GrantRequest::RefreshToken);
        AsyncAccessTokenRequest {
            uri: self
                .oauth
                .get_or_else(OAuthCredential::RefreshTokenURL)
                .unwrap(),
            params: self
                .oauth
                .params(self.grant.available_credentials(GrantRequest::RefreshToken))
                .unwrap(),
        }
    }
}

impl From<AccessTokenGrant> for OAuth {
    fn from(token_grant: AccessTokenGrant) -> Self {
        token_grant.oauth
    }
}

impl AsRef<OAuth> for AccessTokenGrant {
    fn as_ref(&self) -> &OAuth {
        &self.oauth
    }
}

impl fmt::Debug for OAuth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut map_debug: BTreeMap<&str, &str> = BTreeMap::new();
        for (key, value) in self.credentials.iter() {
            if let Some(oac) = OAuthCredential::iter()
                .find(|oac| oac.alias().eq(key.as_str()) && oac.is_debug_redacted())
            {
                map_debug.insert(oac.alias(), "[REDACTED]");
            } else {
                map_debug.insert(key.as_str(), value.as_str());
            }
        }

        f.debug_struct("AccessToken")
            .field("access_token", &"[REDACTED]".to_string())
            .field("credentials", &map_debug)
            .field("scopes", &self.scopes)
            .finish()
    }
}