Re-write email backend, use SMTP directly.

This commit is contained in:
Paul Makles
2020-08-30 17:16:53 +01:00
parent ff0e539c7b
commit cbac802978
21 changed files with 354 additions and 303 deletions

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
assets
target

View File

@@ -1,12 +1,12 @@
use super::get_collection; use super::get_collection;
use lru::LruCache; use lru::LruCache;
use std::sync::{Arc, Mutex};
use mongodb::bson::{doc, from_bson, Bson}; use mongodb::bson::{doc, from_bson, Bson};
use rocket::http::RawStr; use rocket::http::RawStr;
use rocket::request::FromParam; use rocket::request::FromParam;
use rocket_contrib::json::JsonValue; use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LastMessage { pub struct LastMessage {
@@ -50,8 +50,7 @@ impl Channel {
"last_message": self.last_message, "last_message": self.last_message,
"recipients": self.recipients, "recipients": self.recipients,
}), }),
1 => { 1 => json!({
json!({
"id": self.id, "id": self.id,
"type": self.channel_type, "type": self.channel_type,
"last_message": self.last_message, "last_message": self.last_message,
@@ -59,17 +58,14 @@ impl Channel {
"name": self.name, "name": self.name,
"owner": self.owner, "owner": self.owner,
"description": self.description, "description": self.description,
}) }),
} 2 => json!({
2 => {
json!({
"id": self.id, "id": self.id,
"type": self.channel_type, "type": self.channel_type,
"guild": self.guild, "guild": self.guild,
"name": self.name, "name": self.name,
"description": self.description, "description": self.description,
}) }),
}
_ => unreachable!(), _ => unreachable!(),
} }
} }

View File

@@ -1,5 +1,5 @@
use super::get_collection;
use super::channel::fetch_channels; use super::channel::fetch_channels;
use super::get_collection;
use lru::LruCache; use lru::LruCache;
use mongodb::bson::{doc, from_bson, Bson}; use mongodb::bson::{doc, from_bson, Bson};
@@ -66,13 +66,17 @@ impl Guild {
} }
pub fn seralise_with_channels(self) -> Result<JsonValue, String> { pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
let channels = self.fetch_channels()? let channels = self
.fetch_channels()?
.into_iter() .into_iter()
.map(|x| x.serialise()) .map(|x| x.serialise())
.collect(); .collect();
let mut value = self.serialise(); let mut value = self.serialise();
value.as_object_mut().unwrap().insert("channels".to_string(), channels); value
.as_object_mut()
.unwrap()
.insert("channels".to_string(), channels);
Ok(value) Ok(value)
} }
} }
@@ -167,10 +171,7 @@ pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> { pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
let guilds = fetch_guilds(&ids)?; let guilds = fetch_guilds(&ids)?;
let cids: Vec<String> = guilds let cids: Vec<String> = guilds.iter().flat_map(|x| x.channels.clone()).collect();
.iter()
.flat_map(|x| x.channels.clone())
.collect();
let channels = fetch_channels(&cids)?; let channels = fetch_channels(&cids)?;
Ok(guilds Ok(guilds
@@ -180,10 +181,11 @@ pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue
let mut obj = x.serialise(); let mut obj = x.serialise();
obj.as_object_mut().unwrap().insert( obj.as_object_mut().unwrap().insert(
"channels".to_string(), "channels".to_string(),
channels.iter() channels
.iter()
.filter(|x| x.guild.is_some() && x.guild.as_ref().unwrap() == &id) .filter(|x| x.guild.is_some() && x.guild.as_ref().unwrap() == &id)
.map(|x| x.clone().serialise()) .map(|x| x.clone().serialise())
.collect() .collect(),
); );
obj obj
}) })
@@ -315,19 +317,19 @@ pub fn process_event(event: &Notification) {
Notification::guild_user_join(ev) => { Notification::guild_user_join(ev) => {
let mut cache = MEMBER_CACHE.lock().unwrap(); let mut cache = MEMBER_CACHE.lock().unwrap();
cache.put( cache.put(
MemberKey ( ev.id.clone(), ev.user.clone() ), MemberKey(ev.id.clone(), ev.user.clone()),
Member { Member {
id: MemberRef { id: MemberRef {
guild: ev.id.clone(), guild: ev.id.clone(),
user: ev.user.clone() user: ev.user.clone(),
},
nickname: None,
}, },
nickname: None
}
); );
} }
Notification::guild_user_leave(ev) => { Notification::guild_user_leave(ev) => {
let mut cache = MEMBER_CACHE.lock().unwrap(); let mut cache = MEMBER_CACHE.lock().unwrap();
cache.pop(&MemberKey ( ev.id.clone(), ev.user.clone() )); cache.pop(&MemberKey(ev.id.clone(), ev.user.clone()));
} }
_ => {} _ => {}
} }

