Compare commits

..

33 Commits

Author SHA1 Message Date
Paul Makles
a2f14d2d37 Bump version. 2021-02-16 15:26:31 +00:00
Paul Makles
a7ea29d821 Add a way to send messages with attachments. 2021-02-16 15:25:33 +00:00
Paul Makles
b6b51bca26 Route which lets clients determine messages that have updated / deleted. 2021-02-16 09:34:24 +00:00
Paul Makles
2bafffbbc1 Case-insensitive search for emails. 2021-02-14 16:28:23 +00:00
Paul Makles
bdf5fb95d0 Add rAuth captcha support. 2021-02-13 20:18:38 +00:00
Paul Makles
ea8de2400a Add support for rAuth invite-only mode. 2021-02-12 20:37:24 +00:00
Paul Makles
f5e0b49bbb Update rAuth, add templates; add APP_URL variable. 2021-02-12 15:09:42 +00:00
Paul Makles
b0d07ec58f Include DM users in payload; fix permission query. + cargo fmt 2021-02-09 16:41:08 +00:00
Paul Makles
4c99d079e0 Remove ViewAll; check for mutual DMs. 2021-02-09 15:51:35 +00:00
Paul Makles
38bedbaaea Add Gravatar support. 2021-02-02 19:09:13 +00:00
Paul Makles
ea276c3517 Fix assets fr this time 2021-01-30 18:40:58 +00:00
Paul Makles
648e33a13e Include assets in docker image. 2021-01-30 18:23:23 +00:00
Paul Makles
a76ec207b3 Add Prometheus metrics. 2021-01-29 21:56:37 +00:00
Paul Makles
687b300bfc Include assets in Docker image. 2021-01-28 18:51:46 +00:00
Paul Makles
6586d8f02c Fix SSL certificates in container. 2021-01-27 19:37:21 +00:00
Paul Makles
a8a8c08c29 Update Docker image and ports. 2021-01-27 18:31:27 +00:00
Paul Makles
1806ea824b Bump rAuth revision. 2021-01-27 11:08:37 +00:00
Paul Makles
222a417fff Add utility function for including relationship on User. 2021-01-26 22:33:14 +00:00
Paul Makles
3b85dcce14 Include group members in payload. 2021-01-26 22:05:32 +00:00
Paul Makles
f42480886b Re-structure Permissions; add perm to view users from mutual groups. 2021-01-26 21:12:23 +00:00
Paul Makles
23ec2d61f1 Push env variables to rAuth + cargo fmt. 2021-01-26 17:29:03 +00:00
Paul Makles
abd8b1821d Reset migrations; [point of no return for old databases] 2021-01-26 09:30:29 +00:00
Paul Makles
75a35831da Update rauth, pin git repositories in Cargo.toml. 2021-01-25 21:35:47 +00:00
Paul Makles
99e2f874a1 $set instead of overwriting object 2021-01-24 10:28:24 +00:00
Paul Makles
11f7092fcd Add last_message to channels, mark DMs as active. 2021-01-24 10:24:44 +00:00
Paul Makles
cb882ce1b2 Block @revolt from being registered. 2021-01-24 09:29:42 +00:00
Paul Makles
5486a68bfa Move group leave into posthandle hook. 2021-01-24 09:20:43 +00:00
Paul Makles
4aaf328435 Include all channels in payload. 2021-01-24 09:20:07 +00:00
Paul Makles
9d251f794b Update tag in enums. 2021-01-19 21:27:18 +00:00
Paul Makles
1d390d483d Add a database migration for channel tag enum. 2021-01-19 21:11:38 +00:00
Paul Makles
81de29e723 Backtracking again, and adding the channel_type tag. 2021-01-19 20:55:25 +00:00
Paul Makles
984017eb61 Revert tag change, update partials to include ids. 2021-01-19 20:18:29 +00:00
Paul Makles
5ab329dfdd Prevent fetching messages from other channels. Change channel tag to channel_type. 2021-01-19 19:54:37 +00:00
50 changed files with 1462 additions and 754 deletions

View File

@@ -1,3 +1,3 @@
assets
target
.mongo
.env

