Skip to content

Commit

Permalink
Extract auth to config
Browse files Browse the repository at this point in the history
  • Loading branch information
backspace committed Oct 25, 2023
1 parent 8b059b9 commit 8225e6a
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
1 change: 1 addition & 0 deletions unmnemonic_devices_vrs/.env.test
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
AUTH="user:pass"
ROOT_URL="http://example.com"
TWILIO_ACCOUNT_SID="FAKE"
TWILIO_API_KEY_SID="FAKE"
Expand Down
8 changes: 6 additions & 2 deletions unmnemonic_devices_vrs/src/auth.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use crate::config::{ConfigProvider, EnvVarProvider};
use axum::{
async_trait,
extract::FromRequestParts,
http::{request::Parts, StatusCode},
};
use base64::{engine::general_purpose, Engine as _};
use std::str::from_utf8;
use std::{env, str::from_utf8};

// Adapted from https://www.shuttle.rs/blog/2023/09/27/rust-vs-go-comparison#middleware-1

Expand All @@ -23,6 +24,9 @@ where
type Rejection = axum::http::Response<axum::body::Body>;

async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
let env_config_provider = EnvVarProvider::new(env::vars().collect());
let config = &env_config_provider.get_config();

let auth_header = parts
.headers
.get("Authorization")
Expand All @@ -38,7 +42,7 @@ where

// Our username and password are hardcoded here.
// In a real app, you'd want to read them from the environment.
if credential_str == "f:x" {
if credential_str == config.auth {
return Ok(User);
}
}
Expand Down
2 changes: 2 additions & 0 deletions unmnemonic_devices_vrs/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;

#[derive(Debug, Default)]
pub struct Config {
pub auth: String,
pub database_url: String,
pub root_url: String,
pub twilio_account_sid: String,
Expand All @@ -21,6 +22,7 @@ pub struct EnvVarProvider(Config);
impl EnvVarProvider {
pub fn new(args: HashMap<String, String>) -> Self {
let config = Config {
auth: args.get("AUTH").expect("Missing auth").to_string(),
database_url: args
.get("DATABASE_URL")
.expect("Missing database URL")
Expand Down

0 comments on commit 8225e6a

Please sign in to comment.