openauth_social_providers/
github.rs1use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use openauth_oauth::oauth2::{
7 create_authorization_code_request, create_authorization_url, refresh_access_token,
8 validate_authorization_code, AuthorizationCodeRequest, AuthorizationUrlRequest,
9 ClientAuthentication, ClientTokenRequest, OAuth2Tokens, OAuth2UserInfo, OAuthError,
10 OAuthFormRequest, OAuthProviderContract, ProviderOptions, RefreshAccessTokenRequest,
11};
12use serde::{Deserialize, Deserializer, Serialize};
13use serde_json::Value;
14use url::Url;
15
16const DEFAULT_SCOPES: &[&str] = &["read:user", "user:email"];
17const AUTHORIZATION_ENDPOINT: &str = "https://github.com/login/oauth/authorize";
18const TOKEN_ENDPOINT: &str = "https://github.com/login/oauth/access_token";
19const USER_ENDPOINT: &str = "https://api.github.com/user";
20const EMAILS_ENDPOINT: &str = "https://api.github.com/user/emails";
21const USER_AGENT: &str = "better-auth";
22
23type UserMapper = Arc<dyn Fn(&GitHubProfile) -> OAuth2UserInfo + Send + Sync>;
24
25#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
27pub struct GitHubProfile {
28 #[serde(default)]
29 pub login: String,
30 #[serde(default, deserialize_with = "deserialize_string_or_number")]
31 pub id: String,
32 #[serde(default)]
33 pub node_id: Option<String>,
34 #[serde(default)]
35 pub avatar_url: Option<String>,
36 #[serde(default)]
37 pub gravatar_id: Option<String>,
38 #[serde(default)]
39 pub url: Option<String>,
40 #[serde(default)]
41 pub html_url: Option<String>,
42 #[serde(default)]
43 pub followers_url: Option<String>,
44 #[serde(default)]
45 pub following_url: Option<String>,
46 #[serde(default)]
47 pub gists_url: Option<String>,
48 #[serde(default)]
49 pub starred_url: Option<String>,
50 #[serde(default)]
51 pub subscriptions_url: Option<String>,
52 #[serde(default)]
53 pub organizations_url: Option<String>,
54 #[serde(default)]
55 pub repos_url: Option<String>,
56 #[serde(default)]
57 pub events_url: Option<String>,
58 #[serde(default)]
59 pub received_events_url: Option<String>,
60 #[serde(rename = "type", default)]
61 pub profile_type: Option<String>,
62 #[serde(default)]
63 pub site_admin: Option<bool>,
64 #[serde(default)]
65 pub name: Option<String>,
66 #[serde(default)]
67 pub company: Option<String>,
68 #[serde(default)]
69 pub blog: Option<String>,
70 #[serde(default)]
71 pub location: Option<String>,
72 #[serde(default)]
73 pub email: Option<String>,
74 #[serde(default)]
75 pub hireable: Option<bool>,
76 #[serde(default)]
77 pub bio: Option<String>,
78 #[serde(default)]
79 pub twitter_username: Option<String>,
80 #[serde(flatten)]
81 pub extra: BTreeMap<String, Value>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct GitHubEmail {
87 pub email: String,
88 #[serde(default)]
89 pub primary: bool,
90 #[serde(default)]
91 pub verified: bool,
92 #[serde(default)]
93 pub visibility: Option<String>,
94}
95
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98pub struct GitHubUserInfo {
99 pub user: OAuth2UserInfo,
100 pub data: GitHubProfile,
101}
102
103#[derive(Clone, Default)]
105pub struct GitHubOptions {
106 pub oauth: ProviderOptions,
107 pub map_profile_to_user: Option<UserMapper>,
108}
109
110impl From<ProviderOptions> for GitHubOptions {
111 fn from(oauth: ProviderOptions) -> Self {
112 Self {
113 oauth,
114 map_profile_to_user: None,
115 }
116 }
117}
118
119#[derive(Debug, Clone, Default, PartialEq, Eq)]
121pub struct GitHubAuthorizationUrlRequest {
122 pub state: String,
123 pub scopes: Vec<String>,
124 pub login_hint: Option<String>,
125 pub code_verifier: Option<String>,
126 pub redirect_uri: String,
127}
128
129#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct GitHubValidateAuthorizationCodeRequest {
132 pub code: String,
133 pub code_verifier: Option<String>,
134 pub redirect_uri: String,
135}
136
137#[derive(Clone)]
139pub struct GitHubProvider {
140 options: GitHubOptions,
141}
142
143impl GitHubProvider {
144 pub fn new(options: impl Into<GitHubOptions>) -> Self {
145 Self {
146 options: options.into(),
147 }
148 }
149
150 pub fn options(&self) -> &GitHubOptions {
151 &self.options
152 }
153
154 pub fn provider_options(&self) -> &ProviderOptions {
155 &self.options.oauth
156 }
157
158 pub fn create_authorization_url(
159 &self,
160 input: GitHubAuthorizationUrlRequest,
161 ) -> Result<Url, OAuthError> {
162 let mut scopes = Vec::new();
163 if !self.options.oauth.disable_default_scope {
164 scopes.extend(DEFAULT_SCOPES.iter().map(|scope| (*scope).to_owned()));
165 }
166 scopes.extend(self.options.oauth.scope.iter().cloned());
167 scopes.extend(input.scopes);
168
169 create_authorization_url(AuthorizationUrlRequest {
170 id: self.id().to_owned(),
171 options: self.options.oauth.clone(),
172 authorization_endpoint: AUTHORIZATION_ENDPOINT.to_owned(),
173 scopes,
174 state: input.state,
175 code_verifier: input.code_verifier,
176 redirect_uri: input.redirect_uri,
177 login_hint: input.login_hint,
178 prompt: self.options.oauth.prompt.clone(),
179 ..AuthorizationUrlRequest::default()
180 })
181 }
182
183 pub fn create_authorization_code_request(
184 &self,
185 input: GitHubValidateAuthorizationCodeRequest,
186 ) -> Result<OAuthFormRequest, OAuthError> {
187 create_authorization_code_request(AuthorizationCodeRequest {
188 code: input.code,
189 code_verifier: input.code_verifier,
190 redirect_uri: input.redirect_uri,
191 options: self.options.oauth.clone(),
192 authentication: ClientAuthentication::Post,
193 ..AuthorizationCodeRequest::default()
194 })
195 }
196
197 pub async fn validate_authorization_code(
198 &self,
199 input: GitHubValidateAuthorizationCodeRequest,
200 ) -> Result<OAuth2Tokens, OAuthError> {
201 validate_authorization_code(ClientTokenRequest {
202 token_endpoint: TOKEN_ENDPOINT.to_owned(),
203 request: AuthorizationCodeRequest {
204 code: input.code,
205 code_verifier: input.code_verifier,
206 redirect_uri: input.redirect_uri,
207 options: self.options.oauth.clone(),
208 authentication: ClientAuthentication::Post,
209 ..AuthorizationCodeRequest::default()
210 },
211 })
212 .await
213 }
214
215 pub async fn refresh_access_token(
216 &self,
217 refresh_token_value: impl Into<String>,
218 ) -> Result<OAuth2Tokens, OAuthError> {
219 refresh_access_token(ClientTokenRequest {
220 token_endpoint: TOKEN_ENDPOINT.to_owned(),
221 request: RefreshAccessTokenRequest {
222 refresh_token: refresh_token_value.into(),
223 options: self.options.oauth.clone(),
224 authentication: ClientAuthentication::Post,
225 ..RefreshAccessTokenRequest::default()
226 },
227 })
228 .await
229 }
230
231 pub async fn get_user_info(
232 &self,
233 token: &OAuth2Tokens,
234 ) -> Result<Option<GitHubUserInfo>, OAuthError> {
235 let Some(access_token) = token.access_token.as_deref() else {
236 return Ok(None);
237 };
238
239 let client = reqwest::Client::new();
240 let Some(profile) = fetch_github_profile(&client, access_token).await else {
241 return Ok(None);
242 };
243 let emails = fetch_github_emails(&client, access_token)
244 .await
245 .unwrap_or_default();
246
247 let mut user_info = map_github_user_info(profile, &emails);
248 if let Some(mapper) = &self.options.map_profile_to_user {
249 user_info.user = mapper(&user_info.data);
250 }
251
252 Ok(Some(user_info))
253 }
254}
255
256impl OAuthProviderContract for GitHubProvider {
257 fn id(&self) -> &str {
258 "github"
259 }
260
261 fn name(&self) -> &str {
262 "GitHub"
263 }
264}
265
266pub fn github(options: impl Into<GitHubOptions>) -> GitHubProvider {
267 GitHubProvider::new(options)
268}
269
270pub fn map_github_user_info(mut profile: GitHubProfile, emails: &[GitHubEmail]) -> GitHubUserInfo {
271 if profile.email.is_none() {
272 profile.email = emails
273 .iter()
274 .find(|email| email.primary)
275 .or_else(|| emails.first())
276 .map(|email| email.email.clone());
277 }
278
279 let email_verified = profile
280 .email
281 .as_deref()
282 .and_then(|profile_email| {
283 emails
284 .iter()
285 .find(|email| email.email == profile_email)
286 .map(|email| email.verified)
287 })
288 .unwrap_or(false);
289
290 let name = profile
291 .name
292 .as_deref()
293 .filter(|name| !name.is_empty())
294 .unwrap_or(&profile.login)
295 .to_owned();
296
297 GitHubUserInfo {
298 user: OAuth2UserInfo {
299 id: profile.id.clone(),
300 name: Some(name),
301 email: profile.email.clone(),
302 image: profile.avatar_url.clone(),
303 email_verified,
304 },
305 data: profile,
306 }
307}
308
309async fn fetch_github_profile(
310 client: &reqwest::Client,
311 access_token: &str,
312) -> Option<GitHubProfile> {
313 client
314 .get(USER_ENDPOINT)
315 .bearer_auth(access_token)
316 .header("user-agent", USER_AGENT)
317 .send()
318 .await
319 .ok()?
320 .error_for_status()
321 .ok()?
322 .json::<GitHubProfile>()
323 .await
324 .ok()
325}
326
327async fn fetch_github_emails(
328 client: &reqwest::Client,
329 access_token: &str,
330) -> Option<Vec<GitHubEmail>> {
331 client
332 .get(EMAILS_ENDPOINT)
333 .bearer_auth(access_token)
334 .header("user-agent", USER_AGENT)
335 .send()
336 .await
337 .ok()?
338 .error_for_status()
339 .ok()?
340 .json::<Vec<GitHubEmail>>()
341 .await
342 .ok()
343}
344
345fn deserialize_string_or_number<'de, D>(deserializer: D) -> Result<String, D::Error>
346where
347 D: Deserializer<'de>,
348{
349 let value = Option::<Value>::deserialize(deserializer)?;
350 Ok(match value {
351 Some(Value::String(value)) => value,
352 Some(Value::Number(value)) => value.to_string(),
353 Some(other) => other.to_string(),
354 None => String::new(),
355 })
356}