Skip to content

Commit

Permalink
Now authenticating with the correct database
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Meade committed Aug 8, 2024
1 parent 2ae4ed9 commit 4f9bd23
Show file tree
Hide file tree
Showing 11 changed files with 112 additions and 54 deletions.
8 changes: 4 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 @@ -11,6 +11,6 @@ gotham = "0.7.4"
gotham_restful = "0.9.0"
log = "0.4.22"
mongodb = "3.0.1"
serde = "1.0.204"
serde = "1.0.205"
serde_json = "1.0.122"
tokio = { version = "1.39.2", features = [ "full" ] }
8 changes: 7 additions & 1 deletion bin/build-docker
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
#!/usr/bin/env bash
# build-docker

# use `docker buildx build` to create a Docker image of the application
# by default the image is `wipac-disk-tracking:latest-SNAPSHOT` unless
# you set the BUILD_TAG environment variable before calling the script

: ${BUILD_TAG:="latest-SNAPSHOT"}

docker buildx build \
--file Dockerfile \
--tag wipac-disk-tracking:latest-SNAPSHOT \
--tag wipac-disk-tracking:${BUILD_TAG} \
.
10 changes: 7 additions & 3 deletions bin/run-app
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
#!/usr/bin/env bash
# run-app

# use `cargo run` to run an instance of the application locally
# when starting this script, you can provide one of the environment
# variables listed below to override the defaults

export MONGODB_DATABASE=${MONGODB_DATABASE:="disk_tracking"}
export MONGODB_HOSTNAME=${MONGODB_HOSTNAME:="localhost"}
export MONGODB_PASSWORD=${MONGODB_PASSWORD:="hunter2"}
export MONGODB_PORT=${MONGODB_PORT:="27017"}
# export MONGODB_USERNAME=${MONGODB_USERNAME:="disk_tracking"}
export MONGODB_USERNAME=${MONGODB_USERNAME:="root"}
export MONGODB_PORT_NUMBER=${MONGODB_PORT_NUMBER:="27017"}
export MONGODB_USERNAME=${MONGODB_USERNAME:="disk_tracking"}
export PORT=${PORT:="8080"}
export RUST_LOG=${RUST_LOG:="debug"}

cargo run --bin wipac-disk-tracking
29 changes: 22 additions & 7 deletions bin/run-app-docker
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
#!/usr/bin/env bash
# run-app-docker

# use `docker run` to run an instance of the application in a Docker
# container. when starting this script, you can provide one of the
# environment variables listed below to override the defaults

: ${DOCKER_CONTAINER_NAME:="disk_tracking"}
: ${DOCKER_MONGO_CONTAINER_NAME:="disk_tracking_mongo"}
: ${MONGODB_DATABASE:="disk_tracking"}
: ${MONGODB_HOSTNAME:="localhost"}
: ${MONGODB_PASSWORD:="hunter2"}
: ${MONGODB_USERNAME:="disk_tracking"}
: ${MONGODB_PORT_NUMBER:="27017"}
: ${PORT:="8080"}

docker run \
--detach \
--env=MONGODB_HOSTNAME=disk_tracking_mongo \
--env=MONGODB_PASSWORD=hunter2 \
--env=MONGODB_PORT=27017 \
--env=MONGODB_USERNAME=disk_tracking \
--env=MONGODB_DATABASE=${MONGODB_DATABASE} \
--env=MONGODB_HOSTNAME=${DOCKER_MONGO_CONTAINER_NAME} \
--env=MONGODB_PASSWORD=${MONGODB_PASSWORD} \
--env=MONGODB_PORT_NUMBER=${MONGODB_PORT_NUMBER} \
--env=MONGODB_USERNAME=${MONGODB_USERNAME} \
--env=PORT=${PORT} \
--env=RUST_LOG=debug \
--link disk_tracking_mongo:disk_tracking_mongo \
--name=disk_tracking \
--publish 8080:8080 \
--link ${DOCKER_MONGO_CONTAINER_NAME}:${DOCKER_MONGO_CONTAINER_NAME} \
--name=${DOCKER_CONTAINER_NAME} \
--publish ${PORT}:${PORT} \
--rm \
wipac-disk-tracking:latest-SNAPSHOT
26 changes: 19 additions & 7 deletions bin/run-mongo-docker
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
#!/usr/bin/env bash
# run-mongo-docker

# --detach \
# --rm \
# use `docker run` to create a TEMPORARY instance of MongoDB in a
# Docker container for development/testing purposes. when starting
# this script, you can provide one of the environment variables listed
# below to override the defaults

: ${DOCKER_CONTAINER_NAME:="disk_tracking_mongo"}
: ${MONGODB_DATABASE:="disk_tracking"}
: ${MONGODB_PASSWORD:="hunter2"}
: ${MONGODB_USERNAME:="disk_tracking"}
: ${MONGODB_PORT_NUMBER:="27017"}

docker run \
--env=MONGODB_DATABASE=disk_tracking \
--env=MONGODB_PASSWORD=hunter2 \
--detach \
--env=MONGODB_DATABASE=${MONGODB_DATABASE} \
--env=MONGODB_PASSWORD=${MONGODB_PASSWORD} \
--env=MONGODB_ROOT_PASSWORD=hunter2 \
--env=MONGODB_USERNAME=disk_tracking \
--name=disk_tracking_mongo \
--publish 27017:27017 \
--env=MONGODB_USERNAME=${MONGODB_USERNAME} \
--env=MONGODB_PORT_NUMBER=${MONGODB_PORT_NUMBER} \
--name=${DOCKER_CONTAINER_NAME} \
--publish ${MONGODB_PORT_NUMBER}:${MONGODB_PORT_NUMBER} \
--rm \
bitnami/mongodb:latest
13 changes: 12 additions & 1 deletion bin/run-mongo-shell-docker
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
#!/usr/bin/env bash
# run-mongo-shell-docker

