Skip to content

Commit

Permalink
oauth protection for answers POST - init
Browse files Browse the repository at this point in the history
  • Loading branch information
subhojit777 committed Mar 29, 2019
1 parent cd6628e commit a550dd2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
6 changes: 4 additions & 2 deletions src/lib.rs
Expand Up @@ -21,16 +21,17 @@ use diesel::{
r2d2::{ConnectionManager, Pool},
};
use dotenv::dotenv;
use middleware::GitHubUser;
use std::env;

pub mod answers;
pub mod error;
pub mod github;
pub mod helpers;
pub mod index;
pub mod middleware;
pub mod models;
pub mod schema;
pub mod middleware;
pub mod helpers;

pub struct DbExecutor(pub Pool<ConnectionManager<MysqlConnection>>);

Expand All @@ -57,6 +58,7 @@ pub fn create_app() -> App<AppState> {

App::with_state(AppState { db: addr.clone() })
.middleware(Logger::default())
.middleware(GitHubUser)
.resource("/", |r| r.method(Method::GET).f(index::get))
.resource("/answers", |r| {
r.method(Method::POST).with_async(answers::post)
Expand Down
32 changes: 23 additions & 9 deletions src/middleware.rs
@@ -1,20 +1,34 @@
use crate::error;
use crate::error::Oauth;
use actix_web::client::ClientResponse;
use actix_web::http::StatusCode;
use actix_web::middleware::{Middleware, Started};
use actix_web::{Error, HttpRequest};
use actix_web::{client, Error, HttpRequest, HttpResponse};
use futures::future;
use futures::future::Future;

pub struct GitHubUser {
id: i32,
}
pub struct GitHubUser;

impl<S> Middleware<S> for GitHubUser {
fn start(&self, req: &HttpRequest<S>) -> Result<Started, Error> {
if let Some(token) = req.headers().get("authorization") {
match token.to_str() {
Ok(_val) => {
// TODO: Do GET https://api.github.com/user here to retrieve user id.
return Ok(Started::Done);
Ok(access_token) => {
let gh_user_future = client::get("https://api.github.com/user")
.header("Authorization", access_token)
.finish()
.unwrap()
.send()
.from_err()
.and_then(|res: ClientResponse| match res.status() {
StatusCode::OK => {
return future::ok(Some(HttpResponse::Ok().finish()));
}
_ => return future::ok(None),
});

return Ok(Started::Future(Box::new(gh_user_future)));
}
Err(_) => return Err(Error::from(error::Oauth::BadRequest)),
Err(_) => return Err(Error::from(Oauth::BadRequest)),
};
} else {
Ok(Started::Done)
Expand Down

0 comments on commit a550dd2

Please sign in to comment.