Skip to content

Commit

Permalink
use installation token for github auth
Browse files Browse the repository at this point in the history
  • Loading branch information
camila314 committed Jan 22, 2025
1 parent 029fc61 commit 22df7a1
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 4 deletions.
48 changes: 48 additions & 0 deletions src/auth/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,52 @@ impl GithubClient {
ApiError::InternalError
})?)
}

pub async fn get_installation(&self, token: &str) -> Result<GitHubFetchedUser, ApiError> {
let client = Client::new();
let resp = match client
.get("https://api.github.com/installation/repositories")
.header("Accept", HeaderValue::from_str("application/json").unwrap())
.header("User-Agent", "geode_index")
.bearer_auth(token)
.send()
.await
{
Err(e) => {
log::info!("{}", e);
return Err(ApiError::InternalError);
}
Ok(r) => r,
};

if !resp.status().is_success() {
return Err(ApiError::InternalError);
}

let body = match resp.json::<serde_json::Value>().await {
Err(e) => {
log::error!("{}", e);
return Err(ApiError::InternalError);
}
Ok(b) => b,
};

let repos = match body.get("repositories").and_then(|r| r.as_array()) {
None => {
return Err(ApiError::InternalError);
},
Some(r) => r,
};

if repos.len() != 1 {
return Err(ApiError::InternalError);
}

let owner = repos[0].get("owner").ok_or(ApiError::InternalError)?.clone();

serde_json::from_value(owner).map_err(|e| {
log::error!("Failed to create GitHubFetchedUser: {}", e);
ApiError::InternalError
})
}
}
11 changes: 7 additions & 4 deletions src/endpoints/auth/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,13 @@ pub async fn github_token_login(
data.github().client_secret().to_string(),
);

let user = client
.get_user(&json.token)
.await
.map_err(|_| ApiError::BadRequest(format!("Invalid access token: {}", json.token)))?;
let user = match client.get_user(&json.token).await {
Err(_) => client.get_installation(&json.token).await.map_err(|_|
ApiError::BadRequest(format!("Invalid access token: {}", json.token))
)?,

Ok(u) => u
};

let mut pool = data.db().acquire().await.or(Err(ApiError::DbAcquireError))?;
let mut tx = pool.begin().await.or(Err(ApiError::TransactionError))?;
Expand Down

0 comments on commit 22df7a1

Please sign in to comment.