|
| 1 | +use crate::authentication::AuthError; |
| 2 | +use crate::authentication::{validate_credentials, Credentials}; |
| 3 | +use crate::routes::error_chain_fmt; |
| 4 | +use crate::startup::HmacSecret; |
| 5 | +use actix_web::error::InternalError; |
| 6 | +use actix_web::http::header::LOCATION; |
| 7 | +use actix_web::web; |
| 8 | +use actix_web::HttpResponse; |
| 9 | +use hmac::{Hmac, Mac}; |
| 10 | +use secrecy::{ExposeSecret, Secret}; |
| 11 | +use sqlx::PgPool; |
| 12 | + |
| 13 | +#[derive(serde::Deserialize)] |
| 14 | +pub struct FormData { |
| 15 | + username: String, |
| 16 | + password: Secret<String>, |
| 17 | +} |
| 18 | + |
| 19 | +#[tracing::instrument( |
| 20 | + skip(form, pool, secret), |
| 21 | + fields(username=tracing::field::Empty, user_id=tracing::field::Empty) |
| 22 | +)] |
| 23 | +// We are now injecting `PgPool` to retrieve stored credentials from the database |
| 24 | +pub async fn login( |
| 25 | + form: web::Form<FormData>, |
| 26 | + pool: web::Data<PgPool>, |
| 27 | + secret: web::Data<HmacSecret>, |
| 28 | +) -> Result<HttpResponse, InternalError<LoginError>> { |
| 29 | + let credentials = Credentials { |
| 30 | + username: form.0.username, |
| 31 | + password: form.0.password, |
| 32 | + }; |
| 33 | + tracing::Span::current().record("username", &tracing::field::display(&credentials.username)); |
| 34 | + match validate_credentials(credentials, &pool).await { |
| 35 | + Ok(user_id) => { |
| 36 | + tracing::Span::current().record("user_id", &tracing::field::display(&user_id)); |
| 37 | + Ok(HttpResponse::SeeOther() |
| 38 | + .insert_header((LOCATION, "/")) |
| 39 | + .finish()) |
| 40 | + } |
| 41 | + Err(e) => { |
| 42 | + let e = match e { |
| 43 | + AuthError::InvalidCredentials(_) => LoginError::AuthError(e.into()), |
| 44 | + AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()), |
| 45 | + }; |
| 46 | + let query_string = format!("error={}", urlencoding::Encoded::new(e.to_string())); |
| 47 | + let hmac_tag = { |
| 48 | + let mut mac = |
| 49 | + Hmac::<sha2::Sha256>::new_from_slice(secret.0.expose_secret().as_bytes()) |
| 50 | + .unwrap(); |
| 51 | + mac.update(query_string.as_bytes()); |
| 52 | + mac.finalize().into_bytes() |
| 53 | + }; |
| 54 | + let response = HttpResponse::SeeOther() |
| 55 | + .insert_header((LOCATION, format!("/login?{query_string}&tag={hmac_tag:x}"))) |
| 56 | + .finish(); |
| 57 | + Err(InternalError::from_response(e, response)) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[derive(thiserror::Error)] |
| 63 | +pub enum LoginError { |
| 64 | + #[error("Authentication failed")] |
| 65 | + AuthError(#[source] anyhow::Error), |
| 66 | + #[error("Something went wrong")] |
| 67 | + UnexpectedError(#[from] anyhow::Error), |
| 68 | +} |
| 69 | + |
| 70 | +impl std::fmt::Debug for LoginError { |
| 71 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 72 | + error_chain_fmt(self, f) |
| 73 | + } |
| 74 | +} |
0 commit comments