]> Untitled Git - lemmy.git/blob - server/src/lib.rs
Merge branch 'teromene-config_dif_addr'
[lemmy.git] / server / src / lib.rs
1 #![recursion_limit = "512"]
2 #[macro_use]
3 pub extern crate strum_macros;
4 #[macro_use]
5 pub extern crate lazy_static;
6 #[macro_use]
7 pub extern crate failure;
8 #[macro_use]
9 pub extern crate diesel;
10 pub extern crate actix;
11 pub extern crate actix_web;
12 pub extern crate bcrypt;
13 pub extern crate chrono;
14 pub extern crate crypto;
15 pub extern crate dotenv;
16 pub extern crate jsonwebtoken;
17 pub extern crate lettre;
18 pub extern crate lettre_email;
19 pub extern crate rand;
20 pub extern crate regex;
21 pub extern crate serde;
22 pub extern crate serde_json;
23 pub extern crate strum;
24
25 pub mod api;
26 pub mod apub;
27 pub mod db;
28 pub mod feeds;
29 pub mod nodeinfo;
30 pub mod schema;
31 pub mod version;
32 pub mod websocket;
33
34 use chrono::{DateTime, NaiveDateTime, Utc};
35 use dotenv::dotenv;
36 use lettre::smtp::authentication::{Credentials, Mechanism};
37 use lettre::smtp::extension::ClientId;
38 use lettre::smtp::ConnectionReuseParameters;
39 use lettre::{SmtpClient, Transport};
40 use lettre_email::Email;
41 use rand::distributions::Alphanumeric;
42 use rand::{thread_rng, Rng};
43 use regex::Regex;
44 use std::env;
45 use std::net::IpAddr;
46
47 pub struct Settings {
48   pub db_url: String,
49   pub hostname: String,
50   pub bind: IpAddr,
51   pub port: u16,
52   pub jwt_secret: String,
53   pub rate_limit_message: i32,
54   pub rate_limit_message_per_second: i32,
55   pub rate_limit_post: i32,
56   pub rate_limit_post_per_second: i32,
57   pub rate_limit_register: i32,
58   pub rate_limit_register_per_second: i32,
59   pub email_config: Option<EmailConfig>,
60 }
61
62 pub struct EmailConfig {
63   smtp_server: String,
64   smtp_login: String,
65   smtp_password: String,
66   smtp_from_address: String,
67 }
68
69 impl Settings {
70   pub fn get() -> Self {
71     dotenv().ok();
72
73     let email_config =
74       if env::var("SMTP_SERVER").is_ok() && !env::var("SMTP_SERVER").unwrap().eq("") {
75         Some(EmailConfig {
76           smtp_server: env::var("SMTP_SERVER").expect("SMTP_SERVER must be set"),
77           smtp_login: env::var("SMTP_LOGIN").expect("SMTP_LOGIN must be set"),
78           smtp_password: env::var("SMTP_PASSWORD").expect("SMTP_PASSWORD must be set"),
79           smtp_from_address: env::var("SMTP_FROM_ADDRESS").expect("SMTP_FROM_ADDRESS must be set"),
80         })
81       } else {
82         None
83       };
84
85     Settings {
86       db_url: env::var("DATABASE_URL").expect("DATABASE_URL must be set"),
87       hostname: env::var("HOSTNAME").unwrap_or("rrr".to_string()),
88       bind: env::var("BIND")
89         .unwrap_or("0.0.0.0".to_string())
90         .parse()
91         .unwrap(),
92       port: env::var("PORT")
93         .unwrap_or("8536".to_string())
94         .parse()
95         .unwrap(),
96       jwt_secret: env::var("JWT_SECRET").unwrap_or("changeme".to_string()),
97       rate_limit_message: env::var("RATE_LIMIT_MESSAGE")
98         .unwrap_or("30".to_string())
99         .parse()
100         .unwrap(),
101       rate_limit_message_per_second: env::var("RATE_LIMIT_MESSAGE_PER_SECOND")
102         .unwrap_or("60".to_string())
103         .parse()
104         .unwrap(),
105       rate_limit_post: env::var("RATE_LIMIT_POST")
106         .unwrap_or("3".to_string())
107         .parse()
108         .unwrap(),
109       rate_limit_post_per_second: env::var("RATE_LIMIT_POST_PER_SECOND")
110         .unwrap_or("600".to_string())
111         .parse()
112         .unwrap(),
113       rate_limit_register: env::var("RATE_LIMIT_REGISTER")
114         .unwrap_or("1".to_string())
115         .parse()
116         .unwrap(),
117       rate_limit_register_per_second: env::var("RATE_LIMIT_REGISTER_PER_SECOND")
118         .unwrap_or("3600".to_string())
119         .parse()
120         .unwrap(),
121       email_config: email_config,
122     }
123   }
124   fn api_endpoint(&self) -> String {
125     format!("{}/api/v1", self.hostname)
126   }
127 }
128
129 pub fn to_datetime_utc(ndt: NaiveDateTime) -> DateTime<Utc> {
130   DateTime::<Utc>::from_utc(ndt, Utc)
131 }
132
133 pub fn naive_now() -> NaiveDateTime {
134   chrono::prelude::Utc::now().naive_utc()
135 }
136
137 pub fn naive_from_unix(time: i64) -> NaiveDateTime {
138   NaiveDateTime::from_timestamp(time, 0)
139 }
140
141 pub fn is_email_regex(test: &str) -> bool {
142   EMAIL_REGEX.is_match(test)
143 }
144
145 pub fn remove_slurs(test: &str) -> String {
146   SLUR_REGEX.replace_all(test, "*removed*").to_string()
147 }
148
149 pub fn has_slurs(test: &str) -> bool {
150   SLUR_REGEX.is_match(test)
151 }
152
153 pub fn extract_usernames(test: &str) -> Vec<&str> {
154   let mut matches: Vec<&str> = USERNAME_MATCHES_REGEX
155     .find_iter(test)
156     .map(|mat| mat.as_str())
157     .collect();
158
159   // Unique
160   matches.sort_unstable();
161   matches.dedup();
162
163   // Remove /u/
164   matches.iter().map(|t| &t[3..]).collect()
165 }
166
167 pub fn generate_random_string() -> String {
168   thread_rng().sample_iter(&Alphanumeric).take(30).collect()
169 }
170
171 pub fn send_email(
172   subject: &str,
173   to_email: &str,
174   to_username: &str,
175   html: &str,
176 ) -> Result<(), String> {
177   let email_config = Settings::get().email_config.ok_or("no_email_setup")?;
178
179   let email = Email::builder()
180     .to((to_email, to_username))
181     .from((
182       email_config.smtp_login.to_owned(),
183       email_config.smtp_from_address,
184     ))
185     .subject(subject)
186     .html(html)
187     .build()
188     .unwrap();
189
190   let mut mailer = SmtpClient::new_simple(&email_config.smtp_server)
191     .unwrap()
192     .hello_name(ClientId::Domain("localhost".to_string()))
193     .credentials(Credentials::new(
194       email_config.smtp_login.to_owned(),
195       email_config.smtp_password.to_owned(),
196     ))
197     .smtp_utf8(true)
198     .authentication_mechanism(Mechanism::Plain)
199     .connection_reuse(ConnectionReuseParameters::ReuseUnlimited)
200     .transport();
201
202   let result = mailer.send(email.into());
203
204   match result {
205     Ok(_) => Ok(()),
206     Err(_) => Err("no_email_setup".to_string()),
207   }
208 }
209
210 #[cfg(test)]
211 mod tests {
212   use crate::{extract_usernames, has_slurs, is_email_regex, remove_slurs, Settings};
213   #[test]
214   fn test_api() {
215     assert_eq!(Settings::get().api_endpoint(), "rrr/api/v1");
216   }
217
218   #[test]
219   fn test_email() {
220     assert!(is_email_regex("gush@gmail.com"));
221     assert!(!is_email_regex("nada_neutho"));
222   }
223
224   #[test]
225   fn test_slur_filter() {
226     let test =
227       "coons test dindu ladyboy tranny retardeds. This is a bunch of other safe text.".to_string();
228     let slur_free = "No slurs here";
229     assert_eq!(
230       remove_slurs(&test),
231       "*removed* test *removed* *removed* *removed* *removed*. This is a bunch of other safe text."
232         .to_string()
233     );
234     assert!(has_slurs(&test));
235     assert!(!has_slurs(slur_free));
236   }
237
238   #[test]
239   fn test_extract_usernames() {
240     let usernames = extract_usernames("this is a user mention for [/u/testme](/u/testme) and thats all. Oh [/u/another](/u/another) user. And the first again [/u/testme](/u/testme) okay");
241     let expected = vec!["another", "testme"];
242     assert_eq!(usernames, expected);
243   }
244
245   // #[test]
246   // fn test_send_email() {
247   //  let result =  send_email("not a subject", "test_email@gmail.com", "ur user", "<h1>HI there</h1>");
248   //   assert!(result.is_ok());
249   // }
250 }
251
252 lazy_static! {
253   static ref EMAIL_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$").unwrap();
254   static ref SLUR_REGEX: Regex = Regex::new(r"(fag(g|got|tard)?|maricos?|cock\s?sucker(s|ing)?|nig(\b|g?(a|er)?s?)\b|dindu(s?)|mudslime?s?|kikes?|mongoloids?|towel\s*heads?|\bspi(c|k)s?\b|\bchinks?|niglets?|beaners?|\bnips?\b|\bcoons?\b|jungle\s*bunn(y|ies?)|jigg?aboo?s?|\bpakis?\b|rag\s*heads?|gooks?|cunts?|bitch(es|ing|y)?|puss(y|ies?)|twats?|feminazis?|whor(es?|ing)|\bslut(s|t?y)?|\btrann?(y|ies?)|ladyboy(s?)|\b(b|re|r)tard(ed)?s?)").unwrap();
255   static ref USERNAME_MATCHES_REGEX: Regex = Regex::new(r"/u/[a-zA-Z][0-9a-zA-Z_]*").unwrap();
256 }