# use `docker run` to create an interactive mongoshell that connects to
# the TEMPORARY instance of MongoDB for development/testing purposes.
# when starting this script, you can provide one of the environment
# variables listed below to override the defaults

: ${MONGODB_DATABASE:="disk_tracking"}
: ${MONGODB_HOSTNAME:="localhost"}
: ${MONGODB_PASSWORD:="hunter2"}
: ${MONGODB_USERNAME:="disk_tracking"}
: ${MONGODB_PORT_NUMBER:="27017"}

docker run \
--interactive \
--network="host" \
--rm \
--tty \
mongo:latest \
mongosh --host localhost:27017 -u "root" -p "hunter2" --authenticationDatabase "admin"
mongosh --host ${MONGODB_HOSTNAME}:${MONGODB_PORT_NUMBER} -u "${MONGODB_USERNAME}" -p "${MONGODB_PASSWORD}" --authenticationDatabase "${MONGODB_DATABASE}"
17 changes: 14 additions & 3 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,29 @@ pub struct ApplicationContext {

impl ApplicationContext {
pub fn get_mongo_url(&self) -> String {
format!("mongodb://{}:{}@{}:{}/", self.mongo_user, self.mongo_password, self.mongo_host, self.mongo_port)
format!(
"mongodb://{}:{}@{}:{}/{}",
self.mongo_user,
self.mongo_password,
self.mongo_host,
self.mongo_port,
self.mongo_database
)
}
}

pub fn build_context() -> Result<ApplicationContext> {
// read database parameters from the environment
let mongo_host = env::var("MONGODB_HOSTNAME").unwrap_or_else(|_| "localhost".into());
let mongo_port = env::var("MONGODB_PORT").unwrap_or_else(|_| "27017".into());
let mongo_port = env::var("MONGODB_PORT_NUMBER").unwrap_or_else(|_| "27017".into());
let mongo_user = env::var("MONGODB_USERNAME").unwrap_or_else(|_| "disk_tracking".into());
let mongo_database = env::var("MONGO_DB_NAME").unwrap_or_else(|_| "disk_tracking".into());
let mongo_password = match env::var("MONGODB_PASSWORD") {
Err(_) => return Err(ContextError("environment variable MONGODB_PASSWORD not defined".to_string())),
Err(_) => {
return Err(ContextError(
"environment variable MONGODB_PASSWORD not defined".to_string(),
))
}
Ok(x) => x,
};

Expand Down
38 changes: 18 additions & 20 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// database.rs

use mongodb::{bson::document::Document, Client, options::ClientOptions};
use mongodb::{bson::document::Document, options::ClientOptions, Client};

use crate::context::ApplicationContext;
use crate::error::Result;
Expand All @@ -19,25 +19,23 @@ pub async fn setup_mongo(context: &ApplicationContext) -> Result<Client> {
pub async fn count_disk_events(context: &ApplicationContext, client: &Client) -> Result<u64> {
let database = client.database(&context.mongo_database);
let collection = database.collection::<DiskEvent>(DISK_EVENT_COLLECTION);
let count = collection.count_documents(Document::new()).await?;
let count = collection.count_documents(Document::new()).await?;
Ok(count)

// match collection.count_documents(None, None).await {
// Ok(count) => {
// let body = json!({
// "status": "ok",
// "count": count,
// });
// (StatusCode::OK, body.to_string())
// },
// Err(_) => {
// let body = json!({
// "status": "error",
// "message": "Failed to connect to the database",
// });
// (StatusCode::INTERNAL_SERVER_ERROR, body.to_string())
// },
// }

// match collection.count_documents(None, None).await {
// Ok(count) => {
// let body = json!({
// "status": "ok",
// "count": count,
// });
// (StatusCode::OK, body.to_string())
// },
// Err(_) => {
// let body = json!({
// "status": "error",
// "message": "Failed to connect to the database",
// });
// (StatusCode::INTERNAL_SERVER_ERROR, body.to_string())
// },
// }
}

4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ pub fn get_error_message(e: ApplicationError) -> String {
match e {
ApplicationError::ContextError(x) => {
format!("disk-tracking: Unable to build application context: {x}")
},
}
ApplicationError::MongoError(x) => {
format!("disk-tracking: Database error: {x}")
},
}
}
}

Expand Down
11 changes: 6 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,21 @@ pub mod error;
// response::IntoResponse,
// http::StatusCode,
// };
use mongodb::{Client, options::ClientOptions};
// use serde_json::json;
// use std::net::SocketAddr;

use context::{build_context, ApplicationContext};
use context::build_context;
use database::{count_disk_events, setup_mongo};
use error::{get_error_message, Result};

#[tokio::main]
async fn main() {
// initialize logging, configured by environment
env_logger::init();

// run the application
match do_main().await {
Err(e) => eprintln!("Error: {}", get_error_message(e)),
Ok(_) => {},
Ok(_) => {}
}
}

Expand All @@ -35,7 +34,9 @@ async fn do_main() -> Result<()> {
println!("{:?}", context);
println!("{}", context.get_mongo_url());

let client = setup_mongo(&context).await.expect("Unable to initialize MongoDB client");
let client = setup_mongo(&context)
.await
.expect("Unable to initialize MongoDB client");
let count = count_disk_events(&context, &client).await?;
println!("{}", count);

Expand Down

0 comments on commit 4f9bd23

Please sign in to comment.