View File

@@ -1,27 +1,33 @@
use super::super::get_db; use super::super::get_db;
use super::scripts::LATEST_REVISION; use super::scripts::LATEST_REVISION;
use mongodb::options::CreateCollectionOptions;
use mongodb::bson::doc;
use log::info; use log::info;
use mongodb::bson::doc;
use mongodb::options::CreateCollectionOptions;
pub fn create_database() { pub fn create_database() {
info!("Creating database."); info!("Creating database.");
let db = get_db(); let db = get_db();
db.create_collection("users", None).expect("Failed to create users collection."); db.create_collection("users", None)
db.create_collection("channels", None).expect("Failed to create channels collection."); .expect("Failed to create users collection.");
db.create_collection("guilds", None).expect("Failed to create guilds collection."); db.create_collection("channels", None)
db.create_collection("members", None).expect("Failed to create members collection."); .expect("Failed to create channels collection.");
db.create_collection("messages", None).expect("Failed to create messages collection."); db.create_collection("guilds", None)
db.create_collection("migrations", None).expect("Failed to create migrations collection."); .expect("Failed to create guilds collection.");
db.create_collection("members", None)
.expect("Failed to create members collection.");
db.create_collection("messages", None)
.expect("Failed to create messages collection.");
db.create_collection("migrations", None)
.expect("Failed to create migrations collection.");
db.create_collection( db.create_collection(
"pubsub", "pubsub",
CreateCollectionOptions::builder() CreateCollectionOptions::builder()
.capped(true) .capped(true)
.size(1_000_000) .size(1_000_000)
.build() .build(),
) )
.expect("Failed to create pubsub collection."); .expect("Failed to create pubsub collection.");
@@ -31,7 +37,7 @@ pub fn create_database() {
"_id": 0, "_id": 0,
"revision": LATEST_REVISION "revision": LATEST_REVISION
}, },
None None,
) )
.expect("Failed to save migration info."); .expect("Failed to save migration info.");

View File

