Compare commits

...

16 Commits
0.3.1 ... 0.3.2

Author SHA1 Message Date
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
32 changed files with 823 additions and 473 deletions

432
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.2"
authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018"
@@ -12,13 +12,13 @@ many-to-many = "0.1.2"
impl_ops = "0.1.1"
ctrlc = { version = "3.0", features = ["termination"] }
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
rauth = { git = "https://gitlab.insrt.uk/insert/rauth" }
rauth = { git = "https://gitlab.insrt.uk/insert/rauth", rev = "8f3ea627" }
async-std = { version = "1.8.0", features = ["tokio02", "attributes"] }
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_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"

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

@@ -35,30 +35,81 @@ impl Message {
}
}
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

@@ -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,35 @@ 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;
}
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_all() {
self.relations = None;
}
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,99 @@ 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]> {
/*pub async fn calculate(user: &User, target: &Channel) -> Result<u32> {
match target {
Channel::SavedMessages { user: owner, .. } => {
if &user.id == owner {
ChannelPermissions([ChannelPermission::View
Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageMessages])
+ ChannelPermission::ManageMessages)
} else {
ChannelPermissions([0])
Ok(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;
let perms = super::user::get(&user, recipient).await?;
if perms.get_send_message() {
return ChannelPermissions([
ChannelPermission::View + ChannelPermission::SendMessage
]);
return Ok(ChannelPermission::View + ChannelPermission::SendMessage);
}
return ChannelPermissions([ChannelPermission::View as u32]);
return Ok(ChannelPermission::View as u32);
}
}
ChannelPermissions([0])
Ok(0)
}
Channel::Group { recipients, .. } => {
if recipients.iter().find(|x| *x == &user.id).is_some() {
ChannelPermissions([ChannelPermission::View + ChannelPermission::SendMessage])
Ok(ChannelPermission::View + ChannelPermission::SendMessage)
} else {
ChannelPermissions([0])
Ok(0)
}
}
}
}
pub async fn get(user: &User, target: &Channel) -> Result<ChannelPermissions<[u32; 1]>> {
Ok(ChannelPermissions([calculate(&user, &target).await?]))
}*/
impl<'a> PermissionCalculator<'a> {
pub async fn calculate_channel(self) -> Result<u32> {
let channel = if let Some(channel) = self.channel {
channel
} else {
unreachable!()
};
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?;
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,29 @@ use std::ops;
#[repr(u32)]
pub enum UserPermission {
Access = 1,
SendMessage = 2,
Invite = 4,
ViewProfile = 2,
SendMessage = 4,
Invite = 8,
ViewAll = 2147483648,
}
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;
pub get_view_all, _: 0;
}
impl_op_ex!(+ |a: &UserPermission, b: &UserPermission| -> u32 { *a as u32 | *b as u32 });
impl_op_ex!(-|a: &UserPermission, b: &UserPermission| -> u32 { *a as u32 & !(*b as u32) });
impl_op_ex!(-|a: &u32, b: &UserPermission| -> u32 { *a & !(*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 +47,60 @@ 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 - UserPermission::ViewAll),
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! {
"type": "Group",
"$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,13 @@ pub mod notifications;
pub mod routes;
pub mod util;
use chrono::Duration;
use futures::join;
use log::info;
use rauth;
use rauth::auth::Auth;
use rauth::options::{EmailVerification, Options, SMTP};
use rocket_cors::AllowedOrigins;
use util::variables::{PUBLIC_URL, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD, SMTP_USERNAME, USE_EMAIL};
#[async_std::main]
async fn main() {
@@ -55,10 +58,32 @@ async fn launch_web() {
.to_cors()
.expect("Failed to create CORS.");
let auth = rauth::auth::Auth::new(database::get_collection("accounts"));
let auth = Auth::new(
database::get_collection("accounts"),
Options::new()
.base_url(format!("{}/auth", *PUBLIC_URL))
.email_verification(if *USE_EMAIL {
EmailVerification::Enabled {
success_redirect_uri: format!("{}/welcome", *PUBLIC_URL),
verification_expiry: Duration::days(1),
verification_ratelimit: Duration::minutes(1),
routes::mount(rauth::routes::mount(rocket::ignite(), "/auth", auth))
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
}),
);
routes::mount(rocket::ignite())
.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,61 @@ 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());
}
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

@@ -24,7 +24,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)?
}
@@ -56,7 +59,7 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
edited: None,
};
msg.clone().publish().await?;
msg.clone().publish(&target).await?;
Ok(json!(msg))
}

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

@@ -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,24 @@
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

@@ -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

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