From a0278262ae9c7b8cd124740f5dd555bae64a029d Mon Sep 17 00:00:00 2001 From: Jordan Doyle Date: Tue, 07 Sep 2021 15:02:02 +0100 Subject: [PATCH] API authentication using keys from database --- chartered-db/src/users.rs | 1 - chartered-web/src/middleware/auth.rs | 50 +++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/chartered-db/src/users.rs b/chartered-db/src/users.rs index 0d4ed6f..9228b90 100644 --- a/chartered-db/src/users.rs +++ a/chartered-db/src/users.rs @@ -1,9 +1,8 @@ use super::{ schema::{user_api_keys, user_crate_permissions, user_ssh_keys, users}, ConnectionPool, Result, }; use diesel::{prelude::*, Associations, Identifiable, Queryable}; -use std::sync::Arc; #[derive(Identifiable, Queryable, Associations, PartialEq, Eq, Hash, Debug)] pub struct User { diff --git a/chartered-web/src/middleware/auth.rs b/chartered-web/src/middleware/auth.rs index e37cf0a..5a76763 100644 --- a/chartered-web/src/middleware/auth.rs +++ a/chartered-web/src/middleware/auth.rs @@ -1,6 +1,13 @@ -use axum::http::{Request, Response, StatusCode}; +use axum::{ + extract::{self, FromRequest, RequestParts}, + http::{Request, Response, StatusCode}, +}; +use chartered_db::ConnectionPool; use futures::future::BoxFuture; -use std::task::{Context, Poll}; +use std::{ + collections::HashMap, + task::{Context, Poll}, +}; use tower::Service; #[derive(Clone)] @@ -28,14 +35,37 @@ let mut inner = std::mem::replace(&mut self.0, clone); Box::pin(async move { - // if true { - // return Ok(Response::builder() - // .status(StatusCode::UNAUTHORIZED) - // .body(ResBody::default()) - // .unwrap()); - // } - - let res: Response = inner.call(req).await?; + let mut req = RequestParts::new(req); + + let params = extract::Path::>::from_request(&mut req) + .await + .unwrap(); + + let key = params.get("key").map(|v| v.as_str()).unwrap_or_default(); + + let db = req + .extensions() + .unwrap() + .get::() + .unwrap() + .clone(); + + let user = match chartered_db::users::User::find_by_api_key(db, String::from(key)) + .await + .unwrap() + { + Some(user) => user, + None => { + return Ok(Response::builder() + .status(StatusCode::UNAUTHORIZED) + .body(ResBody::default()) + .unwrap()) + } + }; + + req.extensions_mut().unwrap().insert(user); + + let res: Response = inner.call(req.try_into_request().unwrap()).await?; Ok(res) }) -- rgit 0.1.3