700
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package]
name = "revolt"
version = "0.3.1"
version = "0.3.3-alpha.5"
authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018"
@@ -8,17 +8,18 @@ edition = "2018"
[dependencies]
futures = "0.3.8"
many-to-many = "0.1.2"
impl_ops = "0.1.1"
many-to-many = "0.1.2"
ctrlc = { version = "3.0", features = ["termination"] }
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
rauth = { git = "https://gitlab.insrt.uk/insert/rauth" }
async-std = { version = "1.8.0", features = ["tokio02", "attributes"] }
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
rauth = { git = "https://gitlab.insrt.uk/insert/rauth", rev = "c52758a5087cd035b0ed9c6eacc942ba5468d2ce" }
hive_pubsub = { version = "0.4.3", features = ["mongo"] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", branch = "master" }
rocket = { git = "https://github.com/SergioBenitez/Rocket", branch = "master", default-features = false }
rocket_cors = { git = "https://github.com/insertish/rocket_cors", branch = "master" }
rocket_prometheus = { git = "https://github.com/insertish/rocket_prometheus", rev = "3d825aedb42793246c306a81fe67c5b187948983" }
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00" }
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00", default-features = false }
mongodb = { version = "1.1.1", features = ["tokio-runtime"], default-features = false }
once_cell = "1.4.1"
@@ -32,11 +33,13 @@ serde_json = "1.0.57"
bitfield = "0.13.2"
reqwest = { version = "0.10.8", features = ["json"] }
urlencoding = "1.1.1"
lazy_static = "1.4.0"
num_enum = "0.5.1"
chrono = "0.4.15"
time = "0.2.16"
rand = "0.7.3"
md5 = "0.7.0"
regex = "1"
lettre = "0.10.0-alpha.1"

View File

@@ -1,16 +1,21 @@
# Build Stage
FROM ekidd/rust-musl-builder:nightly-2020-11-19 AS builder
FROM ekidd/rust-musl-builder:nightly-2021-01-01 AS builder
WORKDIR /home/rust/src
RUN USER=root cargo new --bin revolt
WORKDIR ./revolt
WORKDIR /home/rust/src/revolt
COPY Cargo.toml Cargo.lock ./
COPY assets/templates ./assets/templates
COPY src ./src
RUN cargo build --release
# Bundle Stage
FROM scratch
FROM alpine:latest
RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/*
COPY --from=builder /home/rust/src/revolt/target/x86_64-unknown-linux-musl/release/revolt ./
COPY assets ./assets
EXPOSE 8000
EXPOSE 9000
ENV ROCKET_ADDRESS 0.0.0.0
ENV ROCKET_PORT 8000
CMD ["./revolt"]

View File

@@ -0,0 +1,62 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Reset your password.</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style type="text/css">
a[x-apple-data-detectors] {color: inherit !important;}
</style>
</head>
<body style="margin: 0; padding: 0;">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="padding: 20px 0 30px 0;">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; border: 1px solid #cccccc;">
<tr>
<td align="center" bgcolor="#ff4654">
<img src="https://revolt.chat/header.png" alt="REVOLT logo" width="600" height="168" style="display: block;" />
</td>
</tr>
<tr>
<td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">
<tr>
<td style="color: #153643; font-family: Arial, sans-serif;">
<h1 style="font-size: 24px; margin: 0;">Reset your password!</h1>
</td>
</tr>
<tr>
<td style="color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; padding: 20px 0 0 0;">
<p style="margin: 0;">
Reset your password by <a href="{{url}}">clicking here</a>.
</p>
<p>
Or by manually navigating to the URL: {{url}}
</p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor="#ff4654" style="padding: 30px 30px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">
<tr>
<td style="color: #ffffff; font-family: Arial, sans-serif; font-size: 14px;">
<p style="margin: 0;">Sent by REVOLT. &middot; <a style="color: white;" href="https://revolt.chat">Website</a> &middot; <a style="color: white;" href="https://gitlab.insrt.uk/revolt">Source Code</a></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,62 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Verify your account.</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style type="text/css">
a[x-apple-data-detectors] {color: inherit !important;}
</style>
</head>
<body style="margin: 0; padding: 0;">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="padding: 20px 0 30px 0;">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse; border: 1px solid #cccccc;">
<tr>
<td align="center" bgcolor="#ff4654">
<img src="https://revolt.chat/header.png" alt="REVOLT logo" width="600" height="168" style="display: block;" />
</td>
</tr>
<tr>
<td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">
<tr>
<td style="color: #153643; font-family: Arial, sans-serif;">
<h1 style="font-size: 24px; margin: 0;">Verify your account!</h1>
</td>
</tr>
<tr>
<td style="color: #153643; font-family: Arial, sans-serif; font-size: 16px; line-height: 24px; padding: 20px 0 0 0;">
<p style="margin: 0;">
Please verify your account by <a href="{{url}}">clicking here</a>.
</p>
<p>
Or by manually navigating to the URL: {{url}}
</p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td bgcolor="#ff4654" style="padding: 30px 30px;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">
<tr>
<td style="color: #ffffff; font-family: Arial, sans-serif; font-size: 14px;">
<p style="margin: 0;">Sent by REVOLT. &middot; <a style="color: white;" href="https://revolt.chat">Website</a> &middot; <a style="color: white;" href="https://gitlab.insrt.uk/revolt">Source Code</a></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

View File

@@ -14,5 +14,5 @@ services:
- REVOLT_UNSAFE_NO_CAPTCHA=1
ports:
- "8000:8000"
- "9999:9999"
- "9000:9000"
restart: unless-stopped

View File

@@ -0,0 +1,21 @@
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
enum Metadata {
File,
Image { width: isize, height: isize },
Video { width: isize, height: isize },
Audio,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct File {
#[serde(rename = "_id")]
pub id: String,
filename: String,
metadata: Metadata,
content_type: String,
message_id: Option<String>
}

View File

@@ -1,12 +1,20 @@
use crate::database::*;
use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use mongodb::bson::{doc, to_document};
use mongodb::bson::{doc, from_document, to_document};
use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub struct LastMessage {
#[serde(rename = "_id")]
id: String,
author: String,
short: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "channel_type")]
pub enum Channel {
SavedMessages {
#[serde(rename = "_id")]
@@ -18,6 +26,8 @@ pub enum Channel {
id: String,
active: bool,
recipients: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
last_message: Option<LastMessage>,
},
Group {
#[serde(rename = "_id")]
@@ -28,6 +38,8 @@ pub enum Channel {
owner: String,
description: String,
recipients: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
last_message: Option<LastMessage>,
},
}
@@ -40,6 +52,22 @@ impl Channel {
}
}
pub async fn get(id: &str) -> Result<Channel> {
let doc = get_collection("channels")
.find_one(doc! { "_id": id }, None)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "channel",
})?
.ok_or_else(|| Error::UnknownChannel)?;
from_document::<Channel>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "channel",
})
}
pub async fn publish(self) -> Result<()> {
get_collection("channels")
.insert_one(
@@ -64,12 +92,15 @@ impl Channel {
Ok(())
}
pub async fn publish_update(&self, partial: JsonValue) -> Result<()> {
pub async fn publish_update(&self, data: JsonValue) -> Result<()> {
let id = self.id().to_string();
ClientboundNotification::ChannelUpdate(partial)
.publish(id)
.await
.ok();
ClientboundNotification::ChannelUpdate {
id: id.clone(),
data,
}
.publish(id)
.await
.ok();
Ok(())
}

View File

@@ -19,6 +19,8 @@ pub struct Message {
pub content: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub attachment: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")]
pub edited: Option<DateTime>,
}
@@ -31,34 +33,86 @@ impl Message {
author,
content,
attachment: None,
edited: None,
}
}
pub async fn publish(self) -> Result<()> {
pub async fn publish(self, channel: &Channel) -> Result<()> {
get_collection("messages")
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
.await
.map_err(|_| Error::DatabaseError {
operation: "insert_one",
with: "messages",
with: "message",
})?;
let channel = self.channel.clone();
// ! FIXME: temp code
let channels = get_collection("channels");
match channel {
Channel::DirectMessage { id, .. } => {
channels
.update_one(
doc! { "_id": id },
doc! {
"$set": {
"active": true,
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": self.content.chars().take(24).collect::<String>()
}
}
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "channel",
})?;
}
Channel::Group { id, .. } => {
channels
.update_one(
doc! { "_id": id },
doc! {
"$set": {
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": self.content.chars().take(24).collect::<String>()
}
}
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "channel",
})?;
}
_ => {}
}
ClientboundNotification::Message(self)
.publish(channel)
.publish(channel.id().to_string())
.await
.ok();
Ok(())
}
pub async fn publish_update(&self, partial: JsonValue) -> Result<()> {
pub async fn publish_update(&self, data: JsonValue) -> Result<()> {
let channel = self.channel.clone();
ClientboundNotification::MessageUpdate(partial)
.publish(channel)
.await
.ok();
ClientboundNotification::MessageUpdate {
id: self.id.clone(),
data,
}
.publish(channel)
.await
.ok();
Ok(())
}

View File

@@ -2,8 +2,10 @@ mod channel;
mod guild;
mod message;
mod user;
mod autumn;
pub use channel::*;
pub use guild::*;
pub use message::*;
pub use user::*;
pub use autumn::*;

View File

@@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::{database::permissions::user::UserPermissions, notifications::websocket::is_online};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum RelationshipStatus {
None,
@@ -32,3 +34,32 @@ pub struct User {
#[serde(skip_serializing_if = "Option::is_none")]
pub online: Option<bool>,
}
impl User {
/// Mutate the user object to include relationship as seen by user.
pub fn from(mut self, user: &User) -> User {
if self.id == user.id {
self.relationship = Some(RelationshipStatus::User);
return self;
}
self.relations = None;
if let Some(relations) = &user.relations {
if let Some(relationship) = relations.iter().find(|x| self.id == x.id) {
self.relationship = Some(relationship.status.clone());
return self;
}
}
self
}
/// Mutate the user object to appear as seen by user.
pub fn with(mut self, permissions: UserPermissions<[u32; 1]>) -> User {
if permissions.get_view_profile() {
self.online = Some(is_online(&self.id));
}
self
}
}

View File

@@ -47,8 +47,13 @@ impl Ref {
self.fetch("channels").await
}
pub async fn fetch_message(&self) -> Result<Message> {
self.fetch("messages").await
pub async fn fetch_message(&self, channel: &Channel) -> Result<Message> {
let message: Message = self.fetch("messages").await?;
if &message.channel != channel.id() {
Err(Error::InvalidOperation)
} else {
Ok(message)
}
}
}

View File

@@ -29,7 +29,10 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
} else {
Outcome::Failure((
Status::InternalServerError,
rauth::util::Error::DatabaseError,
rauth::util::Error::DatabaseError {
operation: "find_one",
with: "user",
},
))
}
}

View File

@@ -9,6 +9,10 @@ pub async fn create_database() {
info!("Creating database.");
let db = get_db();
db.create_collection("accounts", None)
.await
.expect("Failed to create accounts collection.");
db.create_collection("users", None)
.await
.expect("Failed to create users collection.");
@@ -17,14 +21,6 @@ pub async fn create_database() {
.await
.expect("Failed to create channels collection.");
db.create_collection("guilds", None)
.await
.expect("Failed to create guilds collection.");
db.create_collection("members", None)
.await
.expect("Failed to create members collection.");
db.create_collection("messages", None)
.await
.expect("Failed to create messages collection.");
@@ -43,6 +39,39 @@ pub async fn create_database() {
.await
.expect("Failed to create pubsub collection.");
db.run_command(
doc! {
"createIndexes": "accounts",
"indexes": [
{
"key": {
"email": 1
},
"name": "email",
"unique": true,
"collation": {
"locale": "en",
"strength": 2
}
},
{
"key": {
"email_normalised": 1
},
"name": "email_normalised",
"unique": true,
"collation": {
"locale": "en",
"strength": 2
}
}
]
},
None,
)
.await
.expect("Failed to create account index.");
db.run_command(
doc! {
"createIndexes": "users",

View File

@@ -1,9 +1,7 @@
use super::super::{get_collection, get_db};
use crate::database::get_collection;
use crate::rocket::futures::StreamExt;
use log::info;
use mongodb::bson::{doc, from_document};
use mongodb::options::FindOptions;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
@@ -12,7 +10,7 @@ struct MigrationInfo {
revision: i32,
}
pub const LATEST_REVISION: i32 = 3;
pub const LATEST_REVISION: i32 = 0;
pub async fn migrate_database() {
let migrations = get_collection("migrations");
@@ -55,99 +53,6 @@ pub async fn run_migrations(revision: i32) -> i32 {
info!("Running migration [revision 0]: Test migration system.");
}
if revision <= 1 {
info!("Running migration [revision 1]: Add channels to guild object.");
let col = get_collection("guilds");
let mut guilds = col
.find(
None,
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
)
.await
.expect("Failed to fetch guilds.");
let mut result = get_collection("channels")
.find(
doc! {
"type": 2
},
FindOptions::builder()
.projection(doc! { "_id": 1, "guild": 1 })
.build(),
)
.await
.expect("Failed to fetch channels.");
let mut channels = vec![];
while let Some(doc) = result.next().await {
let channel = doc.expect("Failed to fetch channel.");
let id = channel
.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));
}
while let Some(doc) = guilds.next().await {
let guild = doc.expect("Failed to fetch guild.");
let id = guild.get_str("_id").expect("Failed to get guild id.");
let list: Vec<String> = channels
.iter()
.filter(|x| x.1 == id)
.map(|x| x.0.clone())
.collect();
col.update_one(
doc! {
"_id": id
},
doc! {
"$set": {
"channels": list
}
},
None,
)
.await
.expect("Failed to update guild.");
}
}
if revision <= 2 {
info!("Running migration [revision 2]: Add username index to users.");
get_db()
.run_command(
doc! {
"createIndexes": "users",
"indexes": [
{
"key": {
"username": 1
},
"name": "username",
"unique": true,
"collation": {
"locale": "en",
"strength": 2
}
}
]
},
None,
)
.await
.expect("Failed to create username index.");
}
// Reminder to update LATEST_REVISION when adding new migrations.
LATEST_REVISION
}

View File

@@ -1,4 +1,8 @@
use crate::database::*;
use crate::util::result::Result;
use super::PermissionCalculator;
use num_enum::TryFromPrimitive;
use std::ops;
@@ -21,40 +25,59 @@ bitfield! {
impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 });
impl_op_ex_commutative!(+ |a: &u32, b: &ChannelPermission| -> u32 { *a | *b as u32 });
pub async fn calculate(user: &User, target: &Channel) -> ChannelPermissions<[u32; 1]> {
match target {
Channel::SavedMessages { user: owner, .. } => {
if &user.id == owner {
ChannelPermissions([ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageMessages])
} else {
ChannelPermissions([0])
}
}
Channel::DirectMessage { recipients, .. } => {
if recipients.iter().find(|x| *x == &user.id).is_some() {
if let Some(recipient) = recipients.iter().find(|x| *x != &user.id) {
let perms = super::user::calculate(&user, recipient).await;
impl<'a> PermissionCalculator<'a> {
pub async fn calculate_channel(self) -> Result<u32> {
let channel = if let Some(channel) = self.channel {
channel
} else {
unreachable!()
};
if perms.get_send_message() {
return ChannelPermissions([
ChannelPermission::View + ChannelPermission::SendMessage
]);
}
return ChannelPermissions([ChannelPermission::View as u32]);
match channel {
Channel::SavedMessages { user: owner, .. } => {
if &self.perspective.id == owner {
Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageMessages)
} else {
Ok(0)
}
}
Channel::DirectMessage { recipients, .. } => {
if recipients
.iter()
.find(|x| *x == &self.perspective.id)
.is_some()
{
if let Some(recipient) = recipients.iter().find(|x| *x != &self.perspective.id)
{
let perms = self.for_user(recipient).await?;
ChannelPermissions([0])
}
Channel::Group { recipients, .. } => {
if recipients.iter().find(|x| *x == &user.id).is_some() {
ChannelPermissions([ChannelPermission::View + ChannelPermission::SendMessage])
} else {
ChannelPermissions([0])
if perms.get_send_message() {
return Ok(ChannelPermission::View + ChannelPermission::SendMessage);
}
return Ok(ChannelPermission::View as u32);
}
}
Ok(0)
}
Channel::Group { recipients, .. } => {
if recipients
.iter()
.find(|x| *x == &self.perspective.id)
.is_some()
{
Ok(ChannelPermission::View + ChannelPermission::SendMessage)
} else {
Ok(0)
}
}
}
}
pub async fn for_channel(self) -> Result<ChannelPermissions<[u32; 1]>> {
Ok(ChannelPermissions([self.calculate_channel().await?]))
}
}

View File

@@ -1,4 +1,49 @@
pub use crate::database::*;
pub mod channel;
pub mod user;
pub use user::get_relationship;
pub struct PermissionCalculator<'a> {
perspective: &'a User,
user: Option<&'a User>,
channel: Option<&'a Channel>,
has_mutual_conncetion: bool,
}
impl<'a> PermissionCalculator<'a> {
pub fn new(perspective: &'a User) -> PermissionCalculator {
PermissionCalculator {
perspective,
user: None,
channel: None,
has_mutual_conncetion: false,
}
}
pub fn with_user(self, user: &'a User) -> PermissionCalculator {
PermissionCalculator {
user: Some(&user),
..self
}
}
pub fn with_channel(self, channel: &'a Channel) -> PermissionCalculator {
PermissionCalculator {
channel: Some(&channel),
..self
}
}
pub fn with_mutual_connection(self) -> PermissionCalculator<'a> {
PermissionCalculator {
has_mutual_conncetion: true,
..self
}
}
}

View File

@@ -1,4 +1,9 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use super::PermissionCalculator;
use mongodb::bson::doc;
use num_enum::TryFromPrimitive;
use std::ops;
@@ -6,47 +11,23 @@ use std::ops;
#[repr(u32)]
pub enum UserPermission {
Access = 1,
SendMessage = 2,
Invite = 4,
ViewProfile = 2,
SendMessage = 4,
Invite = 8,
}
bitfield! {
pub struct UserPermissions(MSB0 [u32]);
u32;
pub get_access, _: 31;
pub get_send_message, _: 30;
pub get_invite, _: 29;
pub get_view_profile, _: 30;
pub get_send_message, _: 29;
pub get_invite, _: 28;
}
impl_op_ex!(+ |a: &UserPermission, b: &UserPermission| -> u32 { *a as u32 | *b as u32 });
impl_op_ex_commutative!(+ |a: &u32, b: &UserPermission| -> u32 { *a | *b as u32 });
pub async fn calculate(user: &User, target: &str) -> UserPermissions<[u32; 1]> {
// if friends; Access + Message + Invite
// if mutually know each other:
// and has DMs from users enabled -> Access + Message
// otherwise -> Access
// otherwise; None
let mut permissions: u32 = 0;
match get_relationship(&user, &target) {
RelationshipStatus::Friend => {
return UserPermissions([UserPermission::Access
+ UserPermission::SendMessage
+ UserPermission::Invite])
}
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
return UserPermissions([UserPermission::Access as u32])
}
RelationshipStatus::Incoming | RelationshipStatus::Outgoing => {
permissions = UserPermission::Access as u32;
}
_ => {}
}
UserPermissions([permissions])
}
pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus {
if a.id == b {
return RelationshipStatus::Friend;
@@ -60,3 +41,63 @@ pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus {
RelationshipStatus::None
}
impl<'a> PermissionCalculator<'a> {
pub async fn calculate_user(self, target: &str) -> Result<u32> {
if &self.perspective.id == target {
return Ok(u32::MAX);
}
let mut permissions: u32 = 0;
match get_relationship(&self.perspective, &target) {
RelationshipStatus::Friend => return Ok(u32::MAX),
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
return Ok(UserPermission::Access as u32)
}
RelationshipStatus::Incoming | RelationshipStatus::Outgoing => {
permissions = UserPermission::Access as u32;
// ! INFO: if we add boolean switch for permission to
// ! message people who have mutual, we need to get
// ! rid of this return statement.
return Ok(permissions);
}
_ => {}
}
if self.has_mutual_conncetion
|| get_collection("channels")
.find_one(
doc! {
"$or": [
{ "type": "Group" },
{ "type": "DirectMessage" },
],
"$and": [
{ "recipients": &self.perspective.id },
{ "recipients": target }
]
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "channels",
})?
.is_some()
{
return Ok(UserPermission::Access as u32);
}
Ok(permissions)
}
pub async fn for_user(self, target: &str) -> Result<UserPermissions<[u32; 1]>> {
Ok(UserPermissions([self.calculate_user(&target).await?]))
}
pub async fn for_user_given(self) -> Result<UserPermissions<[u32; 1]>> {
let id = &self.user.unwrap().id;
Ok(UserPermissions([self.calculate_user(&id).await?]))
}
}

View File

@@ -18,10 +18,20 @@ pub mod notifications;
pub mod routes;
pub mod util;
use chrono::Duration;
use futures::join;
use log::info;
use rauth;
use rauth::options::{EmailVerification, Options, SMTP};
use rauth::{
auth::Auth,
options::{Template, Templates},
};
use rocket_cors::AllowedOrigins;
use rocket_prometheus::PrometheusMetrics;
use util::variables::{
APP_URL, HCAPTCHA_KEY, INVITE_ONLY, PUBLIC_URL, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD,
SMTP_USERNAME, USE_EMAIL, USE_HCAPTCHA, USE_PROMETHEUS,
};
#[async_std::main]
async fn main() {
@@ -55,10 +65,66 @@ async fn launch_web() {
.to_cors()
.expect("Failed to create CORS.");
let auth = rauth::auth::Auth::new(database::get_collection("accounts"));
let mut options = Options::new()
.base_url(format!("{}/auth", *PUBLIC_URL))
.email_verification(if *USE_EMAIL {
EmailVerification::Enabled {
success_redirect_uri: format!("{}/login", *APP_URL),
welcome_redirect_uri: format!("{}/welcome", *APP_URL),
password_reset_url: Some(format!("{}/login/reset", *APP_URL)),
routes::mount(rauth::routes::mount(rocket::ignite(), "/auth", auth))
verification_expiry: Duration::days(1),
password_reset_expiry: Duration::hours(1),
templates: Templates {
verify_email: Template {
title: "Verify your REVOLT account.",
text: "Verify your email here: {{url}}",
html: include_str!("../assets/templates/verify.html"),
},
reset_password: Template {
title: "Reset your REVOLT password.",
text: "Reset your password here: {{url}}",
html: include_str!("../assets/templates/reset.html"),
},
welcome: None,
},
smtp: SMTP {
from: (*SMTP_FROM).to_string(),
host: (*SMTP_HOST).to_string(),
username: (*SMTP_USERNAME).to_string(),
password: (*SMTP_PASSWORD).to_string(),
},
}
} else {
EmailVerification::Disabled
});
if *INVITE_ONLY {
options = options.invite_only_collection(database::get_collection("invites"))
}
if *USE_HCAPTCHA {
options = options.hcaptcha_secret(HCAPTCHA_KEY.clone());
}
let auth = Auth::new(database::get_collection("accounts"), options);
let mut rocket = rocket::ignite();
if *USE_PROMETHEUS {
info!("Enabled Prometheus metrics!");
let prometheus = PrometheusMetrics::new();
rocket = rocket
.attach(prometheus.clone())
.mount("/metrics", prometheus);
}
routes::mount(rocket)
.mount("/", rocket_cors::catch_all_options_routes())
.mount("/auth", rauth::routes::routes())
.manage(auth)
.manage(cors.clone())
.attach(cors)
.launch()

View File

@@ -39,13 +39,19 @@ pub enum ClientboundNotification {
},
Message(Message),
MessageUpdate(JsonValue),
MessageUpdate {
id: String,
data: JsonValue,
},
MessageDelete {
id: String,
},
ChannelCreate(Channel),
ChannelUpdate(JsonValue),
ChannelUpdate {
id: String,
data: JsonValue,
},
ChannelGroupJoin {
id: String,
user: String,
@@ -94,12 +100,6 @@ pub fn prehandle_hook(notification: &ClientboundNotification) {
}
}
}
ClientboundNotification::ChannelGroupLeave { id, user } => {
get_hive()
.hive
.unsubscribe(&user.to_string(), &id.to_string())
.ok();
}
ClientboundNotification::UserRelationship { id, user, status } => {
if status != &RelationshipStatus::None {
subscribe_if_exists(id.clone(), user.clone()).ok();
@@ -122,6 +122,12 @@ pub fn posthandle_hook(notification: &ClientboundNotification) {
.ok();
}
}
ClientboundNotification::ChannelGroupLeave { id, user } => {
get_hive()
.hive
.unsubscribe(&user.to_string(), &id.to_string())
.ok();
}
_ => {}
}
}

View File

@@ -1,4 +1,6 @@
use crate::notifications::events::ClientboundNotification;
use std::collections::HashSet;
use crate::{database::*, notifications::events::ClientboundNotification};
use crate::{
database::{entities::User, get_collection},
util::result::{Error, Result},
@@ -9,55 +11,16 @@ use mongodb::{
options::FindOptions,
};
use super::websocket::is_online;
pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
let mut users = vec![];
let mut user_ids: HashSet<String> = HashSet::new();
if let Some(relationships) = &user.relations {
let user_ids: Vec<String> = relationships
.iter()
.map(|relationship| relationship.id.clone())
.collect();
let mut cursor = get_collection("users")
.find(
doc! {
"_id": {
"$in": user_ids
}
},
FindOptions::builder()
.projection(doc! { "_id": 1, "username": 1 })
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "users",
})?;
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
let mut user: User = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "user",
})?;
user.relationship = Some(
relationships
.iter()
.find(|x| user.id == x.id)
.ok_or_else(|| Error::InternalError)?
.status
.clone(),
);
user.online = Some(is_online(&user.id));
users.push(user);
}
}
user_ids.extend(
relationships
.iter()
.map(|relationship| relationship.id.clone()),
);
}
let mut cursor = get_collection("channels")
@@ -65,16 +28,15 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
doc! {
"$or": [
{
"type": "SavedMessages",
"channel_type": "SavedMessages",
"user": &user.id
},
{
"type": "DirectMessage",
"recipients": &user.id,
"active": true
"channel_type": "DirectMessage",
"recipients": &user.id
},
{
"type": "Group",
"channel_type": "Group",
"recipients": &user.id
}
]
@@ -90,13 +52,59 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
let mut channels = vec![];
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
channels.push(from_document(doc).map_err(|_| Error::DatabaseError {
let channel = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "channel",
})?);
})?;
if let Channel::Group { recipients, .. } = &channel {
user_ids.extend(recipients.iter().cloned());
} else if let Channel::DirectMessage { recipients, .. } = &channel {
user_ids.extend(recipients.iter().cloned());
}
channels.push(channel);
}
}
user_ids.remove(&user.id);
if user_ids.len() > 0 {
let mut cursor = get_collection("users")
.find(
doc! {
"_id": {
"$in": user_ids.into_iter().collect::<Vec<String>>()
}
},
FindOptions::builder()
.projection(doc! { "_id": 1, "username": 1 })
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "users",
})?;
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
let other: User = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "user",
})?;
let permissions = PermissionCalculator::new(&user)
.with_mutual_connection()
.with_user(&other)
.for_user_given()
.await?;
users.push(other.from(&user).with(permissions));
}
}
}
user.relationship = Some(RelationshipStatus::User);
user.online = Some(true);
users.push(user);

View File

@@ -21,16 +21,15 @@ pub async fn generate_subscriptions(user: &User) -> Result<(), String> {
doc! {
"$or": [
{
"type": "SavedMessages",
"channel_type": "SavedMessages",
"user": &user.id
},
{
"type": "DirectMessage",
"recipients": &user.id,
"active": true
"channel_type": "DirectMessage",
"recipients": &user.id
},
{
"type": "Group",
"channel_type": "Group",
"recipients": &user.id
}
]

View File

@@ -12,7 +12,10 @@ use futures::{pin_mut, prelude::*};
use hive_pubsub::PubSub;
use log::{debug, info};
use many_to_many::ManyToMany;
use rauth::auth::{Auth, Session};
use rauth::{
auth::{Auth, Session},
options::Options,
};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, RwLock};
@@ -84,9 +87,10 @@ async fn accept(stream: TcpStream) {
}
}
if let Ok(validated_session) = Auth::new(get_collection("accounts"))
.verify_session(new_session)
.await
if let Ok(validated_session) =
Auth::new(get_collection("accounts"), Options::new())
.verify_session(new_session)
.await
{
let id = validated_session.user_id.clone();
if let Ok(user) = (Ref { id: id.clone() }).fetch_user().await {

View File

@@ -7,7 +7,10 @@ use mongodb::bson::doc;
pub async fn req(user: User, target: Ref) -> Result<()> {
let target = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &target).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
@@ -101,7 +104,7 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
id.clone(),
format!("<@{}> left the group.", user.id),
)
.publish()
.publish(&target)
.await
.ok();

View File

@@ -7,7 +7,10 @@ use rocket_contrib::json::JsonValue;
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &target).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}

View File

@@ -11,13 +11,15 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
}
let channel = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &channel).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&channel)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
if let Channel::Group { id, recipients, .. } = channel {
if let Channel::Group { id, recipients, .. } = &channel {
if recipients.len() >= *MAX_GROUP_SIZE {
Err(Error::GroupTooLarge {
max: *MAX_GROUP_SIZE,
@@ -56,10 +58,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create(
"00000000000000000000000000".to_string(),
id,
id.clone(),
format!("<@{}> added <@{}> to the group.", user.id, member.id),
)
.publish()
.publish(&channel)
.await
.ok();

View File

@@ -70,6 +70,7 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
.unwrap_or_else(|| "A group.".to_string()),
owner: user.id,
recipients: set.into_iter().collect::<Vec<String>>(),
last_message: None,
};
channel.clone().publish().await?;

View File

@@ -16,9 +16,9 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
owner,
recipients,
..
} = channel
} = &channel
{
if &user.id != &owner {
if &user.id != owner {
// figure out if we want to use perm system here
Err(Error::LabelMe)?
}
@@ -55,10 +55,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create(
"00000000000000000000000000".to_string(),
id,
id.clone(),
format!("<@{}> removed <@{}> from the group.", user.id, member.id),
)
.publish()
.publish(&channel)
.await
.ok();

View File

@@ -7,12 +7,15 @@ use mongodb::bson::doc;
pub async fn req(user: User, target: Ref, msg: Ref) -> Result<()> {
let channel = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &channel).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&channel)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
let message = msg.fetch_message().await?;
let message = msg.fetch_message(&channel).await?;
if message.author != user.id && !perm.get_manage_messages() {
match channel {
Channel::SavedMessages { .. } => unreachable!(),

View File

@@ -19,13 +19,15 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
.map_err(|error| Error::FailedValidation { error })?;
let channel = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &channel).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&channel)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
let message = msg.fetch_message().await?;
let message = msg.fetch_message(&channel).await?;
if message.author != user.id {
Err(Error::CannotEditMessage)?
}

View File

@@ -7,11 +7,14 @@ use rocket_contrib::json::JsonValue;
pub async fn req(user: User, target: Ref, msg: Ref) -> Result<JsonValue> {
let channel = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &channel).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&channel)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
let message = msg.fetch_message().await?;
let message = msg.fetch_message(&channel).await?;
Ok(json!(message))
}

View File

@@ -29,7 +29,10 @@ pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<Json
let target = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &target).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}

View File

@@ -0,0 +1,74 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use futures::StreamExt;
use mongodb::bson::{doc, from_document};
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Options {
ids: Vec<String>
}
#[post("/<target>/messages/stale", data = "<data>")]
pub async fn req(user: User, target: Ref, data: Json<Options>) -> Result<JsonValue> {
if data.ids.len() > 150 {
return Err(Error::LabelMe);
}
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_view() {
Err(Error::LabelMe)?
}
let mut cursor = get_collection("messages")
.find(
doc! {
"_id": {
"$in": &data.ids
},
"channel": target.id()
},
None
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "messages",
})?;
let mut updated = vec![];
let mut found_ids = vec![];
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
let msg = from_document::<Message>(doc)
.map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "message",
})?;
found_ids.push(msg.id.clone());
if msg.edited.is_some() {
updated.push(msg);
}
}
}
let mut deleted = vec![];
for id in &data.ids {
if found_ids.iter().find(|x| *x == id).is_none() {
deleted.push(id);
}
}
Ok(json!({
"updated": updated,
"deleted": deleted
}))
}

View File

@@ -1,7 +1,7 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use mongodb::bson::doc;
use mongodb::{bson::{doc, from_document}, options::FindOneOptions};
use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize};
use ulid::Ulid;
@@ -14,6 +14,8 @@ pub struct Data {
// Maximum length of 36 allows both ULIDs and UUIDs.
#[validate(length(min = 1, max = 36))]
nonce: String,
#[validate(length(min = 1, max = 128))]
attachment: Option<String>,
}
#[post("/<target>/messages", data = "<message>")]
@@ -24,7 +26,10 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
let target = target.fetch_channel().await?;
let perm = permissions::channel::calculate(&user, &target).await;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_send_message() {
Err(Error::LabelMe)?
}
@@ -34,7 +39,9 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
doc! {
"nonce": &message.nonce
},
None,
FindOneOptions::builder()
.projection(doc! { "_id": 1 })
.build()
)
.await
.map_err(|_| Error::DatabaseError {
@@ -46,17 +53,61 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
Err(Error::DuplicateNonce)?
}
let id = Ulid::new().to_string();
let attachments = get_collection("attachments");
let attachment = if let Some(attachment_id) = &message.attachment {
if let Some(doc) = attachments
.find_one(
doc! {
"_id": attachment_id,
"message_id": {
"$exists": false
}
},
None
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "attachment",
})? {
let attachment = from_document::<File>(doc)
.map_err(|_| Error::DatabaseError { operation: "from_document", with: "attachment" })?;
attachments.update_one(
doc! {
"_id": &attachment.id
},
doc! {
"$set": {
"message_id": &id
}
},
None
)
.await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "attachment" })?;
Some(attachment)
} else {
return Err(Error::UnknownAttachment)
}
} else {
None
};
let msg = Message {
id: Ulid::new().to_string(),
id,
channel: target.id().to_string(),
author: user.id,
content: message.content.clone(),
attachment,
nonce: Some(message.nonce.clone()),
edited: None,
};
msg.clone().publish().await?;
msg.clone().publish(&target).await?;
Ok(json!(msg))
}

View File

@@ -9,6 +9,7 @@ mod message_delete;
mod message_edit;
mod message_fetch;
mod message_query;
mod message_query_stale;
mod message_send;
pub fn routes() -> Vec<Route> {
@@ -17,6 +18,7 @@ pub fn routes() -> Vec<Route> {
delete_channel::req,
message_send::req,
message_query::req,
message_query_stale::req,
message_fetch::req,
message_edit::req,
message_delete::req,

View File

@@ -28,6 +28,10 @@ pub async fn req(session: Session, user: Option<User>, data: Json<Data>) -> Resu
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
if data.username == "revolt" {
Err(Error::UsernameTaken)?
}
let col = get_collection("users");
if col
.find_one(

View File

@@ -1,5 +1,5 @@
use crate::util::variables::{
DISABLE_REGISTRATION, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, USE_EMAIL, USE_HCAPTCHA,
DISABLE_REGISTRATION, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY, USE_EMAIL, USE_HCAPTCHA, USE_AUTUMN, AUTUMN_URL
};
use mongodb::bson::doc;
@@ -8,7 +8,7 @@ use rocket_contrib::json::JsonValue;
#[get("/")]
pub async fn root() -> JsonValue {
json!({
"revolt": "0.3.1",
"revolt": "0.3.3-alpha.5",
"features": {
"registration": !*DISABLE_REGISTRATION,
"captcha": {
@@ -16,6 +16,11 @@ pub async fn root() -> JsonValue {
"key": HCAPTCHA_SITEKEY.to_string()
},
"email": *USE_EMAIL,
"invite_only": *INVITE_ONLY,
"autumn": {
"enabled": *USE_AUTUMN,
"url": *AUTUMN_URL
}
},
"ws": *EXTERNAL_WS_URL,
})

View File

@@ -12,11 +12,11 @@ pub async fn req(user: User) -> Result<JsonValue> {
doc! {
"$or": [
{
"type": "DirectMessage",
"channel_type": "DirectMessage",
"active": true
},
{
"type": "Group"
"channel_type": "Group"
}
],
"recipients": user.id

View File

@@ -1,37 +1,20 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use crate::{database::*, notifications::websocket::is_online};
use rocket_contrib::json::JsonValue;
#[get("/<target>")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let mut target = target.fetch_user().await?;
let target = target.fetch_user().await?;
if user.id != target.id {
// Check whether we are allowed to fetch this user.
let perm = permissions::user::calculate(&user, &target.id).await;
if !perm.get_access() {
Err(Error::LabelMe)?
}
let perm = permissions::PermissionCalculator::new(&user)
.with_user(&target)
.for_user_given()
.await?;
// Only return user relationships if the target is the caller.
target.relations = None;
// Add relevant relationship
if let Some(relationships) = &user.relations {
target.relationship = relationships
.iter()
.find(|x| x.id == user.id)
.map(|x| x.status.clone())
.or_else(|| Some(RelationshipStatus::None));
} else {
target.relationship = Some(RelationshipStatus::None);
}
} else {
target.relationship = Some(RelationshipStatus::User);
if !perm.get_access() {
Err(Error::LabelMe)?
}
target.online = Some(is_online(&target.id));
Ok(json!(target))
Ok(json!(target.from(&user).with(perm)))
}

View File

@@ -0,0 +1,41 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use futures::StreamExt;
use mongodb::options::FindOptions;
use mongodb::bson::{Document, doc};
use rocket_contrib::json::JsonValue;
#[get("/<target>/mutual")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let channels = get_collection("channels")
.find(
doc! {
"$or": [
{ "type": "Group" },
],
"$and": [
{ "recipients": &user.id },
{ "recipients": &target.id }
]
},
FindOptions::builder()
.projection(doc! { "_id": 1 })
.build()
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "channels",
})?
.filter_map(async move |s| s.ok())
.collect::<Vec<Document>>()
.await
.into_iter()
.filter_map(|x| x.get_str("_id").ok().map(|x| x.to_string()))
.collect::<Vec<String>>();
Ok(json!({
"channels": channels
}))
}

View File

@@ -1,29 +1,49 @@
use rocket::response::NamedFile;
use std::path::Path;
use md5;
use mongodb::bson::doc;
use mongodb::options::FindOneOptions;
use rocket::response::Redirect;
use urlencoding;
use crate::database::Ref;
use crate::database::*;
use crate::util::result::{Error, Result};
use crate::util::variables::PUBLIC_URL;
#[get("/<target>/avatar")]
pub async fn req(target: Ref) -> Option<NamedFile> {
match target.id.chars().nth(25).unwrap() {
'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => {
NamedFile::open(Path::new("assets/user_red.png")).await.ok()
}
'8' | '9' | 'A' | 'C' | 'B' | 'D' | 'E' | 'F' => {
NamedFile::open(Path::new("assets/user_green.png"))
.await
.ok()
}
'G' | 'H' | 'J' | 'K' | 'M' | 'N' | 'P' | 'Q' => {
NamedFile::open(Path::new("assets/user_blue.png"))
.await
.ok()
}
'R' | 'S' | 'T' | 'V' | 'W' | 'X' | 'Y' | 'Z' => {
NamedFile::open(Path::new("assets/user_yellow.png"))
.await
.ok()
}
_ => unreachable!(),
}
pub async fn req(target: Ref) -> Result<Redirect> {
let doc = get_collection("accounts")
.find_one(
doc! {
"_id": &target.id
},
FindOneOptions::builder()
.projection(doc! { "email": 1 })
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "user",
})?
.ok_or_else(|| Error::UnknownUser)?;
let email = doc
.get_str("email")
.map_err(|_| Error::DatabaseError {
operation: "get_str(email)",
with: "user",
})?
.to_lowercase();
let url = format!(
"https://www.gravatar.com/avatar/{:x}?s=128&d={}",
md5::compute(email),
urlencoding::encode(&format!(
"{}/users/{}/default_avatar",
*PUBLIC_URL, &target.id
))
);
dbg!(&url);
Ok(Redirect::to(url))
}

View File

@@ -0,0 +1,29 @@
use rocket::response::NamedFile;
use std::path::Path;
use crate::database::Ref;
#[get("/<target>/default_avatar")]
pub async fn req(target: Ref) -> Option<NamedFile> {
match target.id.chars().nth(25).unwrap() {
'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => {
NamedFile::open(Path::new("assets/user_red.png")).await.ok()
}
'8' | '9' | 'A' | 'C' | 'B' | 'D' | 'E' | 'F' => {
NamedFile::open(Path::new("assets/user_green.png"))
.await
.ok()
}
'G' | 'H' | 'J' | 'K' | 'M' | 'N' | 'P' | 'Q' => {
NamedFile::open(Path::new("assets/user_blue.png"))
.await
.ok()
}
'R' | 'S' | 'T' | 'V' | 'W' | 'X' | 'Y' | 'Z' => {
NamedFile::open(Path::new("assets/user_yellow.png"))
.await
.ok()
}
_ => unreachable!(),
}
}

View File

@@ -6,7 +6,9 @@ mod fetch_dms;
mod fetch_relationship;
mod fetch_relationships;
mod fetch_user;
mod find_mutual;
mod get_avatar;
mod get_default_avatar;
mod open_dm;
mod remove_friend;
mod unblock_user;
@@ -15,11 +17,13 @@ pub fn routes() -> Vec<Route> {
routes![
// User Information
fetch_user::req,
get_default_avatar::req,
get_avatar::req,
// Direct Messaging
fetch_dms::req,
open_dm::req,
// Relationships
find_mutual::req,
fetch_relationships::req,
fetch_relationship::req,
add_friend::req,

View File

@@ -9,12 +9,12 @@ use ulid::Ulid;
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let query = if user.id == target.id {
doc! {
"type": "SavedMessages",
"channel_type": "SavedMessages",
"user": &user.id
}
} else {
doc! {
"type": "DirectMessage",
"channel_type": "DirectMessage",
"recipients": {
"$all": [ &user.id, &target.id ]
}
@@ -40,6 +40,7 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
id,
active: false,
recipients: vec![user.id, target.id],
last_message: None,
}
};

View File

@@ -1,45 +0,0 @@
use crate::util::variables::{HCAPTCHA_KEY, USE_HCAPTCHA};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
struct CaptchaResponse {
success: bool,
}
pub async fn verify(user_token: &Option<String>) -> Result<(), String> {
if *USE_HCAPTCHA {
if let Some(token) = user_token {
let mut map = HashMap::new();
map.insert("secret", HCAPTCHA_KEY.to_string());
map.insert("response", token.to_string());
let client = Client::new();
if let Ok(response) = client
.post("https://hcaptcha.com/siteverify")
.form(&map)
.send()
.await
{
let result: CaptchaResponse = response
.json()
.await
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
if result.success {
Ok(())
} else {
Err("Unsuccessful captcha verification".to_string())
}
} else {
Err("Failed to verify with hCaptcha".to_string())
}
} else {
Err("Missing hCaptcha token!".to_string())
}
} else {
Ok(())
}
}

View File

@@ -1,96 +0,0 @@
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

@@ -1,19 +1,2 @@
use rand::{distributions::Alphanumeric, Rng};
use std::collections::HashSet;
use std::iter::FromIterator;
pub mod captcha;
pub mod email;
pub mod result;
pub mod variables;
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
HashSet::from_iter(data.iter().cloned())
}
pub fn gen_token(l: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(l)
.collect::<String>()
}

View File

@@ -34,6 +34,10 @@ pub enum Error {
NotFriends,
// ? Channel related errors.
#[snafu(display("This channel does not exist!"))]
UnknownChannel,
#[snafu(display("Attachment does not exist!"))]
UnknownAttachment,
#[snafu(display("Cannot edit someone else's message."))]
CannotEditMessage,
#[snafu(display("Cannot remove yourself from a group, use delete channel instead."))]
@@ -81,6 +85,8 @@ impl<'r> Responder<'r, 'static> for Error {
Error::BlockedByOther => Status::Forbidden,
Error::NotFriends => Status::Forbidden,
Error::UnknownChannel => Status::NotFound,
Error::UnknownAttachment => Status::BadRequest,
Error::CannotEditMessage => Status::Forbidden,
Error::CannotRemoveYourself => Status::BadRequest,
Error::GroupTooLarge { .. } => Status::Forbidden,

View File

@@ -7,19 +7,24 @@ lazy_static! {
// Application Settings
pub static ref MONGO_URI: String =
env::var("REVOLT_MONGO_URI").expect("Missing REVOLT_MONGO_URI environment variable.");
pub static ref WS_HOST: String =
env::var("REVOLT_WS_HOST").unwrap_or_else(|_| "0.0.0.0:9000".to_string());
pub static ref PUBLIC_URL: String =
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable.");
pub static ref APP_URL: String =
env::var("REVOLT_APP_URL").unwrap_or_else(|_| "https://app.revolt.chat".to_string());
pub static ref EXTERNAL_WS_URL: String =
env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable.");
pub static ref AUTUMN_URL: String =
env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string());
pub static ref HCAPTCHA_KEY: String =
env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string());
pub static ref HCAPTCHA_SITEKEY: String =
env::var("REVOLT_HCAPTCHA_SITEKEY").unwrap_or_else(|_| "10000000-ffff-ffff-ffff-000000000001".to_string());
pub static ref WS_HOST: String =
env::var("REVOLT_WS_HOST").unwrap_or_else(|_| "0.0.0.0:9000".to_string());
// Application Flags
pub static ref DISABLE_REGISTRATION: bool = env::var("REVOLT_DISABLE_REGISTRATION").map_or(false, |v| v == "*1");
pub static ref DISABLE_REGISTRATION: bool = env::var("REVOLT_DISABLE_REGISTRATION").map_or(false, |v| v == "1");
pub static ref INVITE_ONLY: bool = env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1");
pub static ref USE_EMAIL: bool = env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
env::var("REVOLT_SMTP_HOST").is_ok()
&& env::var("REVOLT_SMTP_USERNAME").is_ok()
@@ -28,6 +33,8 @@ lazy_static! {
|v| v == *"1"
);
pub static ref USE_HCAPTCHA: bool = env::var("REVOLT_HCAPTCHA_KEY").is_ok();
pub static ref USE_PROMETHEUS: bool = env::var("REVOLT_ENABLE_PROMETHEUS").map_or(false, |v| v == "1");
pub static ref USE_AUTUMN: bool = env::var("AUTUMN_PUBLIC_URL").is_ok();
// SMTP Settings
pub static ref SMTP_HOST: String =