Skip to content

Commit

Permalink
finish chapter 10
Browse files Browse the repository at this point in the history
  • Loading branch information
josemoura212 committed Jun 29, 2024
1 parent c0ff165 commit cfd230c
Show file tree
Hide file tree
Showing 30 changed files with 945 additions and 450 deletions.

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

96 changes: 96 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ name = "zero2prod"
actix-session = { version = "0.9.0", features = ["redis-rs-tls-session"] }
actix-web = "4.5.1"
actix-web-flash-messages = { version = "0.4.2", features = ["cookies"] }
actix-web-lab = "0.20.2"
anyhow = "1.0.86"
argon2 = { version = "0.5.3", features = ["std"] }
base64 = "0.22.1"
Expand Down
49 changes: 49 additions & 0 deletions src/authentication/middleware.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use crate::session_state::TypedSession;
use crate::utils::{e500, see_other};
use actix_web::body::MessageBody;
use actix_web::dev::{ServiceRequest, ServiceResponse};
use actix_web::error::InternalError;
use actix_web::FromRequest;
use actix_web::HttpMessage;
use actix_web_lab::middleware::Next;
use std::ops::Deref;
use uuid::Uuid;

#[derive(Copy, Clone, Debug)]
pub struct UserId(Uuid);

impl std::fmt::Display for UserId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}

impl Deref for UserId {
type Target = Uuid;

fn deref(&self) -> &Self::Target {
&self.0
}
}

pub async fn reject_anonymous_users(
mut req: ServiceRequest,
next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, actix_web::Error> {
let session = {
let (http_request, payload) = req.parts_mut();
TypedSession::from_request(http_request, payload).await
}?;

match session.get_user_id().map_err(e500)? {
Some(user_id) => {
req.extensions_mut().insert(UserId(user_id));
next.call(req).await
}
None => {
let response = see_other("/login");
let e = anyhow::anyhow!("The user has not logged in");
Err(InternalError::from_response(e, response).into())
}
}
}
7 changes: 7 additions & 0 deletions src/authentication/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
mod middleware;
mod password;

pub use password::{change_password, validate_credentials, AuthError, Credentials};

pub use middleware::reject_anonymous_users;
pub use middleware::UserId;
40 changes: 39 additions & 1 deletion src/authentication.rs → src/authentication/password.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::telemetry::spawn_blocking_with_tracing;
use anyhow::Context;
use argon2::{Argon2, PasswordHash, PasswordVerifier};
// use argon2::{Argon2, PasswordHash, PasswordVerifier};
use argon2::password_hash::SaltString;
use argon2::{Algorithm, Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier, Version};
use secrecy::{ExposeSecret, Secret};
use sqlx::PgPool;

Expand Down Expand Up @@ -50,6 +52,42 @@ pub async fn validate_credentials(
.map_err(AuthError::InvalidCredentials)
}

#[tracing::instrument(name = "Change password", skip(password, pool))]
pub async fn change_password(
user_id: uuid::Uuid,
password: Secret<String>,
pool: &PgPool,
) -> Result<(), anyhow::Error> {
let password_hash = spawn_blocking_with_tracing(move || compute_password_hash(password))
.await?
.context("Failed to hash password")?;
sqlx::query!(
r#"
UPDATE users
SET password_hash = $1
WHERE user_id = $2
"#,
password_hash.expose_secret(),
user_id
)
.execute(pool)
.await
.context("Failed to change user's password in the database.")?;
Ok(())
}

fn compute_password_hash(password: Secret<String>) -> Result<Secret<String>, anyhow::Error> {
let salt = SaltString::generate(&mut rand::thread_rng());
let password_hash = Argon2::new(
Algorithm::Argon2id,
Version::V0x13,
Params::new(15000, 2, 1, None).unwrap(),
)
.hash_password(password.expose_secret().as_bytes(), &salt)?
.to_string();
Ok(Secret::new(password_hash))
}

#[tracing::instrument(
name = "Validate credentials",
skip(expected_password_hash, password_candidate)
Expand Down
2 changes: 1 addition & 1 deletion src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl EmailClientSettings {
pub fn sender(&self) -> Result<SubscriberEmail, String> {
SubscriberEmail::parse(self.sender_email.clone())
}
pub fn timout(&self) -> std::time::Duration {
pub fn timeout(&self) -> std::time::Duration {
std::time::Duration::from_millis(self.timeout_milliseconds)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ pub mod routes;
pub mod session_state;
pub mod startup;
pub mod telemetry;
pub mod utils;
20 changes: 12 additions & 8 deletions src/routes/admin/dashboard.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
use crate::session_state::TypedSession;
use crate::utils::e500;
use actix_web::http::header::ContentType;
use actix_web::http::header::LOCATION;
use actix_web::{web, HttpResponse};
use anyhow::Context;
use sqlx::PgPool;
use uuid::Uuid;

fn e500<T>(e: T) -> actix_web::Error
where
T: std::fmt::Debug + std::fmt::Display + 'static,
{
actix_web::error::ErrorInternalServerError(e)
}

pub async fn admin_dashboard(
session: TypedSession,
pool: web::Data<PgPool>,
Expand All @@ -35,13 +29,23 @@ pub async fn admin_dashboard(
</head>
<body>
<p>Welcome {username}!</p>
<p>Available actions:</p>
<ol>
<li><a href="/admin/password">Change password</a></li>
<li><a href="/admin/newsletters">Post a newsletters</a></li>
<li>
<form name="logoutForm" action="/admin/logout" method="post">
<input type="submit" value="Logout">
</form>
</li>
</ol>
</body>
</html>"#
)))
}

#[tracing::instrument(name = "Get username", skip(pool))]
async fn get_username(user_id: Uuid, pool: &PgPool) -> Result<String, anyhow::Error> {
pub async fn get_username(user_id: Uuid, pool: &PgPool) -> Result<String, anyhow::Error> {
let row = sqlx::query!(
r#"
SELECT username
Expand Down
14 changes: 14 additions & 0 deletions src/routes/admin/logout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use crate::session_state::TypedSession;
use crate::utils::{e500, see_other};
use actix_web::HttpResponse;
use actix_web_flash_messages::FlashMessage;

pub async fn log_out(session: TypedSession) -> Result<HttpResponse, actix_web::Error> {
if session.get_user_id().map_err(e500)?.is_none() {
Ok(see_other("/login"))
} else {
session.log_out();
FlashMessage::info("You have successfully logged out.").send();
Ok(see_other("/login"))
}
}
6 changes: 6 additions & 0 deletions src/routes/admin/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
mod dashboard;
mod logout;
mod newsletters;
mod password;

pub use dashboard::admin_dashboard;
pub use logout::log_out;
pub use newsletters::*;
pub use password::*;
Loading

0 comments on commit cfd230c

Please sign in to comment.