From 156122eba44caf979061d9540a422ad30ff8ab93 Mon Sep 17 00:00:00 2001 From: philipp Date: Tue, 25 Jul 2023 13:55:16 +0200 Subject: [PATCH] log useragent on login --- src/tera/auth.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/tera/auth.rs b/src/tera/auth.rs index 0476940..90edcbc 100644 --- a/src/tera/auth.rs +++ b/src/tera/auth.rs @@ -2,12 +2,13 @@ use rocket::{ form::Form, get, http::{Cookie, CookieJar}, + outcome::Outcome, post, - request::FlashMessage, + request::{FlashMessage, FromRequest}, response::{Flash, Redirect}, routes, time::{Duration, OffsetDateTime}, - FromForm, Route, State, + FromForm, Request, Route, State, }; use rocket_dyn_templates::{context, tera, Template}; use serde_json::json; @@ -39,12 +40,37 @@ struct LoginForm<'r> { password: &'r str, } +#[derive(Debug)] +pub struct UserAgent(String); + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for UserAgent { + type Error = std::convert::Infallible; + + async fn from_request( + request: &'r Request<'_>, + ) -> rocket::request::Outcome { + let agent = request + .headers() + .get_one("User-Agent") + .unwrap_or("Unknown") + .to_string(); + Outcome::Success(UserAgent(agent)) + } +} + #[post("/", data = "")] async fn login( login: Form>, db: &State, cookies: &CookieJar<'_>, + agent: UserAgent, ) -> Flash { + Log::create( + db, + format!("{} has this useragent: {:?}", login.name, agent), + ) + .await; let user = match User::login(db, login.name, login.password).await { Ok(user) => user, Err(LoginError::NoPasswordSet(user)) => {