Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load env vars from file #4

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions .env-sample
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
MONGODB_URI=
PORT=
SECRET_KEY=
RSA_KEY=
MONGODB_URI=mongodb://localhost:27017
DATABASE_NAME=base-api
SERVER_PORT=8080
SECRET_KEY=thisisasupersecretkey
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}"
}
]
}
}
12 changes: 7 additions & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"peacock.remoteColor": "#dc322f",
"rust-analyzer.linkedProjects": [
"./Cargo.toml"
]
}
"peacock.remoteColor": "#dc322f",
"rust-analyzer.linkedProjects": ["./Cargo.toml"],
"cSpell.words": [
"dotenv",
"thisisanothersupersecretkey"
]
}
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ sqlx = { version = "~0.7", features = [ "runtime-tokio", "tls-native-tls", "post
stoppable_thread = "~0.2"
thiserror = "~1.0"
tokio = { version = "~1.35", features = ["full"] }
dotenv = "0.15.0"
lazy_static = "1.4.0"

[dev-dependencies]
env_logger = "~0.10"
Expand Down
8 changes: 7 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
RS Base API is a boilerplate to quickstart your backend in Rust.
As of today, it provides basic user management routes and communicates with MongoDB.

# To run
```shell
cp .env-sample .env
# Edit .env file according to your setup
```

# Roadmap

* Implement Sentry
* Send account management e-mails: AWS SES/Scaleway
* Make a generic store
* Handle another DB like SQL
* Handle another DB like [PostgreSQL](https://github.com/launchbadge/sqlx/blob/main/examples/postgres/json/src/main.rs)
* Develop a CLI to generate code interactively: clap
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, DB_NAME};
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 = "supersecret"; //TODO: std::env::var("RSA_KEY");
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(DB_NAME)
.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 = "supersecret"; //TODO: std::env::var("RSA_KEY");
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(DB_NAME)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
let user_object_id = ObjectId::parse_str(user_id).unwrap();
match collection
Expand Down
14 changes: 7 additions & 7 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, DB_NAME,
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(DB_NAME)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
let result = collection.insert_one(user, None).await;
match result {
Expand All @@ -42,7 +42,7 @@ pub async fn create_user(
}
}
}
None => HttpResponse::InternalServerError().body("Parsing error"),
None => HttpResponse::InternalServerError().body("Invalid input"),
}
}

Expand All @@ -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(DB_NAME)
.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(DB_NAME)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);

let user_obj_id = mongodb::bson::oid::ObjectId::from_str(&user_id).unwrap();
Expand Down Expand Up @@ -123,7 +123,7 @@ pub async fn update_user(
}
}
}
None => HttpResponse::InternalServerError().body("User from json error"),
None => HttpResponse::InternalServerError().body("Invalid input"),
}
}

Expand All @@ -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(DB_NAME)
.database(&DATABASE_NAME)
.collection(users::REPOSITORY_NAME);
match collection
.delete_one(doc! { "_id": &user_obj_id }, None)
Expand Down
12 changes: 9 additions & 3 deletions src/drivers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use crate::services::emails;
use anyhow::bail;
use async_trait::async_trait;
use lazy_static::lazy_static;
use mongodb::{error::ErrorKind, Client as mgoClient};
// use sqlx::postgres::PgPool;

use crate::models::users::{self, User};

const DB_NAME: &str = "base-api";

pub mod mongo;
pub mod postgre;

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

#[derive(Debug)]
pub struct GenericDatabaseStatus {
pub kind: String,
Expand Down Expand Up @@ -40,7 +44,9 @@ 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
16 changes: 12 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ 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;
use tokio::sync::broadcast;
Expand All @@ -26,7 +28,12 @@ use crate::{
services::ntp,
};

const DB_NAME: &str = "base-api";
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());
}

/// The maximum size of a package the server will accept.
pub const MAX_FRAME_SIZE: usize = 250_000_000; // 250Mb
Expand All @@ -44,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 @@ -75,9 +83,9 @@ async fn main() -> anyhow::Result<()> {
anyhow::bail!("Failed to connect mongo with drivers: {:?}", error)
}
}
models::users::create_email_index(&mongo_db_client, DB_NAME).await;
models::users::create_email_index(&mongo_db_client, &DATABASE_NAME).await;

let salt = std::env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(16));
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 Expand Up @@ -115,7 +123,7 @@ async fn main() -> anyhow::Result<()> {

let time_thread = app_state.ntp.start_time_thread(app_state.clone());

let port: u16 = std::env::var("PORT")
let port: u16 = std::env::var("SERVER_PORT")
.unwrap_or_else(|_| "8080".into())
.parse()
.unwrap();
Expand Down
7 changes: 5 additions & 2 deletions src/models/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,13 @@ impl User {
}
}
}
None => log::warn!("No organization id for: {email}"),
None => {
log::warn!("No organization id for: {email}");
return None;
}
}

let salt = std::env::var("SECRET_KEY").unwrap_or_else(|_| "0123".repeat(16));
let salt = &std::env::var("SECRET_KEY").unwrap_or_else(|_| "thisisasupersecretkey".into());
let config = Config::default();
let hashed_password =
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &config).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(DB_NAME)
.database(&DATABASE_NAME)
.collection::<User>(users::REPOSITORY_NAME)
.drop(None)
.await
Expand Down