forked from jmug/stoatchat
Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81111c5937 | ||
|
|
49044d7796 | ||
|
|
f44180a980 | ||
|
|
8ee867eec7 | ||
|
|
dde4224deb | ||
|
|
088490dfc3 | ||
|
|
7e7eb34f65 | ||
|
|
74b4238f04 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -1907,7 +1907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "revolt"
|
||||
version = "0.2.7"
|
||||
version = "0.2.9"
|
||||
dependencies = [
|
||||
"bcrypt",
|
||||
"bitfield",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "revolt"
|
||||
version = "0.2.7"
|
||||
version = "0.2.9"
|
||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::get_collection;
|
||||
|
||||
use lru::LruCache;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct LastMessage {
|
||||
@@ -40,6 +41,40 @@ pub struct Channel {
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub fn serialise(self) -> JsonValue {
|
||||
match self.channel_type {
|
||||
0 => json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"last_message": self.last_message,
|
||||
"recipients": self.recipients,
|
||||
}),
|
||||
1 => {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"last_message": self.last_message,
|
||||
"recipients": self.recipients,
|
||||
"name": self.name,
|
||||
"owner": self.owner,
|
||||
"description": self.description,
|
||||
})
|
||||
}
|
||||
2 => {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"type": self.channel_type,
|
||||
"guild": self.guild,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
})
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
@@ -77,19 +112,19 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String> {
|
||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut channels = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for gid in ids {
|
||||
let existing = cache.get(gid);
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(channel) = existing {
|
||||
channels.push((*channel).clone());
|
||||
} else {
|
||||
missing.push(gid);
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -98,7 +133,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(Some(channels));
|
||||
return Ok(channels);
|
||||
}
|
||||
|
||||
let col = get_collection("channels");
|
||||
@@ -117,7 +152,7 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Option<Vec<Channel>>, String>
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(channels))
|
||||
Ok(channels)
|
||||
} else {
|
||||
Err("Failed to fetch channel from database.".to_string())
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use super::get_collection;
|
||||
use super::channel::fetch_channels;
|
||||
|
||||
use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -42,13 +44,39 @@ pub struct Guild {
|
||||
pub description: String,
|
||||
pub owner: String,
|
||||
|
||||
// ? FIXME: ADD: pub channels: Vec<Channel>,
|
||||
pub channels: Vec<String>,
|
||||
pub invites: Vec<Invite>,
|
||||
pub bans: Vec<Ban>,
|
||||
|
||||
pub default_permissions: u32,
|
||||
}
|
||||
|
||||
impl Guild {
|
||||
pub fn serialise(self) -> JsonValue {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"description": self.description,
|
||||
"owner": self.owner
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
||||
super::channel::fetch_channels(&self.channels)
|
||||
}
|
||||
|
||||
pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
||||
let channels = self.fetch_channels()?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
|
||||
let mut value = self.serialise();
|
||||
value.as_object_mut().unwrap().insert("channels".to_string(), channels);
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Hash, Eq, PartialEq)]
|
||||
pub struct MemberKey(pub String, pub String);
|
||||
|
||||
@@ -91,6 +119,77 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut guilds = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(guild) = existing {
|
||||
guilds.push((*guild).clone());
|
||||
} else {
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(guilds);
|
||||
}
|
||||
|
||||
let col = get_collection("guilds");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||
cache.put(guild.id.clone(), guild.clone());
|
||||
guilds.push(guild);
|
||||
} else {
|
||||
return Err("Failed to deserialize guild!".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to fetch guild.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(guilds)
|
||||
} else {
|
||||
Err("Failed to fetch channel from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
||||
let guilds = fetch_guilds(&ids)?;
|
||||
let cids: Vec<String> = guilds
|
||||
.iter()
|
||||
.flat_map(|x| x.channels.clone())
|
||||
.collect();
|
||||
|
||||
let channels = fetch_channels(&cids)?;
|
||||
Ok(guilds
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let id = x.id.clone();
|
||||
let mut obj = x.serialise();
|
||||
obj.as_object_mut().unwrap().insert(
|
||||
"channels".to_string(),
|
||||
channels.iter()
|
||||
.filter(|x| x.guild.is_some() && x.guild.as_ref().unwrap() == &id)
|
||||
.map(|x| x.clone().serialise())
|
||||
.collect()
|
||||
);
|
||||
obj
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::super::get_collection;
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use mongodb::bson::{Bson, from_bson, doc};
|
||||
use mongodb::options::FindOptions;
|
||||
use log::info;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -10,7 +11,7 @@ struct MigrationInfo {
|
||||
revision: i32
|
||||
}
|
||||
|
||||
pub const LATEST_REVISION: i32 = 1;
|
||||
pub const LATEST_REVISION: i32 = 2;
|
||||
|
||||
pub fn migrate_database() {
|
||||
let migrations = get_collection("migrations");
|
||||
@@ -48,6 +49,60 @@ pub 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 guilds = col.find(
|
||||
None,
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build()
|
||||
)
|
||||
.expect("Failed to fetch guilds.");
|
||||
|
||||
let result = get_collection("channels").find(
|
||||
doc! {
|
||||
"type": 2
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1, "guild": 1 })
|
||||
.build()
|
||||
).expect("Failed to fetch channels.");
|
||||
|
||||
let mut channels = vec![];
|
||||
for doc in result {
|
||||
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 ));
|
||||
}
|
||||
|
||||
for doc in guilds {
|
||||
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
|
||||
).expect("Failed to update guild.");
|
||||
}
|
||||
}
|
||||
|
||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||
LATEST_REVISION
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::sync::{Client, Collection, Database};
|
||||
use std::env;
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use super::get_collection;
|
||||
use super::guild::{serialise_guilds_with_channels};
|
||||
use super::channel::{fetch_channels};
|
||||
|
||||
use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson, DateTime};
|
||||
use mongodb::options::FindOptions;
|
||||
use rocket::http::{RawStr, Status};
|
||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use rocket::Outcome;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -36,6 +40,111 @@ pub struct User {
|
||||
pub relations: Option<Vec<UserRelationship>>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn serialise(self, relationship: i32) -> JsonValue {
|
||||
if relationship == super::Relationship::SELF as i32 {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"email": self.email,
|
||||
"verified": self.email_verification.verified,
|
||||
})
|
||||
} else {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"username": self.username,
|
||||
"display_name": self.display_name,
|
||||
"relationship": relationship
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_guilds(&self) -> Result<Vec<String>, String> {
|
||||
let members = get_collection("members")
|
||||
.find(
|
||||
doc! {
|
||||
"_id.user": &self.id
|
||||
},
|
||||
None
|
||||
).map_err(|_| "Failed to fetch members.")?;
|
||||
|
||||
Ok(members.into_iter()
|
||||
.filter_map(|x| match x {
|
||||
Ok(doc) => {
|
||||
match doc.get_document("_id") {
|
||||
Ok(id) => {
|
||||
match id.get_str("guild") {
|
||||
Ok(value) => Some(value.to_string()),
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
Err(_) => None
|
||||
}
|
||||
}
|
||||
Err(_) => None
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn find_dms(&self) -> Result<Vec<String>, String> {
|
||||
let channels = get_collection("channels")
|
||||
.find(
|
||||
doc! {
|
||||
"recipients": &self.id
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build()
|
||||
).map_err(|_| "Failed to fetch channel ids.")?;
|
||||
|
||||
Ok(channels.into_iter()
|
||||
.filter_map(|x| x.ok())
|
||||
.filter_map(|x| {
|
||||
match x.get_str("_id") {
|
||||
Ok(value) => Some(value.to_string()),
|
||||
Err(_) => None
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn create_payload(self) -> Result<JsonValue, String> {
|
||||
let v = vec![];
|
||||
let relations = self.relations.as_ref().unwrap_or(&v);
|
||||
|
||||
let users: Vec<JsonValue> = fetch_users(
|
||||
&relations
|
||||
.iter()
|
||||
.map(|x| x.id.clone())
|
||||
.collect()
|
||||
)?
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let id = x.id.clone();
|
||||
x.serialise(
|
||||
relations.iter()
|
||||
.find(|y| y.id == id)
|
||||
.unwrap()
|
||||
.status as i32
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms()?)?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
|
||||
Ok(json!({
|
||||
"users": users,
|
||||
"channels": channels,
|
||||
"guilds": serialise_guilds_with_channels(&self.find_guilds()?)?,
|
||||
"user": self.serialise(super::Relationship::SELF as i32)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref CACHE: Arc<Mutex<LruCache<String, User>>> =
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
@@ -73,6 +182,52 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut users = vec![];
|
||||
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
for id in ids {
|
||||
let existing = cache.get(id);
|
||||
|
||||
if let Some(user) = existing {
|
||||
users.push((*user).clone());
|
||||
} else {
|
||||
missing.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to lock cache.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if missing.len() == 0 {
|
||||
return Ok(users);
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||
cache.put(user.id.clone(), user.clone());
|
||||
users.push(user);
|
||||
} else {
|
||||
return Err("Failed to deserialize user!".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Failed to fetch user.".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(users)
|
||||
} else {
|
||||
Err("Failed to fetch user from database.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AuthError {
|
||||
Failed,
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Handler for Server {
|
||||
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
||||
StateResult::Success(user_id) => {
|
||||
let user = crate::database::user::fetch_user(&user_id).unwrap().unwrap();
|
||||
self.user_id = Some(user_id);
|
||||
|
||||
self.sender.send(
|
||||
json!({
|
||||
@@ -46,14 +47,10 @@ impl Handler for Server {
|
||||
.to_string(),
|
||||
)?;
|
||||
|
||||
self.user_id = Some(user_id);
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "ready",
|
||||
"data": {
|
||||
// ! FIXME: rewrite
|
||||
"user": user,
|
||||
}
|
||||
"data": user.create_payload()
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::Response;
|
||||
use crate::database;
|
||||
use crate::email;
|
||||
use crate::util::gen_token;
|
||||
use crate::util::captcha;
|
||||
|
||||
use bcrypt::{hash, verify};
|
||||
use chrono::prelude::*;
|
||||
@@ -17,6 +18,7 @@ pub struct Create {
|
||||
username: String,
|
||||
password: String,
|
||||
email: String,
|
||||
captcha: Option<String>,
|
||||
}
|
||||
|
||||
/// create a new Revolt account
|
||||
@@ -28,6 +30,18 @@ pub struct Create {
|
||||
/// (3) add user and send email verification
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create(info: Json<Create>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
return Response::BadRequest(
|
||||
json!({ "error": error })
|
||||
);
|
||||
}
|
||||
|
||||
if true {
|
||||
return Response::BadRequest(
|
||||
json!({ "error": "Registration disabled." })
|
||||
);
|
||||
}
|
||||
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if info.username.len() < 2 || info.username.len() > 32 {
|
||||
@@ -150,6 +164,7 @@ pub fn verify_email(code: String) -> Response {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Resend {
|
||||
email: String,
|
||||
captcha: Option<String>,
|
||||
}
|
||||
|
||||
/// resend a verification email
|
||||
@@ -158,6 +173,12 @@ pub struct Resend {
|
||||
/// (3) resend the email
|
||||
#[post("/resend", data = "<info>")]
|
||||
pub fn resend_email(info: Json<Resend>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
return Response::BadRequest(
|
||||
json!({ "error": error })
|
||||
);
|
||||
}
|
||||
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Some(u) = col
|
||||
@@ -218,6 +239,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
||||
pub struct Login {
|
||||
email: String,
|
||||
password: String,
|
||||
captcha: Option<String>,
|
||||
}
|
||||
|
||||
/// login to a Revolt account
|
||||
@@ -226,6 +248,12 @@ pub struct Login {
|
||||
/// (3) return access token
|
||||
#[post("/login", data = "<info>")]
|
||||
pub fn login(info: Json<Login>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
return Response::BadRequest(
|
||||
json!({ "error": error })
|
||||
);
|
||||
}
|
||||
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Some(u) = col
|
||||
|
||||
@@ -129,51 +129,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
#[get("/<target>")]
|
||||
pub fn channel(user: User, target: Channel) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
match target.channel_type {
|
||||
0 => Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"last_message": target.last_message,
|
||||
"recipients": target.recipients,
|
||||
}))),
|
||||
1 => {
|
||||
/*if let Some(info) = target.fetch_data(doc! {
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
"owner": 1,
|
||||
}) {*/
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"last_message": target.last_message,
|
||||
"recipients": target.recipients,
|
||||
"name": target.name,
|
||||
"owner": target.owner,
|
||||
"description": target.description,
|
||||
})))
|
||||
/*} else {
|
||||
None
|
||||
}*/
|
||||
}
|
||||
2 => {
|
||||
/*if let Some(info) = target.fetch_data(doc! {
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
}) {*/
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"type": target.channel_type,
|
||||
"guild": target.guild,
|
||||
"name": target.name,
|
||||
"description": target.description,
|
||||
})))
|
||||
/*} else {
|
||||
None
|
||||
}*/
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Some(Response::Success(target.serialise()))
|
||||
}
|
||||
|
||||
/// [groups] add user to channel
|
||||
@@ -447,7 +403,8 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
"$pull": {
|
||||
"invites": {
|
||||
"channel": &target.id
|
||||
}
|
||||
},
|
||||
"channels": &target.id
|
||||
}
|
||||
},
|
||||
None,
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::channel::ChannelType;
|
||||
use super::Response;
|
||||
use crate::database::guild::{fetch_member as get_member, get_invite, Guild, MemberKey};
|
||||
use crate::database::{
|
||||
self, channel::fetch_channel, channel::Channel, Permission, PermissionCalculator, user::User
|
||||
self, channel::fetch_channel, guild::serialise_guilds_with_channels, channel::Channel, Permission, PermissionCalculator, user::User
|
||||
};
|
||||
use crate::notifications::{
|
||||
self,
|
||||
@@ -10,13 +10,14 @@ use crate::notifications::{
|
||||
};
|
||||
use crate::util::gen_token;
|
||||
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use mongodb::bson::{doc, Bson};
|
||||
use mongodb::options::{FindOneOptions, FindOptions};
|
||||
use rocket::request::Form;
|
||||
use rocket_contrib::json::Json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ulid::Ulid;
|
||||
|
||||
// ! FIXME: GET RID OF THIS
|
||||
macro_rules! with_permissions {
|
||||
($user: expr, $target: expr) => {{
|
||||
let permissions = PermissionCalculator::new($user.clone())
|
||||
@@ -35,53 +36,9 @@ macro_rules! with_permissions {
|
||||
/// fetch your guilds
|
||||
#[get("/@me")]
|
||||
pub fn my_guilds(user: User) -> Response {
|
||||
if let Ok(result) = database::get_collection("members").find(
|
||||
doc! {
|
||||
"_id.user": &user.id
|
||||
},
|
||||
None,
|
||||
) {
|
||||
let mut guilds = vec![];
|
||||
for item in result {
|
||||
if let Ok(entry) = item {
|
||||
guilds.push(Bson::String(
|
||||
entry
|
||||
.get_document("_id")
|
||||
.unwrap()
|
||||
.get_str("guild")
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(result) = database::get_collection("guilds").find(
|
||||
doc! {
|
||||
"_id": {
|
||||
"$in": guilds
|
||||
}
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! {
|
||||
"_id": 1,
|
||||
"name": 1,
|
||||
"description": 1,
|
||||
"owner": 1,
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
let mut parsed = vec![];
|
||||
for item in result {
|
||||
let doc = item.unwrap();
|
||||
parsed.push(json!({
|
||||
"id": doc.get_str("_id").unwrap(),
|
||||
"name": doc.get_str("name").unwrap(),
|
||||
"description": doc.get_str("description").unwrap(),
|
||||
"owner": doc.get_str("owner").unwrap(),
|
||||
}));
|
||||
}
|
||||
|
||||
Response::Success(json!(parsed))
|
||||
if let Ok(gids) = user.find_guilds() {
|
||||
if let Ok(data) = serialise_guilds_with_channels(&gids) {
|
||||
Response::Success(json!(data))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
||||
}
|
||||
@@ -94,40 +51,11 @@ pub fn my_guilds(user: User) -> Response {
|
||||
#[get("/<target>")]
|
||||
pub fn guild(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
let col = database::get_collection("channels");
|
||||
match col.find(
|
||||
doc! {
|
||||
"type": 2,
|
||||
"guild": &target.id,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
Ok(results) => {
|
||||
let mut channels = vec![];
|
||||
for item in results {
|
||||
if let Ok(entry) = item {
|
||||
if let Ok(channel) = from_bson(Bson::Document(entry)) as Result<Channel, _> {
|
||||
channels.push(json!({
|
||||
"id": channel.id,
|
||||
"name": channel.name,
|
||||
"description": channel.description,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(Response::Success(json!({
|
||||
"id": target.id,
|
||||
"name": target.name,
|
||||
"description": target.description,
|
||||
"owner": target.owner,
|
||||
"channels": channels,
|
||||
})))
|
||||
}
|
||||
Err(_) => Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to fetch channels." }),
|
||||
)),
|
||||
|
||||
if let Ok(result) = target.seralise_with_channels() {
|
||||
Some(Response::Success(result))
|
||||
} else {
|
||||
Some(Response::InternalServerError(json!({ "error": "Failed to fetch channels!" })))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,20 +233,39 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_channel_create(ChannelCreate {
|
||||
id: target.id.clone(),
|
||||
channel: id.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
}),
|
||||
);
|
||||
if database::get_collection("guilds")
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": &target.id
|
||||
},
|
||||
doc! {
|
||||
"$addToSet": {
|
||||
"channels": &id
|
||||
}
|
||||
},
|
||||
None
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_channel_create(ChannelCreate {
|
||||
id: target.id.clone(),
|
||||
channel: id.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Success(json!({ "id": &id })))
|
||||
Some(Response::Success(json!({ "id": &id })))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Couldn't save channel list." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::BadRequest(
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Couldn't create channel." }),
|
||||
))
|
||||
}
|
||||
@@ -590,6 +537,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"owner": &user.id,
|
||||
"channels": [ channel_id.clone() ],
|
||||
"invites": [],
|
||||
"bans": [],
|
||||
"default_permissions": 51,
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
use super::Response;
|
||||
|
||||
use mongodb::bson::doc;
|
||||
use std::env;
|
||||
|
||||
/// root
|
||||
#[get("/")]
|
||||
pub fn root() -> Response {
|
||||
Response::Success(json!({
|
||||
"revolt": "0.2.7",
|
||||
"revolt": "0.2.9",
|
||||
"version": {
|
||||
"major": 0,
|
||||
"minor": 2,
|
||||
"patch": 7
|
||||
"patch": 9
|
||||
},
|
||||
"features": {
|
||||
"captcha": env::var("HCAPTCHA_KEY").is_ok()
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -15,29 +15,18 @@ use ulid::Ulid;
|
||||
/// retrieve your user information
|
||||
#[get("/@me")]
|
||||
pub fn me(user: User) -> Response {
|
||||
Response::Success(json!({
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"display_name": user.display_name,
|
||||
"email": user.email,
|
||||
"verified": user.email_verification.verified,
|
||||
}))
|
||||
Response::Success(
|
||||
user.serialise(Relationship::SELF as i32)
|
||||
)
|
||||
}
|
||||
|
||||
/// retrieve another user's information
|
||||
#[get("/<target>")]
|
||||
pub fn user(user: User, target: User) -> Response {
|
||||
Response::Success(json!({
|
||||
"id": target.id,
|
||||
"username": target.username,
|
||||
"display_name": target.display_name,
|
||||
"relationship": get_relationship(&user, &target) as i32,
|
||||
"mutual": {
|
||||
"guilds": mutual::find_mutual_guilds(&user.id, &target.id),
|
||||
"friends": mutual::find_mutual_friends(&user.id, &target.id),
|
||||
"groups": mutual::find_mutual_groups(&user.id, &target.id),
|
||||
}
|
||||
}))
|
||||
let relationship = get_relationship(&user, &target) as i32;
|
||||
Response::Success(
|
||||
user.serialise(relationship)
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
|
||||
42
src/util/captcha.rs
Normal file
42
src/util/captcha.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use serde::{Serialize, Deserialize};
|
||||
use reqwest::blocking::Client;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CaptchaResponse {
|
||||
success: bool
|
||||
}
|
||||
|
||||
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||
if let Ok(key) = env::var("HCAPTCHA_KEY") {
|
||||
if let Some(token) = user_token {
|
||||
let mut map = HashMap::new();
|
||||
map.insert("secret", key);
|
||||
map.insert("response", token.to_string());
|
||||
|
||||
let client = Client::new();
|
||||
if let Ok(response) = client
|
||||
.post("https://hcaptcha.com/siteverify")
|
||||
.form(&map)
|
||||
.send()
|
||||
{
|
||||
let result: CaptchaResponse = response
|
||||
.json()
|
||||
.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(())
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ use hashbrown::HashSet;
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
use std::iter::FromIterator;
|
||||
|
||||
pub mod captcha;
|
||||
|
||||
pub fn vec_to_set<T: Clone + Eq + std::hash::Hash>(data: &[T]) -> HashSet<T> {
|
||||
HashSet::from_iter(data.iter().cloned())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user