Merge branch 'main' into better-caching

This commit is contained in:
KitaitiMakoto
2020-12-06 17:31:53 +00:00
43 changed files with 1727 additions and 928 deletions
+13 -23
View File
@@ -62,30 +62,20 @@ pub fn oauth(
let conn = &*rockets.conn;
let app = App::find_by_client_id(conn, &query.client_id)?;
if app.client_secret == query.client_secret {
if let Ok(user) = User::find_by_fqn(&rockets, &query.username) {
if user.auth(&query.password) {
let token = ApiToken::insert(
conn,
NewApiToken {
app_id: app.id,
user_id: user.id,
value: random_hex(),
scopes: query.scopes.clone(),
},
)?;
Ok(Json(json!({
"token": token.value
})))
} else {
Ok(Json(json!({
"error": "Invalid credentials"
})))
}
if let Ok(user) = User::login(conn, &query.username, &query.password) {
let token = ApiToken::insert(
conn,
NewApiToken {
app_id: app.id,
user_id: user.id,
value: random_hex(),
scopes: query.scopes.clone(),
},
)?;
Ok(Json(json!({
"token": token.value
})))
} else {
// Making fake password verification to avoid different
// response times that would make it possible to know
// if a username is registered or not.
User::get(conn, 1)?.auth(&query.password);
Ok(Json(json!({
"error": "Invalid credentials"
})))
+2 -2
View File
@@ -1,5 +1,5 @@
use chrono::NaiveDateTime;
use heck::{CamelCase, KebabCase};
use heck::KebabCase;
use rocket_contrib::json::Json;
use crate::api::{authorization::*, Api};
@@ -181,7 +181,7 @@ pub fn create(
Tag::insert(
conn,
NewTag {
tag: hashtag.to_camel_case(),
tag: hashtag,
is_hashtag: true,
post_id: post.id,
},
Regular → Executable
+26 -1
View File
@@ -10,6 +10,7 @@ extern crate serde_json;
#[macro_use]
extern crate validator_derive;
use chrono::Utc;
use clap::App;
use diesel::r2d2::ConnectionManager;
use plume_models::{
@@ -21,6 +22,8 @@ use plume_models::{
};
use rocket_csrf::CsrfFairingBuilder;
use scheduled_thread_pool::ScheduledThreadPool;
use std::fs;
use std::path::Path;
use std::process::exit;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -98,8 +101,30 @@ Then try to restart Plume.
}
let workpool = ScheduledThreadPool::with_name("worker {}", num_cpus::get());
// we want a fast exit here, so
let mut open_searcher =
UnmanagedSearcher::open(&CONFIG.search_index, &CONFIG.search_tokenizers);
if let Err(Error::Search(SearcherError::InvalidIndexDataError)) = open_searcher {
if UnmanagedSearcher::create(&CONFIG.search_index, &CONFIG.search_tokenizers).is_err() {
let current_path = Path::new(&CONFIG.search_index);
let backup_path = format!("{}.{}", &current_path.display(), Utc::now().timestamp());
let backup_path = Path::new(&backup_path);
fs::rename(current_path, backup_path)
.expect("main: error on backing up search index directory for recreating");
if UnmanagedSearcher::create(&CONFIG.search_index, &CONFIG.search_tokenizers).is_ok() {
if fs::remove_dir_all(backup_path).is_err() {
eprintln!(
"error on removing backup directory: {}. it remains",
backup_path.display()
);
}
} else {
panic!("main: error on recreating search index in new index format. remove search index and run `plm search init` manually");
}
}
open_searcher = UnmanagedSearcher::open(&CONFIG.search_index, &CONFIG.search_tokenizers);
}
#[allow(clippy::match_wild_err_arm)]
let searcher = match UnmanagedSearcher::open(&CONFIG.search_index, &CONFIG.search_tokenizers) {
let searcher = match open_searcher {
Err(Error::Search(e)) => match e {
SearcherError::WriteLockAcquisitionError => panic!(
r#"
+13 -5
View File
@@ -210,11 +210,19 @@ pub fn add_email_blocklist(
form: LenientForm<NewBlocklistedEmail>,
rockets: PlumeRocket,
) -> Result<Flash<Redirect>, ErrorPage> {
BlocklistedEmail::insert(&*rockets.conn, form.0)?;
Ok(Flash::success(
Redirect::to(uri!(admin_email_blocklist: page = None)),
i18n!(rockets.intl.catalog, "Email Blocked"),
))
let result = BlocklistedEmail::insert(&*rockets.conn, form.0);
if let Err(Error::Db(_)) = result {
Ok(Flash::error(
Redirect::to(uri!(admin_email_blocklist: page = None)),
i18n!(rockets.intl.catalog, "Email already blocked"),
))
} else {
Ok(Flash::success(
Redirect::to(uri!(admin_email_blocklist: page = None)),
i18n!(rockets.intl.catalog, "Email Blocked"),
))
}
}
#[get("/admin/emails?<page>")]
pub fn admin_email_blocklist(
+6 -7
View File
@@ -1,5 +1,5 @@
use chrono::Utc;
use heck::{CamelCase, KebabCase};
use heck::KebabCase;
use rocket::request::LenientForm;
use rocket::response::{Flash, Redirect};
use rocket_i18n::I18n;
@@ -314,18 +314,17 @@ pub fn update(
let tags = form
.tags
.split(',')
.map(|t| t.trim().to_camel_case())
.map(|t| t.trim())
.filter(|t| !t.is_empty())
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|t| Tag::build_activity(t).ok())
.filter_map(|t| Tag::build_activity(t.to_string()).ok())
.collect::<Vec<_>>();
post.update_tags(&conn, tags)
.expect("post::update: tags error");
let hashtags = hashtags
.into_iter()
.map(|h| h.to_camel_case())
.collect::<HashSet<_>>()
.into_iter()
.filter_map(|t| Tag::build_activity(t).ok())
@@ -489,14 +488,14 @@ pub fn create(
let tags = form
.tags
.split(',')
.map(|t| t.trim().to_camel_case())
.map(|t| t.trim())
.filter(|t| !t.is_empty())
.collect::<HashSet<_>>();
for tag in tags {
Tag::insert(
&*conn,
NewTag {
tag,
tag: tag.to_string(),
is_hashtag: false,
post_id: post.id,
},
@@ -507,7 +506,7 @@ pub fn create(
Tag::insert(
&*conn,
NewTag {
tag: hashtag.to_camel_case(),
tag: hashtag,
is_hashtag: true,
post_id: post.id,
},
+3 -22
View File
@@ -48,38 +48,19 @@ pub fn create(
rockets: PlumeRocket,
) -> RespondOrRedirect {
let conn = &*rockets.conn;
let user = User::find_by_email(&*conn, &form.email_or_name)
.or_else(|_| User::find_by_fqn(&rockets, &form.email_or_name));
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
Err(e) => e,
};
let user = User::login(conn, &form.email_or_name, &form.password);
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()
}
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
User::get(&*conn, 1)
.map(|u| u.auth(&form.password))
.expect("No user is registered");
let mut err = ValidationError::new("invalid_login");
err.message = Some(Cow::from("Invalid username, or password"));
errors.add("email_or_name", err);
String::new()
};
if !errors.is_empty() {
return render!(session::login(&rockets.to_context(), None, &*form, errors)).into();
}
};
cookies.add_private(
Cookie::build(AUTH_COOKIE, user_id)
+1 -1
View File
@@ -541,7 +541,7 @@ pub fn create(
Role::Normal,
"",
form.email.to_string(),
User::hash_pass(&form.password).map_err(to_validation)?,
Some(User::hash_pass(&form.password).map_err(to_validation)?),
).map_err(to_validation)?;
Ok(Flash::success(
Redirect::to(uri!(super::session::new: m = _)),