Skip to content

Commit 86f1d08

Browse files
committed
use installation token for github auth
1 parent 9d92e90 commit 86f1d08

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/auth/github.rs

+43
Original file line numberDiff line numberDiff line change
@@ -194,4 +194,47 @@ impl GithubClient {
194194

195195
Ok(body)
196196
}
197+
198+
pub async fn get_installation(&self, token: &str) -> Result<serde_json::Value, ApiError> {
199+
let client = Client::new();
200+
let resp = match client
201+
.get("https://api.github.com/installation/repositories")
202+
.header("Accept", HeaderValue::from_str("application/json").unwrap())
203+
.header("User-Agent", "geode_index")
204+
.bearer_auth(token)
205+
.send()
206+
.await
207+
{
208+
Err(e) => {
209+
log::info!("{}", e);
210+
return Err(ApiError::InternalError);
211+
}
212+
Ok(r) => r,
213+
};
214+
215+
if !resp.status().is_success() {
216+
return Err(ApiError::InternalError);
217+
}
218+
219+
let body = match resp.json::<serde_json::Value>().await {
220+
Err(e) => {
221+
log::error!("{}", e);
222+
return Err(ApiError::InternalError);
223+
}
224+
Ok(b) => b,
225+
};
226+
227+
let repos = match body.get("repositories").and_then(|r| r.as_array()) {
228+
None => {
229+
return Err(ApiError::InternalError);
230+
},
231+
Some(r) => r,
232+
};
233+
234+
if repos.len() != 1 {
235+
return Err(ApiError::InternalError);
236+
}
237+
238+
repos[0].get("owner").ok_or(ApiError::InternalError).cloned()
239+
}
197240
}

src/endpoints/auth/github.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -199,8 +199,13 @@ pub async fn github_token_login(
199199
data.github_client_secret.to_string(),
200200
);
201201

202-
let user = client.get_user(&json.token).await
203-
.map_err(|_| ApiError::BadRequest(format!("Invalid access token: {}", json.token)))?;
202+
let user = match client.get_user(&json.token).await {
203+
Err(_) => client.get_installation(&json.token).await.map_err(|_|
204+
ApiError::BadRequest(format!("Invalid access token: {}", json.token))
205+
)?,
206+
207+
Ok(u) => u
208+
};
204209

205210
let mut pool = data.db.acquire().await.or(Err(ApiError::DbAcquireError))?;
206211
let mut transaction = pool.begin().await.or(Err(ApiError::TransactionError))?;

0 commit comments

Comments
 (0)