Skip to content

Bump to oauth2:2.0.0 #1842

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ tar = "0.4.16"
base64 = "0.9"

openssl = "0.10.13"
oauth2 = "0.3"
oauth2 = "2.0.0"
log = "0.4"
env_logger = "0.5"
hex = "0.3"
Expand Down
25 changes: 16 additions & 9 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{db, Config, Env};
use std::{path::PathBuf, sync::Arc, time::Duration};

use diesel::r2d2;
use oauth2::basic::BasicClient;
use reqwest::Client;
use scheduled_thread_pool::ScheduledThreadPool;

Expand All @@ -16,7 +17,7 @@ pub struct App {
pub diesel_database: db::DieselPool,

/// The GitHub OAuth2 configuration
pub github: oauth2::Config,
pub github: BasicClient,

/// A unique key used with conduit_cookie to generate cookies
pub session_key: String,
Expand All @@ -43,15 +44,21 @@ impl App {
///
/// - GitHub OAuth
/// - Database connection pools
/// - Holds an HTTP `Client` and associated connection pool, if provided
/// - A `git2::Repository` instance from the index repo checkout (that server.rs ensures exists)
pub fn new(config: &Config, http_client: Option<Client>) -> App {
let mut github = oauth2::Config::new(
&config.gh_client_id,
&config.gh_client_secret,
"https://github.com/login/oauth/authorize",
"https://github.com/login/oauth/access_token",
);
github.scopes.push(String::from("read:org"));
use oauth2::prelude::*;
use oauth2::{AuthUrl, ClientId, ClientSecret, Scope, TokenUrl};
use url::Url;

let github = BasicClient::new(
ClientId::new(config.gh_client_id.clone()),
Some(ClientSecret::new(config.gh_client_secret.clone())),
AuthUrl::new(Url::parse("https://github.com/login/oauth/authorize").unwrap()),
Some(TokenUrl::new(
Url::parse("https://github.com/login/oauth/access_token").unwrap(),
)),
)
.add_scope(Scope::new("read:org".to_string()));

let db_pool_size = match (dotenv::var("DB_POOL_SIZE"), config.env) {
(Ok(num), _) => num.parse().expect("couldn't parse DB_POOL_SIZE"),
Expand Down
2 changes: 1 addition & 1 deletion src/controllers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ mod prelude {

fn query(&self) -> IndexMap<String, String> {
url::form_urlencoded::parse(self.query_string().unwrap_or("").as_bytes())
.map(|(a, b)| (a.into_owned(), b.into_owned()))
.into_owned()
.collect()
}

Expand Down
29 changes: 15 additions & 14 deletions src/controllers/user/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use crate::controllers::prelude::*;

use crate::github;
use conduit_cookie::RequestSession;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use oauth2::{prelude::*, AuthorizationCode, TokenResponse};

use crate::models::{NewUser, User};
use crate::schema::users;
Expand All @@ -25,17 +24,14 @@ use crate::util::errors::{CargoError, ReadOnlyMode};
/// }
/// ```
pub fn github_authorize(req: &mut dyn Request) -> CargoResult<Response> {
// Generate a random 16 char ASCII string
let mut rng = thread_rng();
let state: String = std::iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(16)
.collect();
let (url, state) = req
.app()
.github
.authorize_url(oauth2::CsrfToken::new_random);
let state = state.secret().to_string();
req.session()
.insert("github_oauth_state".to_string(), state.clone());

let url = req.app().github.authorize_url(state.clone());

#[derive(Serialize)]
struct R {
url: String,
Expand Down Expand Up @@ -92,11 +88,16 @@ pub fn github_access_token(req: &mut dyn Request) -> CargoResult<Response> {
}

// Fetch the access token from github using the code we just got
let token = req.app().github.exchange(code).map_err(|s| human(&s))?;

let ghuser = github::github::<GithubUser>(req.app(), "/user", &token)?;
let user = ghuser.save_to_database(&token.access_token, &*req.db_conn()?)?;

let code = AuthorizationCode::new(code);
let token = req
.app()
.github
.exchange_code(code)
.map_err(|s| human(&s))?;
let token = token.access_token();
let ghuser = github::github_api::<GithubUser>(req.app(), "/user", token)?;
let user = ghuser.save_to_database(&token.secret(), &*req.db_conn()?)?;
req.session()
.insert("user_id".to_string(), user.id.to_string());
req.mut_extensions().insert(user);
Expand Down
19 changes: 3 additions & 16 deletions src/github.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module implements functionality for interacting with GitHub.

use oauth2::*;
use oauth2::{prelude::*, AccessToken};
use reqwest::{self, header};

use serde::de::DeserializeOwned;
Expand All @@ -13,7 +13,7 @@ use crate::util::{errors::NotFound, human, internal, CargoError, CargoResult};
/// Does all the nonsense for sending a GET to Github. Doesn't handle parsing
/// because custom error-code handling may be desirable. Use
/// `parse_github_response` to handle the "common" processing of responses.
pub fn github<T>(app: &App, url: &str, auth: &Token) -> CargoResult<T>
pub fn github_api<T>(app: &App, url: &str, auth: &AccessToken) -> CargoResult<T>
where
T: DeserializeOwned,
{
Expand All @@ -23,10 +23,7 @@ where
app.http_client()
.get(&url)
.header(header::ACCEPT, "application/vnd.github.v3+json")
.header(
header::AUTHORIZATION,
format!("token {}", auth.access_token),
)
.header(header::AUTHORIZATION, format!("token {}", auth.secret()))
.send()?
.error_for_status()
.map_err(|e| handle_error_response(&e))?
Expand Down Expand Up @@ -55,16 +52,6 @@ fn handle_error_response(error: &reqwest::Error) -> Box<dyn CargoError> {
}
}

/// Gets a token with the given string as the access token, but all
/// other info null'd out. Generally, just to be fed to the `github` fn.
pub fn token(token: String) -> Token {
Token {
access_token: token,
scopes: Vec::new(),
token_type: String::new(),
}
}

pub fn team_url(login: &str) -> String {
let mut login_pieces = login.split(':');
login_pieces.next();
Expand Down
16 changes: 9 additions & 7 deletions src/models/team.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use diesel::prelude::*;

use crate::app::App;
use crate::github;
use crate::github::{github_api, team_url};
use crate::util::{errors::NotFound, human, CargoResult};

use oauth2::{prelude::*, AccessToken};

use crate::models::{Crate, CrateOwner, Owner, OwnerKind, User};
use crate::schema::{crate_owners, teams};
use crate::views::EncodableTeam;
Expand Down Expand Up @@ -141,8 +143,8 @@ impl Team {
// FIXME: we just set per_page=100 and don't bother chasing pagination
// links. A hundred teams should be enough for any org, right?
let url = format!("/orgs/{}/teams?per_page=100", org_name);
let token = github::token(req_user.gh_access_token.clone());
let teams = github::github::<Vec<GithubTeam>>(app, &url, &token)?;
let token = AccessToken::new(req_user.gh_access_token.clone());
let teams = github_api::<Vec<GithubTeam>>(app, &url, &token)?;

let team = teams
.into_iter()
Expand All @@ -164,7 +166,7 @@ impl Team {
}

let url = format!("/orgs/{}", org_name);
let org = github::github::<Org>(app, &url, &token)?;
let org = github_api::<Org>(app, &url, &token)?;

NewTeam::new(&login.to_lowercase(), team.id, team.name, org.avatar_url)
.create_or_update(conn)
Expand Down Expand Up @@ -200,7 +202,7 @@ impl Team {
avatar,
..
} = self;
let url = github::team_url(&login);
let url = team_url(&login);

EncodableTeam {
id,
Expand All @@ -222,8 +224,8 @@ fn team_with_gh_id_contains_user(app: &App, github_id: i32, user: &User) -> Carg
}

let url = format!("/teams/{}/memberships/{}", &github_id, &user.gh_login);
let token = github::token(user.gh_access_token.clone());
let membership = match github::github::<Membership>(app, &url, &token) {
let token = AccessToken::new(user.gh_access_token.clone());
let membership = match github_api::<Membership>(app, &url, &token) {
// Officially how `false` is returned
Err(ref e) if e.is::<NotFound>() => return Ok(false),
x => x?,
Expand Down