Skip to content

Commit

Permalink
fix: using DATABASE_NAME instead of URI
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien3d committed Mar 19, 2024
1 parent 9a9286f commit aeb9d13
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .env-sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ MONGODB_URI=mongodb://localhost:27017
DATABASE_NAME=base-api
SERVER_PORT=8080
SECRET_KEY=thisisasupersecretkey
RSA_KEY=thisisanothersupersecretkey
RSA_KEY=thisisanothersupersecretkey
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@
"cwd": "${workspaceFolder}"
}
]
}
}
5 changes: 4 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"peacock.remoteColor": "#dc322f",
"rust-analyzer.linkedProjects": ["./Cargo.toml"],
"cSpell.words": ["thisisanothersupersecretkey"]
"cSpell.words": [
"dotenv",
"thisisanothersupersecretkey"
]
}
13 changes: 7 additions & 6 deletions src/controllers/authentication.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::controllers::error::*;
use crate::models::users::{self, User};
use crate::{ProgramAppState, MONGODB_URI};
use crate::{ProgramAppState, DATABASE_NAME};
use actix_web::{
dev::ServiceRequest,
http::StatusCode,
Expand Down Expand Up @@ -36,15 +36,15 @@ pub(crate) async fn authentication(
req_body: web::Json<users::AuthReq>,
) -> impl Responder {
//println!("{} {}", req_body.email, req_body.password);
let secret_key = &std::env::var("RSA_KEY").unwrap_or_else(|_| "thisisanothersupersecretkey".into());
let secret_key =
&std::env::var("RSA_KEY").unwrap_or_else(|_| "thisisanothersupersecretkey".into());

let now = chrono::Utc::now();
let iat = now.timestamp() as usize;
let exp = (now + chrono::Duration::days(1)).timestamp() as usize;

let collection: Collection<users::User> = app_state
.mongo_db_client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
match collection
.find_one(doc! { "email": &req_body.email.to_string() }, None)
Expand Down Expand Up @@ -92,7 +92,8 @@ pub struct ErrorResponse {
}

pub fn check_jwt(token: String) -> Result<TokenClaims, (StatusCode, Json<ErrorResponse>)> {
let secret_key = &std::env::var("RSA_KEY").unwrap_or_else(|_| "thisisanothersupersecretkey".into());
let secret_key =
&std::env::var("RSA_KEY").unwrap_or_else(|_| "thisisanothersupersecretkey".into());

let claims = decode::<TokenClaims>(
&token,
Expand Down Expand Up @@ -269,7 +270,7 @@ impl AuthState {
async fn get_user_info(&self, user_id: String) -> Result<User, Error> {
let collection: Collection<users::User> = self
.mongo_db
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
let user_object_id = ObjectId::parse_str(user_id).unwrap();
match collection
Expand Down
10 changes: 5 additions & 5 deletions src/controllers/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::str::FromStr;
use crate::{
controllers::authentication::Authenticated,
models::users::{self, User},
ProgramAppState, MONGODB_URI,
ProgramAppState, DATABASE_NAME,
};
use actix_web::{delete, get, post, put, web, HttpResponse};
use json;
Expand All @@ -30,7 +30,7 @@ pub async fn create_user(
Some(user) => {
let collection: Collection<User> = app_state
.mongo_db_client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
let result = collection.insert_one(user, None).await;
match result {
Expand Down Expand Up @@ -61,7 +61,7 @@ pub async fn get_user_by_email(
let email = email.into_inner();
let collection: Collection<users::User> = app_state
.mongo_db_client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
match collection.find_one(doc! { "email": &email }, None).await {
Ok(Some(user)) => HttpResponse::Ok().json(user.sanitize()),
Expand Down Expand Up @@ -91,7 +91,7 @@ pub async fn update_user(
Some(new_user) => {
let collection: Collection<User> = app_state
.mongo_db_client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);

let user_obj_id = mongodb::bson::oid::ObjectId::from_str(&user_id).unwrap();
Expand Down Expand Up @@ -137,7 +137,7 @@ pub async fn delete_user_by_id(
let user_obj_id = mongodb::bson::oid::ObjectId::from_str(&id).unwrap();
let collection: Collection<users::User> = app_state
.mongo_db_client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
match collection
.delete_one(doc! { "_id": &user_obj_id }, None)
Expand Down
4 changes: 2 additions & 2 deletions src/drivers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub mod mongo;
pub mod postgre;

lazy_static! {
static ref DB_NAME: String = std::env::var("DATABASE_NAME").unwrap_or_else(|_| "mongodb://localhost:27017".into());
static ref DATABASE_NAME: String = std::env::var("DATABASE_NAME").unwrap_or_else(|_| "base-api".into());
}

#[derive(Debug)]
Expand Down Expand Up @@ -43,7 +43,7 @@ impl MongoDatabase {
pub async fn seed_user(&self, user: User) -> anyhow::Result<&Self> {
match &self.client {
Some(client) => {
let collection = client.database(&DB_NAME).collection(users::REPOSITORY_NAME);
let collection = client.database(&DATABASE_NAME).collection(users::REPOSITORY_NAME);
match collection.insert_one(user.clone(), None).await {
Ok(_) => {
let _ = emails::send_email_with_aws_ses(&user.email, "Welcome", "Message")
Expand Down
10 changes: 7 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use actix_cors::Cors;
use actix_identity::IdentityMiddleware;
use actix_web::{http, middleware, web, App, HttpServer};
use argon2::Config;
use dotenv::dotenv;
use lazy_static::lazy_static;
use mongodb::{bson::oid::ObjectId, Client};
use services::ntp::Ntp;
Expand All @@ -28,8 +29,10 @@ use crate::{
};

lazy_static! {
static ref MONGODB_URI: String = std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".into());
static ref DATABASE_NAME: String = std::env::var("DATABASE_NAME").unwrap_or_else(|_| "base-api".into());
static ref MONGODB_URI: String =
std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".into());
static ref DATABASE_NAME: String =
std::env::var("DATABASE_NAME").unwrap_or_else(|_| "base-api".into());
}

/// The maximum size of a package the server will accept.
Expand All @@ -48,6 +51,7 @@ pub struct ProgramAppState {

#[actix_web::main]
async fn main() -> anyhow::Result<()> {
dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

// Start NTP and define the timestamp format
Expand Down Expand Up @@ -81,7 +85,7 @@ async fn main() -> anyhow::Result<()> {
}
models::users::create_email_index(&mongo_db_client, &DATABASE_NAME).await;

let salt = &std::env::var("SECRET_KEY").unwrap_or_else(|_| "thisisasupersecretkey".into());
let salt = &std::env::var("SECRET_KEY").unwrap_or_else(|_| "thisisasupersecretkey".into());

let hashed_password =
argon2::hash_encoded("password".as_bytes(), salt.as_bytes(), &Config::original()).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn test() {

// Clear any data currently in the users collection.
client
.database(&MONGODB_URI)
.database(&DATABASE_NAME)
.collection::<User>(users::REPOSITORY_NAME)
.drop(None)
.await
Expand Down

0 comments on commit aeb9d13

Please sign in to comment.