Running cargo fmt.

This commit is contained in:
Dessalines 2019-11-01 23:43:21 -07:00
parent b89d6305ba
commit 76a47acacd
7 changed files with 101 additions and 90 deletions

View file

@ -5,13 +5,13 @@ use crate::db::community::*;
use crate::db::community_view::*; use crate::db::community_view::*;
use crate::db::moderator::*; use crate::db::moderator::*;
use crate::db::moderator_views::*; use crate::db::moderator_views::*;
use crate::db::password_reset_request::*;
use crate::db::post::*; use crate::db::post::*;
use crate::db::post_view::*; use crate::db::post_view::*;
use crate::db::user::*; use crate::db::user::*;
use crate::db::user_mention::*; use crate::db::user_mention::*;
use crate::db::user_mention_view::*; use crate::db::user_mention_view::*;
use crate::db::user_view::*; use crate::db::user_view::*;
use crate::db::password_reset_request::*;
use crate::db::*; use crate::db::*;
use crate::{extract_usernames, has_slurs, naive_from_unix, naive_now, remove_slurs, Settings}; use crate::{extract_usernames, has_slurs, naive_from_unix, naive_now, remove_slurs, Settings};
use failure::Error; use failure::Error;

View file

@ -1,7 +1,7 @@
use super::*; use super::*;
use crate::{generate_random_string, send_email};
use bcrypt::verify; use bcrypt::verify;
use std::str::FromStr; use std::str::FromStr;
use crate::{generate_random_string,send_email};
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct Login { pub struct Login {
@ -140,7 +140,6 @@ pub struct DeleteAccount {
auth: String, auth: String,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct PasswordReset { pub struct PasswordReset {
email: String, email: String,
@ -852,12 +851,7 @@ impl Perform<PasswordResetResponse> for Oper<PasswordReset> {
let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", user.name, hostname, &token); let html = &format!("<h1>Password Reset Request for {}</h1><br><a href={}/password_change/{}>Click here to reset your password</a>", user.name, hostname, &token);
match send_email(subject, user_email, &user.name, html) { match send_email(subject, user_email, &user.name, html) {
Ok(_o) => _o, Ok(_o) => _o,
Err(_e) => { Err(_e) => return Err(APIError::err(&self.op, &_e.to_string()))?,
return Err(APIError::err(
&self.op,
&_e.to_string(),
))?
}
}; };
Ok(PasswordResetResponse { Ok(PasswordResetResponse {

View file

@ -11,13 +11,13 @@ pub mod community;
pub mod community_view; pub mod community_view;
pub mod moderator; pub mod moderator;
pub mod moderator_views; pub mod moderator_views;
pub mod password_reset_request;
pub mod post; pub mod post;
pub mod post_view; pub mod post_view;
pub mod user; pub mod user;
pub mod user_mention; pub mod user_mention;
pub mod user_mention_view; pub mod user_mention_view;
pub mod user_view; pub mod user_view;
pub mod password_reset_request;
pub trait Crud<T> { pub trait Crud<T> {
fn create(conn: &PgConnection, form: &T) -> Result<Self, Error> fn create(conn: &PgConnection, form: &T) -> Result<Self, Error>

View file

@ -1,8 +1,8 @@
use super::*; use super::*;
use crate::schema::password_reset_request; use crate::schema::password_reset_request;
use crate::schema::password_reset_request::dsl::*; use crate::schema::password_reset_request::dsl::*;
use crypto::sha2::Sha256;
use crypto::digest::Digest; use crypto::digest::Digest;
use crypto::sha2::Sha256;
#[derive(Queryable, Identifiable, PartialEq, Debug)] #[derive(Queryable, Identifiable, PartialEq, Debug)]
#[table_name = "password_reset_request"] #[table_name = "password_reset_request"]
@ -23,15 +23,23 @@ pub struct PasswordResetRequestForm {
impl Crud<PasswordResetRequestForm> for PasswordResetRequest { impl Crud<PasswordResetRequestForm> for PasswordResetRequest {
fn read(conn: &PgConnection, password_reset_request_id: i32) -> Result<Self, Error> { fn read(conn: &PgConnection, password_reset_request_id: i32) -> Result<Self, Error> {
use crate::schema::password_reset_request::dsl::*; use crate::schema::password_reset_request::dsl::*;
password_reset_request.find(password_reset_request_id).first::<Self>(conn) password_reset_request
.find(password_reset_request_id)
.first::<Self>(conn)
} }
fn delete(conn: &PgConnection, password_reset_request_id: i32) -> Result<usize, Error> { fn delete(conn: &PgConnection, password_reset_request_id: i32) -> Result<usize, Error> {
diesel::delete(password_reset_request.find(password_reset_request_id)).execute(conn) diesel::delete(password_reset_request.find(password_reset_request_id)).execute(conn)
} }
fn create(conn: &PgConnection, form: &PasswordResetRequestForm) -> Result<Self, Error> { fn create(conn: &PgConnection, form: &PasswordResetRequestForm) -> Result<Self, Error> {
insert_into(password_reset_request).values(form).get_result::<Self>(conn) insert_into(password_reset_request)
.values(form)
.get_result::<Self>(conn)
} }
fn update(conn: &PgConnection, password_reset_request_id: i32, form: &PasswordResetRequestForm) -> Result<Self, Error> { fn update(
conn: &PgConnection,
password_reset_request_id: i32,
form: &PasswordResetRequestForm,
) -> Result<Self, Error> {
diesel::update(password_reset_request.find(password_reset_request_id)) diesel::update(password_reset_request.find(password_reset_request_id))
.set(form) .set(form)
.get_result::<Self>(conn) .get_result::<Self>(conn)
@ -64,8 +72,8 @@ impl PasswordResetRequest {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use super::super::user::*; use super::super::user::*;
use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {
@ -93,7 +101,8 @@ mod tests {
token_encrypted: "no".into(), token_encrypted: "no".into(),
}; };
let inserted_password_reset_request = PasswordResetRequest::create(&conn, &new_password_reset_request).unwrap(); let inserted_password_reset_request =
PasswordResetRequest::create(&conn, &new_password_reset_request).unwrap();
let expected_password_reset_request = PasswordResetRequest { let expected_password_reset_request = PasswordResetRequest {
id: inserted_password_reset_request.id, id: inserted_password_reset_request.id,
@ -102,11 +111,15 @@ mod tests {
published: inserted_password_reset_request.published, published: inserted_password_reset_request.published,
}; };
let read_password_reset_request = PasswordResetRequest::read(&conn, inserted_password_reset_request.id).unwrap(); let read_password_reset_request =
PasswordResetRequest::read(&conn, inserted_password_reset_request.id).unwrap();
let num_deleted = User_::delete(&conn, inserted_user.id).unwrap(); let num_deleted = User_::delete(&conn, inserted_user.id).unwrap();
assert_eq!(expected_password_reset_request, read_password_reset_request); assert_eq!(expected_password_reset_request, read_password_reset_request);
assert_eq!(expected_password_reset_request, inserted_password_reset_request); assert_eq!(
expected_password_reset_request,
inserted_password_reset_request
);
assert_eq!(1, num_deleted); assert_eq!(1, num_deleted);
} }
} }

View file

@ -69,7 +69,11 @@ impl User_ {
Self::create(&conn, &edited_user) Self::create(&conn, &edited_user)
} }
pub fn update_password(conn: &PgConnection, user_id: i32, form: &UserForm) -> Result<Self, Error> { pub fn update_password(
conn: &PgConnection,
user_id: i32,
form: &UserForm,
) -> Result<Self, Error> {
let mut edited_user = form.clone(); let mut edited_user = form.clone();
let password_hash = let password_hash =
hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password"); hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password");
@ -139,16 +143,10 @@ impl User_ {
} }
} }
pub fn find_by_email( pub fn find_by_email(conn: &PgConnection, from_email: &str) -> Result<Self, Error> {
conn: &PgConnection, user_.filter(email.eq(from_email)).first::<User_>(conn)
from_email: &str,
) -> Result<Self, Error> {
user_
.filter(email.eq(from_email))
.first::<User_>(conn)
} }
pub fn find_by_jwt(conn: &PgConnection, jwt: &str) -> Result<Self, Error> { pub fn find_by_jwt(conn: &PgConnection, jwt: &str) -> Result<Self, Error> {
let claims: Claims = Claims::decode(&jwt).expect("Invalid token").claims; let claims: Claims = Claims::decode(&jwt).expect("Invalid token").claims;
Self::read(&conn, claims.id) Self::read(&conn, claims.id)
@ -157,8 +155,8 @@ impl User_ {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use super::User_; use super::User_;
use super::*;
#[test] #[test]
fn test_crud() { fn test_crud() {

View file

@ -11,16 +11,16 @@ pub extern crate actix;
pub extern crate actix_web; pub extern crate actix_web;
pub extern crate bcrypt; pub extern crate bcrypt;
pub extern crate chrono; pub extern crate chrono;
pub extern crate crypto;
pub extern crate dotenv; pub extern crate dotenv;
pub extern crate jsonwebtoken; pub extern crate jsonwebtoken;
pub extern crate lettre;
pub extern crate lettre_email;
pub extern crate rand; pub extern crate rand;
pub extern crate regex; pub extern crate regex;
pub extern crate serde; pub extern crate serde;
pub extern crate serde_json; pub extern crate serde_json;
pub extern crate strum; pub extern crate strum;
pub extern crate lettre;
pub extern crate lettre_email;
pub extern crate crypto;
pub mod api; pub mod api;
pub mod apub; pub mod apub;
@ -30,15 +30,15 @@ pub mod websocket;
use chrono::{DateTime, NaiveDateTime, Utc}; use chrono::{DateTime, NaiveDateTime, Utc};
use dotenv::dotenv; use dotenv::dotenv;
use regex::Regex;
use std::env;
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
use lettre::{SmtpClient, Transport};
use lettre_email::{Email};
use lettre::smtp::authentication::{Credentials, Mechanism}; use lettre::smtp::authentication::{Credentials, Mechanism};
use lettre::smtp::extension::ClientId; use lettre::smtp::extension::ClientId;
use lettre::smtp::ConnectionReuseParameters; use lettre::smtp::ConnectionReuseParameters;
use lettre::{SmtpClient, Transport};
use lettre_email::Email;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use regex::Regex;
use std::env;
pub struct Settings { pub struct Settings {
db_url: String, db_url: String,
@ -64,17 +64,17 @@ impl Settings {
fn get() -> Self { fn get() -> Self {
dotenv().ok(); dotenv().ok();
let email_config = if env::var("SMTP_SERVER").is_ok() && let email_config =
!env::var("SMTP_SERVER").unwrap().eq("") { if env::var("SMTP_SERVER").is_ok() && !env::var("SMTP_SERVER").unwrap().eq("") {
Some(EmailConfig { Some(EmailConfig {
smtp_server: env::var("SMTP_SERVER").expect("SMTP_SERVER must be set"), smtp_server: env::var("SMTP_SERVER").expect("SMTP_SERVER must be set"),
smtp_login: env::var("SMTP_LOGIN").expect("SMTP_LOGIN must be set"), smtp_login: env::var("SMTP_LOGIN").expect("SMTP_LOGIN must be set"),
smtp_password: env::var("SMTP_PASSWORD").expect("SMTP_PASSWORD must be set"), smtp_password: env::var("SMTP_PASSWORD").expect("SMTP_PASSWORD must be set"),
smtp_from_address: env::var("SMTP_FROM_ADDRESS").expect("SMTP_FROM_ADDRESS must be set") smtp_from_address: env::var("SMTP_FROM_ADDRESS").expect("SMTP_FROM_ADDRESS must be set"),
}) })
} else { } else {
None None
}; };
Settings { Settings {
db_url: env::var("DATABASE_URL").expect("DATABASE_URL must be set"), db_url: env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
@ -104,7 +104,7 @@ impl Settings {
.unwrap_or("3600".to_string()) .unwrap_or("3600".to_string())
.parse() .parse()
.unwrap(), .unwrap(),
email_config: email_config, email_config: email_config,
} }
} }
fn api_endpoint(&self) -> String { fn api_endpoint(&self) -> String {
@ -151,29 +151,35 @@ pub fn extract_usernames(test: &str) -> Vec<&str> {
} }
pub fn generate_random_string() -> String { pub fn generate_random_string() -> String {
thread_rng() thread_rng().sample_iter(&Alphanumeric).take(30).collect()
.sample_iter(&Alphanumeric)
.take(30)
.collect()
} }
pub fn send_email(subject: &str, to_email: &str, to_username: &str, html: &str) -> Result<(), String> { pub fn send_email(
subject: &str,
to_email: &str,
to_username: &str,
html: &str,
) -> Result<(), String> {
let email_config = Settings::get().email_config.ok_or("no_email_setup")?; let email_config = Settings::get().email_config.ok_or("no_email_setup")?;
let email = Email::builder() let email = Email::builder()
.to((to_email, to_username)) .to((to_email, to_username))
.from((email_config.smtp_login.to_owned(), email_config.smtp_from_address)) .from((
email_config.smtp_login.to_owned(),
email_config.smtp_from_address,
))
.subject(subject) .subject(subject)
.html(html) .html(html)
.build() .build()
.unwrap(); .unwrap();
let mut mailer = SmtpClient::new_simple(&email_config.smtp_server).unwrap() let mut mailer = SmtpClient::new_simple(&email_config.smtp_server)
.unwrap()
.hello_name(ClientId::Domain("localhost".to_string())) .hello_name(ClientId::Domain("localhost".to_string()))
.credentials(Credentials::new( .credentials(Credentials::new(
email_config.smtp_login.to_owned(), email_config.smtp_login.to_owned(),
email_config.smtp_password.to_owned())) email_config.smtp_password.to_owned(),
))
.smtp_utf8(true) .smtp_utf8(true)
.authentication_mechanism(Mechanism::Plain) .authentication_mechanism(Mechanism::Plain)
.connection_reuse(ConnectionReuseParameters::ReuseUnlimited) .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)

View file

@ -329,30 +329,30 @@ joinable!(user_mention -> comment (comment_id));
joinable!(user_mention -> user_ (recipient_id)); joinable!(user_mention -> user_ (recipient_id));
allow_tables_to_appear_in_same_query!( allow_tables_to_appear_in_same_query!(
category, category,
comment, comment,
comment_like, comment_like,
comment_saved, comment_saved,
community, community,
community_follower, community_follower,
community_moderator, community_moderator,
community_user_ban, community_user_ban,
mod_add, mod_add,
mod_add_community, mod_add_community,
mod_ban, mod_ban,
mod_ban_from_community, mod_ban_from_community,
mod_lock_post, mod_lock_post,
mod_remove_comment, mod_remove_comment,
mod_remove_community, mod_remove_community,
mod_remove_post, mod_remove_post,
mod_sticky_post, mod_sticky_post,
password_reset_request, password_reset_request,
post, post,
post_like, post_like,
post_read, post_read,
post_saved, post_saved,
site, site,
user_, user_,
user_ban, user_ban,
user_mention, user_mention,
); );