@@ -6,10 +6,9 @@ pub mod scripts;
pub fn run_migrations() { pub fn run_migrations() {
let client = get_connection(); let client = get_connection();
let list = client.list_database_names( let list = client
None, .list_database_names(None, None)
None .expect("Failed to fetch database names.");
).expect("Failed to fetch database names.");
if list.iter().position(|x| x == "revolt").is_none() { if list.iter().position(|x| x == "revolt").is_none() {
init::create_database(); init::create_database();

View File

@@ -1,30 +1,32 @@
use super::super::get_collection; use super::super::get_collection;
use serde::{Serialize, Deserialize};
use mongodb::bson::{Bson, from_bson, doc};
use mongodb::options::FindOptions;
use log::info; use log::info;
use mongodb::bson::{doc, from_bson, Bson};
use mongodb::options::FindOptions;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct MigrationInfo { struct MigrationInfo {
_id: i32, _id: i32,
revision: i32 revision: i32,
} }
pub const LATEST_REVISION: i32 = 2; pub const LATEST_REVISION: i32 = 2;
pub fn migrate_database() { pub fn migrate_database() {
let migrations = get_collection("migrations"); let migrations = get_collection("migrations");
let data = migrations.find_one(None, None) let data = migrations
.find_one(None, None)
.expect("Failed to fetch migration data."); .expect("Failed to fetch migration data.");
if let Some(doc) = data { if let Some(doc) = data {
let info: MigrationInfo = from_bson(Bson::Document(doc)) let info: MigrationInfo =
.expect("Failed to read migration information."); from_bson(Bson::Document(doc)).expect("Failed to read migration information.");
let revision = run_migrations(info.revision); let revision = run_migrations(info.revision);
migrations.update_one( migrations
.update_one(
doc! { doc! {
"_id": info._id "_id": info._id
}, },
@@ -33,8 +35,9 @@ pub fn migrate_database() {
"revision": revision "revision": revision
} }
}, },
None None,
).expect("Failed to commit migration information."); )
.expect("Failed to commit migration information.");
info!("Migration complete. Currently at revision {}.", revision); info!("Migration complete. Currently at revision {}.", revision);
} else { } else {
@@ -53,30 +56,37 @@ pub fn run_migrations(revision: i32) -> i32 {
info!("Running migration [revision 1]: Add channels to guild object."); info!("Running migration [revision 1]: Add channels to guild object.");
let col = get_collection("guilds"); let col = get_collection("guilds");
let guilds = col.find( let guilds = col
.find(
None, None,
FindOptions::builder() FindOptions::builder().projection(doc! { "_id": 1 }).build(),
.projection(doc! { "_id": 1 })
.build()
) )
.expect("Failed to fetch guilds."); .expect("Failed to fetch guilds.");
let result = get_collection("channels").find( let result = get_collection("channels")
.find(
doc! { doc! {
"type": 2 "type": 2
}, },
FindOptions::builder() FindOptions::builder()
.projection(doc! { "_id": 1, "guild": 1 }) .projection(doc! { "_id": 1, "guild": 1 })
.build() .build(),
).expect("Failed to fetch channels."); )
.expect("Failed to fetch channels.");
let mut channels = vec![]; let mut channels = vec![];
for doc in result { for doc in result {
let channel = doc.expect("Failed to fetch channel."); let channel = doc.expect("Failed to fetch channel.");
let id = channel.get_str("_id").expect("Failed to get channel id.").to_string(); let id = channel
let gid = channel.get_str("guild").expect("Failed to get guild id.").to_string(); .get_str("_id")
.expect("Failed to get channel id.")
.to_string();
let gid = channel
.get_str("guild")
.expect("Failed to get guild id.")
.to_string();
channels.push(( id, gid )); channels.push((id, gid));
} }
for doc in guilds { for doc in guilds {
@@ -98,8 +108,9 @@ pub fn run_migrations(revision: i32) -> i32 {
"channels": list "channels": list
} }
}, },
None None,
).expect("Failed to update guild."); )
.expect("Failed to update guild.");
} }
} }

View File

@@ -118,13 +118,11 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
} }
false false
} else { } else if result.count() > 0 {
if result.count() > 0 {
true true
} else { } else {
false false
} }
}
} else { } else {
false false
} }

View File

