guard bootstrap

This commit is contained in:
Aravinth Manivannan 2021-03-09 15:44:26 +05:30
parent 8e065f8051
commit e89938f663
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88
15 changed files with 2726 additions and 17 deletions

1903
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -11,7 +11,7 @@ edition = "2018"
readme = "README.md" readme = "README.md"
[workspace] [workspace]
members = [ ".", "browser", "cli" ] members = [ ".", "browser", "cli", "guard" ]
[dependencies] [dependencies]

3
cli/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
tarpaulin-report.html
.env

3
guard/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/target
tarpaulin-report.html
.env

32
guard/Cargo.toml Normal file
View file

@ -0,0 +1,32 @@
[package]
name = "guard"
version = "0.1.0"
authors = ["realaravinth <realaravinth@batsense.net>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "3"
sqlx = { version = "0.4.0", features = [ "runtime-actix-rustls", "postgres" ] }
argon2-creds = { version = "0.2", git = "https://github.com/realaravinth/argon2-creds" }
config = "0.10"
validator = "0.12"
derive_builder = "0.9"
derive_more = "0.99"
serde = "1"
serde_json = "1"
url = "2.2"
pretty_env_logger = "0.3"
log = "0.4"
lazy_static = "1.4"
actix-identity = "0.3"
actix-http = "2.2"

85
guard/README.md Normal file
View file

@ -0,0 +1,85 @@
NOTE: This is an actix boilerplate repo
- Uses sqlx so set up database and carryout migrations before `cargo run`
- also change `placeholder` to github username and `placeholder-repo`
to repo name
- change `PLACEHOLDER` to app name as mentioned in `./src/settings.rs`
# placeholder-repo
![CI (Linux)](<https://github.com/placeholder/placeholder-repo/workflows/CI%20(Linux)/badge.svg>)
[![codecov](https://codecov.io/gh/placeholder/placeholder-repo/branch/master/graph/badge.svg?token=4HjfPHCBEN)](https://codecov.io/gh/placeholder/placeholder-repo)
[![AGPL License](https://img.shields.io/badge/license-AGPL-blue.svg)](http://www.gnu.org/licenses/agpl-3.0)
[![dependency status](https://deps.rs/repo/github/placeholder/placeholder-repo/status.svg)](https://deps.rs/repo/github/placeholder/placeholder-repo)
### STATUS: ACTIVE DEVELOPMENT (fancy word for unusable)
</div>
**placeholder-repo** is an placeholder-repo and access management platform built for the
[IndieWeb](indieweb.org)
### How to build
- Install Cargo using [rustup](https://rustup.rs/) with:
```
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
- Clone the repository with:
```
$ git clone https://github.com/placeholder/placeholder-repo
```
- Build with Cargo:
```
$ cd placeholder-repo && cargo build
```
### Configuration:
placeholder-repo is highly configurable.
Configuration is applied/merged in the following order:
1. `config/default.toml`
2. environment variables.
To make installation process seamless, placeholder-repo ships with a CLI tool to
assist in database migrations.
#### Setup
##### Environment variables:
Setting environment variables are optional. The configuration files have
all the necessary parameters listed. By setting environment variables,
you will be overriding the values set in the configuration files.
###### Database:
| Name | Value |
| ------------------------------- | -------------------------------------- |
| `PLACEHOLDER_DATEBASE_PASSWORD` | Postgres password |
| `PLACEHOLDER_DATEBASE_NAME` | Postgres database name |
| `PLACEHOLDER_DATEBASE_PORT` | Postgres port |
| `PLACEHOLDER_DATEBASE_HOSTNAME` | Postgres hostmane |
| `PLACEHOLDER_DATEBASE_USERNAME` | Postgres username |
| `PLACEHOLDER_DATEBASE_POOL` | Postgres database connection pool size |
###### Redis cache:
| Name | Value |
| ---------------------------- | -------------- |
| `PLACEHOLDER_REDIS_PORT` | Redis port |
| `PLACEHOLDER_REDIS_HOSTNAME` | Redis hostmane |
###### Server:
| Name | Value |
| ----------------------------------------- | --------------------------------------------------- |
| `PLACEHOLDER_SERVER_PORT` (or) `PORT`\*\* | The port on which you want wagon to listen to |
| `PLACEHOLDER_SERVER_IP` | The IP address on which you want wagon to listen to |
| `PLACEHOLDER_SERVER_STATIC_FILES_DIR` | Path to directory containing static files |

30
guard/config/default.toml Normal file
View file

@ -0,0 +1,30 @@
debug = true
[database]
# This section deals with the database location and how to access it
# Please note that at the moment, we have support for only postgresqa.
# Example, if you are Batman, your config would be:
# hostname = "batcave.org"
# port = "5432"
# username = "batman"
# password = "somereallycomplicatedBatmanpassword"
hostname = "localhost"
port = "5432"
username = "postgres"
password = "password"
name = "webhunt-postgress"
pool = 4
# This section deals with the configuration of the actual server
[server]
cookie_secret = "Zae0OOxf^bOJ#zN^&k7VozgW&QAx%n02TQFXpRMG4cCU0xMzgu3dna@tQ9dvc&TlE6p*n#kXUdLZJCQsuODIV%r$@o4%770ePQB7m#dpV!optk01NpY0@615w5e2Br4d"
# The port at which you want authentication to listen to
# takes a number, choose from 1000-10000 if you dont know what you are doing
port = 7000
#IP address. Enter 0.0.0.0 to listen on all availale addresses
ip= "0.0.0.0"
# enter your hostname, eg: example.com
domain = "localhost"
allow_registration = true
# directory containing static files
static_files_dir = "./frontend/dist"

View file

@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS mcaptcha_users (
name VARCHAR(100) NOT NULL UNIQUE,
ID SERIAL PRIMARY KEY NOT NULL
);

View file

@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS mcaptcha_config (
name VARCHAR(100) references mcaptcha_users(name),
id VARCHAR(32) PRIMARY KEY NOT NULL UNIQUE,
duration INTEGER NOT NULL
);

View file

@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS mcaptcha_levels (
id VARCHAR(32) references mcaptcha_config(id),
difficulty_factor INTEGER NOT NULL,
visitor_threshold INTEGER NOT NULL
);

49
guard/src/data.rs Normal file
View file

@ -0,0 +1,49 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use argon2_creds::{Config, ConfigBuilder, PasswordPolicy};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use crate::SETTINGS;
#[derive(Clone)]
pub struct Data {
pub db: PgPool,
pub creds: Config,
}
impl Data {
#[cfg(not(tarpaulin_include))]
pub async fn new() -> Self {
let db = PgPoolOptions::new()
.max_connections(SETTINGS.database.pool)
.connect(&SETTINGS.database.url)
.await
.expect("Unable to form database pool");
let creds = ConfigBuilder::default()
.username_case_mapped(false)
.profanity(true)
.blacklist(false)
.password_policy(PasswordPolicy::default())
.build()
.unwrap();
Data { creds, db }
}
}

139
guard/src/errors.rs Normal file
View file

@ -0,0 +1,139 @@
use std::io::{Error as IOError, ErrorKind as IOErrorKind};
use actix_web::{
dev::HttpResponseBuilder,
error::ResponseError,
http::{header, StatusCode},
HttpResponse,
};
use argon2_creds::errors::CredsError;
use derive_more::{Display, Error};
use log::debug;
use serde::Serialize;
// use validator::ValidationErrors;
use std::convert::From;
#[derive(Debug, Display, Clone, PartialEq, Error)]
#[cfg(not(tarpaulin_include))]
pub enum ServiceError {
#[display(fmt = "internal server error")]
InternalServerError,
#[display(fmt = "The value you entered for email is not an email")] //405j
NotAnEmail,
#[display(fmt = "File not found")]
FileNotFound,
#[display(fmt = "File exists")]
FileExists,
#[display(fmt = "Permission denied")]
PermissionDenied,
#[display(fmt = "Invalid credentials")]
InvalidCredentials,
#[display(fmt = "Authorization required")]
AuthorizationRequired,
/// when the value passed contains profainity
#[display(fmt = "Can't allow profanity in usernames")]
ProfainityError,
/// when the value passed contains blacklisted words
/// see [blacklist](https://github.com/shuttlecraft/The-Big-Username-Blacklist)
#[display(fmt = "Username contains blacklisted words")]
BlacklistError,
/// when the value passed contains characters not present
/// in [UsernameCaseMapped](https://tools.ietf.org/html/rfc8265#page-7)
/// profile
#[display(fmt = "username_case_mapped violation")]
UsernameCaseMappedError,
/// when the value passed contains profainity
#[display(fmt = "Username not available")]
UsernameTaken,
/// when a question is already answered
#[display(fmt = "Already answered")]
AlreadyAnswered,
}
#[derive(Serialize)]
#[cfg(not(tarpaulin_include))]
struct ErrorToResponse {
error: String,
}
impl ResponseError for ServiceError {
fn error_response(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status_code())
.set_header(header::CONTENT_TYPE, "application/json; charset=UTF-8")
.json(ErrorToResponse {
error: self.to_string(),
})
}
fn status_code(&self) -> StatusCode {
match *self {
ServiceError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::NotAnEmail => StatusCode::BAD_REQUEST,
ServiceError::FileNotFound => StatusCode::NOT_FOUND,
ServiceError::FileExists => StatusCode::METHOD_NOT_ALLOWED,
ServiceError::PermissionDenied => StatusCode::UNAUTHORIZED,
ServiceError::InvalidCredentials => StatusCode::UNAUTHORIZED,
ServiceError::AuthorizationRequired => StatusCode::UNAUTHORIZED,
ServiceError::ProfainityError => StatusCode::BAD_REQUEST,
ServiceError::BlacklistError => StatusCode::BAD_REQUEST,
ServiceError::UsernameCaseMappedError => StatusCode::BAD_REQUEST,
ServiceError::UsernameTaken => StatusCode::BAD_REQUEST,
ServiceError::AlreadyAnswered => StatusCode::BAD_REQUEST,
}
}
}
impl From<IOError> for ServiceError {
fn from(e: IOError) -> ServiceError {
debug!("{:?}", &e);
match e.kind() {
IOErrorKind::NotFound => ServiceError::FileNotFound,
IOErrorKind::PermissionDenied => ServiceError::PermissionDenied,
IOErrorKind::AlreadyExists => ServiceError::FileExists,
_ => ServiceError::InternalServerError,
}
}
}
impl From<CredsError> for ServiceError {
fn from(e: CredsError) -> ServiceError {
debug!("{:?}", &e);
match e {
CredsError::UsernameCaseMappedError => ServiceError::UsernameCaseMappedError,
CredsError::ProfainityError => ServiceError::ProfainityError,
CredsError::BlacklistError => ServiceError::BlacklistError,
CredsError::NotAnEmail => ServiceError::NotAnEmail,
CredsError::Argon2Error(_) => ServiceError::InternalServerError,
_ => ServiceError::InternalServerError,
}
}
}
// impl From<ValidationErrors> for ServiceError {
// fn from(_: ValidationErrors) -> ServiceError {
// ServiceError::NotAnEmail
// }
// }
//
impl From<sqlx::Error> for ServiceError {
fn from(e: sqlx::Error) -> Self {
use sqlx::error::Error;
use std::borrow::Cow;
debug!("{:?}", &e);
if let Error::Database(err) = e {
if err.code() == Some(Cow::from("23505")) {
return ServiceError::UsernameTaken;
}
}
ServiceError::InternalServerError
}
}
pub type ServiceResult<V> = std::result::Result<V, ServiceError>;

82
guard/src/main.rs Normal file
View file

@ -0,0 +1,82 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_web::{
error::InternalError, http::StatusCode, middleware, web::JsonConfig, App, HttpServer,
};
use lazy_static::lazy_static;
mod data;
mod errors;
//mod routes;
mod settings;
pub use data::Data;
pub use settings::Settings;
lazy_static! {
pub static ref SETTINGS: Settings = Settings::new().unwrap();
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// use routes::services;
// let data = Data::new().await;
pretty_env_logger::init();
// sqlx::migrate!("./migrations/").run(&data.db).await.unwrap();
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.wrap(get_identity_service())
.wrap(middleware::Compress::default())
// .data(data.clone())
.wrap(middleware::NormalizePath::new(
middleware::normalize::TrailingSlash::Trim,
))
.app_data(get_json_err())
//.configure(services)
})
.bind(SETTINGS.server.get_ip())
.unwrap()
.run()
.await
}
#[cfg(not(tarpaulin_include))]
fn get_json_err() -> JsonConfig {
JsonConfig::default().error_handler(|err, _| {
//debug!("JSON deserialization error: {:?}", &err);
InternalError::new(err, StatusCode::BAD_REQUEST).into()
})
}
#[cfg(not(tarpaulin_include))]
fn get_identity_service() -> IdentityService<CookieIdentityPolicy> {
let cookie_secret = &SETTINGS.server.cookie_secret;
IdentityService::new(
CookieIdentityPolicy::new(cookie_secret.as_bytes())
.name("Authorization")
//TODO change cookie age
.max_age(216000)
.domain(&SETTINGS.server.domain)
.secure(false),
)
}

248
guard/src/routes.rs Normal file
View file

@ -0,0 +1,248 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use actix_identity::Identity;
use actix_web::{
get, post,
web::{self, Path as WebPath, ServiceConfig},
HttpResponse, Responder,
};
use log::debug;
use serde::{Deserialize, Serialize};
use crate::errors::*;
use crate::Data;
#[derive(Clone, Debug, Deserialize, Serialize)]
struct SomeData {
pub a: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Creds {
pub username: String,
pub password: String,
}
#[post("/api/signup")]
async fn signup(payload: web::Json<Creds>, data: web::Data<Data>) -> ServiceResult<impl Responder> {
let username = data.creds.username(&payload.username)?;
let hash = data.creds.password(&payload.password)?;
sqlx::query!(
"INSERT INTO users (name , password) VALUES ($1, $2)",
username,
hash
)
.execute(&data.db)
.await?;
Ok(HttpResponse::Ok())
}
struct Password {
password: String,
}
#[post("/api/signin")]
async fn signin(
id: Identity,
payload: web::Json<Creds>,
data: web::Data<Data>,
) -> ServiceResult<impl Responder> {
use argon2_creds::Config;
let rec = sqlx::query_as!(
Password,
"SELECT password FROM users WHERE name = ($1)",
&payload.username
)
.fetch_one(&data.db)
.await?;
if Config::verify(&rec.password, &payload.password)? {
debug!("remembered {}", payload.username);
id.remember(payload.into_inner().username);
return Ok(HttpResponse::Ok());
} else {
return Err(ServiceError::InvalidCredentials);
}
}
#[get("/api/signout")]
async fn signout(id: Identity) -> impl Responder {
if let Some(_) = id.identity() {
id.forget();
}
HttpResponse::Ok()
}
#[get("/questions/{id}")]
async fn get_question(
//session: Session,
id: Identity,
path: WebPath<(u32,)>,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
Ok(HttpResponse::Ok().body(format!("User detail: {}", path.into_inner().0)))
}
struct LevelScore {
level: i32,
points: i32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Answer {
answer: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct AnswerDatabaseFetch {
answer: String,
points: i32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct AnswerVerifyResp {
correct: bool,
points: i32,
}
#[post("/api/answer/verify/{id}")]
async fn verify_answer(
//session: Session,
payload: web::Json<Answer>,
data: web::Data<Data>,
id: Identity,
path: WebPath<(u32,)>,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let name = id.identity().unwrap();
let rec = sqlx::query_as!(
LevelScore,
"SELECT level, points FROM users WHERE name = ($1)",
&name
)
.fetch_one(&data.db)
.await?;
let current = path.into_inner().0 as i32;
if rec.level == current {
// TODO
// check answer
let answer = sqlx::query_as!(
AnswerDatabaseFetch,
"SELECT answer, points FROM answers WHERE question_num = ($1)",
&current
)
.fetch_one(&data.db)
.await?;
let resp;
// TODO all answers lowercase?
if payload.answer.trim().to_lowercase() == answer.answer {
let points = rec.points + answer.points;
resp = AnswerVerifyResp {
correct: true,
points,
};
sqlx::query!(
"UPDATE users SET points = $1, level = $2 WHERE name = $3",
points,
rec.level + 1,
name
)
.execute(&data.db)
.await?;
} else {
resp = AnswerVerifyResp {
correct: false,
points: rec.points,
};
}
return Ok(HttpResponse::Ok().json(resp));
} else if rec.level > current {
return Err(ServiceError::AlreadyAnswered);
} else {
return Err(ServiceError::AuthorizationRequired);
}
}
#[get("/api/score")]
async fn score(
//session: Session,
// payload: web::Json<SomeData>,
data: web::Data<Data>,
id: Identity,
) -> ServiceResult<impl Responder> {
debug!("{:?}", id.identity());
is_authenticated(&id)?;
let recs = sqlx::query_as!(
Leader,
"SELECT name, points FROM users ORDER BY points DESC"
)
.fetch_all(&data.db)
.await?;
Ok(HttpResponse::Ok().json(recs))
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Leader {
name: String,
points: i32,
}
#[get("/api/leaderboard")]
async fn leaderboard(
//session: Session,
// payload: web::Json<SomeData>,
data: web::Data<Data>,
id: Identity,
) -> ServiceResult<impl Responder> {
is_authenticated(&id)?;
let recs = sqlx::query_as!(
Leader,
"SELECT name, points FROM users ORDER BY points DESC"
)
.fetch_all(&data.db)
.await?;
debug!("{:?}", &recs);
Ok(HttpResponse::Ok().json(recs))
}
pub fn services(cfg: &mut ServiceConfig) {
cfg.service(get_question);
cfg.service(verify_answer);
cfg.service(score);
cfg.service(leaderboard);
cfg.service(signout);
cfg.service(signin);
cfg.service(signup);
}
fn is_authenticated(id: &Identity) -> ServiceResult<bool> {
debug!("{:?}", id.identity());
// access request identity
if let Some(_) = id.identity() {
Ok(true)
} else {
Err(ServiceError::AuthorizationRequired)
}
}

153
guard/src/settings.rs Normal file
View file

@ -0,0 +1,153 @@
/*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::env;
use config::{Config, ConfigError, Environment, File};
use log::debug;
use serde::Deserialize;
use url::Url;
#[derive(Debug, Clone, Deserialize)]
pub struct Server {
// TODO yet to be configured
pub allow_registration: bool,
pub port: u32,
pub domain: String,
pub cookie_secret: String,
pub ip: String,
}
impl Server {
pub fn get_ip(&self) -> String {
format!("{}:{}", self.ip, self.port)
}
}
#[derive(Debug, Clone, Deserialize)]
struct DatabaseBuilder {
pub port: u32,
pub hostname: String,
pub username: String,
pub password: String,
pub name: String,
pub url: String,
}
impl DatabaseBuilder {
fn extract_database_url(url: &Url) -> Self {
// if url.scheme() != "postgres" || url.scheme() != "postgresql" {
// panic!("URL must be postgres://url, url found: {}", url.scheme());
// } else {
debug!("Databse name: {}", url.path());
let mut path = url.path().split("/");
path.next();
let name = path.next().expect("no database name").to_string();
DatabaseBuilder {
port: url.port().expect("Enter database port").into(),
hostname: url.host().expect("Enter database host").to_string(),
username: url.username().into(),
url: url.to_string(),
password: url.password().expect("Enter database password").into(),
name,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Database {
pub url: String,
pub pool: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
pub debug: bool,
pub database: Database,
pub server: Server,
}
#[cfg(not(tarpaulin_include))]
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();
// setting default values
#[cfg(test)]
s.set_default("database.pool", 2.to_string())
.expect("Couldn't get the number of CPUs");
// merging default config from file
s.merge(File::with_name("./config/default.toml"))?;
// TODO change PLACEHOLDER to app name
s.merge(Environment::with_prefix("WEBHUNT"))?;
match env::var("PORT") {
Ok(val) => {
s.set("server.port", val).unwrap();
}
Err(e) => println!("couldn't interpret PORT: {}", e),
}
match env::var("DATABASE_URL") {
Ok(val) => {
let url = Url::parse(&val).expect("couldn't parse Database URL");
let database_conf = DatabaseBuilder::extract_database_url(&url);
set_from_database_url(&mut s, &database_conf);
}
Err(e) => println!("couldn't interpret DATABASE_URL: {}", e),
}
set_database_url(&mut s);
s.try_into()
}
}
fn set_from_database_url(s: &mut Config, database_conf: &DatabaseBuilder) {
s.set("database.username", database_conf.username.clone())
.expect("Couldn't set database username");
s.set("database.password", database_conf.password.clone())
.expect("Couldn't access database password");
s.set("database.hostname", database_conf.hostname.clone())
.expect("Couldn't access database hostname");
s.set("database.port", database_conf.port as i64)
.expect("Couldn't access database port");
s.set("database.name", database_conf.name.clone())
.expect("Couldn't access database name");
}
fn set_database_url(s: &mut Config) {
s.set(
"database.url",
format!(
r"postgres://{}:{}@{}:{}/{}",
s.get::<String>("database.username")
.expect("Couldn't access database username"),
s.get::<String>("database.password")
.expect("Couldn't access database password"),
s.get::<String>("database.hostname")
.expect("Couldn't access database hostname"),
s.get::<String>("database.port")
.expect("Couldn't access database port"),
s.get::<String>("database.name")
.expect("Couldn't access database name")
),
)
.expect("Couldn't set databse url");
}