Read the http header from the proxy to get the client IP

This commit is contained in:
Greg Burri 2022-11-27 02:01:23 +01:00
parent b6235fb76c
commit 8a3fef096d
6 changed files with 29 additions and 25 deletions

1
Cargo.lock generated
View file

@ -1567,6 +1567,7 @@ dependencies = [
"futures", "futures",
"itertools", "itertools",
"lettre", "lettre",
"log",
"r2d2", "r2d2",
"r2d2_sqlite", "r2d2_sqlite",
"rand", "rand",

View file

@ -5,6 +5,7 @@
* Two CSS: one for desktop and one for mobile * Two CSS: one for desktop and one for mobile
* Define the logic behind each page and action. * Define the logic behind each page and action.
[ok] How to log error to journalctl?
[ok] Sign out [ok] Sign out
[ok] Read all the askama doc and see if the current approach is good [ok] Read all the askama doc and see if the current approach is good
[ok] Handle 404 [ok] Handle 404

View file

@ -17,6 +17,7 @@ ron = "0.8" # Rust object notation, to load configuration files.
itertools = "0.10" itertools = "0.10"
clap = {version = "4", features = ["derive"]} clap = {version = "4", features = ["derive"]}
log = "0.4"
env_logger = "0.9" env_logger = "0.9"
r2d2_sqlite = "0.21" # Connection pool with rusqlite (SQLite access). r2d2_sqlite = "0.21" # Connection pool with rusqlite (SQLite access).
@ -33,4 +34,4 @@ rand_core = {version = "0.6", features = ["std"]}
rand = "0.8" rand = "0.8"
lettre = {version = "0.10", default-features = false, features = ["smtp-transport", "pool", "hostname", "builder", "rustls-tls"]} lettre = {version = "0.10", default-features = false, features = ["smtp-transport", "pool", "hostname", "builder", "rustls-tls"]}

View file

@ -3,4 +3,5 @@ pub const FILE_CONF: &str = "conf.ron";
pub const DB_DIRECTORY: &str = "data"; pub const DB_DIRECTORY: &str = "data";
pub const DB_FILENAME: &str = "recipes.sqlite"; pub const DB_FILENAME: &str = "recipes.sqlite";
pub const SQL_FILENAME: &str = "sql/version_{VERSION}.sql"; pub const SQL_FILENAME: &str = "sql/version_{VERSION}.sql";
pub const VALIDATION_TOKEN_DURATION: i64 = 1 * 60 * 60; // 1 hour. [s]. pub const VALIDATION_TOKEN_DURATION: i64 = 1 * 60 * 60; // 1 hour. [s].
pub const REVERSE_PROXY_IP_HTTP_FIELD: &str = "x-real-ip";

View file

@ -1,8 +1,7 @@
use lettre::{transport::smtp::{authentication::Credentials}, Message, SmtpTransport, Transport}; use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
/// ///
pub fn send_validation(site_url: &str, email: &str, token: &str, smtp_login: &str, smtp_password: &str) -> Result<(), Box<dyn std::error::Error>> { pub fn send_validation(site_url: &str, email: &str, token: &str, smtp_login: &str, smtp_password: &str) -> Result<(), Box<dyn std::error::Error>> {
let email = Message::builder() let email = Message::builder()
.message_id(None) .message_id(None)
.from("recipes@gburri.org".parse()?) .from("recipes@gburri.org".parse()?)
@ -15,7 +14,7 @@ pub fn send_validation(site_url: &str, email: &str, token: &str, smtp_login: &st
let mailer = SmtpTransport::relay("mail.gandi.net")?.credentials(credentials).build(); let mailer = SmtpTransport::relay("mail.gandi.net")?.credentials(credentials).build();
if let Err(error) = mailer.send(&email) { if let Err(error) = mailer.send(&email) {
println!("Error when sending E-mail:\n{:?}", &error); eprintln!("Error when sending E-mail:\n{:?}", &error);
} }
Ok(()) Ok(())

View file

@ -6,6 +6,7 @@ use askama_actix::{Template, TemplateToResponse};
use chrono::{prelude::*, Duration}; use chrono::{prelude::*, Duration};
use clap::Parser; use clap::Parser;
use serde::Deserialize; use serde::Deserialize;
use log::{debug, error, log_enabled, info, Level};
use config::Config; use config::Config;
use user::User; use user::User;
@ -23,8 +24,14 @@ const COOKIE_AUTH_TOKEN_NAME: &str = "auth_token";
///// UTILS ///// ///// UTILS /////
fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) { fn get_ip_and_user_agent(req: &HttpRequest) -> (String, String) {
let ip =
match req.headers().get(consts::REVERSE_PROXY_IP_HTTP_FIELD) {
Some(v) => v.to_str().unwrap_or_default().to_string(),
None => req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default()
};
let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string(); let user_agent = req.headers().get(header::USER_AGENT).map(|v| v.to_str().unwrap_or_default()).unwrap_or_default().to_string();
let ip = req.peer_addr().map(|addr| addr.ip().to_string()).unwrap_or_default();
(ip, user_agent) (ip, user_agent)
} }
@ -42,12 +49,12 @@ fn get_current_user(req: &HttpRequest, connection: &web::Data<db::Connection>) -
Ok(user) => Ok(user) =>
Some(user), Some(user),
Err(error) => { Err(error) => {
eprintln!("Error during authentication: {:?}", error); error!("Error during authentication: {}", error);
None None
} }
}, },
Err(error) => { Err(error) => {
eprintln!("Error during authentication: {:?}", error); error!("Error during authentication: {}", error);
None None
}, },
}, },
@ -146,8 +153,6 @@ enum SignUpError {
#[post("/signup")] #[post("/signup")]
async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connection: web::Data<db::Connection>, config: web::Data<Config>) -> impl Responder { async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connection: web::Data<db::Connection>, config: web::Data<Config>) -> impl Responder {
println!("Sign up, email: {}, passwords: {}/{}", form.email, form.password_1, form.password_2);
fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>, user: Option<User>) -> HttpResponse { fn error_response(error: SignUpError, form: &web::Form<SignUpFormData>, user: Option<User>) -> HttpResponse {
SignUpFormTemplate { SignUpFormTemplate {
user, user,
@ -212,13 +217,13 @@ async fn sign_up_post(req: HttpRequest, form: web::Form<SignUpFormData>, connect
.insert_header((header::LOCATION, "/signup_check_email")) .insert_header((header::LOCATION, "/signup_check_email"))
.finish(), .finish(),
Err(error) => { Err(error) => {
eprintln!("Email validation error: {:?}", error); error!("Email validation error: {}", error);
error_response(SignUpError::UnableSendEmail, &form, user) error_response(SignUpError::UnableSendEmail, &form, user)
}, },
} }
}, },
Err(error) => { Err(error) => {
eprintln!("Signup database error: {:?}", error); error!("Signup database error: {}", error);
error_response(SignUpError::DatabaseError, &form, user) error_response(SignUpError::DatabaseError, &form, user)
}, },
} }
@ -250,7 +255,7 @@ async fn sign_up_validation(req: HttpRequest, query: web::Query<HashMap<String,
Ok(user) => Ok(user) =>
Some(user), Some(user),
Err(error) => { Err(error) => {
eprintln!("Error retrieving user by id: {}", error); error!("Error retrieving user by id: {}", error);
None None
} }
}; };
@ -263,7 +268,7 @@ async fn sign_up_validation(req: HttpRequest, query: web::Query<HashMap<String,
}.to_response(); }.to_response();
if let Err(error) = response.add_cookie(&cookie) { if let Err(error) = response.add_cookie(&cookie) {
eprintln!("Unable to set cookie after validation: {:?}", error); error!("Unable to set cookie after validation: {}", error);
}; };
response response
@ -324,8 +329,6 @@ enum SignInError {
#[post("/signin")] #[post("/signin")]
async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connection: web::Data<db::Connection>) -> impl Responder { async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connection: web::Data<db::Connection>) -> impl Responder {
println!("Sign in, email: {}, password: {}", form.email, form.password);
fn error_response(error: SignInError, form: &web::Form<SignInFormData>, user: Option<User>) -> HttpResponse { fn error_response(error: SignInError, form: &web::Form<SignInFormData>, user: Option<User>) -> HttpResponse {
SignInFormTemplate { SignInFormTemplate {
user, user,
@ -354,12 +357,12 @@ async fn sign_in_post(req: HttpRequest, form: web::Form<SignInFormData>, connect
.insert_header((header::LOCATION, "/")) .insert_header((header::LOCATION, "/"))
.finish(); .finish();
if let Err(error) = response.add_cookie(&cookie) { if let Err(error) = response.add_cookie(&cookie) {
eprintln!("Unable to set cookie after sign in: {:?}", error); error!("Unable to set cookie after sign in: {}", error);
}; };
response response
}, },
Err(error) => { Err(error) => {
eprintln!("Signin error: {:?}", error); error!("Signin error: {}", error);
error_response(SignInError::AuthenticationFailed, &form, user) error_response(SignInError::AuthenticationFailed, &form, user)
}, },
} }
@ -377,11 +380,11 @@ async fn sign_out(req: HttpRequest, connection: web::Data<db::Connection>) -> im
if let Some(token_cookie) = req.cookie(COOKIE_AUTH_TOKEN_NAME) { if let Some(token_cookie) = req.cookie(COOKIE_AUTH_TOKEN_NAME) {
if let Err(error) = connection.sign_out(token_cookie.value()) { if let Err(error) = connection.sign_out(token_cookie.value()) {
eprintln!("Unable to sign out: {:?}", error); error!("Unable to sign out: {}", error);
}; };
if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) { if let Err(error) = response.add_removal_cookie(&Cookie::new(COOKIE_AUTH_TOKEN_NAME, "")) {
eprintln!("Unable to set a removal cookie after sign out: {:?}", error); error!("Unable to set a removal cookie after sign out: {}", error);
}; };
}; };
response response
@ -400,7 +403,7 @@ async fn not_found(req: HttpRequest, connection: web::Data<db::Connection>) -> i
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
if process_args() { return Ok(()) } if process_args() { return Ok(()) }
std::env::set_var("RUST_LOG", "actix_web=debug"); std::env::set_var("RUST_LOG", "info,actix_web=info");
env_logger::init(); env_logger::init();
println!("Starting Recipes as web server..."); println!("Starting Recipes as web server...");
@ -412,8 +415,6 @@ async fn main() -> std::io::Result<()> {
let db_connection = web::Data::new(db::Connection::new().unwrap()); let db_connection = web::Data::new(db::Connection::new().unwrap());
std::env::set_var("RUST_LOG", "actix_web=info");
let server = let server =
HttpServer::new(move || { HttpServer::new(move || {
App::new() App::new()
@ -450,13 +451,13 @@ fn process_args() -> bool {
match db::Connection::new() { match db::Connection::new() {
Ok(con) => { Ok(con) => {
if let Err(error) = con.execute_file("sql/data_test.sql") { if let Err(error) = con.execute_file("sql/data_test.sql") {
println!("Error: {:?}", error); error!("{}", error);
} }
// Set the creation datetime to 'now'. // Set the creation datetime to 'now'.
con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap(); con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap();
}, },
Err(error) => { Err(error) => {
println!("Error: {:?}", error) error!("Error: {}", error)
}, },
} }