log useragent on login

This commit is contained in:
philipp 2023-07-25 13:55:16 +02:00
parent 9a3636f05f
commit 156122eba4

View File

@ -2,12 +2,13 @@ use rocket::{
form::Form, form::Form,
get, get,
http::{Cookie, CookieJar}, http::{Cookie, CookieJar},
outcome::Outcome,
post, post,
request::FlashMessage, request::{FlashMessage, FromRequest},
response::{Flash, Redirect}, response::{Flash, Redirect},
routes, routes,
time::{Duration, OffsetDateTime}, time::{Duration, OffsetDateTime},
FromForm, Route, State, FromForm, Request, Route, State,
}; };
use rocket_dyn_templates::{context, tera, Template}; use rocket_dyn_templates::{context, tera, Template};
use serde_json::json; use serde_json::json;
@ -39,12 +40,37 @@ struct LoginForm<'r> {
password: &'r str, 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<UserAgent, Self::Error> {
let agent = request
.headers()
.get_one("User-Agent")
.unwrap_or("Unknown")
.to_string();
Outcome::Success(UserAgent(agent))
}
}
#[post("/", data = "<login>")] #[post("/", data = "<login>")]
async fn login( async fn login(
login: Form<LoginForm<'_>>, login: Form<LoginForm<'_>>,
db: &State<SqlitePool>, db: &State<SqlitePool>,
cookies: &CookieJar<'_>, cookies: &CookieJar<'_>,
agent: UserAgent,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
Log::create(
db,
format!("{} has this useragent: {:?}", login.name, agent),
)
.await;
let user = match User::login(db, login.name, login.password).await { let user = match User::login(db, login.name, login.password).await {
Ok(user) => user, Ok(user) => user,
Err(LoginError::NoPasswordSet(user)) => { Err(LoginError::NoPasswordSet(user)) => {