Plume/src/routes/session.rs

249 lines
6.8 KiB
Rust
Raw Normal View History

2020-01-21 07:02:03 +01:00
use crate::routes::RespondOrRedirect;
use plume_models::lettre::Transport;
2019-03-20 17:56:17 +01:00
use rocket::http::ext::IntoOwned;
2018-05-19 09:39:59 +02:00
use rocket::{
2019-03-20 17:56:17 +01:00
http::{uri::Uri, Cookie, Cookies, SameSite},
request::LenientForm,
response::{Flash, Redirect},
2019-03-20 17:56:17 +01:00
State,
2018-05-19 09:39:59 +02:00
};
use rocket_i18n::I18n;
2019-03-20 17:56:17 +01:00
use std::{
borrow::Cow,
sync::{Arc, Mutex},
time::Instant,
};
2021-01-11 00:38:41 +01:00
use tracing::warn;
2019-03-20 17:56:17 +01:00
use validator::{Validate, ValidationError, ValidationErrors};
2018-04-24 11:21:39 +02:00
2020-01-21 07:02:03 +01:00
use crate::mail::{build_mail, Mailer};
use crate::template_utils::{IntoContext, Ructe};
use plume_models::{
2021-01-30 13:44:29 +01:00
db_conn::DbConn,
password_reset_requests::*,
2019-03-20 17:56:17 +01:00
users::{User, AUTH_COOKIE},
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
Error, PlumeRocket, CONFIG,
};
#[get("/login?<m>")]
2021-01-30 13:44:29 +01:00
pub fn new(m: Option<String>, conn: DbConn, rockets: PlumeRocket) -> Ructe {
render!(session::login(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
m,
&LoginForm::default(),
ValidationErrors::default()
))
}
#[derive(Default, FromForm, Validate)]
pub struct LoginForm {
2022-01-06 20:55:49 +01:00
#[validate(length(min = 1, message = "We need an email, or a username to identify you"))]
pub email_or_name: String,
2022-01-06 20:55:49 +01:00
#[validate(length(min = 1, message = "Your password can't be empty"))]
2019-03-20 17:56:17 +01:00
pub password: String,
2018-04-23 11:52:44 +02:00
}
#[post("/login", data = "<form>")]
2019-03-20 17:56:17 +01:00
pub fn create(
form: LenientForm<LoginForm>,
2020-01-21 07:02:03 +01:00
mut cookies: Cookies<'_>,
2021-01-30 13:44:29 +01:00
conn: DbConn,
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
rockets: PlumeRocket,
) -> RespondOrRedirect {
2018-07-06 11:51:19 +02:00
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
2019-03-20 17:56:17 +01:00
Err(e) => e,
2018-04-23 11:52:44 +02:00
};
2021-01-30 13:44:29 +01:00
let user = User::login(&conn, &form.email_or_name, &form.password);
let user_id = if let Ok(user) = user {
user.id.to_string()
} else {
2018-08-18 12:37:40 +02:00
let mut err = ValidationError::new("invalid_login");
err.message = Some(Cow::from("Invalid username, or password"));
errors.add("email_or_name", err);
2021-01-30 13:44:29 +01:00
return render!(session::login(
&(&conn, &rockets).to_context(),
None,
&*form,
errors
))
.into();
};
cookies.add_private(
Cookie::build(AUTH_COOKIE, user_id)
.same_site(SameSite::Lax)
.finish(),
);
let destination = rockets
.flash_msg
.clone()
.and_then(
|(name, msg)| {
if name == "callback" {
Some(msg)
} else {
None
}
},
)
.unwrap_or_else(|| "/".to_owned());
if let Ok(uri) = Uri::parse(&destination).map(IntoOwned::into_owned) {
Flash::success(
Redirect::to(uri),
i18n!(&rockets.intl.catalog, "You are now connected."),
)
.into()
2018-07-06 11:51:19 +02:00
} else {
render!(session::login(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets.intl.catalog, None, None),
None,
&*form,
errors
))
.into()
2018-04-23 11:52:44 +02:00
}
}
2018-04-23 13:13:49 +02:00
#[get("/logout")]
2020-01-21 07:02:03 +01:00
pub fn delete(mut cookies: Cookies<'_>, intl: I18n) -> Flash<Redirect> {
if let Some(cookie) = cookies.get_private(AUTH_COOKIE) {
cookies.remove_private(cookie);
}
Flash::success(
Redirect::to("/"),
i18n!(intl.catalog, "You are now logged off."),
)
2018-04-23 13:13:49 +02:00
}
#[derive(Clone)]
pub struct ResetRequest {
pub mail: String,
pub id: String,
pub creation_date: Instant,
}
impl PartialEq for ResetRequest {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
#[get("/password-reset")]
2021-01-30 13:44:29 +01:00
pub fn password_reset_request_form(conn: DbConn, rockets: PlumeRocket) -> Ructe {
render!(session::password_reset_request(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
&ResetForm::default(),
ValidationErrors::default()
))
}
#[derive(FromForm, Validate, Default)]
pub struct ResetForm {
#[validate(email)]
pub email: String,
}
#[post("/password-reset", data = "<form>")]
pub fn password_reset_request(
2020-01-21 07:02:03 +01:00
mail: State<'_, Arc<Mutex<Mailer>>>,
form: LenientForm<ResetForm>,
2021-01-30 13:44:29 +01:00
conn: DbConn,
rockets: PlumeRocket,
) -> Ructe {
2021-01-30 13:44:29 +01:00
if User::find_by_email(&conn, &form.email).is_ok() {
let token = PasswordResetRequest::insert(&conn, &form.email)
.expect("password_reset_request::insert: error");
let url = format!("https://{}/password-reset/{}", CONFIG.base_url, token);
if let Some(message) = build_mail(
form.email.clone(),
i18n!(rockets.intl.catalog, "Password reset"),
i18n!(rockets.intl.catalog, "Here is the link to reset your password: {0}"; url),
) {
if let Some(ref mut mail) = *mail.lock().unwrap() {
2019-03-20 17:56:17 +01:00
mail.send(message.into())
.map_err(|_| warn!("Couldn't send password reset email"))
2019-03-20 17:56:17 +01:00
.ok();
}
}
}
2021-01-30 13:44:29 +01:00
render!(session::password_reset_request_ok(
&(&conn, &rockets).to_context()
))
}
#[get("/password-reset/<token>")]
2021-01-30 13:44:29 +01:00
pub fn password_reset_form(
token: String,
conn: DbConn,
rockets: PlumeRocket,
) -> Result<Ructe, Ructe> {
PasswordResetRequest::find_by_token(&conn, &token)
.map_err(|err| password_reset_error_response(err, &conn, &rockets))?;
Ok(render!(session::password_reset(
2021-01-30 13:44:29 +01:00
&(&conn, &rockets).to_context(),
&NewPasswordForm::default(),
ValidationErrors::default()
)))
}
#[derive(FromForm, Default, Validate)]
2019-03-20 17:56:17 +01:00
#[validate(schema(
function = "passwords_match",
2022-01-06 20:55:49 +01:00
skip_on_field_errors = false,
2019-03-20 17:56:17 +01:00
message = "Passwords are not matching"
))]
pub struct NewPasswordForm {
pub password: String,
pub password_confirmation: String,
}
fn passwords_match(form: &NewPasswordForm) -> Result<(), ValidationError> {
if form.password != form.password_confirmation {
Err(ValidationError::new("password_match"))
} else {
Ok(())
}
}
#[post("/password-reset/<token>", data = "<form>")]
pub fn password_reset(
token: String,
form: LenientForm<NewPasswordForm>,
2021-01-30 13:44:29 +01:00
conn: DbConn,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, Ructe> {
2021-01-30 13:44:29 +01:00
form.validate().map_err(|err| {
render!(session::password_reset(
&(&conn, &rockets).to_context(),
&form,
err
))
})?;
2021-01-30 13:44:29 +01:00
PasswordResetRequest::find_and_delete_by_token(&conn, &token)
.and_then(|request| User::find_by_email(&conn, &request.email))
.and_then(|user| user.reset_password(&conn, &form.password))
.map_err(|err| password_reset_error_response(err, &conn, &rockets))?;
Ok(Flash::success(
2021-01-15 17:13:45 +01:00
Redirect::to(uri!(new: m = _)),
i18n!(
rockets.intl.catalog,
"Your password was successfully reset."
),
))
}
2021-01-30 13:44:29 +01:00
fn password_reset_error_response(err: Error, conn: &DbConn, rockets: &PlumeRocket) -> Ructe {
match err {
Error::Expired => render!(session::password_reset_request_expired(
2021-01-30 13:44:29 +01:00
&(conn, rockets).to_context()
)),
2021-01-30 13:44:29 +01:00
_ => render!(errors::not_found(&(conn, rockets).to_context())),
}
}