1use renox::http::Http;
5use renox::prelude::*;
6use serde::Deserialize;
7
8use crate::provider::get_json;
9use crate::{BoxFuture, Credentials, Profile, Provider, Token};
10
11pub const USER: &str = "https://api.github.com/user";
13pub const EMAILS: &str = "https://api.github.com/user/emails";
15const ACCEPT: &str = "application/vnd.github+json";
16
17#[derive(Debug, Clone)]
20pub struct GitHub {
21 credentials: Credentials,
22}
23
24impl GitHub {
25 pub fn from_config() -> Self {
27 Self {
28 credentials: Credentials::from_config("GITHUB"),
29 }
30 }
31
32 pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
34 Self {
35 credentials: Credentials::new(client_id, client_secret),
36 }
37 }
38}
39
40#[derive(Deserialize)]
41struct User {
42 id: i64,
43 login: String,
44 name: Option<String>,
45 email: Option<String>,
46 avatar_url: Option<String>,
47}
48
49#[derive(Deserialize)]
50struct Email {
51 email: String,
52 #[serde(default)]
53 primary: bool,
54 #[serde(default)]
55 verified: bool,
56}
57
58impl Provider for GitHub {
59 fn name(&self) -> &str {
60 "github"
61 }
62
63 fn label(&self) -> &str {
64 "GitHub"
65 }
66
67 fn credentials(&self) -> &Credentials {
68 &self.credentials
69 }
70
71 fn authorize_endpoint(&self) -> &str {
72 "https://github.com/login/oauth/authorize"
73 }
74
75 fn token_endpoint(&self) -> &str {
76 "https://github.com/login/oauth/access_token"
77 }
78
79 fn scopes(&self) -> &[&str] {
80 &["read:user", "user:email"]
81 }
82
83 fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>> {
84 Box::pin(async move {
85 let user: User = get_json(http, USER, token, ACCEPT).await?;
86 let emails: Vec<Email> = get_json(http, EMAILS, token, ACCEPT)
90 .await
91 .unwrap_or_default();
92 let verified = emails
93 .iter()
94 .find(|e| e.primary && e.verified)
95 .or_else(|| emails.iter().find(|e| e.verified));
96 let mut profile = Profile::new(user.id.to_string());
97 if let Some(email) = verified {
98 profile = profile.email(email.email.clone(), true);
99 } else if let Some(email) = user.email {
100 profile = profile.email(email, false);
101 }
102 let name = user.name.or(Some(user.login));
103 Ok(profile.name(name).avatar(user.avatar_url))
104 })
105 }
106}