Plume/src/routes/session.rs

249 lines
7.2 KiB
Rust
Raw Normal View History

2020-01-21 07:02:03 +01:00
use crate::routes::RespondOrRedirect;
use 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::{Form, 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,
};
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::{
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>")]
pub fn new(m: Option<String>, rockets: PlumeRocket) -> Ructe {
render!(session::login(
&rockets.to_context(),
m,
&LoginForm::default(),
ValidationErrors::default()
))
}
#[derive(Default, FromForm, Validate)]
pub struct LoginForm {
#[validate(length(min = "1", message = "We need an email, or a username to identify you"))]
pub email_or_name: String,
2018-08-18 12:37:40 +02: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<'_>,
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 {
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
let conn = &*rockets.conn;
let user = User::find_by_email(&*conn, &form.email_or_name)
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
.or_else(|_| User::find_by_fqn(&rockets, &form.email_or_name));
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
};
let user_id = if let Ok(user) = user {
if !user.auth(&form.password) {
let mut err = ValidationError::new("invalid_login");
err.message = Some(Cow::from("Invalid username, or password"));
errors.add("email_or_name", err);
String::new()
} else {
user.id.to_string()
}
} else {
// Fake password verification, only to avoid different login times
// that could be used to see if an email adress is registered or not
2019-03-20 17:56:17 +01:00
User::get(&*conn, 1)
.map(|u| u.auth(&form.password))
.expect("No user is registered");
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);
String::new()
};
2018-08-18 12:37:40 +02:00
if !errors.is_empty() {
return render!(session::login(&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(
&(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")]
pub fn password_reset_request_form(rockets: PlumeRocket) -> Ructe {
render!(session::password_reset_request(
&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: Form<ResetForm>,
rockets: PlumeRocket,
) -> Ructe {
if User::find_by_email(&*rockets.conn, &form.email).is_ok() {
let token = PasswordResetRequest::insert(&*rockets.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(|_| eprintln!("Couldn't send password reset email"))
2019-03-20 17:56:17 +01:00
.ok();
}
}
}
render!(session::password_reset_request_ok(&rockets.to_context()))
}
#[get("/password-reset/<token>")]
pub fn password_reset_form(token: String, rockets: PlumeRocket) -> Result<Ructe, Ructe> {
PasswordResetRequest::find_by_token(&*rockets.conn, &token)
.map_err(|err| password_reset_error_response(err, &rockets))?;
Ok(render!(session::password_reset(
&rockets.to_context(),
&NewPasswordForm::default(),
ValidationErrors::default()
)))
}
#[derive(FromForm, Default, Validate)]
2019-03-20 17:56:17 +01:00
#[validate(schema(
function = "passwords_match",
skip_on_field_errors = "false",
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,
2019-03-20 17:56:17 +01:00
form: Form<NewPasswordForm>,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, Ructe> {
form.validate()
.map_err(|err| render!(session::password_reset(&rockets.to_context(), &form, err)))?;
PasswordResetRequest::find_and_delete_by_token(&*rockets.conn, &token)
.and_then(|request| User::find_by_email(&*rockets.conn, &request.email))
.and_then(|user| user.reset_password(&*rockets.conn, &form.password))
.map_err(|err| password_reset_error_response(err, &rockets))?;
Ok(Flash::success(
Redirect::to(uri!(
new: m = _
)),
i18n!(
rockets.intl.catalog,
"Your password was successfully reset."
),
))
}
fn password_reset_error_response(err: Error, rockets: &PlumeRocket) -> Ructe {
match err {
Error::Expired => render!(session::password_reset_request_expired(
&rockets.to_context()
)),
_ => render!(errors::not_found(&rockets.to_context())),
}
}