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
use async_trait::async_trait;
use oauth2::{
    AuthorizationCode,
    AuthUrl,
    basic::BasicClient,
    ClientId,
    ClientSecret,
    RequestTokenError,
    reqwest::async_http_client,
    reqwest::Error,
    TokenResponse,
    TokenUrl,
};
use reqwest::header::HeaderMap;
use serde::Deserialize;

pub struct Client {
    cli: BasicClient,
    http_cli: reqwest::Client,
}

#[derive(Debug, Deserialize)]
pub struct User {
    pub id: i64,
    pub login: String,
    pub name: String,
}

#[derive(Debug, Deserialize)]
pub struct Organization {
    pub id: i64,
    pub login: String,
    pub name: String,
}

impl Client {
    pub fn new(client_id: &str, client_secret: &str) -> Self {
        let cli = BasicClient::new(
            ClientId::new(client_id.to_string()),
            Some(ClientSecret::new(client_secret.to_string())),
            AuthUrl::new("https://github.com/login/oauth/access_token".to_string()).unwrap(),
            Some(TokenUrl::new("https://github.com/login/oauth/access_token".to_string()).unwrap()),
        );

        let mut headers = HeaderMap::new();
        headers.insert("User-Agent", "HiAuth".parse().unwrap());
        let http_cli = reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .unwrap();
        Self { cli, http_cli }
    }

    pub async fn login(&self, code: &str) -> super::Result<String> {
        Ok(self
            .cli
            .exchange_code(AuthorizationCode::new(code.to_string()))
            .request_async(async_http_client)
            .await
            .map(|resp| resp.access_token().secret().to_string())
            .map_err(|e| {
                match e {
                    RequestTokenError::ServerResponse(e) => {
                        super::Error(e.to_string())
                    }
                    RequestTokenError::Request(r) => {
                        match r {
                            Error::Reqwest(e) => {
                                super::Error(e.to_string())
                            }
                            e => {
                                super::Error(e.to_string())
                            }
                        }
                    }
                    e => {
                        super::Error(e.to_string())
                    }
                }
            })?)
    }

    pub async fn user(&self, access_token: &str) -> super::Result<User> {
        Ok(self
            .http_cli
            .get("https://api.github.com/user")
            .bearer_auth(&access_token)
            .send()
            .await?
            .json::<User>()
            .await?)
    }
    pub async fn orgs(&self, access_token: &str) -> super::Result<Vec<Organization>> {
        Ok(self
            .http_cli
            .get("https://api.github.com/user/orgs")
            .bearer_auth(&access_token)
            .send()
            .await?
            .json::<Vec<Organization>>()
            .await?)
    }
}

#[async_trait]
impl super::Profile for Client {
    async fn userinfo(&self, code: &str) -> crate::Result<super::Userinfo> {
        let at = self.login(code).await?;
        let user = self.user(&at).await?;
        let orgs = self.orgs(&at).await?;
        Ok(super::Userinfo {
            unique_id: user.id.to_string(),
            name: user.name,
            account: user.login,
            email: None,
            organization: Some(orgs.into_iter().map(|e| super::Organization {
                unique_id: e.id.to_string(),
                name: e.name,
                account: e.login,
            }).collect()),
        })
    }
}