@@ -173,8 +173,11 @@ impl PermissionCalculator {
} }
if let Some(other) = other_user { if let Some(other) = other_user {
let relationship = let relationship = get_relationship_internal(
get_relationship_internal(&self.user.id, &other, &self.user.relations); &self.user.id,
&other,
&self.user.relations,
);
if relationship == Relationship::Friend { if relationship == Relationship::Friend {
permissions = 1024 + 128 + 32 + 16 + 1; permissions = 1024 + 128 + 32 + 16 + 1;

View File

@@ -1,16 +1,16 @@
use super::channel::fetch_channels;
use super::get_collection; use super::get_collection;
use super::guild::{serialise_guilds_with_channels}; use super::guild::serialise_guilds_with_channels;
use super::channel::{fetch_channels};
use lru::LruCache; use lru::LruCache;
use mongodb::bson::{doc, from_bson, Bson, DateTime}; use mongodb::bson::{doc, from_bson, Bson, DateTime};
use mongodb::options::FindOptions; use mongodb::options::FindOptions;
use rocket::http::{RawStr, Status}; use rocket::http::{RawStr, Status};
use rocket::request::{self, FromParam, FromRequest, Request}; use rocket::request::{self, FromParam, FromRequest, Request};
use rocket_contrib::json::JsonValue;
use rocket::Outcome; use rocket::Outcome;
use std::sync::{Arc, Mutex}; use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserEmailVerification { pub struct UserEmailVerification {
@@ -66,23 +66,21 @@ impl User {
doc! { doc! {
"_id.user": &self.id "_id.user": &self.id
}, },
None None,
).map_err(|_| "Failed to fetch members.")?; )
.map_err(|_| "Failed to fetch members.")?;
Ok(members.into_iter() Ok(members
.into_iter()
.filter_map(|x| match x { .filter_map(|x| match x {
Ok(doc) => { Ok(doc) => match doc.get_document("_id") {
match doc.get_document("_id") { Ok(id) => match id.get_str("guild") {
Ok(id) => {
match id.get_str("guild") {
Ok(value) => Some(value.to_string()), Ok(value) => Some(value.to_string()),
Err(_) => None Err(_) => None,
} },
} Err(_) => None,
Err(_) => None },
} Err(_) => None,
}
Err(_) => None
}) })
.collect()) .collect())
} }
@@ -93,18 +91,16 @@ impl User {
doc! { doc! {
"recipients": &self.id "recipients": &self.id
}, },
FindOptions::builder() FindOptions::builder().projection(doc! { "_id": 1 }).build(),
.projection(doc! { "_id": 1 }) )
.build() .map_err(|_| "Failed to fetch channel ids.")?;
).map_err(|_| "Failed to fetch channel ids.")?;
Ok(channels.into_iter() Ok(channels
.into_iter()
.filter_map(|x| x.ok()) .filter_map(|x| x.ok())
.filter_map(|x| { .filter_map(|x| match x.get_str("_id") {
match x.get_str("_id") {
Ok(value) => Some(value.to_string()), Ok(value) => Some(value.to_string()),
Err(_) => None Err(_) => None,
}
}) })
.collect()) .collect())
} }
@@ -113,21 +109,11 @@ impl User {
let v = vec![]; let v = vec![];
let relations = self.relations.as_ref().unwrap_or(&v); let relations = self.relations.as_ref().unwrap_or(&v);
let users: Vec<JsonValue> = fetch_users( let users: Vec<JsonValue> = fetch_users(&relations.iter().map(|x| x.id.clone()).collect())?
&relations
.iter()
.map(|x| x.id.clone())
.collect()
)?
.into_iter() .into_iter()
.map(|x| { .map(|x| {
let id = x.id.clone(); let id = x.id.clone();
x.serialise( x.serialise(relations.iter().find(|y| y.id == id).unwrap().status as i32)
relations.iter()
.find(|y| y.id == id)
.unwrap()
.status as i32
)
}) })
.collect(); .collect();
@@ -298,17 +284,13 @@ pub fn process_event(event: &Notification) {
if let Some(pos) = relations.iter().position(|x| x.id == ev.user) { if let Some(pos) = relations.iter().position(|x| x.id == ev.user) {
relations.remove(pos); relations.remove(pos);
} }
} else { } else if let Some(entry) = relations.iter_mut().find(|x| x.id == ev.user) {
if let Some(entry) = relations.iter_mut().find(|x| x.id == ev.user) {
entry.status = ev.status as u8; entry.status = ev.status as u8;
} else { } else {
relations.push( relations.push(UserRelationship {
UserRelationship {
id: ev.id.clone(), id: ev.id.clone(),
status: ev.status as u8 status: ev.status as u8,
} });
);
}
} }
} }
} }

View File

@@ -1,61 +0,0 @@
use reqwest::blocking::Client;
use std::collections::HashMap;
use std::env;
fn public_uri() -> String {
env::var("PUBLIC_URI").expect("PUBLIC_URI not in environment variables!")
}
fn portal() -> String {
env::var("PORTAL_URL").expect("PORTAL_URL not in environment variables!")
}
pub fn send_email(target: String, subject: String, body: String, html: String) -> Result<(), ()> {
let mut map = HashMap::new();
map.insert("target", target.clone());
map.insert("subject", subject);
map.insert("body", body);
map.insert("html", html);
let client = Client::new();
match client.post(&portal()).json(&map).send() {
Ok(_) => Ok(()),
Err(_) => Err(()),
}
}
pub fn send_verification_email(email: String, code: String) -> bool {
let url = format!("{}/api/account/verify/{}", public_uri(), code);
send_email(
email,
"Verify your email!".to_string(),
format!("Verify your email here: {}", url),
format!("<a href=\"{}\">Click to verify your email!</a>", url),
)
.is_ok()
}
pub fn send_password_reset(email: String, code: String) -> bool {
let url = format!("{}/api/account/reset/{}", public_uri(), code);
send_email(
email,
"Reset your password.".to_string(),
format!("Reset your password here: {}", url),
format!("<a href=\"{}\">Click to reset your password!</a>", url),
)
.is_ok()
}
pub fn send_welcome_email(email: String, username: String) -> bool {
send_email(
email,
"Welcome to REVOLT!".to_string(),
format!("Welcome, {}! You can now use REVOLT.", username.clone()),
format!(
"<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>",
username.clone(),
public_uri()
),
)
.is_ok()
}

View File

@@ -9,13 +9,11 @@ extern crate bitfield;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
pub mod notifications;
pub mod database; pub mod database;
pub mod notifications;
pub mod routes; pub mod routes;
pub mod email;
pub mod util; pub mod util;
use dotenv;
use rocket_cors::AllowedOrigins; use rocket_cors::AllowedOrigins;
use std::thread; use std::thread;

View File

@@ -36,7 +36,9 @@ impl Handler for Server {
match state.try_authenticate(self.id.clone(), token.to_string()) { match state.try_authenticate(self.id.clone(), token.to_string()) {
StateResult::Success(user_id) => { StateResult::Success(user_id) => {
let user = crate::database::user::fetch_user(&user_id).unwrap().unwrap(); let user = crate::database::user::fetch_user(&user_id)
.unwrap()
.unwrap();
self.user_id = Some(user_id); self.user_id = Some(user_id);
self.sender.send( self.sender.send(

View File

@@ -1,12 +1,11 @@
use super::Response; use super::Response;
use crate::database; use crate::database;
use crate::email; use crate::util::{captcha, email, gen_token};
use crate::util::gen_token;
use crate::util::captcha;
use bcrypt::{hash, verify}; use bcrypt::{hash, verify};
use chrono::prelude::*; use chrono::prelude::*;
use database::user::User; use database::user::User;
use log::error;
use mongodb::bson::{doc, from_bson, Bson}; use mongodb::bson::{doc, from_bson, Bson};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -31,15 +30,11 @@ pub struct Create {
#[post("/create", data = "<info>")] #[post("/create", data = "<info>")]
pub fn create(info: Json<Create>) -> Response { pub fn create(info: Json<Create>) -> Response {
if let Err(error) = captcha::verify(&info.captcha) { if let Err(error) = captcha::verify(&info.captcha) {
return Response::BadRequest( return Response::BadRequest(json!({ "error": error }));
json!({ "error": error })
);
} }
if true { if true {
return Response::BadRequest( return Response::BadRequest(json!({ "error": "Registration disabled." }));
json!({ "error": "Registration disabled." })
);
} }
let col = database::get_collection("users"); let col = database::get_collection("users");
@@ -152,7 +147,9 @@ pub fn verify_email(code: String) -> Response {
) )
.expect("Failed to update user!"); .expect("Failed to update user!");
email::send_welcome_email(target.to_string(), user.username); if let Err(err) = email::send_welcome_email(target.to_string(), user.username) {
error!("Failed to send welcome email! {}", err);
}
Response::Redirect(super::Redirect::to("https://app.revolt.chat")) Response::Redirect(super::Redirect::to("https://app.revolt.chat"))
} }
@@ -174,9 +171,7 @@ pub struct Resend {
#[post("/resend", data = "<info>")] #[post("/resend", data = "<info>")]
pub fn resend_email(info: Json<Resend>) -> Response { pub fn resend_email(info: Json<Resend>) -> Response {
if let Err(error) = captcha::verify(&info.captcha) { if let Err(error) = captcha::verify(&info.captcha) {
return Response::BadRequest( return Response::BadRequest(json!({ "error": error }));
json!({ "error": error })
);
} }
let col = database::get_collection("users"); let col = database::get_collection("users");
@@ -223,12 +218,11 @@ pub fn resend_email(info: Json<Resend>) -> Response {
None, None,
).expect("Failed to update user!"); ).expect("Failed to update user!");
match email::send_verification_email(info.email.to_string(), code) { if let Err(err) = email::send_verification_email(info.email.clone(), code) {
true => Response::Result(super::Status::Ok), return Response::InternalServerError(json!({ "error": err }));
false => Response::InternalServerError(
json!({ "error": "Failed to send email! Likely an issue with the backend API." }),
),
} }
Response::Result(super::Status::Ok)
} }
} else { } else {
Response::NotFound(json!({ "error": "Email not found or pending verification!" })) Response::NotFound(json!({ "error": "Email not found or pending verification!" }))
@@ -249,9 +243,7 @@ pub struct Login {
#[post("/login", data = "<info>")] #[post("/login", data = "<info>")]
pub fn login(info: Json<Login>) -> Response { pub fn login(info: Json<Login>) -> Response {
if let Err(error) = captcha::verify(&info.captcha) { if let Err(error) = captcha::verify(&info.captcha) {
return Response::BadRequest( return Response::BadRequest(json!({ "error": error }));
json!({ "error": error })
);
} }
let col = database::get_collection("users"); let col = database::get_collection("users");

View File

@@ -1,7 +1,7 @@
use super::Response; use super::Response;
use crate::database::{ use crate::database::{
self, channel::Channel, get_relationship, get_relationship_internal, message::Message, self, channel::Channel, get_relationship, get_relationship_internal, message::Message,
Permission, PermissionCalculator, Relationship, user::User user::User, Permission, PermissionCalculator, Relationship,
}; };
use crate::notifications::{ use crate::notifications::{
self, self,
@@ -506,11 +506,7 @@ pub struct SendMessage {
/// send a message to a channel /// send a message to a channel
#[post("/<target>/messages", data = "<message>")] #[post("/<target>/messages", data = "<message>")]
pub fn send_message( pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
user: User,
target: Channel,
message: Json<SendMessage>,
) -> Option<Response> {
let permissions = with_permissions!(user, target); let permissions = with_permissions!(user, target);
if !permissions.get_send_messages() { if !permissions.get_send_messages() {
@@ -657,11 +653,9 @@ pub fn edit_message(
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> { pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
let permissions = with_permissions!(user, target); let permissions = with_permissions!(user, target);
if !permissions.get_manage_messages() { if !permissions.get_manage_messages() && message.author != user.id {
if message.author != user.id {
return Some(Response::LackingPermission(Permission::ManageMessages)); return Some(Response::LackingPermission(Permission::ManageMessages));
} }
}
let col = database::get_collection("messages"); let col = database::get_collection("messages");

View File

@@ -2,7 +2,8 @@ use super::channel::ChannelType;
use super::Response; use super::Response;
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey}; use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
use crate::database::{ use crate::database::{
self, channel::fetch_channel, guild::serialise_guilds_with_channels, channel::Channel, Permission, PermissionCalculator, user::User self, channel::fetch_channel, channel::Channel, guild::serialise_guilds_with_channels,
user::User, Permission, PermissionCalculator,
}; };
use crate::notifications::{ use crate::notifications::{
self, self,
@@ -55,7 +56,9 @@ pub fn guild(user: User, target: Guild) -> Option<Response> {
if let Ok(result) = target.seralise_with_channels() { if let Ok(result) = target.seralise_with_channels() {
Some(Response::Success(result)) Some(Response::Success(result))
} else { } else {
Some(Response::InternalServerError(json!({ "error": "Failed to fetch channels!" }))) Some(Response::InternalServerError(
json!({ "error": "Failed to fetch channels!" }),
))
} }
} }
@@ -153,8 +156,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
json!({ "error": "Could not fetch channels." }), json!({ "error": "Could not fetch channels." }),
)) ))
} }
} else { } else if database::get_collection("members")
if database::get_collection("members")
.delete_one( .delete_one(
doc! { doc! {
"_id.guild": &target.id, "_id.guild": &target.id,
@@ -180,7 +182,6 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
json!({ "error": "Failed to remove you from the guild." }), json!({ "error": "Failed to remove you from the guild." }),
)) ))
} }
}
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -243,7 +244,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
"channels": &id "channels": &id
} }
}, },
None None,
) )
.is_ok() .is_ok()
{ {
@@ -326,11 +327,9 @@ pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response
let (permissions, _) = with_permissions!(user, target); let (permissions, _) = with_permissions!(user, target);
if let Some((guild_id, _, invite)) = get_invite(&code, None) { if let Some((guild_id, _, invite)) = get_invite(&code, None) {
if invite.creator != user.id { if invite.creator != user.id && !permissions.get_manage_server() {
if !permissions.get_manage_server() {
return Some(Response::LackingPermission(Permission::ManageServer)); return Some(Response::LackingPermission(Permission::ManageServer));
} }
}
if database::get_collection("guilds") if database::get_collection("guilds")
.update_one( .update_one(
@@ -621,14 +620,16 @@ pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response>
return Some(Response::LackingPermission(Permission::KickMembers)); return Some(Response::LackingPermission(Permission::KickMembers));
} }
if let Ok(result) = get_member(MemberKey( target.id.clone(), other.clone() )) { if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
if result.is_none() { if result.is_none() {
return Some(Response::BadRequest( return Some(Response::BadRequest(
json!({ "error": "User not part of guild." }), json!({ "error": "User not part of guild." }),
)); ));
} }
} else { } else {
return Some(Response::InternalServerError(json!({ "error": "Failed to fetch member." }))) return Some(Response::InternalServerError(
json!({ "error": "Failed to fetch member." }),
));
} }
if database::get_collection("members") if database::get_collection("members")
@@ -691,14 +692,16 @@ pub fn ban_member(
return Some(Response::LackingPermission(Permission::BanMembers)); return Some(Response::LackingPermission(Permission::BanMembers));
} }
if let Ok(result) = get_member(MemberKey( target.id.clone(), other.clone() )) { if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
if result.is_none() { if result.is_none() {
return Some(Response::BadRequest( return Some(Response::BadRequest(
json!({ "error": "User not part of guild." }), json!({ "error": "User not part of guild." }),
)); ));
} }
} else { } else {
return Some(Response::InternalServerError(json!({ "error": "Failed to fetch member." }))) return Some(Response::InternalServerError(
json!({ "error": "Failed to fetch member." }),
));
} }
if database::get_collection("guilds") if database::get_collection("guilds")

View File

@@ -1,7 +1,7 @@
use super::Response; use super::Response;
use crate::util::variables::{USE_EMAIL_VERIFICATION, USE_HCAPTCHA};
use mongodb::bson::doc; use mongodb::bson::doc;
use std::env;
/// root /// root
#[get("/")] #[get("/")]
@@ -14,7 +14,8 @@ pub fn root() -> Response {
"patch": 9 "patch": 9
}, },
"features": { "features": {
"captcha": env::var("HCAPTCHA_KEY").is_ok() "email_verification": USE_EMAIL_VERIFICATION.clone(),
"captcha": USE_HCAPTCHA.clone(),
} }
})) }))
} }

View File

@@ -1,5 +1,7 @@
use super::Response; use super::Response;
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship, user::User}; use crate::database::{
self, get_relationship, get_relationship_internal, user::User, Relationship,
};
use crate::notifications::{ use crate::notifications::{
self, self,
events::{users::*, Notification}, events::{users::*, Notification},
@@ -15,18 +17,14 @@ use ulid::Ulid;
/// retrieve your user information /// retrieve your user information
#[get("/@me")] #[get("/@me")]
pub fn me(user: User) -> Response { pub fn me(user: User) -> Response {
Response::Success( Response::Success(user.serialise(Relationship::SELF as i32))
user.serialise(Relationship::SELF as i32)
)
} }
/// retrieve another user's information /// retrieve another user's information
#[get("/<target>")] #[get("/<target>")]
pub fn user(user: User, target: User) -> Response { pub fn user(user: User, target: User) -> Response {
let relationship = get_relationship(&user, &target) as i32; let relationship = get_relationship(&user, &target) as i32;
Response::Success( Response::Success(user.serialise(relationship))
user.serialise(relationship)
)
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]

View File

@@ -1,11 +1,11 @@
use serde::{Serialize, Deserialize};
use reqwest::blocking::Client; use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct CaptchaResponse { struct CaptchaResponse {
success: bool success: bool,
} }
pub fn verify(user_token: &Option<String>) -> Result<(), String> { pub fn verify(user_token: &Option<String>) -> Result<(), String> {

96
src/util/email.rs Normal file
View File

@@ -0,0 +1,96 @@
use lettre::message::{header, MultiPart, SinglePart};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};
use super::variables::{PUBLIC_URL, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD, SMTP_USERNAME};
lazy_static! {
static ref MAILER: lettre::transport::smtp::SmtpTransport =
SmtpTransport::relay(SMTP_HOST.as_ref())
.unwrap()
.credentials(Credentials::new(
SMTP_USERNAME.to_string(),
SMTP_PASSWORD.to_string()
))
.build();
}
fn send(message: Message) -> Result<(), String> {
MAILER
.send(&message)
.map_err(|err| format!("Failed to send email! {}", err.to_string()))?;
Ok(())
}
fn generate_multipart(text: &str, html: &str) -> MultiPart {
MultiPart::mixed().multipart(
MultiPart::alternative()
.singlepart(
SinglePart::quoted_printable()
.header(header::ContentType(
"text/plain; charset=utf8".parse().unwrap(),
))
.body(text),
)
.multipart(
MultiPart::related().singlepart(
SinglePart::eight_bit()
.header(header::ContentType(
"text/html; charset=utf8".parse().unwrap(),
))
.body(html),
),
),
)
}
pub fn send_verification_email(email: String, code: String) -> Result<(), String> {
let url = format!("{}/api/account/verify/{}", PUBLIC_URL.to_string(), code);
let email = Message::builder()
.from(SMTP_FROM.to_string().parse().unwrap())
.to(email.parse().unwrap())
.subject("Verify your email!")
.multipart(generate_multipart(
&format!("Verify your email here: {}", url),
&format!("<a href=\"{}\">Click to verify your email!</a>", url),
))
.unwrap();
send(email)
}
pub fn send_password_reset(email: String, code: String) -> Result<(), String> {
let url = format!("{}/api/account/reset/{}", PUBLIC_URL.to_string(), code);
let email = Message::builder()
.from(SMTP_FROM.to_string().parse().unwrap())
.to(email.parse().unwrap())
.subject("Reset your password.")
.multipart(generate_multipart(
&format!("Reset your password here: {}", url),
&format!("<a href=\"{}\">Click to reset your password!</a>", url),
))
.unwrap();
send(email)
}
pub fn send_welcome_email(email: String, username: String) -> Result<(), String> {
let email = Message::builder()
.from(SMTP_FROM.to_string().parse().unwrap())
.to(email.parse().unwrap())
.subject("Welcome to REVOLT!")
.multipart(
generate_multipart(
&format!("Welcome, {}! You can now use REVOLT.", username),
&format!(
"<b>Welcome, {}!</b><br/>You can now use REVOLT.<br/><a href=\"{}\">Go to REVOLT</a>",
username,
PUBLIC_URL.to_string()
)
)
)
.unwrap();
send(email)
}

View File

@@ -3,6 +3,8 @@ use rand::{distributions::Alphanumeric, Rng};
use std::iter::FromIterator; use std::iter::FromIterator;
pub mod captcha; pub mod captcha;
pub mod email;
pub mod variables;
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> { pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
HashSet::from_iter(data.iter().cloned()) HashSet::from_iter(data.iter().cloned())

27
src/util/variables.rs Normal file
View File

@@ -0,0 +1,27 @@
use std::env;
lazy_static! {
pub static ref MONGO_URI: String =
env::var("REVOLT_MONGO_URI").expect("Missing REVOLT_MONGO_URI environment variable.");
pub static ref PUBLIC_URL: String =
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable.");
pub static ref USE_EMAIL_VERIFICATION: bool = env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
env::var("REVOLT_SMTP_HOST").is_ok()
&& env::var("REVOLT_SMTP_USERNAME").is_ok()
&& env::var("REVOLT_SMTP_PASSWORD").is_ok()
&& env::var("REVOLT_SMTP_FROM").is_ok(),
|v| v == *"1"
);
pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok();
pub static ref SMTP_HOST: String =
env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string());
pub static ref SMTP_USERNAME: String =
env::var("SMTP_USERNAME").unwrap_or_else(|_| "".to_string());
pub static ref SMTP_PASSWORD: String =
env::var("SMTP_PASSWORD").unwrap_or_else(|_| "".to_string());
pub static ref SMTP_FROM: String = env::var("SMTP_FROM").unwrap_or_else(|_| "".to_string());
pub static ref HCAPTCHA_KEY: String =
env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "".to_string());
pub static ref WS_HOST: String =
env::var("REVOLT_WS_HOST").unwrap_or_else(|_| "0.0.0.0:9999".to_string());
}