Compare commits
1 commit
main
...
wip/federa
Author | SHA1 | Date | |
---|---|---|---|
4972aa37c4 |
85 changed files with 1604 additions and 4070 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -21,3 +21,4 @@ Cargo.lock
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
#.idea/
|
#.idea/
|
||||||
/config.toml
|
/config.toml
|
||||||
|
/key.pem
|
||||||
|
|
|
@ -1,13 +1,14 @@
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
branch: main
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: build-x86_64
|
- name: build-x86_64
|
||||||
image: rust:1.88-bookworm
|
image: rust:bookworm
|
||||||
commands:
|
commands:
|
||||||
- cargo build --release
|
- cargo build --release
|
||||||
when:
|
|
||||||
- event: push
|
|
||||||
|
|
||||||
- name: build-arm64
|
- name: build-arm64
|
||||||
image: rust:1.88-bookworm
|
image: rust:bookworm
|
||||||
commands:
|
commands:
|
||||||
- dpkg --add-architecture arm64
|
- dpkg --add-architecture arm64
|
||||||
- apt-get update -y && apt-get install -y crossbuild-essential-arm64 libssl-dev:arm64
|
- apt-get update -y && apt-get install -y crossbuild-essential-arm64 libssl-dev:arm64
|
||||||
|
@ -17,9 +18,6 @@ steps:
|
||||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
||||||
PKG_CONFIG_ALLOW_CROSS: 1
|
PKG_CONFIG_ALLOW_CROSS: 1
|
||||||
PKG_CONFIG_PATH: /usr/aarch64-linux-gnu/lib/pkgconfig
|
PKG_CONFIG_PATH: /usr/aarch64-linux-gnu/lib/pkgconfig
|
||||||
when:
|
|
||||||
- event: push
|
|
||||||
|
|
||||||
- name: container-build-and-publish
|
- name: container-build-and-publish
|
||||||
image: docker
|
image: docker
|
||||||
commands:
|
commands:
|
||||||
|
@ -30,20 +28,3 @@ steps:
|
||||||
from_secret: docker_password
|
from_secret: docker_password
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/podman/podman.sock:/var/run/docker.sock
|
- /var/run/podman/podman.sock:/var/run/docker.sock
|
||||||
when:
|
|
||||||
- branch: main
|
|
||||||
event: push
|
|
||||||
|
|
||||||
- name: container-build-and-publish-staging
|
|
||||||
image: docker
|
|
||||||
commands:
|
|
||||||
- docker login --username radical --password $PASSWORD git.gorb.app
|
|
||||||
- docker buildx build --platform linux/amd64,linux/arm64 --rm --push -t git.gorb.app/gorb/backend:staging .
|
|
||||||
environment:
|
|
||||||
PASSWORD:
|
|
||||||
from_secret: docker_password
|
|
||||||
volumes:
|
|
||||||
- /var/run/podman/podman.sock:/var/run/docker.sock
|
|
||||||
when:
|
|
||||||
- branch: staging
|
|
||||||
event: push
|
|
||||||
|
|
|
@ -4,7 +4,7 @@ when:
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: build-docs
|
- name: build-docs
|
||||||
image: rust:1.88-bookworm
|
image: rust:bookworm
|
||||||
commands:
|
commands:
|
||||||
- cargo doc --release --no-deps
|
- cargo doc --release --no-deps
|
||||||
|
|
||||||
|
|
69
Cargo.toml
69
Cargo.toml
|
@ -15,49 +15,38 @@ strip = "debuginfo"
|
||||||
codegen-units = 512
|
codegen-units = 512
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
thiserror = "2.0.12"
|
actix-cors = "0.7.1"
|
||||||
|
actix-web = "4.11"
|
||||||
# CLI
|
|
||||||
clap = { version = "4.5", features = ["derive"] }
|
|
||||||
log = "0.4"
|
|
||||||
|
|
||||||
# async
|
|
||||||
tokio = { version = "1.46", features = ["full"] }
|
|
||||||
futures-util = "0.3.31"
|
|
||||||
|
|
||||||
# Data (de)serialization
|
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
serde_json = "1.0"
|
|
||||||
toml = "0.9"
|
|
||||||
bytes = "1.10.1"
|
|
||||||
|
|
||||||
# File Storage
|
|
||||||
bindet = "0.3.2"
|
|
||||||
bunny-api-tokio = { version = "0.4", features = ["edge_storage"], default-features = false }
|
|
||||||
|
|
||||||
# Web Server
|
|
||||||
axum = { version = "0.8.4", features = ["multipart", "ws"] }
|
|
||||||
axum-extra = { version = "0.10.1", features = ["cookie", "typed-header"] }
|
|
||||||
tower-http = { version = "0.6.6", features = ["cors"] }
|
|
||||||
#socketioxide = { version = "0.17.2", features = ["state"] }
|
|
||||||
url = { version = "2.5", features = ["serde"] }
|
|
||||||
time = "0.3.41"
|
|
||||||
|
|
||||||
# Database
|
|
||||||
uuid = { version = "1.17", features = ["serde", "v7"] }
|
|
||||||
redis = { version = "0.32", features= ["tokio-comp"] }
|
|
||||||
deadpool = "0.12"
|
|
||||||
diesel = { version = "2.2", features = ["uuid", "chrono"], default-features = false }
|
|
||||||
diesel-async = { version = "0.6", features = ["deadpool", "postgres", "async-connection-wrapper"] }
|
|
||||||
diesel_migrations = { version = "2.2.0", features = ["postgres"] }
|
|
||||||
|
|
||||||
# Authentication
|
|
||||||
argon2 = { version = "0.5.3", features = ["std"] }
|
argon2 = { version = "0.5.3", features = ["std"] }
|
||||||
|
clap = { version = "4.5", features = ["derive"] }
|
||||||
|
futures = "0.3"
|
||||||
getrandom = "0.3"
|
getrandom = "0.3"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
|
log = "0.4"
|
||||||
regex = "1.11"
|
regex = "1.11"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
||||||
|
simple_logger = "5.0.0"
|
||||||
|
redis = { version = "0.31.0", features= ["tokio-comp"] }
|
||||||
|
tokio-tungstenite = { version = "0.26", features = ["native-tls", "url"] }
|
||||||
|
toml = "0.8"
|
||||||
|
url = { version = "2.5", features = ["serde"] }
|
||||||
|
uuid = { version = "1.17", features = ["serde", "v7"] }
|
||||||
random-string = "1.1"
|
random-string = "1.1"
|
||||||
lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls"] }
|
actix-ws = "0.3.0"
|
||||||
|
futures-util = "0.3.31"
|
||||||
|
bunny-api-tokio = "0.3.0"
|
||||||
|
bindet = "0.3.2"
|
||||||
|
deadpool = "0.12"
|
||||||
|
diesel = { version = "2.2", features = ["uuid", "chrono"], default-features = false }
|
||||||
|
diesel-async = { version = "0.5", features = ["deadpool", "postgres", "async-connection-wrapper"] }
|
||||||
|
diesel_migrations = { version = "2.2.0", features = ["postgres"] }
|
||||||
|
thiserror = "2.0.12"
|
||||||
|
actix-multipart = "0.7.2"
|
||||||
|
lettre = { version = "0.11.16", features = ["tokio1", "tokio1-native-tls"] }
|
||||||
chrono = { version = "0.4.41", features = ["serde"] }
|
chrono = { version = "0.4.41", features = ["serde"] }
|
||||||
tracing-subscriber = "0.3.19"
|
ed25519-dalek = { version = "2.1.1", features = ["pem", "pkcs8", "rand_core"] }
|
||||||
rand = "0.9.1"
|
|
||||||
|
[dependencies.tokio]
|
||||||
|
version = "1.45"
|
||||||
|
features = ["full"]
|
||||||
|
|
2
build.rs
2
build.rs
|
@ -12,5 +12,5 @@ fn main() {
|
||||||
.unwrap_or_else(|| "UNKNOWN".to_string());
|
.unwrap_or_else(|| "UNKNOWN".to_string());
|
||||||
|
|
||||||
// Tell Cargo to set `GIT_SHORT_HASH` for the main compilation
|
// Tell Cargo to set `GIT_SHORT_HASH` for the main compilation
|
||||||
println!("cargo:rustc-env=GIT_SHORT_HASH={git_short_hash}");
|
println!("cargo:rustc-env=GIT_SHORT_HASH={}", git_short_hash);
|
||||||
}
|
}
|
||||||
|
|
|
@ -65,4 +65,4 @@ rotate_log "/gorb/logs/backend.log"
|
||||||
# Give the DB time to start up before connecting
|
# Give the DB time to start up before connecting
|
||||||
sleep 5
|
sleep 5
|
||||||
|
|
||||||
/usr/bin/gorb-backend --config /gorb/config/config.toml 2>&1 | tee /gorb/logs/backend.log
|
/usr/bin/gorb-backend --config /gorb/config/config.toml --private-key /gorb/config/federation-privkey.pem 2>&1 | tee /gorb/logs/backend.log
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
-- This file should undo anything in `up.sql`
|
||||||
|
DROP TABLE federated_users;
|
||||||
|
DROP TABLE instances;
|
10
migrations/2025-06-03-123458_federated_instances/up.sql
Normal file
10
migrations/2025-06-03-123458_federated_instances/up.sql
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
-- Your SQL goes here
|
||||||
|
CREATE TABLE instances (
|
||||||
|
instance_url VARCHAR(8000) PRIMARY KEY NOT NULL,
|
||||||
|
public_key VARCHAR(500) UNIQUE NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE federated_users (
|
||||||
|
uuid UUID PRIMARY KEY NOT NULL,
|
||||||
|
instance_url VARCHAR(8000) NOT NULL REFERENCES instances(instance_url)
|
||||||
|
);
|
|
@ -1,14 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE guilds
|
|
||||||
ADD COLUMN owner_uuid UUID REFERENCES users(uuid);
|
|
||||||
|
|
||||||
UPDATE guilds g
|
|
||||||
SET owner_uuid = gm.user_uuid
|
|
||||||
FROM guild_members gm
|
|
||||||
WHERE gm.guild_uuid = g.uuid AND gm.is_owner = TRUE;
|
|
||||||
|
|
||||||
ALTER TABLE guilds
|
|
||||||
ALTER COLUMN owner_uuid SET NOT NULL;
|
|
||||||
|
|
||||||
ALTER TABLE guild_members
|
|
||||||
DROP COLUMN is_owner;
|
|
|
@ -1,14 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE guild_members
|
|
||||||
ADD COLUMN is_owner BOOLEAN NOT NULL DEFAULT false;
|
|
||||||
|
|
||||||
UPDATE guild_members gm
|
|
||||||
SET is_owner = true
|
|
||||||
FROM guilds g
|
|
||||||
WHERE gm.guild_uuid = g.uuid AND gm.user_uuid = g.owner_uuid;
|
|
||||||
|
|
||||||
CREATE UNIQUE INDEX one_owner_per_guild ON guild_members (guild_uuid)
|
|
||||||
WHERE is_owner;
|
|
||||||
|
|
||||||
ALTER TABLE guilds
|
|
||||||
DROP COLUMN owner_uuid;
|
|
|
@ -1,3 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE users ALTER COLUMN avatar TYPE varchar(100);
|
|
||||||
ALTER TABLE guilds ALTER COLUMN icon TYPE varchar(100);
|
|
|
@ -1,3 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE users ALTER COLUMN avatar TYPE varchar(8000);
|
|
||||||
ALTER TABLE guilds ALTER COLUMN icon TYPE varchar(8000);
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE messages DROP COLUMN reply_to;
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE messages ADD COLUMN reply_to UUID REFERENCES messages(uuid) DEFAULT NULL;
|
|
|
@ -1,4 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
DROP TABLE friend_requests;
|
|
||||||
DROP FUNCTION check_friend_request;
|
|
||||||
DROP TABLE friends;
|
|
|
@ -1,35 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
CREATE TABLE friends (
|
|
||||||
uuid1 UUID REFERENCES users(uuid),
|
|
||||||
uuid2 UUID REFERENCES users(uuid),
|
|
||||||
accepted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
||||||
PRIMARY KEY (uuid1, uuid2),
|
|
||||||
CHECK (uuid1 < uuid2)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE friend_requests (
|
|
||||||
sender UUID REFERENCES users(uuid),
|
|
||||||
receiver UUID REFERENCES users(uuid),
|
|
||||||
requested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
||||||
PRIMARY KEY (sender, receiver),
|
|
||||||
CHECK (sender <> receiver)
|
|
||||||
);
|
|
||||||
|
|
||||||
-- Create a function to check for existing friendships
|
|
||||||
CREATE FUNCTION check_friend_request()
|
|
||||||
RETURNS TRIGGER AS $$
|
|
||||||
BEGIN
|
|
||||||
IF EXISTS (
|
|
||||||
SELECT 1 FROM friends
|
|
||||||
WHERE (uuid1, uuid2) = (LEAST(NEW.sender, NEW.receiver), GREATEST(NEW.sender, NEW.receiver))
|
|
||||||
) THEN
|
|
||||||
RAISE EXCEPTION 'Users are already friends';
|
|
||||||
END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
|
|
||||||
-- Create the trigger
|
|
||||||
CREATE TRIGGER prevent_friend_request_conflict
|
|
||||||
BEFORE INSERT OR UPDATE ON friend_requests
|
|
||||||
FOR EACH ROW EXECUTE FUNCTION check_friend_request();
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE guild_members DROP CONSTRAINT guild_members_user_uuid_guild_uuid_key;
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE guild_members ADD UNIQUE (user_uuid, guild_uuid)
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE refresh_tokens ALTER COLUMN device_name TYPE varchar(16);
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE refresh_tokens ALTER COLUMN device_name TYPE varchar(64);
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
DROP TABLE guild_bans;
|
|
|
@ -1,8 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
CREATE TABLE guild_bans (
|
|
||||||
guild_uuid uuid NOT NULL REFERENCES guilds(uuid) ON DELETE CASCADE,
|
|
||||||
user_uuid uuid NOT NULL REFERENCES users(uuid),
|
|
||||||
reason VARCHAR(200) DEFAULT NULL,
|
|
||||||
banned_since TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
||||||
PRIMARY KEY (user_uuid, guild_uuid)
|
|
||||||
);
|
|
|
@ -1,5 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
DROP INDEX roles_guuid_uuid;
|
|
||||||
ALTER TABLE roles DROP CONSTRAINT roles_pkey;
|
|
||||||
CREATE UNIQUE INDEX roles_pkey ON roles (uuid, guild_uuid);
|
|
||||||
ALTER TABLE roles ADD PRIMARY KEY USING INDEX roles_pkey;
|
|
|
@ -1,5 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE roles DROP CONSTRAINT roles_pkey;
|
|
||||||
CREATE UNIQUE INDEX roles_pkey ON roles (uuid);
|
|
||||||
ALTER TABLE roles ADD PRIMARY KEY USING INDEX roles_pkey;
|
|
||||||
CREATE UNIQUE INDEX roles_guuid_uuid ON roles (uuid, guild_uuid);
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- This file should undo anything in `up.sql`
|
|
||||||
ALTER TABLE users DROP COLUMN online_status;
|
|
|
@ -1,2 +0,0 @@
|
||||||
-- Your SQL goes here
|
|
||||||
ALTER TABLE users ADD COLUMN online_status INT2 NOT NULL DEFAULT 0;
|
|
|
@ -1,16 +1,13 @@
|
||||||
//! `/api` Contains the entire API
|
//! `/api` Contains the entire API
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::Scope;
|
||||||
|
use actix_web::web;
|
||||||
use axum::{Router, routing::get};
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
mod v1;
|
mod v1;
|
||||||
mod versions;
|
mod versions;
|
||||||
|
|
||||||
pub fn router(path: &str, app_state: Arc<AppState>) -> Router<Arc<AppState>> {
|
pub fn web(path: &str) -> Scope {
|
||||||
Router::new()
|
web::scope(path.trim_end_matches('/'))
|
||||||
.route(&format!("{path}/versions"), get(versions::versions))
|
.service(v1::web())
|
||||||
.nest(&format!("{path}/v1"), v1::router(app_state))
|
.service(versions::get)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,51 +0,0 @@
|
||||||
//! `/api/v1/auth/devices` Returns list of logged in devices
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper};
|
|
||||||
use diesel_async::RunQueryDsl;
|
|
||||||
use serde::Serialize;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
schema::refresh_tokens::{self, dsl},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Serialize, Selectable, Queryable)]
|
|
||||||
#[diesel(table_name = refresh_tokens)]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
|
||||||
struct Device {
|
|
||||||
device_name: String,
|
|
||||||
created_at: i64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `GET /api/v1/auth/devices` Returns list of logged in devices
|
|
||||||
///
|
|
||||||
/// requires auth: no
|
|
||||||
///
|
|
||||||
/// ### Response Example
|
|
||||||
/// ```
|
|
||||||
/// json!([
|
|
||||||
/// {
|
|
||||||
/// "device_name": "My Device!"
|
|
||||||
/// "created_at": "1752418856"
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// ]);
|
|
||||||
/// ```
|
|
||||||
pub async fn get(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let devices: Vec<Device> = dsl::refresh_tokens
|
|
||||||
.filter(dsl::uuid.eq(uuid))
|
|
||||||
.select(Device::as_select())
|
|
||||||
.get_results(&mut app_state.pool.get().await?)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(devices)))
|
|
||||||
}
|
|
|
@ -1,47 +1,42 @@
|
||||||
use std::{
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
sync::Arc,
|
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
|
use actix_web::{HttpResponse, post, web};
|
||||||
use argon2::{PasswordHash, PasswordVerifier};
|
use argon2::{PasswordHash, PasswordVerifier};
|
||||||
use axum::{
|
|
||||||
Json,
|
|
||||||
extract::State,
|
|
||||||
http::{HeaderValue, StatusCode},
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl, dsl::insert_into};
|
use diesel::{ExpressionMethods, QueryDsl, dsl::insert_into};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::Response;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::*,
|
schema::*,
|
||||||
utils::{
|
utils::{
|
||||||
PASSWORD_REGEX, generate_device_name, generate_token, new_refresh_token_cookie,
|
PASSWORD_REGEX, generate_access_token, generate_refresh_token, new_refresh_token_cookie,
|
||||||
user_uuid_from_identifier,
|
user_uuid_from_identifier,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use super::Response;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct LoginInformation {
|
struct LoginInformation {
|
||||||
username: String,
|
username: String,
|
||||||
password: String,
|
password: String,
|
||||||
|
device_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("/login")]
|
||||||
pub async fn response(
|
pub async fn response(
|
||||||
State(app_state): State<Arc<AppState>>,
|
login_information: web::Json<LoginInformation>,
|
||||||
Json(login_information): Json<LoginInformation>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
if !PASSWORD_REGEX.is_match(&login_information.password) {
|
if !PASSWORD_REGEX.is_match(&login_information.password) {
|
||||||
return Err(Error::BadRequest("Bad password".to_string()));
|
return Ok(HttpResponse::Forbidden().json(r#"{ "password_hashed": false }"#));
|
||||||
}
|
}
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
let uuid = user_uuid_from_identifier(&mut conn, &login_information.username).await?;
|
let uuid = user_uuid_from_identifier(&mut conn, &login_information.username).await?;
|
||||||
|
|
||||||
|
@ -54,7 +49,7 @@ pub async fn response(
|
||||||
let parsed_hash = PasswordHash::new(&database_password)
|
let parsed_hash = PasswordHash::new(&database_password)
|
||||||
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
||||||
|
|
||||||
if app_state
|
if data
|
||||||
.argon2
|
.argon2
|
||||||
.verify_password(login_information.password.as_bytes(), &parsed_hash)
|
.verify_password(login_information.password.as_bytes(), &parsed_hash)
|
||||||
.is_err()
|
.is_err()
|
||||||
|
@ -64,21 +59,19 @@ pub async fn response(
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let refresh_token = generate_token::<32>()?;
|
let refresh_token = generate_refresh_token()?;
|
||||||
let access_token = generate_token::<16>()?;
|
let access_token = generate_access_token()?;
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
||||||
|
|
||||||
use refresh_tokens::dsl as rdsl;
|
use refresh_tokens::dsl as rdsl;
|
||||||
|
|
||||||
let device_name = generate_device_name();
|
|
||||||
|
|
||||||
insert_into(refresh_tokens::table)
|
insert_into(refresh_tokens::table)
|
||||||
.values((
|
.values((
|
||||||
rdsl::token.eq(&refresh_token),
|
rdsl::token.eq(&refresh_token),
|
||||||
rdsl::uuid.eq(uuid),
|
rdsl::uuid.eq(uuid),
|
||||||
rdsl::created_at.eq(current_time),
|
rdsl::created_at.eq(current_time),
|
||||||
rdsl::device_name.eq(&device_name),
|
rdsl::device_name.eq(&login_information.device_name),
|
||||||
))
|
))
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
@ -95,21 +88,7 @@ pub async fn response(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let mut response = (
|
Ok(HttpResponse::Ok()
|
||||||
StatusCode::OK,
|
.cookie(new_refresh_token_cookie(&data.config, refresh_token))
|
||||||
Json(Response {
|
.json(Response { access_token }))
|
||||||
access_token,
|
|
||||||
device_name,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response();
|
|
||||||
|
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(
|
|
||||||
&new_refresh_token_cookie(&app_state.config, refresh_token).to_string(),
|
|
||||||
)?,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,9 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, post, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
extract::State,
|
|
||||||
http::{HeaderValue, StatusCode},
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use axum_extra::extract::CookieJar;
|
|
||||||
use diesel::{ExpressionMethods, delete};
|
use diesel::{ExpressionMethods, delete};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::refresh_tokens::{self, dsl},
|
schema::refresh_tokens::{self, dsl},
|
||||||
};
|
};
|
||||||
|
@ -20,46 +13,26 @@ use crate::{
|
||||||
/// requires auth: kinda, needs refresh token set but no access token is technically required
|
/// requires auth: kinda, needs refresh token set but no access token is technically required
|
||||||
///
|
///
|
||||||
/// ### Responses
|
/// ### Responses
|
||||||
///
|
|
||||||
/// 200 Logged out
|
/// 200 Logged out
|
||||||
///
|
|
||||||
/// 404 Refresh token is invalid
|
/// 404 Refresh token is invalid
|
||||||
///
|
|
||||||
/// 401 Unauthorized (no refresh token found)
|
/// 401 Unauthorized (no refresh token found)
|
||||||
///
|
///
|
||||||
pub async fn res(
|
#[post("/logout")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn res(req: HttpRequest, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
jar: CookieJar,
|
let mut refresh_token_cookie = req.cookie("refresh_token").ok_or(Error::Unauthorized(
|
||||||
) -> Result<impl IntoResponse, Error> {
|
"request has no refresh token".to_string(),
|
||||||
let mut refresh_token_cookie = jar
|
))?;
|
||||||
.get("refresh_token")
|
|
||||||
.ok_or(Error::Unauthorized(
|
|
||||||
"request has no refresh token".to_string(),
|
|
||||||
))?
|
|
||||||
.to_owned();
|
|
||||||
|
|
||||||
let refresh_token = String::from(refresh_token_cookie.value_trimmed());
|
let refresh_token = String::from(refresh_token_cookie.value());
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
let deleted = delete(refresh_tokens::table)
|
delete(refresh_tokens::table)
|
||||||
.filter(dsl::token.eq(refresh_token))
|
.filter(dsl::token.eq(refresh_token))
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let mut response;
|
|
||||||
|
|
||||||
if deleted == 0 {
|
|
||||||
response = StatusCode::NOT_FOUND.into_response();
|
|
||||||
} else {
|
|
||||||
response = StatusCode::OK.into_response();
|
|
||||||
}
|
|
||||||
|
|
||||||
refresh_token_cookie.make_removal();
|
refresh_token_cookie.make_removal();
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(&refresh_token_cookie.to_string())?,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(response)
|
Ok(HttpResponse::Ok().cookie(refresh_token_cookie).finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,27 +1,13 @@
|
||||||
use std::{
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
sync::Arc,
|
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
use axum::{
|
use actix_web::{Scope, web};
|
||||||
Router,
|
|
||||||
extract::{Request, State},
|
|
||||||
middleware::{Next, from_fn_with_state},
|
|
||||||
response::IntoResponse,
|
|
||||||
routing::{delete, get, post},
|
|
||||||
};
|
|
||||||
use axum_extra::{
|
|
||||||
TypedHeader,
|
|
||||||
headers::{Authorization, authorization::Bearer},
|
|
||||||
};
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl};
|
use diesel::{ExpressionMethods, QueryDsl};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{AppState, Conn, error::Error, schema::access_tokens::dsl};
|
use crate::{Conn, error::Error, schema::access_tokens::dsl};
|
||||||
|
|
||||||
mod devices;
|
|
||||||
mod login;
|
mod login;
|
||||||
mod logout;
|
mod logout;
|
||||||
mod refresh;
|
mod refresh;
|
||||||
|
@ -31,27 +17,21 @@ mod revoke;
|
||||||
mod verify_email;
|
mod verify_email;
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct Response {
|
struct Response {
|
||||||
access_token: String,
|
access_token: String,
|
||||||
device_name: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
let router_with_auth = Router::new()
|
web::scope("/auth")
|
||||||
.route("/verify-email", get(verify_email::get))
|
.service(register::res)
|
||||||
.route("/verify-email", post(verify_email::post))
|
.service(login::response)
|
||||||
.route("/revoke", post(revoke::post))
|
.service(logout::res)
|
||||||
.route("/devices", get(devices::get))
|
.service(refresh::res)
|
||||||
.layer(from_fn_with_state(app_state, CurrentUser::check_auth_layer));
|
.service(revoke::res)
|
||||||
|
.service(verify_email::get)
|
||||||
Router::new()
|
.service(verify_email::post)
|
||||||
.route("/register", post(register::post))
|
.service(reset_password::get)
|
||||||
.route("/login", post(login::response))
|
.service(reset_password::post)
|
||||||
.route("/logout", delete(logout::res))
|
|
||||||
.route("/refresh", post(refresh::post))
|
|
||||||
.route("/reset-password", get(reset_password::get))
|
|
||||||
.route("/reset-password", post(reset_password::post))
|
|
||||||
.merge(router_with_auth)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn check_access_token(access_token: &str, conn: &mut Conn) -> Result<Uuid, Error> {
|
pub async fn check_access_token(access_token: &str, conn: &mut Conn) -> Result<Uuid, Error> {
|
||||||
|
@ -78,21 +58,3 @@ pub async fn check_access_token(access_token: &str, conn: &mut Conn) -> Result<U
|
||||||
|
|
||||||
Ok(uuid)
|
Ok(uuid)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CurrentUser<Uuid>(pub Uuid);
|
|
||||||
|
|
||||||
impl CurrentUser<Uuid> {
|
|
||||||
pub async fn check_auth_layer(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
|
|
||||||
mut req: Request,
|
|
||||||
next: Next,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let current_user =
|
|
||||||
CurrentUser(check_access_token(auth.token(), &mut app_state.pool.get().await?).await?);
|
|
||||||
|
|
||||||
req.extensions_mut().insert(current_user);
|
|
||||||
Ok(next.run(req).await)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,45 +1,32 @@
|
||||||
use axum::{
|
use actix_web::{HttpRequest, HttpResponse, post, web};
|
||||||
Json,
|
|
||||||
extract::State,
|
|
||||||
http::{HeaderValue, StatusCode},
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use axum_extra::extract::CookieJar;
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl, delete, update};
|
use diesel::{ExpressionMethods, QueryDsl, delete, update};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use log::error;
|
use log::error;
|
||||||
use std::{
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
sync::Arc,
|
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::Response;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::{
|
schema::{
|
||||||
access_tokens::{self, dsl},
|
access_tokens::{self, dsl},
|
||||||
refresh_tokens::{self, dsl as rdsl},
|
refresh_tokens::{self, dsl as rdsl},
|
||||||
},
|
},
|
||||||
utils::{generate_token, new_refresh_token_cookie},
|
utils::{generate_access_token, generate_refresh_token, new_refresh_token_cookie},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn post(
|
use super::Response;
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
jar: CookieJar,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut refresh_token_cookie = jar
|
|
||||||
.get("refresh_token")
|
|
||||||
.ok_or(Error::Unauthorized(
|
|
||||||
"request has no refresh token".to_string(),
|
|
||||||
))?
|
|
||||||
.to_owned();
|
|
||||||
|
|
||||||
let mut refresh_token = String::from(refresh_token_cookie.value_trimmed());
|
#[post("/refresh")]
|
||||||
|
pub async fn res(req: HttpRequest, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
|
let mut refresh_token_cookie = req.cookie("refresh_token").ok_or(Error::Unauthorized(
|
||||||
|
"request has no refresh token".to_string(),
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let mut refresh_token = String::from(refresh_token_cookie.value());
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
if let Ok(created_at) = rdsl::refresh_tokens
|
if let Ok(created_at) = rdsl::refresh_tokens
|
||||||
.filter(rdsl::token.eq(&refresh_token))
|
.filter(rdsl::token.eq(&refresh_token))
|
||||||
|
@ -55,25 +42,20 @@ pub async fn post(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
error!("{error}");
|
error!("{}", error);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut response = StatusCode::UNAUTHORIZED.into_response();
|
|
||||||
|
|
||||||
refresh_token_cookie.make_removal();
|
refresh_token_cookie.make_removal();
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(&refresh_token_cookie.to_string())?,
|
|
||||||
);
|
|
||||||
|
|
||||||
return Ok(response);
|
return Ok(HttpResponse::Unauthorized()
|
||||||
|
.cookie(refresh_token_cookie)
|
||||||
|
.finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
||||||
let mut device_name: String = String::new();
|
|
||||||
|
|
||||||
if lifetime > 1987200 {
|
if lifetime > 1987200 {
|
||||||
let new_refresh_token = generate_token::<32>()?;
|
let new_refresh_token = generate_refresh_token()?;
|
||||||
|
|
||||||
match update(refresh_tokens::table)
|
match update(refresh_tokens::table)
|
||||||
.filter(rdsl::token.eq(&refresh_token))
|
.filter(rdsl::token.eq(&refresh_token))
|
||||||
|
@ -81,21 +63,19 @@ pub async fn post(
|
||||||
rdsl::token.eq(&new_refresh_token),
|
rdsl::token.eq(&new_refresh_token),
|
||||||
rdsl::created_at.eq(current_time),
|
rdsl::created_at.eq(current_time),
|
||||||
))
|
))
|
||||||
.returning(rdsl::device_name)
|
.execute(&mut conn)
|
||||||
.get_result::<String>(&mut conn)
|
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(existing_device_name) => {
|
Ok(_) => {
|
||||||
refresh_token = new_refresh_token;
|
refresh_token = new_refresh_token;
|
||||||
device_name = existing_device_name;
|
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
error!("{error}");
|
error!("{}", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let access_token = generate_token::<16>()?;
|
let access_token = generate_access_token()?;
|
||||||
|
|
||||||
update(access_tokens::table)
|
update(access_tokens::table)
|
||||||
.filter(dsl::refresh_token.eq(&refresh_token))
|
.filter(dsl::refresh_token.eq(&refresh_token))
|
||||||
|
@ -106,33 +86,14 @@ pub async fn post(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let mut response = (
|
return Ok(HttpResponse::Ok()
|
||||||
StatusCode::OK,
|
.cookie(new_refresh_token_cookie(&data.config, refresh_token))
|
||||||
Json(Response {
|
.json(Response { access_token }));
|
||||||
access_token,
|
|
||||||
device_name,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response();
|
|
||||||
|
|
||||||
// TODO: Dont set this when refresh token is unchanged
|
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(
|
|
||||||
&new_refresh_token_cookie(&app_state.config, refresh_token).to_string(),
|
|
||||||
)?,
|
|
||||||
);
|
|
||||||
|
|
||||||
return Ok(response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut response = StatusCode::UNAUTHORIZED.into_response();
|
|
||||||
|
|
||||||
refresh_token_cookie.make_removal();
|
refresh_token_cookie.make_removal();
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(&refresh_token_cookie.to_string())?,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(response)
|
Ok(HttpResponse::Unauthorized()
|
||||||
|
.cookie(refresh_token_cookie)
|
||||||
|
.finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,18 +1,10 @@
|
||||||
use std::{
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
sync::Arc,
|
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
|
||||||
};
|
|
||||||
|
|
||||||
|
use actix_web::{HttpResponse, post, web};
|
||||||
use argon2::{
|
use argon2::{
|
||||||
PasswordHasher,
|
PasswordHasher,
|
||||||
password_hash::{SaltString, rand_core::OsRng},
|
password_hash::{SaltString, rand_core::OsRng},
|
||||||
};
|
};
|
||||||
use axum::{
|
|
||||||
Json,
|
|
||||||
extract::State,
|
|
||||||
http::{HeaderValue, StatusCode},
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use diesel::{ExpressionMethods, dsl::insert_into};
|
use diesel::{ExpressionMethods, dsl::insert_into};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
@ -20,35 +12,39 @@ use uuid::Uuid;
|
||||||
|
|
||||||
use super::Response;
|
use super::Response;
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::Member,
|
|
||||||
schema::{
|
schema::{
|
||||||
access_tokens::{self, dsl as adsl},
|
access_tokens::{self, dsl as adsl},
|
||||||
refresh_tokens::{self, dsl as rdsl},
|
refresh_tokens::{self, dsl as rdsl},
|
||||||
users::{self, dsl as udsl},
|
users::{self, dsl as udsl},
|
||||||
},
|
},
|
||||||
utils::{
|
utils::{
|
||||||
EMAIL_REGEX, PASSWORD_REGEX, USERNAME_REGEX, generate_device_name, generate_token,
|
EMAIL_REGEX, PASSWORD_REGEX, USERNAME_REGEX, generate_access_token, generate_refresh_token,
|
||||||
new_refresh_token_cookie,
|
new_refresh_token_cookie,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct AccountInformation {
|
struct AccountInformation {
|
||||||
identifier: String,
|
identifier: String,
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
|
device_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct ResponseError {
|
struct ResponseError {
|
||||||
signups_enabled: bool,
|
signups_enabled: bool,
|
||||||
gorb_id_valid: bool,
|
gorb_id_valid: bool,
|
||||||
gorb_id_available: bool,
|
gorb_id_available: bool,
|
||||||
email_valid: bool,
|
email_valid: bool,
|
||||||
email_available: bool,
|
email_available: bool,
|
||||||
password_strength: bool,
|
password_hashed: bool,
|
||||||
|
password_minimum_length: bool,
|
||||||
|
password_special_characters: bool,
|
||||||
|
password_letters: bool,
|
||||||
|
password_numbers: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ResponseError {
|
impl Default for ResponseError {
|
||||||
|
@ -59,16 +55,21 @@ impl Default for ResponseError {
|
||||||
gorb_id_available: true,
|
gorb_id_available: true,
|
||||||
email_valid: true,
|
email_valid: true,
|
||||||
email_available: true,
|
email_available: true,
|
||||||
password_strength: true,
|
password_hashed: true,
|
||||||
|
password_minimum_length: true,
|
||||||
|
password_special_characters: true,
|
||||||
|
password_letters: true,
|
||||||
|
password_numbers: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post(
|
#[post("/register")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn res(
|
||||||
Json(account_information): Json<AccountInformation>,
|
account_information: web::Json<AccountInformation>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
if !app_state.config.instance.registration {
|
) -> Result<HttpResponse, Error> {
|
||||||
|
if !data.config.instance.registration {
|
||||||
return Err(Error::Forbidden(
|
return Err(Error::Forbidden(
|
||||||
"registration is disabled on this instance".to_string(),
|
"registration is disabled on this instance".to_string(),
|
||||||
));
|
));
|
||||||
|
@ -77,48 +78,36 @@ pub async fn post(
|
||||||
let uuid = Uuid::now_v7();
|
let uuid = Uuid::now_v7();
|
||||||
|
|
||||||
if !EMAIL_REGEX.is_match(&account_information.email) {
|
if !EMAIL_REGEX.is_match(&account_information.email) {
|
||||||
return Ok((
|
return Ok(HttpResponse::Forbidden().json(ResponseError {
|
||||||
StatusCode::FORBIDDEN,
|
email_valid: false,
|
||||||
Json(ResponseError {
|
..Default::default()
|
||||||
email_valid: false,
|
}));
|
||||||
..Default::default()
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !USERNAME_REGEX.is_match(&account_information.identifier)
|
if !USERNAME_REGEX.is_match(&account_information.identifier)
|
||||||
|| account_information.identifier.len() < 3
|
|| account_information.identifier.len() < 3
|
||||||
|| account_information.identifier.len() > 32
|
|| account_information.identifier.len() > 32
|
||||||
{
|
{
|
||||||
return Ok((
|
return Ok(HttpResponse::Forbidden().json(ResponseError {
|
||||||
StatusCode::FORBIDDEN,
|
gorb_id_valid: false,
|
||||||
Json(ResponseError {
|
..Default::default()
|
||||||
gorb_id_valid: false,
|
}));
|
||||||
..Default::default()
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !PASSWORD_REGEX.is_match(&account_information.password) {
|
if !PASSWORD_REGEX.is_match(&account_information.password) {
|
||||||
return Ok((
|
return Ok(HttpResponse::Forbidden().json(ResponseError {
|
||||||
StatusCode::FORBIDDEN,
|
password_hashed: false,
|
||||||
Json(ResponseError {
|
..Default::default()
|
||||||
password_strength: false,
|
}));
|
||||||
..Default::default()
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let salt = SaltString::generate(&mut OsRng);
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
|
||||||
if let Ok(hashed_password) = app_state
|
if let Ok(hashed_password) = data
|
||||||
.argon2
|
.argon2
|
||||||
.hash_password(account_information.password.as_bytes(), &salt)
|
.hash_password(account_information.password.as_bytes(), &salt)
|
||||||
{
|
{
|
||||||
let mut conn = app_state.pool.get().await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
// TODO: Check security of this implementation
|
// TODO: Check security of this implementation
|
||||||
insert_into(users::table)
|
insert_into(users::table)
|
||||||
|
@ -131,19 +120,17 @@ pub async fn post(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let refresh_token = generate_token::<32>()?;
|
let refresh_token = generate_refresh_token()?;
|
||||||
let access_token = generate_token::<16>()?;
|
let access_token = generate_access_token()?;
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
|
||||||
|
|
||||||
let device_name = generate_device_name();
|
|
||||||
|
|
||||||
insert_into(refresh_tokens::table)
|
insert_into(refresh_tokens::table)
|
||||||
.values((
|
.values((
|
||||||
rdsl::token.eq(&refresh_token),
|
rdsl::token.eq(&refresh_token),
|
||||||
rdsl::uuid.eq(uuid),
|
rdsl::uuid.eq(uuid),
|
||||||
rdsl::created_at.eq(current_time),
|
rdsl::created_at.eq(current_time),
|
||||||
rdsl::device_name.eq(&device_name),
|
rdsl::device_name.eq(&account_information.device_name),
|
||||||
))
|
))
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
@ -158,28 +145,10 @@ pub async fn post(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if let Some(initial_guild) = app_state.config.instance.initial_guild {
|
return Ok(HttpResponse::Ok()
|
||||||
Member::new(&mut conn, &app_state.cache_pool, uuid, initial_guild).await?;
|
.cookie(new_refresh_token_cookie(&data.config, refresh_token))
|
||||||
}
|
.json(Response { access_token }));
|
||||||
|
|
||||||
let mut response = (
|
|
||||||
StatusCode::OK,
|
|
||||||
Json(Response {
|
|
||||||
access_token,
|
|
||||||
device_name,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.into_response();
|
|
||||||
|
|
||||||
response.headers_mut().append(
|
|
||||||
"Set-Cookie",
|
|
||||||
HeaderValue::from_str(
|
|
||||||
&new_refresh_token_cookie(&app_state.config, refresh_token).to_string(),
|
|
||||||
)?,
|
|
||||||
);
|
|
||||||
|
|
||||||
return Ok(response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(StatusCode::INTERNAL_SERVER_ERROR.into_response())
|
Ok(HttpResponse::InternalServerError().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,20 +1,13 @@
|
||||||
//! `/api/v1/auth/reset-password` Endpoints for resetting user password
|
//! `/api/v1/auth/reset-password` Endpoints for resetting user password
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpResponse, get, post, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Json,
|
|
||||||
extract::{Query, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use chrono::{Duration, Utc};
|
use chrono::{Duration, Utc};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::{AppState, error::Error, objects::PasswordResetToken};
|
use crate::{Data, error::Error, objects::PasswordResetToken};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct QueryParams {
|
struct Query {
|
||||||
identifier: String,
|
identifier: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -27,28 +20,17 @@ pub struct QueryParams {
|
||||||
///
|
///
|
||||||
/// ### Responses
|
/// ### Responses
|
||||||
/// 200 Email sent
|
/// 200 Email sent
|
||||||
///
|
|
||||||
/// 429 Too Many Requests
|
/// 429 Too Many Requests
|
||||||
///
|
|
||||||
/// 404 Not found
|
/// 404 Not found
|
||||||
///
|
|
||||||
/// 400 Bad request
|
/// 400 Bad request
|
||||||
///
|
///
|
||||||
pub async fn get(
|
#[get("/reset-password")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(query: web::Query<Query>, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
query: Query<QueryParams>,
|
if let Ok(password_reset_token) =
|
||||||
) -> Result<impl IntoResponse, Error> {
|
PasswordResetToken::get_with_identifier(&data, query.identifier.clone()).await
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
if let Ok(password_reset_token) = PasswordResetToken::get_with_identifier(
|
|
||||||
&mut conn,
|
|
||||||
&app_state.cache_pool,
|
|
||||||
query.identifier.clone(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
{
|
||||||
if Utc::now().signed_duration_since(password_reset_token.created_at) > Duration::hours(1) {
|
if Utc::now().signed_duration_since(password_reset_token.created_at) > Duration::hours(1) {
|
||||||
password_reset_token.delete(&app_state.cache_pool).await?;
|
password_reset_token.delete(&data).await?;
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::TooManyRequests(
|
return Err(Error::TooManyRequests(
|
||||||
"Please allow 1 hour before sending a new email".to_string(),
|
"Please allow 1 hour before sending a new email".to_string(),
|
||||||
|
@ -56,13 +38,13 @@ pub async fn get(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
PasswordResetToken::new(&mut conn, &app_state, query.identifier.clone()).await?;
|
PasswordResetToken::new(&data, query.identifier.clone()).await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct ResetPassword {
|
struct ResetPassword {
|
||||||
password: String,
|
password: String,
|
||||||
token: String,
|
token: String,
|
||||||
}
|
}
|
||||||
|
@ -81,27 +63,21 @@ pub struct ResetPassword {
|
||||||
///
|
///
|
||||||
/// ### Responses
|
/// ### Responses
|
||||||
/// 200 Success
|
/// 200 Success
|
||||||
///
|
|
||||||
/// 410 Token Expired
|
/// 410 Token Expired
|
||||||
///
|
|
||||||
/// 404 Not Found
|
/// 404 Not Found
|
||||||
///
|
|
||||||
/// 400 Bad Request
|
/// 400 Bad Request
|
||||||
///
|
///
|
||||||
|
#[post("/reset-password")]
|
||||||
pub async fn post(
|
pub async fn post(
|
||||||
State(app_state): State<Arc<AppState>>,
|
reset_password: web::Json<ResetPassword>,
|
||||||
reset_password: Json<ResetPassword>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let password_reset_token =
|
let password_reset_token =
|
||||||
PasswordResetToken::get(&app_state.cache_pool, reset_password.token.clone()).await?;
|
PasswordResetToken::get(&data, reset_password.token.clone()).await?;
|
||||||
|
|
||||||
password_reset_token
|
password_reset_token
|
||||||
.set_password(
|
.set_password(&data, reset_password.password.clone())
|
||||||
&mut app_state.pool.get().await?,
|
|
||||||
&app_state,
|
|
||||||
reset_password.password.clone(),
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,35 +1,38 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, post, web};
|
||||||
|
|
||||||
use argon2::{PasswordHash, PasswordVerifier};
|
use argon2::{PasswordHash, PasswordVerifier};
|
||||||
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl, delete};
|
use diesel::{ExpressionMethods, QueryDsl, delete};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::{
|
schema::refresh_tokens::{self, dsl as rdsl},
|
||||||
refresh_tokens::{self, dsl as rdsl},
|
schema::users::dsl as udsl,
|
||||||
users::dsl as udsl,
|
utils::get_auth_header,
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct RevokeRequest {
|
struct RevokeRequest {
|
||||||
password: String,
|
password: String,
|
||||||
device_name: String,
|
device_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Should maybe be a delete request?
|
// TODO: Should maybe be a delete request?
|
||||||
pub async fn post(
|
#[post("/revoke")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn res(
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
req: HttpRequest,
|
||||||
Json(revoke_request): Json<RevokeRequest>,
|
revoke_request: web::Json<RevokeRequest>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
let mut conn = app_state.pool.get().await?;
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
let database_password: String = udsl::users
|
let database_password: String = udsl::users
|
||||||
.filter(udsl::uuid.eq(uuid))
|
.filter(udsl::uuid.eq(uuid))
|
||||||
|
@ -40,7 +43,7 @@ pub async fn post(
|
||||||
let hashed_password = PasswordHash::new(&database_password)
|
let hashed_password = PasswordHash::new(&database_password)
|
||||||
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
||||||
|
|
||||||
if app_state
|
if data
|
||||||
.argon2
|
.argon2
|
||||||
.verify_password(revoke_request.password.as_bytes(), &hashed_password)
|
.verify_password(revoke_request.password.as_bytes(), &hashed_password)
|
||||||
.is_err()
|
.is_err()
|
||||||
|
@ -56,5 +59,5 @@ pub async fn post(
|
||||||
.execute(&mut conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,26 +1,19 @@
|
||||||
//! `/api/v1/auth/verify-email` Endpoints for verifying user emails
|
//! `/api/v1/auth/verify-email` Endpoints for verifying user emails
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension,
|
|
||||||
extract::{Query, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use chrono::{Duration, Utc};
|
use chrono::{Duration, Utc};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{EmailToken, Me},
|
objects::{EmailToken, Me},
|
||||||
|
utils::get_auth_header,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct QueryParams {
|
struct Query {
|
||||||
token: String,
|
token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -33,39 +26,37 @@ pub struct QueryParams {
|
||||||
///
|
///
|
||||||
/// ### Responses
|
/// ### Responses
|
||||||
/// 200 Success
|
/// 200 Success
|
||||||
///
|
|
||||||
/// 204 Already verified
|
|
||||||
///
|
|
||||||
/// 410 Token Expired
|
/// 410 Token Expired
|
||||||
///
|
|
||||||
/// 404 Not Found
|
/// 404 Not Found
|
||||||
///
|
|
||||||
/// 401 Unauthorized
|
/// 401 Unauthorized
|
||||||
///
|
///
|
||||||
|
#[get("/verify-email")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Query(query): Query<QueryParams>,
|
query: web::Query<Query>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
let me = Me::get(&mut conn, uuid).await?;
|
||||||
|
|
||||||
if me.email_verified {
|
let email_token = EmailToken::get(&data, me.uuid).await?;
|
||||||
return Ok(StatusCode::NO_CONTENT);
|
|
||||||
}
|
|
||||||
|
|
||||||
let email_token = EmailToken::get(&app_state.cache_pool, me.uuid).await?;
|
|
||||||
|
|
||||||
if query.token != email_token.token {
|
if query.token != email_token.token {
|
||||||
return Ok(StatusCode::UNAUTHORIZED);
|
return Ok(HttpResponse::Unauthorized().finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
me.verify_email(&mut conn).await?;
|
me.verify_email(&mut conn).await?;
|
||||||
|
|
||||||
email_token.delete(&app_state.cache_pool).await?;
|
email_token.delete(&data).await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/auth/verify-email` Sends user verification email
|
/// `POST /api/v1/auth/verify-email` Sends user verification email
|
||||||
|
@ -74,26 +65,29 @@ pub async fn get(
|
||||||
///
|
///
|
||||||
/// ### Responses
|
/// ### Responses
|
||||||
/// 200 Email sent
|
/// 200 Email sent
|
||||||
///
|
|
||||||
/// 204 Already verified
|
/// 204 Already verified
|
||||||
///
|
|
||||||
/// 429 Too Many Requests
|
/// 429 Too Many Requests
|
||||||
///
|
|
||||||
/// 401 Unauthorized
|
/// 401 Unauthorized
|
||||||
///
|
///
|
||||||
pub async fn post(
|
#[post("/verify-email")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn post(req: HttpRequest, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
let headers = req.headers();
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let me = Me::get(&mut app_state.pool.get().await?, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
let me = Me::get(&mut conn, uuid).await?;
|
||||||
|
|
||||||
if me.email_verified {
|
if me.email_verified {
|
||||||
return Ok(StatusCode::NO_CONTENT);
|
return Ok(HttpResponse::NoContent().finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(email_token) = EmailToken::get(&app_state.cache_pool, me.uuid).await {
|
if let Ok(email_token) = EmailToken::get(&data, me.uuid).await {
|
||||||
if Utc::now().signed_duration_since(email_token.created_at) > Duration::hours(1) {
|
if Utc::now().signed_duration_since(email_token.created_at) > Duration::hours(1) {
|
||||||
email_token.delete(&app_state.cache_pool).await?;
|
email_token.delete(&data).await?;
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::TooManyRequests(
|
return Err(Error::TooManyRequests(
|
||||||
"Please allow 1 hour before sending a new email".to_string(),
|
"Please allow 1 hour before sending a new email".to_string(),
|
||||||
|
@ -101,7 +95,7 @@ pub async fn post(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
EmailToken::new(&app_state, me).await?;
|
EmailToken::new(&data, me).await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,25 +1,12 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{Scope, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Router,
|
|
||||||
middleware::from_fn_with_state,
|
|
||||||
routing::{any, delete, get, patch},
|
|
||||||
};
|
|
||||||
//use socketioxide::SocketIo;
|
|
||||||
|
|
||||||
use crate::{AppState, api::v1::auth::CurrentUser};
|
|
||||||
|
|
||||||
mod uuid;
|
mod uuid;
|
||||||
|
|
||||||
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
let router_with_auth = Router::new()
|
web::scope("/channels")
|
||||||
.route("/{uuid}", get(uuid::get))
|
.service(uuid::get)
|
||||||
.route("/{uuid}", delete(uuid::delete))
|
.service(uuid::delete)
|
||||||
.route("/{uuid}", patch(uuid::patch))
|
.service(uuid::patch)
|
||||||
.route("/{uuid}/messages", get(uuid::messages::get))
|
.service(uuid::messages::get)
|
||||||
.layer(from_fn_with_state(app_state, CurrentUser::check_auth_layer));
|
.service(uuid::socket::ws)
|
||||||
|
|
||||||
Router::new()
|
|
||||||
.route("/{uuid}/socket", any(uuid::socket::ws))
|
|
||||||
.merge(router_with_auth)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,25 +1,18 @@
|
||||||
//! `/api/v1/channels/{uuid}/messages` Endpoints related to channel messages
|
//! `/api/v1/channels/{uuid}/messages` Endpoints related to channel messages
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Channel, Member},
|
objects::{Channel, Member},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
use ::uuid::Uuid;
|
use ::uuid::Uuid;
|
||||||
use axum::{
|
use actix_web::{HttpRequest, HttpResponse, get, web};
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, Query, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct MessageRequest {
|
struct MessageRequest {
|
||||||
amount: i64,
|
amount: i64,
|
||||||
offset: i64,
|
offset: i64,
|
||||||
}
|
}
|
||||||
|
@ -54,28 +47,32 @@ pub struct MessageRequest {
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
|
#[get("/{uuid}/messages")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(channel_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Query(message_request): Query<MessageRequest>,
|
message_request: web::Query<MessageRequest>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
|
let channel_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
let channel = Channel::fetch_one(&data, channel_uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
||||||
|
|
||||||
let messages = channel
|
let messages = channel
|
||||||
.fetch_messages(
|
.fetch_messages(&data, message_request.amount, message_request.offset)
|
||||||
&mut conn,
|
|
||||||
&app_state.cache_pool,
|
|
||||||
message_request.amount,
|
|
||||||
message_request.offset,
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(messages)))
|
Ok(HttpResponse::Ok().json(messages))
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,65 +3,71 @@
|
||||||
pub mod messages;
|
pub mod messages;
|
||||||
pub mod socket;
|
pub mod socket;
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Channel, Member, Permissions},
|
objects::{Channel, Member},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
use axum::{
|
use actix_web::{HttpRequest, HttpResponse, delete, get, patch, web};
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[get("/{uuid}")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(channel_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
|
let channel_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
let channel = Channel::fetch_one(&data, channel_uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(channel)))
|
Ok(HttpResponse::Ok().json(channel))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[delete("/{uuid}")]
|
||||||
pub async fn delete(
|
pub async fn delete(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(channel_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
|
let channel_uuid = path.into_inner().0;
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
member
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageChannel)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
channel.delete(&mut conn, &app_state.cache_pool).await?;
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
let channel = Channel::fetch_one(&data, channel_uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
||||||
|
|
||||||
|
channel.delete(&data).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct NewInfo {
|
struct NewInfo {
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
is_above: Option<String>,
|
is_above: Option<String>,
|
||||||
|
@ -98,45 +104,44 @@ pub struct NewInfo {
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
|
#[patch("/{uuid}")]
|
||||||
pub async fn patch(
|
pub async fn patch(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(channel_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
new_info: web::Json<NewInfo>,
|
||||||
Json(new_info): Json<NewInfo>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let mut channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
|
let channel_uuid = path.into_inner().0;
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
member
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageChannel)
|
|
||||||
.await?;
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
let mut channel = Channel::fetch_one(&data, channel_uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
||||||
|
|
||||||
if let Some(new_name) = &new_info.name {
|
if let Some(new_name) = &new_info.name {
|
||||||
channel
|
channel.set_name(&data, new_name.to_string()).await?;
|
||||||
.set_name(&mut conn, &app_state.cache_pool, new_name.to_string())
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(new_description) = &new_info.description {
|
if let Some(new_description) = &new_info.description {
|
||||||
channel
|
channel
|
||||||
.set_description(
|
.set_description(&data, new_description.to_string())
|
||||||
&mut conn,
|
|
||||||
&app_state.cache_pool,
|
|
||||||
new_description.to_string(),
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(new_is_above) = &new_info.is_above {
|
if let Some(new_is_above) = &new_info.is_above {
|
||||||
channel
|
channel
|
||||||
.set_description(&mut conn, &app_state.cache_pool, new_is_above.to_string())
|
.set_description(&data, new_is_above.to_string())
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(channel)))
|
Ok(HttpResponse::Ok().json(channel))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,137 +1,109 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{
|
||||||
|
Error, HttpRequest, HttpResponse, get,
|
||||||
use axum::{
|
http::header::{HeaderValue, SEC_WEBSOCKET_PROTOCOL},
|
||||||
extract::{Path, State, WebSocketUpgrade, ws::Message},
|
rt, web,
|
||||||
http::HeaderMap,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
};
|
||||||
use futures_util::{SinkExt, StreamExt};
|
use actix_ws::AggregatedMessage;
|
||||||
use serde::Deserialize;
|
use futures_util::StreamExt as _;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::check_access_token,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
|
||||||
objects::{Channel, Member},
|
objects::{Channel, Member},
|
||||||
utils::global_checks,
|
utils::{get_ws_protocol_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[get("/{uuid}/socket")]
|
||||||
struct MessageBody {
|
|
||||||
message: String,
|
|
||||||
reply_to: Option<Uuid>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn ws(
|
pub async fn ws(
|
||||||
ws: WebSocketUpgrade,
|
req: HttpRequest,
|
||||||
State(app_state): State<Arc<AppState>>,
|
path: web::Path<(Uuid,)>,
|
||||||
Path(channel_uuid): Path<Uuid>,
|
stream: web::Payload,
|
||||||
headers: HeaderMap,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
|
// Get all headers
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
// Retrieve auth header
|
// Retrieve auth header
|
||||||
let auth_token = headers.get(axum::http::header::SEC_WEBSOCKET_PROTOCOL);
|
let auth_header = get_ws_protocol_header(headers)?;
|
||||||
|
|
||||||
if auth_token.is_none() {
|
// Get uuid from path
|
||||||
return Err(Error::Unauthorized(
|
let channel_uuid = path.into_inner().0;
|
||||||
"No authorization header provided".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let auth_raw = auth_token.unwrap().to_str()?;
|
let mut conn = data.pool.get().await.map_err(crate::error::Error::from)?;
|
||||||
|
|
||||||
let mut auth = auth_raw.split_whitespace();
|
|
||||||
|
|
||||||
let response_proto = auth.next();
|
|
||||||
|
|
||||||
let auth_value = auth.next();
|
|
||||||
|
|
||||||
if response_proto.is_none() {
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
"Sec-WebSocket-Protocol header is empty".to_string(),
|
|
||||||
));
|
|
||||||
} else if response_proto.is_some_and(|rp| rp != "Authorization,") {
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
"First protocol should be Authorization".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if auth_value.is_none() {
|
|
||||||
return Err(Error::BadRequest("No token provided".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let auth_header = auth_value.unwrap();
|
|
||||||
|
|
||||||
let mut conn = app_state
|
|
||||||
.pool
|
|
||||||
.get()
|
|
||||||
.await
|
|
||||||
.map_err(crate::error::Error::from)?;
|
|
||||||
|
|
||||||
// Authorize client using auth header
|
// Authorize client using auth header
|
||||||
let uuid = check_access_token(auth_header, &mut conn).await?;
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
let channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
|
let channel = Channel::fetch_one(&data, channel_uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
|
||||||
|
|
||||||
let mut pubsub = app_state
|
let (mut res, mut session_1, stream) = actix_ws::handle(&req, stream)?;
|
||||||
|
|
||||||
|
let mut stream = stream
|
||||||
|
.aggregate_continuations()
|
||||||
|
// aggregate continuation frames up to 1MiB
|
||||||
|
.max_continuation_size(2_usize.pow(20));
|
||||||
|
|
||||||
|
let mut pubsub = data
|
||||||
.cache_pool
|
.cache_pool
|
||||||
.get_async_pubsub()
|
.get_async_pubsub()
|
||||||
.await
|
.await
|
||||||
.map_err(crate::error::Error::from)?;
|
.map_err(crate::error::Error::from)?;
|
||||||
|
|
||||||
let mut res = ws.on_upgrade(async move |socket| {
|
let mut session_2 = session_1.clone();
|
||||||
let (mut sender, mut receiver) = socket.split();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
rt::spawn(async move {
|
||||||
pubsub.subscribe(channel_uuid.to_string()).await?;
|
pubsub.subscribe(channel_uuid.to_string()).await?;
|
||||||
while let Some(msg) = pubsub.on_message().next().await {
|
while let Some(msg) = pubsub.on_message().next().await {
|
||||||
let payload: String = msg.get_payload()?;
|
let payload: String = msg.get_payload()?;
|
||||||
sender.send(payload.into()).await?;
|
session_1.text(payload).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok::<(), crate::error::Error>(())
|
Ok::<(), crate::error::Error>(())
|
||||||
});
|
});
|
||||||
|
|
||||||
tokio::spawn(async move {
|
// start task but don't wait for it
|
||||||
while let Some(msg) = receiver.next().await {
|
rt::spawn(async move {
|
||||||
if let Ok(Message::Text(text)) = msg {
|
// receive messages from websocket
|
||||||
let message_body: MessageBody = serde_json::from_str(&text)?;
|
while let Some(msg) = stream.next().await {
|
||||||
|
match msg {
|
||||||
|
Ok(AggregatedMessage::Text(text)) => {
|
||||||
|
let mut conn = data.cache_pool.get_multiplexed_tokio_connection().await?;
|
||||||
|
|
||||||
let message = channel
|
let message = channel.new_message(&data, uuid, text.to_string()).await?;
|
||||||
.new_message(
|
|
||||||
&mut conn,
|
|
||||||
&app_state.cache_pool,
|
|
||||||
uuid,
|
|
||||||
message_body.message,
|
|
||||||
message_body.reply_to,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
redis::cmd("PUBLISH")
|
redis::cmd("PUBLISH")
|
||||||
.arg(&[channel_uuid.to_string(), serde_json::to_string(&message)?])
|
.arg(&[channel_uuid.to_string(), serde_json::to_string(&message)?])
|
||||||
.exec_async(
|
.exec_async(&mut conn)
|
||||||
&mut app_state
|
|
||||||
.cache_pool
|
|
||||||
.get_multiplexed_tokio_connection()
|
|
||||||
.await?,
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
Ok::<(), crate::error::Error>(())
|
Ok(AggregatedMessage::Binary(bin)) => {
|
||||||
});
|
// echo binary message
|
||||||
|
session_2.binary(bin).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(AggregatedMessage::Ping(msg)) => {
|
||||||
|
// respond to PING frame with PONG frame
|
||||||
|
session_2.pong(&msg).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok::<(), crate::error::Error>(())
|
||||||
});
|
});
|
||||||
|
|
||||||
let headers = res.headers_mut();
|
let headers = res.headers_mut();
|
||||||
|
|
||||||
headers.append(
|
headers.append(
|
||||||
axum::http::header::SEC_WEBSOCKET_PROTOCOL,
|
SEC_WEBSOCKET_PROTOCOL,
|
||||||
"Authorization".parse()?,
|
HeaderValue::from_str("Authorization")?,
|
||||||
);
|
);
|
||||||
|
|
||||||
// respond immediately with response connected to WS session
|
// respond immediately with response connected to WS session
|
||||||
|
|
44
src/api/v1/federation/mod.rs
Normal file
44
src/api/v1/federation/mod.rs
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
use actix_web::{post, web, HttpRequest, Scope};
|
||||||
|
|
||||||
|
use crate::{objects::Signature, Data};
|
||||||
|
|
||||||
|
mod pubkey;
|
||||||
|
|
||||||
|
pub fn web() -> Scope {
|
||||||
|
web::scope("/federation")
|
||||||
|
.service(pubkey::get)
|
||||||
|
.service(post)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("")]
|
||||||
|
pub async fn post(
|
||||||
|
req: HttpRequest,
|
||||||
|
channel_info: web::Json<>,
|
||||||
|
data: web::Data<Data>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let signature = Signature::from_signature_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
|
// FIXME: Logic to check permissions, should probably be done in utils.rs
|
||||||
|
|
||||||
|
let channel = Channel::new(
|
||||||
|
data.clone(),
|
||||||
|
guild_uuid,
|
||||||
|
channel_info.name.clone(),
|
||||||
|
channel_info.description.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(channel))
|
||||||
|
}
|
29
src/api/v1/federation/pubkey.rs
Normal file
29
src/api/v1/federation/pubkey.rs
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
//! `/api/v1/users/{uuid}` Specific user endpoints
|
||||||
|
|
||||||
|
use actix_web::{HttpResponse, get, web};
|
||||||
|
use ed25519_dalek::pkcs8::{spki::der::pem::LineEnding, EncodePublicKey};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
Data,
|
||||||
|
error::Error,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// `GET /api/v1/users/{uuid}` Returns user with the given UUID
|
||||||
|
///
|
||||||
|
/// requires auth: yes
|
||||||
|
///
|
||||||
|
/// requires relation: yes
|
||||||
|
///
|
||||||
|
/// ### Response Example
|
||||||
|
/// ```
|
||||||
|
/// ""
|
||||||
|
/// ```
|
||||||
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
|
#[get("/pubkey")]
|
||||||
|
pub async fn get(
|
||||||
|
data: web::Data<Data>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let pubkey = data.signing_key.verifying_key().to_public_key_pem(LineEnding::LF)?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().body(pubkey))
|
||||||
|
}
|
|
@ -1,37 +1,28 @@
|
||||||
//! `/api/v1/guilds` Guild related endpoints
|
//! `/api/v1/guilds` Guild related endpoints
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, Scope, get, post, web};
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
|
||||||
use axum::{
|
|
||||||
Extension, Json, Router,
|
|
||||||
extract::State,
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
routing::{get, post},
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
mod uuid;
|
mod uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Guild, StartAmountQuery},
|
objects::{Guild, StartAmountQuery},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct GuildInfo {
|
struct GuildInfo {
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
Router::new()
|
web::scope("/guilds")
|
||||||
.route("/", post(new))
|
.service(post)
|
||||||
.route("/", get(get_guilds))
|
.service(get)
|
||||||
.nest("/{uuid}", uuid::router())
|
.service(uuid::web())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `POST /api/v1/guilds` Creates a new guild
|
/// `POST /api/v1/guilds` Creates a new guild
|
||||||
|
@ -58,19 +49,23 @@ pub fn router() -> Router<Arc<AppState>> {
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
pub async fn new(
|
#[post("")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn post(
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
req: HttpRequest,
|
||||||
Json(guild_info): Json<GuildInfo>,
|
guild_info: web::Json<GuildInfo>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
let guild = Guild::new(
|
) -> Result<HttpResponse, Error> {
|
||||||
&mut app_state.pool.get().await?,
|
let headers = req.headers();
|
||||||
guild_info.name.clone(),
|
|
||||||
uuid,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(guild)))
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
let guild = Guild::new(&mut conn, guild_info.name.clone(), uuid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(guild))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/servers` Fetches all guilds
|
/// `GET /api/v1/servers` Fetches all guilds
|
||||||
|
@ -120,19 +115,25 @@ pub async fn new(
|
||||||
/// ]);
|
/// ]);
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
pub async fn get_guilds(
|
#[get("")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
req: HttpRequest,
|
||||||
Json(request_query): Json<StartAmountQuery>,
|
request_query: web::Query<StartAmountQuery>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let start = request_query.start.unwrap_or(0);
|
let start = request_query.start.unwrap_or(0);
|
||||||
|
|
||||||
let amount = request_query.amount.unwrap_or(10);
|
let amount = request_query.amount.unwrap_or(10);
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let uuid = check_access_token(auth_header, &mut data.pool.get().await?).await?;
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
let guilds = Guild::fetch_amount(&mut conn, start, amount).await?;
|
let guilds = Guild::fetch_amount(&data.pool, start, amount).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(guilds)))
|
Ok(HttpResponse::Ok().json(guilds))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,57 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
objects::{GuildBan, Member, Permissions},
|
|
||||||
utils::global_checks,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn get(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(guild_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let caller = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
|
||||||
caller
|
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::BanMember)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let all_guild_bans = GuildBan::fetch_all(&mut conn, guild_uuid).await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(all_guild_bans)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn unban(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path((guild_uuid, user_uuid)): Path<(Uuid, Uuid)>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let caller = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
|
||||||
caller
|
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::BanMember)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let ban = GuildBan::fetch_one(&mut conn, guild_uuid, user_uuid).await?;
|
|
||||||
|
|
||||||
ban.unban(&mut conn).await?;
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
|
|
@ -1,87 +1,90 @@
|
||||||
use std::sync::Arc;
|
use crate::{
|
||||||
|
Data,
|
||||||
use ::uuid::Uuid;
|
api::v1::auth::check_access_token,
|
||||||
use axum::{
|
error::Error,
|
||||||
Extension, Json,
|
objects::{Channel, Member},
|
||||||
extract::{Path, State},
|
utils::{get_auth_header, global_checks, order_by_is_above},
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
};
|
||||||
|
use ::uuid::Uuid;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
objects::{Channel, Member, Permissions},
|
|
||||||
utils::{CacheFns, global_checks, order_by_is_above},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct ChannelInfo {
|
struct ChannelInfo {
|
||||||
name: String,
|
name: String,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[get("{uuid}/channels")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
if let Ok(cache_hit) = app_state
|
if let Ok(cache_hit) = data.get_cache_key(format!("{}_channels", guild_uuid)).await {
|
||||||
.cache_pool
|
return Ok(HttpResponse::Ok()
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{guild_uuid}_channels"))
|
.content_type("application/json")
|
||||||
.await
|
.body(cache_hit));
|
||||||
{
|
|
||||||
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let channels = Channel::fetch_all(&mut conn, guild_uuid).await?;
|
let channels = Channel::fetch_all(&data.pool, guild_uuid).await?;
|
||||||
|
|
||||||
let channels_ordered = order_by_is_above(channels).await?;
|
let channels_ordered = order_by_is_above(channels).await?;
|
||||||
|
|
||||||
app_state
|
data.set_cache_key(
|
||||||
.cache_pool
|
format!("{}_channels", guild_uuid),
|
||||||
.set_cache_key(
|
channels_ordered.clone(),
|
||||||
format!("{guild_uuid}_channels"),
|
1800,
|
||||||
channels_ordered.clone(),
|
)
|
||||||
1800,
|
.await?;
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(channels_ordered)).into_response())
|
Ok(HttpResponse::Ok().json(channels_ordered))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("{uuid}/channels")]
|
||||||
pub async fn create(
|
pub async fn create(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
channel_info: web::Json<ChannelInfo>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
path: web::Path<(Uuid,)>,
|
||||||
Json(channel_info): Json<ChannelInfo>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
member
|
let mut conn = data.pool.get().await?;
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageChannel)
|
|
||||||
.await?;
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
|
// FIXME: Logic to check permissions, should probably be done in utils.rs
|
||||||
|
|
||||||
let channel = Channel::new(
|
let channel = Channel::new(
|
||||||
&mut conn,
|
data.clone(),
|
||||||
&app_state.cache_pool,
|
|
||||||
guild_uuid,
|
guild_uuid,
|
||||||
channel_info.name.clone(),
|
channel_info.name.clone(),
|
||||||
channel_info.description.clone(),
|
channel_info.description.clone(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(channel)))
|
Ok(HttpResponse::Ok().json(channel))
|
||||||
}
|
}
|
||||||
|
|
58
src/api/v1/guilds/uuid/icon.rs
Normal file
58
src/api/v1/guilds/uuid/icon.rs
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
//! `/api/v1/guilds/{uuid}/icon` icon related endpoints, will probably be replaced by a multipart post to above endpoint
|
||||||
|
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, put, web};
|
||||||
|
use futures_util::StreamExt as _;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
Data,
|
||||||
|
api::v1::auth::check_access_token,
|
||||||
|
error::Error,
|
||||||
|
objects::{Guild, Member},
|
||||||
|
utils::{get_auth_header, global_checks},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// `PUT /api/v1/guilds/{uuid}/icon` Icon upload
|
||||||
|
///
|
||||||
|
/// requires auth: no
|
||||||
|
///
|
||||||
|
/// put request expects a file and nothing else
|
||||||
|
#[put("{uuid}/icon")]
|
||||||
|
pub async fn upload(
|
||||||
|
req: HttpRequest,
|
||||||
|
path: web::Path<(Uuid,)>,
|
||||||
|
mut payload: web::Payload,
|
||||||
|
data: web::Data<Data>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
|
let mut guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
||||||
|
|
||||||
|
let mut bytes = web::BytesMut::new();
|
||||||
|
while let Some(item) = payload.next().await {
|
||||||
|
bytes.extend_from_slice(&item?);
|
||||||
|
}
|
||||||
|
|
||||||
|
guild
|
||||||
|
.set_icon(
|
||||||
|
&data.bunny_cdn,
|
||||||
|
&mut conn,
|
||||||
|
data.config.bunny.cdn_url.clone(),
|
||||||
|
bytes,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().finish())
|
||||||
|
}
|
|
@ -1,35 +1,37 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Guild, Member, Permissions},
|
objects::{Guild, Member},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct InviteRequest {
|
struct InviteRequest {
|
||||||
custom_id: Option<String>,
|
custom_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[get("{uuid}/invites")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
|
@ -37,30 +39,33 @@ pub async fn get(
|
||||||
|
|
||||||
let invites = guild.get_invites(&mut conn).await?;
|
let invites = guild.get_invites(&mut conn).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(invites)))
|
Ok(HttpResponse::Ok().json(invites))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("{uuid}/invites")]
|
||||||
pub async fn create(
|
pub async fn create(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
invite_request: web::Json<InviteRequest>,
|
||||||
Json(invite_request): Json<InviteRequest>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
member
|
let mut conn = data.pool.get().await?;
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::CreateInvite)
|
|
||||||
.await?;
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
||||||
|
|
||||||
let invite = guild
|
let invite = guild.create_invite(&mut conn, uuid, invite_request.custom_id.clone()).await?;
|
||||||
.create_invite(&mut conn, uuid, invite_request.custom_id.clone())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(invite)))
|
Ok(HttpResponse::Ok().json(invite))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,43 +1,34 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, Query, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Me, Member, PaginationRequest},
|
objects::Member,
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
use ::uuid::Uuid;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, get, web};
|
||||||
|
|
||||||
|
#[get("{uuid}/members")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Query(pagination): Query<PaginationRequest>,
|
data: web::Data<Data>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
) -> Result<HttpResponse, Error> {
|
||||||
) -> Result<impl IntoResponse, Error> {
|
let headers = req.headers();
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
let members = Member::fetch_all(&data, guild_uuid).await?;
|
||||||
|
|
||||||
let members = Member::fetch_page(
|
Ok(HttpResponse::Ok().json(members))
|
||||||
&mut conn,
|
|
||||||
&app_state.cache_pool,
|
|
||||||
&me,
|
|
||||||
guild_uuid,
|
|
||||||
pagination,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(members)))
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,51 +1,40 @@
|
||||||
//! `/api/v1/guilds/{uuid}` Specific server endpoints
|
//! `/api/v1/guilds/{uuid}` Specific server endpoints
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, Scope, get, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Json, Router,
|
|
||||||
extract::{Multipart, Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
routing::{delete, get, patch, post},
|
|
||||||
};
|
|
||||||
use bytes::Bytes;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
mod bans;
|
|
||||||
mod channels;
|
mod channels;
|
||||||
|
mod icon;
|
||||||
mod invites;
|
mod invites;
|
||||||
mod members;
|
mod members;
|
||||||
mod roles;
|
mod roles;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Guild, Member, Permissions},
|
objects::{Guild, Member},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
Router::new()
|
web::scope("")
|
||||||
// Servers
|
// Servers
|
||||||
.route("/", get(get_guild))
|
.service(get)
|
||||||
.route("/", patch(edit))
|
|
||||||
// Channels
|
// Channels
|
||||||
.route("/channels", get(channels::get))
|
.service(channels::get)
|
||||||
.route("/channels", post(channels::create))
|
.service(channels::create)
|
||||||
// Roles
|
// Roles
|
||||||
.route("/roles", get(roles::get))
|
.service(roles::get)
|
||||||
.route("/roles", post(roles::create))
|
.service(roles::create)
|
||||||
.route("/roles/{role_uuid}", get(roles::uuid::get))
|
.service(roles::uuid::get)
|
||||||
// Invites
|
// Invites
|
||||||
.route("/invites", get(invites::get))
|
.service(invites::get)
|
||||||
.route("/invites", post(invites::create))
|
.service(invites::create)
|
||||||
|
// Icon
|
||||||
|
.service(icon::upload)
|
||||||
// Members
|
// Members
|
||||||
.route("/members", get(members::get))
|
.service(members::get)
|
||||||
// Bans
|
|
||||||
.route("/bans", get(bans::get))
|
|
||||||
.route("/bans/{uuid}", delete(bans::unban))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/guilds/{uuid}` DESCRIPTION
|
/// `GET /api/v1/guilds/{uuid}` DESCRIPTION
|
||||||
|
@ -81,58 +70,27 @@ pub fn router() -> Router<Arc<AppState>> {
|
||||||
/// "member_count": 20
|
/// "member_count": 20
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn get_guild(
|
#[get("/{uuid}")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(
|
||||||
Path(guild_uuid): Path<Uuid>,
|
req: HttpRequest,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
path: web::Path<(Uuid,)>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
let mut conn = app_state.pool.get().await?;
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(guild)))
|
Ok(HttpResponse::Ok().json(guild))
|
||||||
}
|
|
||||||
|
|
||||||
/// `PATCH /api/v1/guilds/{uuid}` change guild settings
|
|
||||||
///
|
|
||||||
/// requires auth: yes
|
|
||||||
pub async fn edit(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(guild_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
mut multipart: Multipart,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
|
||||||
|
|
||||||
member
|
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageGuild)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
|
|
||||||
|
|
||||||
let mut icon: Option<Bytes> = None;
|
|
||||||
|
|
||||||
while let Some(field) = multipart.next_field().await.unwrap() {
|
|
||||||
let name = field
|
|
||||||
.name()
|
|
||||||
.ok_or(Error::BadRequest("Field has no name".to_string()))?;
|
|
||||||
|
|
||||||
if name == "icon" {
|
|
||||||
icon = Some(field.bytes().await?);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(icon) = icon {
|
|
||||||
guild.set_icon(&mut conn, &app_state, icon).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,77 +1,80 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
use ::uuid::Uuid;
|
||||||
use axum::{
|
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Member, Permissions, Role},
|
objects::{Member, Role},
|
||||||
utils::{CacheFns, global_checks, order_by_is_above},
|
utils::{get_auth_header, global_checks, order_by_is_above},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub mod uuid;
|
pub mod uuid;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct RoleInfo {
|
struct RoleInfo {
|
||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[get("{uuid}/roles")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
if let Ok(cache_hit) = app_state
|
if let Ok(cache_hit) = data.get_cache_key(format!("{}_roles", guild_uuid)).await {
|
||||||
.cache_pool
|
return Ok(HttpResponse::Ok()
|
||||||
.get_cache_key::<Vec<Role>>(format!("{guild_uuid}_roles"))
|
.content_type("application/json")
|
||||||
.await
|
.body(cache_hit));
|
||||||
{
|
|
||||||
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let roles = Role::fetch_all(&mut conn, guild_uuid).await?;
|
let roles = Role::fetch_all(&mut conn, guild_uuid).await?;
|
||||||
|
|
||||||
let roles_ordered = order_by_is_above(roles).await?;
|
let roles_ordered = order_by_is_above(roles).await?;
|
||||||
|
|
||||||
app_state
|
data.set_cache_key(format!("{}_roles", guild_uuid), roles_ordered.clone(), 1800)
|
||||||
.cache_pool
|
|
||||||
.set_cache_key(format!("{guild_uuid}_roles"), roles_ordered.clone(), 1800)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(roles_ordered)).into_response())
|
Ok(HttpResponse::Ok().json(roles_ordered))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("{uuid}/roles")]
|
||||||
pub async fn create(
|
pub async fn create(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(guild_uuid): Path<Uuid>,
|
role_info: web::Json<RoleInfo>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
path: web::Path<(Uuid,)>,
|
||||||
Json(role_info): Json<RoleInfo>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let member = Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
let guild_uuid = path.into_inner().0;
|
||||||
|
|
||||||
member
|
let mut conn = data.pool.get().await?;
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageRole)
|
|
||||||
.await?;
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
|
// FIXME: Logic to check permissions, should probably be done in utils.rs
|
||||||
|
|
||||||
let role = Role::new(&mut conn, guild_uuid, role_info.name.clone()).await?;
|
let role = Role::new(&mut conn, guild_uuid, role_info.name.clone()).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(role)).into_response())
|
Ok(HttpResponse::Ok().json(role))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,46 +1,43 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Member, Role},
|
objects::{Member, Role},
|
||||||
utils::{CacheFns, global_checks},
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
use ::uuid::Uuid;
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, get, web};
|
||||||
|
|
||||||
|
#[get("{uuid}/roles/{role_uuid}")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path((guild_uuid, role_uuid)): Path<(Uuid, Uuid)>,
|
path: web::Path<(Uuid, Uuid)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let (guild_uuid, role_uuid) = path.into_inner();
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
|
||||||
|
|
||||||
if let Ok(cache_hit) = app_state
|
if let Ok(cache_hit) = data.get_cache_key(format!("{}", role_uuid)).await {
|
||||||
.cache_pool
|
return Ok(HttpResponse::Ok()
|
||||||
.get_cache_key::<Role>(format!("{role_uuid}"))
|
.content_type("application/json")
|
||||||
.await
|
.body(cache_hit));
|
||||||
{
|
|
||||||
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let role = Role::fetch_one(&mut conn, role_uuid).await?;
|
let role = Role::fetch_one(&mut conn, role_uuid).await?;
|
||||||
|
|
||||||
app_state
|
data.set_cache_key(format!("{}", role_uuid), role.clone(), 60)
|
||||||
.cache_pool
|
|
||||||
.set_cache_key(format!("{role_uuid}"), role.clone(), 60)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(role)).into_response())
|
Ok(HttpResponse::Ok().json(role))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,48 +1,49 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, get, post, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Guild, Invite, Member},
|
objects::{Guild, Invite, Member},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn get(
|
#[get("{id}")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(path: web::Path<(String,)>, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
Path(invite_id): Path<String>,
|
let mut conn = data.pool.get().await?;
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let invite_id = path.into_inner().0;
|
||||||
|
|
||||||
let invite = Invite::fetch_one(&mut conn, invite_id).await?;
|
let invite = Invite::fetch_one(&mut conn, invite_id).await?;
|
||||||
|
|
||||||
let guild = Guild::fetch_one(&mut conn, invite.guild_uuid).await?;
|
let guild = Guild::fetch_one(&mut conn, invite.guild_uuid).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(guild)))
|
Ok(HttpResponse::Ok().json(guild))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[post("{id}")]
|
||||||
pub async fn join(
|
pub async fn join(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(invite_id): Path<String>,
|
path: web::Path<(String,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let invite_id = path.into_inner().0;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
let invite = Invite::fetch_one(&mut conn, invite_id).await?;
|
let invite = Invite::fetch_one(&mut conn, invite_id).await?;
|
||||||
|
|
||||||
let guild = Guild::fetch_one(&mut conn, invite.guild_uuid).await?;
|
let guild = Guild::fetch_one(&mut conn, invite.guild_uuid).await?;
|
||||||
|
|
||||||
Member::new(&mut conn, &app_state.cache_pool, uuid, guild.uuid).await?;
|
Member::new(&data, uuid, guild.uuid).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(guild)))
|
Ok(HttpResponse::Ok().json(guild))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,7 @@
|
||||||
use std::sync::Arc;
|
use actix_web::{Scope, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Router,
|
|
||||||
routing::{get, post},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
mod id;
|
mod id;
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
Router::new()
|
web::scope("/invites").service(id::get).service(id::join)
|
||||||
.route("/{id}", get(id::get))
|
|
||||||
.route("/{id}", post(id::join))
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,72 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
|
||||||
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
pub mod uuid;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
objects::Me,
|
|
||||||
utils::{global_checks, user_uuid_from_username},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Returns a list of users that are your friends
|
|
||||||
pub async fn get(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
|
||||||
|
|
||||||
let friends = me.get_friends(&mut conn, &app_state.cache_pool).await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(friends)))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
pub struct UserReq {
|
|
||||||
username: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `POST /api/v1/me/friends` Send friend request
|
|
||||||
///
|
|
||||||
/// requires auth? yes
|
|
||||||
///
|
|
||||||
/// ### Request Example:
|
|
||||||
/// ```
|
|
||||||
/// json!({
|
|
||||||
/// "uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
|
|
||||||
/// });
|
|
||||||
/// ```
|
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
|
||||||
///
|
|
||||||
/// ### Responses
|
|
||||||
/// 200 Success
|
|
||||||
///
|
|
||||||
/// 404 Not Found
|
|
||||||
///
|
|
||||||
/// 400 Bad Request (usually means users are already friends)
|
|
||||||
///
|
|
||||||
pub async fn post(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
Json(user_request): Json<UserReq>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
|
||||||
|
|
||||||
let target_uuid = user_uuid_from_username(&mut conn, &user_request.username).await?;
|
|
||||||
me.add_friend(&mut conn, target_uuid).await?;
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState, api::v1::auth::CurrentUser, error::Error, objects::Me, utils::global_checks,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn delete(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(friend_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
|
||||||
|
|
||||||
me.remove_friend(&mut conn, friend_uuid).await?;
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
|
|
@ -1,12 +1,13 @@
|
||||||
//! `/api/v1/me/guilds` Contains endpoint related to guild memberships
|
//! `/api/v1/me/guilds` Contains endpoint related to guild memberships
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, get, web};
|
||||||
|
|
||||||
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, api::v1::auth::CurrentUser, error::Error, objects::Me, utils::global_checks,
|
Data,
|
||||||
|
api::v1::auth::check_access_token,
|
||||||
|
error::Error,
|
||||||
|
objects::Me,
|
||||||
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// `GET /api/v1/me/guilds` Returns all guild memberships in a list
|
/// `GET /api/v1/me/guilds` Returns all guild memberships in a list
|
||||||
|
@ -54,17 +55,21 @@ use crate::{
|
||||||
/// ]);
|
/// ]);
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
pub async fn get(
|
#[get("/guilds")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(req: HttpRequest, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
let headers = req.headers();
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
let me = Me::get(&mut conn, uuid).await?;
|
||||||
|
|
||||||
let memberships = me.fetch_memberships(&mut conn).await?;
|
let memberships = me.fetch_memberships(&mut conn).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(memberships)))
|
Ok(HttpResponse::Ok().json(memberships))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,120 +1,104 @@
|
||||||
use std::sync::Arc;
|
use actix_multipart::form::{MultipartForm, json::Json as MpJson, tempfile::TempFile};
|
||||||
|
use actix_web::{HttpRequest, HttpResponse, Scope, get, patch, web};
|
||||||
use axum::{
|
|
||||||
Extension, Json, Router,
|
|
||||||
extract::{DefaultBodyLimit, Multipart, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
routing::{delete, get, patch, post},
|
|
||||||
};
|
|
||||||
use bytes::Bytes;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, api::v1::auth::CurrentUser, error::Error, objects::Me, utils::global_checks,
|
Data,
|
||||||
|
api::v1::auth::check_access_token,
|
||||||
|
error::Error,
|
||||||
|
objects::Me,
|
||||||
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
mod friends;
|
|
||||||
mod guilds;
|
mod guilds;
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
Router::new()
|
web::scope("/me")
|
||||||
.route("/", get(get_me))
|
.service(get)
|
||||||
.route(
|
.service(update)
|
||||||
"/",
|
.service(guilds::get)
|
||||||
patch(update).layer(DefaultBodyLimit::max(
|
|
||||||
100 * 1024 * 1024, /* limit is in bytes */
|
|
||||||
)),
|
|
||||||
)
|
|
||||||
.route("/guilds", get(guilds::get))
|
|
||||||
.route("/friends", get(friends::get))
|
|
||||||
.route("/friends", post(friends::post))
|
|
||||||
.route("/friends/{uuid}", delete(friends::uuid::delete))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_me(
|
#[get("")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(req: HttpRequest, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
let headers = req.headers();
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let me = Me::get(&mut app_state.pool.get().await?, uuid).await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(me)))
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
let me = Me::get(&mut conn, uuid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(me))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Debug, Deserialize, Clone)]
|
#[derive(Debug, Deserialize, Clone)]
|
||||||
struct NewInfo {
|
struct NewInfo {
|
||||||
username: Option<String>,
|
username: Option<String>,
|
||||||
display_name: Option<String>,
|
display_name: Option<String>,
|
||||||
|
//password: Option<String>, will probably be handled through a reset password link
|
||||||
email: Option<String>,
|
email: Option<String>,
|
||||||
pronouns: Option<String>,
|
pronouns: Option<String>,
|
||||||
about: Option<String>,
|
about: Option<String>,
|
||||||
online_status: Option<i16>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, MultipartForm)]
|
||||||
|
struct UploadForm {
|
||||||
|
#[multipart(limit = "100MB")]
|
||||||
|
avatar: Option<TempFile>,
|
||||||
|
json: MpJson<NewInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[patch("")]
|
||||||
pub async fn update(
|
pub async fn update(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
MultipartForm(form): MultipartForm<UploadForm>,
|
||||||
mut multipart: Multipart,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut json_raw: Option<NewInfo> = None;
|
let headers = req.headers();
|
||||||
let mut avatar: Option<Bytes> = None;
|
|
||||||
|
|
||||||
while let Some(field) = multipart.next_field().await.unwrap() {
|
let auth_header = get_auth_header(headers)?;
|
||||||
let name = field
|
|
||||||
.name()
|
|
||||||
.ok_or(Error::BadRequest("Field has no name".to_string()))?;
|
|
||||||
|
|
||||||
if name == "avatar" {
|
let mut conn = data.pool.get().await?;
|
||||||
avatar = Some(field.bytes().await?);
|
|
||||||
} else if name == "json" {
|
|
||||||
json_raw = Some(serde_json::from_str(&field.text().await?)?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let json = json_raw.unwrap_or_default();
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
if form.avatar.is_some() || form.json.username.is_some() || form.json.display_name.is_some() {
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
if avatar.is_some() || json.username.is_some() || json.display_name.is_some() {
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut me = Me::get(&mut conn, uuid).await?;
|
let mut me = Me::get(&mut conn, uuid).await?;
|
||||||
|
|
||||||
if let Some(avatar) = avatar {
|
if let Some(avatar) = form.avatar {
|
||||||
me.set_avatar(&mut conn, &app_state, avatar).await?;
|
let bytes = tokio::fs::read(avatar.file).await?;
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(username) = &json.username {
|
let byte_slice: &[u8] = &bytes;
|
||||||
me.set_username(&mut conn, &app_state.cache_pool, username.clone())
|
|
||||||
|
me.set_avatar(&data, data.config.bunny.cdn_url.clone(), byte_slice.into())
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(display_name) = &json.display_name {
|
if let Some(username) = &form.json.username {
|
||||||
me.set_display_name(&mut conn, &app_state.cache_pool, display_name.clone())
|
me.set_username(&data, username.clone()).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(email) = &json.email {
|
if let Some(display_name) = &form.json.display_name {
|
||||||
me.set_email(&mut conn, &app_state.cache_pool, email.clone())
|
me.set_display_name(&data, display_name.clone()).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(pronouns) = &json.pronouns {
|
if let Some(email) = &form.json.email {
|
||||||
me.set_pronouns(&mut conn, &app_state.cache_pool, pronouns.clone())
|
me.set_email(&data, email.clone()).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(about) = &json.about {
|
if let Some(pronouns) = &form.json.pronouns {
|
||||||
me.set_about(&mut conn, &app_state.cache_pool, about.clone())
|
me.set_pronouns(&data, pronouns.clone()).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(online_status) = &json.online_status {
|
if let Some(about) = &form.json.about {
|
||||||
me.set_online_status(&mut conn, &app_state.cache_pool, *online_status)
|
me.set_about(&data, about.clone()).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
Ok(HttpResponse::Ok().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Router,
|
|
||||||
routing::{delete, get, post},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
mod uuid;
|
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
|
||||||
Router::new()
|
|
||||||
.route("/{uuid}", get(uuid::get))
|
|
||||||
.route("/{uuid}", delete(uuid::delete))
|
|
||||||
.route("/{uuid}/ban", post(uuid::ban::post))
|
|
||||||
}
|
|
|
@ -1,48 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension,
|
|
||||||
extract::{Json, Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
objects::{Member, Permissions},
|
|
||||||
utils::global_checks,
|
|
||||||
};
|
|
||||||
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
pub struct RequstBody {
|
|
||||||
reason: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn post(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(member_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
Json(payload): Json<RequstBody>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let member =
|
|
||||||
Member::fetch_one_with_uuid(&mut conn, &app_state.cache_pool, None, member_uuid).await?;
|
|
||||||
|
|
||||||
let caller = Member::check_membership(&mut conn, uuid, member.guild_uuid).await?;
|
|
||||||
|
|
||||||
caller
|
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::BanMember)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
member.ban(&mut conn, &payload.reason).await?;
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
|
|
@ -1,66 +0,0 @@
|
||||||
//! `/api/v1/members/{uuid}` Member specific endpoints
|
|
||||||
|
|
||||||
pub mod ban;
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
AppState,
|
|
||||||
api::v1::auth::CurrentUser,
|
|
||||||
error::Error,
|
|
||||||
objects::{Me, Member, Permissions},
|
|
||||||
utils::global_checks,
|
|
||||||
};
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
pub async fn get(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(member_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
|
||||||
|
|
||||||
let member =
|
|
||||||
Member::fetch_one_with_uuid(&mut conn, &app_state.cache_pool, Some(&me), member_uuid)
|
|
||||||
.await?;
|
|
||||||
Member::check_membership(&mut conn, uuid, member.guild_uuid).await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(member)))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn delete(
|
|
||||||
State(app_state): State<Arc<AppState>>,
|
|
||||||
Path(member_uuid): Path<Uuid>,
|
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
|
||||||
) -> Result<impl IntoResponse, Error> {
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
|
||||||
|
|
||||||
let member =
|
|
||||||
Member::fetch_one_with_uuid(&mut conn, &app_state.cache_pool, Some(&me), member_uuid)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let deleter = Member::check_membership(&mut conn, uuid, member.guild_uuid).await?;
|
|
||||||
|
|
||||||
deleter
|
|
||||||
.check_permission(&mut conn, &app_state.cache_pool, Permissions::KickMember)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
member.delete(&mut conn).await?;
|
|
||||||
|
|
||||||
Ok(StatusCode::OK)
|
|
||||||
}
|
|
|
@ -1,35 +1,24 @@
|
||||||
//! `/api/v1` Contains version 1 of the api
|
//! `/api/v1` Contains version 1 of the api
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{Scope, web};
|
||||||
|
|
||||||
use axum::{Router, middleware::from_fn_with_state, routing::get};
|
|
||||||
|
|
||||||
use crate::{AppState, api::v1::auth::CurrentUser};
|
|
||||||
|
|
||||||
mod auth;
|
mod auth;
|
||||||
mod channels;
|
mod channels;
|
||||||
mod guilds;
|
mod guilds;
|
||||||
mod invites;
|
mod invites;
|
||||||
mod me;
|
mod me;
|
||||||
mod members;
|
|
||||||
mod stats;
|
mod stats;
|
||||||
mod users;
|
mod users;
|
||||||
|
mod federation;
|
||||||
|
|
||||||
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
let router_with_auth = Router::new()
|
web::scope("/v1")
|
||||||
.nest("/users", users::router())
|
.service(stats::res)
|
||||||
.nest("/guilds", guilds::router())
|
.service(auth::web())
|
||||||
.nest("/invites", invites::router())
|
.service(users::web())
|
||||||
.nest("/members", members::router())
|
.service(channels::web())
|
||||||
.nest("/me", me::router())
|
.service(guilds::web())
|
||||||
.layer(from_fn_with_state(
|
.service(invites::web())
|
||||||
app_state.clone(),
|
.service(me::web())
|
||||||
CurrentUser::check_auth_layer,
|
.service(federation::web())
|
||||||
));
|
|
||||||
|
|
||||||
Router::new()
|
|
||||||
.route("/stats", get(stats::res))
|
|
||||||
.nest("/auth", auth::router(app_state.clone()))
|
|
||||||
.nest("/channels", channels::router(app_state))
|
|
||||||
.merge(router_with_auth)
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,17 +1,13 @@
|
||||||
//! `/api/v1/stats` Returns stats about the server
|
//! `/api/v1/stats` Returns stats about the server
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
|
||||||
use axum::Json;
|
use actix_web::{HttpResponse, get, web};
|
||||||
use axum::extract::State;
|
|
||||||
use axum::http::StatusCode;
|
|
||||||
use axum::response::IntoResponse;
|
|
||||||
use diesel::QueryDsl;
|
use diesel::QueryDsl;
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::AppState;
|
use crate::Data;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::schema::users::dsl::{users, uuid};
|
use crate::schema::users::dsl::{users, uuid};
|
||||||
|
|
||||||
|
@ -43,26 +39,27 @@ struct Response {
|
||||||
/// "build_number": "39d01bb"
|
/// "build_number": "39d01bb"
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn res(State(app_state): State<Arc<AppState>>) -> Result<impl IntoResponse, Error> {
|
#[get("/stats")]
|
||||||
|
pub async fn res(data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
let accounts: i64 = users
|
let accounts: i64 = users
|
||||||
.select(uuid)
|
.select(uuid)
|
||||||
.count()
|
.count()
|
||||||
.get_result(&mut app_state.pool.get().await?)
|
.get_result(&mut data.pool.get().await?)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let response = Response {
|
let response = Response {
|
||||||
// TODO: Get number of accounts from db
|
// TODO: Get number of accounts from db
|
||||||
accounts,
|
accounts,
|
||||||
uptime: SystemTime::now()
|
uptime: SystemTime::now()
|
||||||
.duration_since(app_state.start_time)
|
.duration_since(data.start_time)
|
||||||
.expect("Seriously why dont you have time??")
|
.expect("Seriously why dont you have time??")
|
||||||
.as_secs(),
|
.as_secs(),
|
||||||
version: String::from(VERSION.unwrap_or("UNKNOWN")),
|
version: String::from(VERSION.unwrap_or("UNKNOWN")),
|
||||||
registration_enabled: app_state.config.instance.registration,
|
registration_enabled: data.config.instance.registration,
|
||||||
email_verification_required: app_state.config.instance.require_email_verification,
|
email_verification_required: data.config.instance.require_email_verification,
|
||||||
// TODO: Get build number from git hash or remove this from the spec
|
// TODO: Get build number from git hash or remove this from the spec
|
||||||
build_number: String::from(GIT_SHORT_HASH),
|
build_number: String::from(GIT_SHORT_HASH),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(response)))
|
Ok(HttpResponse::Ok().json(response))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,30 +1,19 @@
|
||||||
//! `/api/v1/users` Contains endpoints related to all users
|
//! `/api/v1/users` Contains endpoints related to all users
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, Scope, get, web};
|
||||||
|
|
||||||
use ::uuid::Uuid;
|
|
||||||
use axum::{
|
|
||||||
Extension, Json, Router,
|
|
||||||
extract::{Query, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
routing::get,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{StartAmountQuery, User},
|
objects::{StartAmountQuery, User},
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
mod uuid;
|
mod uuid;
|
||||||
|
|
||||||
pub fn router() -> Router<Arc<AppState>> {
|
pub fn web() -> Scope {
|
||||||
Router::new()
|
web::scope("/users").service(get).service(uuid::get)
|
||||||
.route("/", get(users))
|
|
||||||
.route("/{uuid}", get(uuid::get))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `GET /api/v1/users` Returns all users on this instance
|
/// `GET /api/v1/users` Returns all users on this instance
|
||||||
|
@ -57,24 +46,31 @@ pub fn router() -> Router<Arc<AppState>> {
|
||||||
/// ]);
|
/// ]);
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
pub async fn users(
|
#[get("")]
|
||||||
State(app_state): State<Arc<AppState>>,
|
pub async fn get(
|
||||||
Query(request_query): Query<StartAmountQuery>,
|
req: HttpRequest,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
request_query: web::Query<StartAmountQuery>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
data: web::Data<Data>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let headers = req.headers();
|
||||||
|
|
||||||
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let start = request_query.start.unwrap_or(0);
|
let start = request_query.start.unwrap_or(0);
|
||||||
|
|
||||||
let amount = request_query.amount.unwrap_or(10);
|
let amount = request_query.amount.unwrap_or(10);
|
||||||
|
|
||||||
if amount > 100 {
|
if amount > 100 {
|
||||||
return Ok(StatusCode::BAD_REQUEST.into_response());
|
return Ok(HttpResponse::BadRequest().finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut conn = app_state.pool.get().await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
let users = User::fetch_amount(&mut conn, start, amount).await?;
|
let users = User::fetch_amount(&mut conn, start, amount).await?;
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(users)).into_response())
|
Ok(HttpResponse::Ok().json(users))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,21 +1,14 @@
|
||||||
//! `/api/v1/users/{uuid}` Specific user endpoints
|
//! `/api/v1/users/{uuid}` Specific user endpoints
|
||||||
|
|
||||||
use std::sync::Arc;
|
use actix_web::{HttpRequest, HttpResponse, get, web};
|
||||||
|
|
||||||
use axum::{
|
|
||||||
Extension, Json,
|
|
||||||
extract::{Path, State},
|
|
||||||
http::StatusCode,
|
|
||||||
response::IntoResponse,
|
|
||||||
};
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState,
|
Data,
|
||||||
api::v1::auth::CurrentUser,
|
api::v1::auth::check_access_token,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Me, User},
|
objects::User,
|
||||||
utils::global_checks,
|
utils::{get_auth_header, global_checks},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// `GET /api/v1/users/{uuid}` Returns user with the given UUID
|
/// `GET /api/v1/users/{uuid}` Returns user with the given UUID
|
||||||
|
@ -34,19 +27,25 @@ use crate::{
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
/// NOTE: UUIDs in this response are made using `uuidgen`, UUIDs made by the actual backend will be UUIDv7 and have extractable timestamps
|
||||||
|
#[get("/{uuid}")]
|
||||||
pub async fn get(
|
pub async fn get(
|
||||||
State(app_state): State<Arc<AppState>>,
|
req: HttpRequest,
|
||||||
Path(user_uuid): Path<Uuid>,
|
path: web::Path<(Uuid,)>,
|
||||||
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
|
data: web::Data<Data>,
|
||||||
) -> Result<impl IntoResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
let mut conn = app_state.pool.get().await?;
|
let headers = req.headers();
|
||||||
|
|
||||||
global_checks(&mut conn, &app_state.config, uuid).await?;
|
let user_uuid = path.into_inner().0;
|
||||||
|
|
||||||
let me = Me::get(&mut conn, uuid).await?;
|
let auth_header = get_auth_header(headers)?;
|
||||||
|
|
||||||
let user =
|
let mut conn = data.pool.get().await?;
|
||||||
User::fetch_one_with_friendship(&mut conn, &app_state.cache_pool, &me, user_uuid).await?;
|
|
||||||
|
|
||||||
Ok((StatusCode::OK, Json(user)))
|
let uuid = check_access_token(auth_header, &mut conn).await?;
|
||||||
|
|
||||||
|
global_checks(&data, uuid).await?;
|
||||||
|
|
||||||
|
let user = User::fetch_one(&data, user_uuid).await?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(user))
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
//! `/api/v1/versions` Returns info about api versions
|
//! `/api/v1/versions` Returns info about api versions
|
||||||
use axum::{Json, http::StatusCode, response::IntoResponse};
|
use actix_web::{HttpResponse, Responder, get};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
|
@ -24,12 +24,13 @@ struct UnstableFeatures;
|
||||||
/// ]
|
/// ]
|
||||||
/// });
|
/// });
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn versions() -> impl IntoResponse {
|
#[get("/versions")]
|
||||||
|
pub async fn get() -> impl Responder {
|
||||||
let response = Response {
|
let response = Response {
|
||||||
unstable_features: UnstableFeatures,
|
unstable_features: UnstableFeatures,
|
||||||
// TODO: Find a way to dynamically update this possibly?
|
// TODO: Find a way to dynamically update this possibly?
|
||||||
versions: vec![String::from("1")],
|
versions: vec![String::from("1")],
|
||||||
};
|
};
|
||||||
|
|
||||||
(StatusCode::OK, Json(response))
|
HttpResponse::Ok().json(response)
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,7 +5,6 @@ use log::debug;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tokio::fs::read_to_string;
|
use tokio::fs::read_to_string;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct ConfigBuilder {
|
pub struct ConfigBuilder {
|
||||||
|
@ -49,7 +48,6 @@ struct InstanceBuilder {
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
registration: Option<bool>,
|
registration: Option<bool>,
|
||||||
require_email_verification: Option<bool>,
|
require_email_verification: Option<bool>,
|
||||||
initial_guild: Option<Uuid>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
@ -76,7 +74,7 @@ pub struct Smtp {
|
||||||
|
|
||||||
impl ConfigBuilder {
|
impl ConfigBuilder {
|
||||||
pub async fn load(path: String) -> Result<Self, Error> {
|
pub async fn load(path: String) -> Result<Self, Error> {
|
||||||
debug!("loading config from: {path}");
|
debug!("loading config from: {}", path);
|
||||||
let raw = read_to_string(path).await?;
|
let raw = read_to_string(path).await?;
|
||||||
|
|
||||||
let config = toml::from_str(&raw)?;
|
let config = toml::from_str(&raw)?;
|
||||||
|
@ -121,13 +119,11 @@ impl ConfigBuilder {
|
||||||
name: instance.name.unwrap_or("Gorb".to_string()),
|
name: instance.name.unwrap_or("Gorb".to_string()),
|
||||||
registration: instance.registration.unwrap_or(true),
|
registration: instance.registration.unwrap_or(true),
|
||||||
require_email_verification: instance.require_email_verification.unwrap_or(false),
|
require_email_verification: instance.require_email_verification.unwrap_or(false),
|
||||||
initial_guild: instance.initial_guild,
|
|
||||||
},
|
},
|
||||||
None => Instance {
|
None => Instance {
|
||||||
name: "Gorb".to_string(),
|
name: "Gorb".to_string(),
|
||||||
registration: true,
|
registration: true,
|
||||||
require_email_verification: false,
|
require_email_verification: false,
|
||||||
initial_guild: None,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -165,7 +161,6 @@ pub struct Instance {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub registration: bool,
|
pub registration: bool,
|
||||||
pub require_email_verification: bool,
|
pub require_email_verification: bool,
|
||||||
pub initial_guild: Option<Uuid>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
|
|
78
src/error.rs
78
src/error.rs
|
@ -1,21 +1,18 @@
|
||||||
use std::{io, time::SystemTimeError};
|
use std::{io, time::SystemTimeError};
|
||||||
|
|
||||||
use axum::{
|
use actix_web::{
|
||||||
Json,
|
HttpResponse,
|
||||||
extract::{
|
error::{PayloadError, ResponseError},
|
||||||
multipart::MultipartError,
|
|
||||||
rejection::{JsonRejection, QueryRejection},
|
|
||||||
},
|
|
||||||
http::{
|
http::{
|
||||||
StatusCode,
|
StatusCode,
|
||||||
header::{InvalidHeaderValue, ToStrError},
|
header::{ContentType, ToStrError},
|
||||||
},
|
},
|
||||||
response::IntoResponse,
|
|
||||||
};
|
};
|
||||||
use bunny_api_tokio::error::Error as BunnyError;
|
use bunny_api_tokio::error::Error as BunnyError;
|
||||||
use deadpool::managed::{BuildError, PoolError};
|
use deadpool::managed::{BuildError, PoolError};
|
||||||
use diesel::{ConnectionError, result::Error as DieselError};
|
use diesel::{ConnectionError, result::Error as DieselError};
|
||||||
use diesel_async::pooled_connection::PoolError as DieselPoolError;
|
use diesel_async::pooled_connection::PoolError as DieselPoolError;
|
||||||
|
use ed25519_dalek::pkcs8::{self, spki};
|
||||||
use lettre::{
|
use lettre::{
|
||||||
address::AddressError, error::Error as EmailError, transport::smtp::Error as SmtpError,
|
address::AddressError, error::Error as EmailError, transport::smtp::Error as SmtpError,
|
||||||
};
|
};
|
||||||
|
@ -58,19 +55,19 @@ pub enum Error {
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
UrlParseError(#[from] url::ParseError),
|
UrlParseError(#[from] url::ParseError),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
JsonRejection(#[from] JsonRejection),
|
PayloadError(#[from] PayloadError),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
QueryRejection(#[from] QueryRejection),
|
WsClosed(#[from] actix_ws::Closed),
|
||||||
#[error(transparent)]
|
|
||||||
MultipartError(#[from] MultipartError),
|
|
||||||
#[error(transparent)]
|
|
||||||
InvalidHeaderValue(#[from] InvalidHeaderValue),
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
EmailError(#[from] EmailError),
|
EmailError(#[from] EmailError),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
SmtpError(#[from] SmtpError),
|
SmtpError(#[from] SmtpError),
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
SmtpAddressError(#[from] AddressError),
|
SmtpAddressError(#[from] AddressError),
|
||||||
|
#[error(transparent)]
|
||||||
|
Pkcs8Error(#[from] pkcs8::Error),
|
||||||
|
#[error(transparent)]
|
||||||
|
SpkiError(#[from] spki::Error),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
PasswordHashError(String),
|
PasswordHashError(String),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
|
@ -83,45 +80,28 @@ pub enum Error {
|
||||||
TooManyRequests(String),
|
TooManyRequests(String),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
InternalServerError(String),
|
InternalServerError(String),
|
||||||
// TODO: remove when doing socket.io
|
|
||||||
#[error(transparent)]
|
|
||||||
AxumError(#[from] axum::Error),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for Error {
|
impl ResponseError for Error {
|
||||||
fn into_response(self) -> axum::response::Response {
|
fn error_response(&self) -> HttpResponse {
|
||||||
let error = match self {
|
debug!("{:?}", self);
|
||||||
Error::SqlError(DieselError::NotFound) => {
|
error!("{}: {}", self.status_code(), self);
|
||||||
(StatusCode::NOT_FOUND, Json(WebError::new(self.to_string())))
|
|
||||||
}
|
|
||||||
Error::BunnyError(BunnyError::NotFound(_)) => {
|
|
||||||
(StatusCode::NOT_FOUND, Json(WebError::new(self.to_string())))
|
|
||||||
}
|
|
||||||
Error::BadRequest(_) => (
|
|
||||||
StatusCode::BAD_REQUEST,
|
|
||||||
Json(WebError::new(self.to_string())),
|
|
||||||
),
|
|
||||||
Error::Unauthorized(_) => (
|
|
||||||
StatusCode::UNAUTHORIZED,
|
|
||||||
Json(WebError::new(self.to_string())),
|
|
||||||
),
|
|
||||||
Error::Forbidden(_) => (StatusCode::FORBIDDEN, Json(WebError::new(self.to_string()))),
|
|
||||||
Error::TooManyRequests(_) => (
|
|
||||||
StatusCode::TOO_MANY_REQUESTS,
|
|
||||||
Json(WebError::new(self.to_string())),
|
|
||||||
),
|
|
||||||
_ => (
|
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
Json(WebError::new(self.to_string())),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
let (code, _) = error;
|
HttpResponse::build(self.status_code())
|
||||||
|
.insert_header(ContentType::json())
|
||||||
|
.json(WebError::new(self.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
debug!("{self:?}");
|
fn status_code(&self) -> StatusCode {
|
||||||
error!("{code}: {self}");
|
match *self {
|
||||||
|
Error::SqlError(DieselError::NotFound) => StatusCode::NOT_FOUND,
|
||||||
error.into_response()
|
Error::BunnyError(BunnyError::NotFound(_)) => StatusCode::NOT_FOUND,
|
||||||
|
Error::BadRequest(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Error::Unauthorized(_) => StatusCode::UNAUTHORIZED,
|
||||||
|
Error::Forbidden(_) => StatusCode::FORBIDDEN,
|
||||||
|
Error::TooManyRequests(_) => StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
145
src/main.rs
145
src/main.rs
|
@ -1,17 +1,18 @@
|
||||||
use argon2::Argon2;
|
use actix_cors::Cors;
|
||||||
use axum::{
|
use actix_web::{App, HttpServer, web};
|
||||||
Router,
|
use argon2::{password_hash::rand_core::OsRng, Argon2};
|
||||||
http::{Method, header},
|
|
||||||
};
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use config::{Config, ConfigBuilder};
|
|
||||||
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
|
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
|
||||||
use diesel_async::pooled_connection::deadpool::Pool;
|
use diesel_async::pooled_connection::deadpool::Pool;
|
||||||
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
|
use ed25519_dalek::{pkcs8::{spki::der::pem::LineEnding, DecodePrivateKey, EncodePrivateKey}, SigningKey};
|
||||||
use error::Error;
|
use error::Error;
|
||||||
use objects::MailClient;
|
use objects::MailClient;
|
||||||
use std::{sync::Arc, time::SystemTime};
|
use simple_logger::SimpleLogger;
|
||||||
use tower_http::cors::{AllowOrigin, CorsLayer};
|
use tokio::{fs::{read_to_string, File}, io::AsyncWriteExt};
|
||||||
|
use std::time::SystemTime;
|
||||||
|
mod config;
|
||||||
|
use config::{Config, ConfigBuilder};
|
||||||
|
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
|
||||||
|
|
||||||
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
|
||||||
|
|
||||||
|
@ -19,23 +20,22 @@ type Conn =
|
||||||
deadpool::managed::Object<AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>>;
|
deadpool::managed::Object<AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>>;
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod config;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod objects;
|
pub mod objects;
|
||||||
pub mod schema;
|
pub mod schema;
|
||||||
//mod socket;
|
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
mod wordlist;
|
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(version, about, long_about = None)]
|
#[command(version, about, long_about = None)]
|
||||||
struct Args {
|
struct Args {
|
||||||
#[arg(short, long, default_value_t = String::from("/etc/gorb/config.toml"))]
|
#[arg(short, long, default_value_t = String::from("/etc/gorb/config.toml"))]
|
||||||
config: String,
|
config: String,
|
||||||
|
#[arg(short, long, default_value_t = String::from("/etc/gorb/privkey.pem"))]
|
||||||
|
private_key: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppState {
|
pub struct Data {
|
||||||
pub pool: deadpool::managed::Pool<
|
pub pool: deadpool::managed::Pool<
|
||||||
AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>,
|
AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>,
|
||||||
Conn,
|
Conn,
|
||||||
|
@ -44,14 +44,19 @@ pub struct AppState {
|
||||||
pub config: Config,
|
pub config: Config,
|
||||||
pub argon2: Argon2<'static>,
|
pub argon2: Argon2<'static>,
|
||||||
pub start_time: SystemTime,
|
pub start_time: SystemTime,
|
||||||
pub bunny_storage: bunny_api_tokio::EdgeStorageClient,
|
pub bunny_cdn: bunny_api_tokio::Client,
|
||||||
pub mail_client: MailClient,
|
pub mail_client: MailClient,
|
||||||
|
pub signing_key: SigningKey,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Error> {
|
async fn main() -> Result<(), Error> {
|
||||||
tracing_subscriber::fmt::init();
|
SimpleLogger::new()
|
||||||
|
.with_level(log::LevelFilter::Info)
|
||||||
|
.with_colors(true)
|
||||||
|
.env()
|
||||||
|
.init()
|
||||||
|
.unwrap();
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
let config = ConfigBuilder::load(args.config).await?.build();
|
let config = ConfigBuilder::load(args.config).await?.build();
|
||||||
|
@ -65,11 +70,14 @@ async fn main() -> Result<(), Error> {
|
||||||
|
|
||||||
let cache_pool = redis::Client::open(config.cache_database.url())?;
|
let cache_pool = redis::Client::open(config.cache_database.url())?;
|
||||||
|
|
||||||
|
let mut bunny_cdn = bunny_api_tokio::Client::new("").await?;
|
||||||
|
|
||||||
let bunny = config.bunny.clone();
|
let bunny = config.bunny.clone();
|
||||||
|
|
||||||
let bunny_storage =
|
bunny_cdn
|
||||||
bunny_api_tokio::EdgeStorageClient::new(bunny.api_key, bunny.endpoint, bunny.storage_zone)
|
.storage
|
||||||
.await?;
|
.init(bunny.api_key, bunny.endpoint, bunny.storage_zone)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let mail = config.mail.clone();
|
let mail = config.mail.clone();
|
||||||
|
|
||||||
|
@ -95,6 +103,18 @@ async fn main() -> Result<(), Error> {
|
||||||
.await?
|
.await?
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
let signing_key;
|
||||||
|
|
||||||
|
if let Ok(content) = read_to_string(&args.private_key).await {
|
||||||
|
signing_key = SigningKey::from_pkcs8_pem(&content)?;
|
||||||
|
} else {
|
||||||
|
let mut csprng = OsRng;
|
||||||
|
signing_key = tokio::task::spawn_blocking(move || SigningKey::generate(&mut csprng)).await?;
|
||||||
|
|
||||||
|
let mut file = File::create(args.private_key).await?;
|
||||||
|
file.write_all(signing_key.to_pkcs8_pem(LineEnding::LF)?.as_bytes()).await?;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
**Stored for later possible use**
|
**Stored for later possible use**
|
||||||
|
|
||||||
|
@ -112,65 +132,52 @@ async fn main() -> Result<(), Error> {
|
||||||
)
|
)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
let app_state = Arc::new(AppState {
|
let data = Data {
|
||||||
pool,
|
pool,
|
||||||
cache_pool,
|
cache_pool,
|
||||||
config,
|
config,
|
||||||
// TODO: Possibly implement "pepper" into this (thinking it could generate one if it doesnt exist and store it on disk)
|
// TODO: Possibly implement "pepper" into this (thinking it could generate one if it doesnt exist and store it on disk)
|
||||||
argon2: Argon2::default(),
|
argon2: Argon2::default(),
|
||||||
start_time: SystemTime::now(),
|
start_time: SystemTime::now(),
|
||||||
bunny_storage,
|
bunny_cdn,
|
||||||
mail_client,
|
mail_client,
|
||||||
});
|
signing_key,
|
||||||
|
};
|
||||||
|
|
||||||
let cors = CorsLayer::new()
|
HttpServer::new(move || {
|
||||||
// Allow any origin (equivalent to allowed_origin_fn returning true)
|
// Set CORS headers
|
||||||
.allow_origin(AllowOrigin::predicate(|_origin, _request_head| true))
|
let cors = Cors::default()
|
||||||
.allow_methods(vec![
|
/*
|
||||||
Method::GET,
|
Set Allowed-Control-Allow-Origin header to whatever
|
||||||
Method::POST,
|
the request's Origin header is. Must be done like this
|
||||||
Method::PUT,
|
rather than setting it to "*" due to CORS not allowing
|
||||||
Method::DELETE,
|
sending of credentials (cookies) with wildcard origin.
|
||||||
Method::HEAD,
|
*/
|
||||||
Method::OPTIONS,
|
.allowed_origin_fn(|_origin, _req_head| true)
|
||||||
Method::CONNECT,
|
/*
|
||||||
Method::PATCH,
|
Allows any request method in CORS preflight requests.
|
||||||
Method::TRACE,
|
This will be restricted to only ones actually in use later.
|
||||||
])
|
*/
|
||||||
.allow_headers(vec![
|
.allow_any_method()
|
||||||
header::ACCEPT,
|
/*
|
||||||
header::ACCEPT_LANGUAGE,
|
Allows any header(s) in request in CORS preflight requests.
|
||||||
header::AUTHORIZATION,
|
This wll be restricted to only ones actually in use later.
|
||||||
header::CONTENT_LANGUAGE,
|
*/
|
||||||
header::CONTENT_TYPE,
|
.allow_any_header()
|
||||||
header::ORIGIN,
|
/*
|
||||||
header::ACCEPT,
|
Allows browser to include cookies in requests.
|
||||||
header::COOKIE,
|
This is needed for receiving the secure HttpOnly refresh_token cookie.
|
||||||
"x-requested-with".parse().unwrap(),
|
*/
|
||||||
])
|
.supports_credentials();
|
||||||
// Allow credentials
|
|
||||||
.allow_credentials(true);
|
|
||||||
|
|
||||||
/*let (socket_io, io) = SocketIo::builder()
|
App::new()
|
||||||
.with_state(app_state.clone())
|
.app_data(web::Data::new(data.clone()))
|
||||||
.build_layer();
|
.wrap(cors)
|
||||||
|
.service(api::web(data.config.web.backend_url.path()))
|
||||||
io.ns("/", socket::on_connect);
|
})
|
||||||
*/
|
.bind((web.ip, web.port))?
|
||||||
// build our application with a route
|
.run()
|
||||||
let app = Router::new()
|
.await?;
|
||||||
// `GET /` goes to `root`
|
|
||||||
.merge(api::router(
|
|
||||||
web.backend_url.path().trim_end_matches("/"),
|
|
||||||
app_state.clone(),
|
|
||||||
))
|
|
||||||
.with_state(app_state)
|
|
||||||
//.layer(socket_io)
|
|
||||||
.layer(cors);
|
|
||||||
|
|
||||||
// run our app with hyper, listening globally on port 3000
|
|
||||||
let listener = tokio::net::TcpListener::bind(web.ip + ":" + &web.port.to_string()).await?;
|
|
||||||
axum::serve(listener, app).await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,57 +0,0 @@
|
||||||
use diesel::{ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use diesel_async::RunQueryDsl;
|
|
||||||
|
|
||||||
use crate::{Conn, error::Error, objects::load_or_empty, schema::guild_bans};
|
|
||||||
|
|
||||||
#[derive(Selectable, Queryable, Serialize, Deserialize)]
|
|
||||||
#[diesel(table_name = guild_bans)]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
|
||||||
pub struct GuildBan {
|
|
||||||
pub guild_uuid: Uuid,
|
|
||||||
pub user_uuid: Uuid,
|
|
||||||
pub reason: Option<String>,
|
|
||||||
pub banned_since: chrono::DateTime<chrono::Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GuildBan {
|
|
||||||
pub async fn fetch_one(
|
|
||||||
conn: &mut Conn,
|
|
||||||
guild_uuid: Uuid,
|
|
||||||
user_uuid: Uuid,
|
|
||||||
) -> Result<GuildBan, Error> {
|
|
||||||
use guild_bans::dsl;
|
|
||||||
let guild_ban = dsl::guild_bans
|
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
|
||||||
.filter(dsl::user_uuid.eq(user_uuid))
|
|
||||||
.select(GuildBan::as_select())
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(guild_ban)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_all(conn: &mut Conn, guild_uuid: Uuid) -> Result<Vec<Self>, Error> {
|
|
||||||
use guild_bans::dsl;
|
|
||||||
let all_guild_bans = load_or_empty(
|
|
||||||
dsl::guild_bans
|
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(all_guild_bans)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn unban(self, conn: &mut Conn) -> Result<(), Error> {
|
|
||||||
use guild_bans::dsl;
|
|
||||||
diesel::delete(guild_bans::table)
|
|
||||||
.filter(dsl::guild_uuid.eq(self.guild_uuid))
|
|
||||||
.filter(dsl::user_uuid.eq(self.user_uuid))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -2,15 +2,15 @@ use diesel::{
|
||||||
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, delete,
|
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, delete,
|
||||||
insert_into, update,
|
insert_into, update,
|
||||||
};
|
};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::{RunQueryDsl, pooled_connection::AsyncDieselConnectionManager};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Conn,
|
Conn, Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::{channel_permissions, channels, messages},
|
schema::{channel_permissions, channels, messages},
|
||||||
utils::{CHANNEL_REGEX, CacheFns, order_by_is_above},
|
utils::{CHANNEL_REGEX, order_by_is_above},
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{HasIsAbove, HasUuid, Message, load_or_empty, message::MessageBuilder};
|
use super::{HasIsAbove, HasUuid, Message, load_or_empty, message::MessageBuilder};
|
||||||
|
@ -79,53 +79,56 @@ impl HasIsAbove for Channel {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Channel {
|
impl Channel {
|
||||||
pub async fn fetch_all(conn: &mut Conn, guild_uuid: Uuid) -> Result<Vec<Self>, Error> {
|
pub async fn fetch_all(
|
||||||
|
pool: &deadpool::managed::Pool<
|
||||||
|
AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>,
|
||||||
|
Conn,
|
||||||
|
>,
|
||||||
|
guild_uuid: Uuid,
|
||||||
|
) -> Result<Vec<Self>, Error> {
|
||||||
|
let mut conn = pool.get().await?;
|
||||||
|
|
||||||
use channels::dsl;
|
use channels::dsl;
|
||||||
let channel_builders: Vec<ChannelBuilder> = load_or_empty(
|
let channel_builders: Vec<ChannelBuilder> = load_or_empty(
|
||||||
dsl::channels
|
dsl::channels
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
.filter(dsl::guild_uuid.eq(guild_uuid))
|
||||||
.select(ChannelBuilder::as_select())
|
.select(ChannelBuilder::as_select())
|
||||||
.load(conn)
|
.load(&mut conn)
|
||||||
.await,
|
.await,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut channels = vec![];
|
let channel_futures = channel_builders.iter().map(async move |c| {
|
||||||
|
let mut conn = pool.get().await?;
|
||||||
|
c.clone().build(&mut conn).await
|
||||||
|
});
|
||||||
|
|
||||||
for builder in channel_builders {
|
futures::future::try_join_all(channel_futures).await
|
||||||
channels.push(builder.build(conn).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(channels)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_one(
|
pub async fn fetch_one(data: &Data, channel_uuid: Uuid) -> Result<Self, Error> {
|
||||||
conn: &mut Conn,
|
if let Ok(cache_hit) = data.get_cache_key(channel_uuid.to_string()).await {
|
||||||
cache_pool: &redis::Client,
|
return Ok(serde_json::from_str(&cache_hit)?);
|
||||||
channel_uuid: Uuid,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
if let Ok(cache_hit) = cache_pool.get_cache_key(channel_uuid.to_string()).await {
|
|
||||||
return Ok(cache_hit);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use channels::dsl;
|
use channels::dsl;
|
||||||
let channel_builder: ChannelBuilder = dsl::channels
|
let channel_builder: ChannelBuilder = dsl::channels
|
||||||
.filter(dsl::uuid.eq(channel_uuid))
|
.filter(dsl::uuid.eq(channel_uuid))
|
||||||
.select(ChannelBuilder::as_select())
|
.select(ChannelBuilder::as_select())
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let channel = channel_builder.build(conn).await?;
|
let channel = channel_builder.build(&mut conn).await?;
|
||||||
|
|
||||||
cache_pool
|
data.set_cache_key(channel_uuid.to_string(), channel.clone(), 60)
|
||||||
.set_cache_key(channel_uuid.to_string(), channel.clone(), 60)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(channel)
|
Ok(channel)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn new(
|
pub async fn new(
|
||||||
conn: &mut Conn,
|
data: actix_web::web::Data<Data>,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
guild_uuid: Uuid,
|
guild_uuid: Uuid,
|
||||||
name: String,
|
name: String,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
|
@ -134,9 +137,11 @@ impl Channel {
|
||||||
return Err(Error::BadRequest("Channel name is invalid".to_string()));
|
return Err(Error::BadRequest("Channel name is invalid".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
let channel_uuid = Uuid::now_v7();
|
let channel_uuid = Uuid::now_v7();
|
||||||
|
|
||||||
let channels = Self::fetch_all(conn, guild_uuid).await?;
|
let channels = Self::fetch_all(&data.pool, guild_uuid).await?;
|
||||||
|
|
||||||
let channels_ordered = order_by_is_above(channels).await?;
|
let channels_ordered = order_by_is_above(channels).await?;
|
||||||
|
|
||||||
|
@ -152,7 +157,7 @@ impl Channel {
|
||||||
|
|
||||||
insert_into(channels::table)
|
insert_into(channels::table)
|
||||||
.values(new_channel.clone())
|
.values(new_channel.clone())
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if let Some(old_last_channel) = last_channel {
|
if let Some(old_last_channel) = last_channel {
|
||||||
|
@ -160,7 +165,7 @@ impl Channel {
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(old_last_channel.uuid))
|
.filter(dsl::uuid.eq(old_last_channel.uuid))
|
||||||
.set(dsl::is_above.eq(new_channel.uuid))
|
.set(dsl::is_above.eq(new_channel.uuid))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -174,68 +179,32 @@ impl Channel {
|
||||||
permissions: vec![],
|
permissions: vec![],
|
||||||
};
|
};
|
||||||
|
|
||||||
cache_pool
|
data.set_cache_key(channel_uuid.to_string(), channel.clone(), 1800)
|
||||||
.set_cache_key(channel_uuid.to_string(), channel.clone(), 1800)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{guild_uuid}_channels"))
|
.get_cache_key(format!("{}_channels", guild_uuid))
|
||||||
.await
|
.await
|
||||||
.is_ok()
|
.is_ok()
|
||||||
{
|
{
|
||||||
cache_pool
|
data.del_cache_key(format!("{}_channels", guild_uuid))
|
||||||
.del_cache_key(format!("{guild_uuid}_channels"))
|
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(channel)
|
Ok(channel)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete(self, conn: &mut Conn, cache_pool: &redis::Client) -> Result<(), Error> {
|
pub async fn delete(self, data: &Data) -> Result<(), Error> {
|
||||||
use channels::dsl;
|
let mut conn = data.pool.get().await?;
|
||||||
match update(channels::table)
|
|
||||||
.filter(dsl::is_above.eq(self.uuid))
|
|
||||||
.set(dsl::is_above.eq(None::<Uuid>))
|
|
||||||
.execute(conn)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(r) => Ok(r),
|
|
||||||
Err(diesel::result::Error::NotFound) => Ok(0),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}?;
|
|
||||||
|
|
||||||
|
use channels::dsl;
|
||||||
delete(channels::table)
|
delete(channels::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
match update(channels::table)
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.filter(dsl::is_above.eq(self.uuid))
|
data.del_cache_key(self.uuid.to_string()).await?;
|
||||||
.set(dsl::is_above.eq(self.is_above))
|
|
||||||
.execute(conn)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(r) => Ok(r),
|
|
||||||
Err(diesel::result::Error::NotFound) => Ok(0),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}?;
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Channel>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool
|
|
||||||
.del_cache_key(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -243,39 +212,34 @@ impl Channel {
|
||||||
|
|
||||||
pub async fn fetch_messages(
|
pub async fn fetch_messages(
|
||||||
&self,
|
&self,
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
amount: i64,
|
amount: i64,
|
||||||
offset: i64,
|
offset: i64,
|
||||||
) -> Result<Vec<Message>, Error> {
|
) -> Result<Vec<Message>, Error> {
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use messages::dsl;
|
use messages::dsl;
|
||||||
let message_builders: Vec<MessageBuilder> = load_or_empty(
|
let messages: Vec<MessageBuilder> = load_or_empty(
|
||||||
dsl::messages
|
dsl::messages
|
||||||
.filter(dsl::channel_uuid.eq(self.uuid))
|
.filter(dsl::channel_uuid.eq(self.uuid))
|
||||||
.select(MessageBuilder::as_select())
|
.select(MessageBuilder::as_select())
|
||||||
.order(dsl::uuid.desc())
|
.order(dsl::uuid.desc())
|
||||||
.limit(amount)
|
.limit(amount)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
.load(conn)
|
.load(&mut conn)
|
||||||
.await,
|
.await,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut messages = vec![];
|
let message_futures = messages.iter().map(async move |b| b.build(data).await);
|
||||||
|
|
||||||
for builder in message_builders {
|
futures::future::try_join_all(message_futures).await
|
||||||
messages.push(builder.build(conn, cache_pool).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(messages)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn new_message(
|
pub async fn new_message(
|
||||||
&self,
|
&self,
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
user_uuid: Uuid,
|
user_uuid: Uuid,
|
||||||
message: String,
|
message: String,
|
||||||
reply_to: Option<Uuid>,
|
|
||||||
) -> Result<Message, Error> {
|
) -> Result<Message, Error> {
|
||||||
let message_uuid = Uuid::now_v7();
|
let message_uuid = Uuid::now_v7();
|
||||||
|
|
||||||
|
@ -284,104 +248,64 @@ impl Channel {
|
||||||
channel_uuid: self.uuid,
|
channel_uuid: self.uuid,
|
||||||
user_uuid,
|
user_uuid,
|
||||||
message,
|
message,
|
||||||
reply_to,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
insert_into(messages::table)
|
insert_into(messages::table)
|
||||||
.values(message.clone())
|
.values(message.clone())
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
message.build(conn, cache_pool).await
|
message.build(data).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_name(
|
pub async fn set_name(&mut self, data: &Data, new_name: String) -> Result<(), Error> {
|
||||||
&mut self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_name: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !CHANNEL_REGEX.is_match(&new_name) {
|
if !CHANNEL_REGEX.is_match(&new_name) {
|
||||||
return Err(Error::BadRequest("Channel name is invalid".to_string()));
|
return Err(Error::BadRequest("Channel name is invalid".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use channels::dsl;
|
use channels::dsl;
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::name.eq(&new_name))
|
.set(dsl::name.eq(&new_name))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.name = new_name;
|
self.name = new_name;
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Channel>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool
|
|
||||||
.del_cache_key(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_description(
|
pub async fn set_description(
|
||||||
&mut self,
|
&mut self,
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_description: String,
|
new_description: String,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use channels::dsl;
|
use channels::dsl;
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::description.eq(&new_description))
|
.set(dsl::description.eq(&new_description))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.description = Some(new_description);
|
self.description = Some(new_description);
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Channel>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool
|
|
||||||
.del_cache_key(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn move_channel(
|
pub async fn move_channel(&mut self, data: &Data, new_is_above: Uuid) -> Result<(), Error> {
|
||||||
&mut self,
|
let mut conn = data.pool.get().await?;
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_is_above: Uuid,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
use channels::dsl;
|
use channels::dsl;
|
||||||
let old_above_uuid: Option<Uuid> = match dsl::channels
|
let old_above_uuid: Option<Uuid> = match dsl::channels
|
||||||
.filter(dsl::is_above.eq(self.uuid))
|
.filter(dsl::is_above.eq(self.uuid))
|
||||||
.select(dsl::uuid)
|
.select(dsl::uuid)
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(r) => Ok(Some(r)),
|
Ok(r) => Ok(Some(r)),
|
||||||
|
@ -393,14 +317,14 @@ impl Channel {
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(uuid))
|
.filter(dsl::uuid.eq(uuid))
|
||||||
.set(dsl::is_above.eq(None::<Uuid>))
|
.set(dsl::is_above.eq(None::<Uuid>))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
match update(channels::table)
|
match update(channels::table)
|
||||||
.filter(dsl::is_above.eq(new_is_above))
|
.filter(dsl::is_above.eq(new_is_above))
|
||||||
.set(dsl::is_above.eq(self.uuid))
|
.set(dsl::is_above.eq(self.uuid))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(r) => Ok(r),
|
Ok(r) => Ok(r),
|
||||||
|
@ -411,37 +335,19 @@ impl Channel {
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::is_above.eq(new_is_above))
|
.set(dsl::is_above.eq(new_is_above))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if let Some(uuid) = old_above_uuid {
|
if let Some(uuid) = old_above_uuid {
|
||||||
update(channels::table)
|
update(channels::table)
|
||||||
.filter(dsl::uuid.eq(uuid))
|
.filter(dsl::uuid.eq(uuid))
|
||||||
.set(dsl::is_above.eq(self.is_above))
|
.set(dsl::is_above.eq(self.is_above))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.is_above = Some(new_is_above);
|
self.is_above = Some(new_is_above);
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Channel>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<Vec<Channel>>(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool
|
|
||||||
.del_cache_key(format!("{}_channels", self.guild_uuid))
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,11 +3,7 @@ use lettre::message::MultiPart;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{Data, error::Error, utils::generate_refresh_token};
|
||||||
AppState,
|
|
||||||
error::Error,
|
|
||||||
utils::{CacheFns, generate_token},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::Me;
|
use super::Me;
|
||||||
|
|
||||||
|
@ -19,53 +15,46 @@ pub struct EmailToken {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EmailToken {
|
impl EmailToken {
|
||||||
pub async fn get(cache_pool: &redis::Client, user_uuid: Uuid) -> Result<EmailToken, Error> {
|
pub async fn get(data: &Data, user_uuid: Uuid) -> Result<EmailToken, Error> {
|
||||||
let email_token = cache_pool
|
let email_token = serde_json::from_str(&data.get_cache_key(format!("{}_email_verify", user_uuid)).await?)?;
|
||||||
.get_cache_key(format!("{user_uuid}_email_verify"))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(email_token)
|
Ok(email_token)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::new_ret_no_self)]
|
#[allow(clippy::new_ret_no_self)]
|
||||||
pub async fn new(app_state: &AppState, me: Me) -> Result<(), Error> {
|
pub async fn new(data: &Data, me: Me) -> Result<(), Error> {
|
||||||
let token = generate_token::<32>()?;
|
let token = generate_refresh_token()?;
|
||||||
|
|
||||||
let email_token = EmailToken {
|
let email_token = EmailToken {
|
||||||
user_uuid: me.uuid,
|
user_uuid: me.uuid,
|
||||||
token: token.clone(),
|
token: token.clone(),
|
||||||
// TODO: Check if this can be replaced with something built into valkey
|
// TODO: Check if this can be replaced with something built into valkey
|
||||||
created_at: Utc::now(),
|
created_at: Utc::now()
|
||||||
};
|
};
|
||||||
|
|
||||||
app_state
|
data.set_cache_key(format!("{}_email_verify", me.uuid), email_token, 86400).await?;
|
||||||
.cache_pool
|
|
||||||
.set_cache_key(format!("{}_email_verify", me.uuid), email_token, 86400)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut verify_endpoint = app_state.config.web.frontend_url.join("verify-email")?;
|
let mut verify_endpoint = data.config.web.frontend_url.join("verify-email")?;
|
||||||
|
|
||||||
verify_endpoint.set_query(Some(&format!("token={token}")));
|
verify_endpoint.set_query(Some(&format!("token={}", token)));
|
||||||
|
|
||||||
let email = app_state
|
let email = data
|
||||||
.mail_client
|
.mail_client
|
||||||
.message_builder()
|
.message_builder()
|
||||||
.to(me.email.parse()?)
|
.to(me.email.parse()?)
|
||||||
.subject(format!("{} E-mail Verification", app_state.config.instance.name))
|
.subject(format!("{} E-mail Verification", data.config.instance.name))
|
||||||
.multipart(MultiPart::alternative_plain_html(
|
.multipart(MultiPart::alternative_plain_html(
|
||||||
format!("Verify your {} account\n\nHello, {}!\nThanks for creating a new account on Gorb.\nThe final step to create your account is to verify your email address by visiting the page, within 24 hours.\n\n{}\n\nIf you didn't ask to verify this address, you can safely ignore this email\n\nThanks, The gorb team.", app_state.config.instance.name, me.username, verify_endpoint),
|
format!("Verify your {} account\n\nHello, {}!\nThanks for creating a new account on Gorb.\nThe final step to create your account is to verify your email address by visiting the page, within 24 hours.\n\n{}\n\nIf you didn't ask to verify this address, you can safely ignore this email\n\nThanks, The gorb team.", data.config.instance.name, me.username, verify_endpoint),
|
||||||
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root{{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark){{:root{{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px){{.container{{width: 100%;}}}}body{{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header{{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button{{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover{{background-color: var(--secondary-colour);}}.content{{padding: 20px 30px;}}.footer{{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>Verify your {} Account</h1></div><div class="content"><h2>Hello, {}!</h2><p>Thanks for creating a new account on Gorb.</p><p>The final step to create your account is to verify your email address by clicking the button below, within 24 hours.</p><a href="{}" class="verify-button">VERIFY ACCOUNT</a><p>If you didn't ask to verify this address, you can safely ignore this email.</p><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, app_state.config.instance.name, me.username, verify_endpoint)
|
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root{{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark){{:root{{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px){{.container{{width: 100%;}}}}body{{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header{{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button{{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover{{background-color: var(--secondary-colour);}}.content{{padding: 20px 30px;}}.footer{{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>Verify your {} Account</h1></div><div class="content"><h2>Hello, {}!</h2><p>Thanks for creating a new account on Gorb.</p><p>The final step to create your account is to verify your email address by clicking the button below, within 24 hours.</p><a href="{}" class="verify-button">VERIFY ACCOUNT</a><p>If you didn't ask to verify this address, you can safely ignore this email.</p><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, data.config.instance.name, me.username, verify_endpoint)
|
||||||
))?;
|
))?;
|
||||||
|
|
||||||
app_state.mail_client.send_mail(email).await?;
|
data.mail_client.send_mail(email).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete(&self, cache_pool: &redis::Client) -> Result<(), Error> {
|
pub async fn delete(&self, data: &Data) -> Result<(), Error> {
|
||||||
cache_pool
|
data.del_cache_key(format!("{}_email_verify", self.user_uuid)).await?;
|
||||||
.del_cache_key(format!("{}_email_verify", self.user_uuid))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +0,0 @@
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use diesel::{Queryable, Selectable};
|
|
||||||
use serde::Serialize;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use crate::schema::{friend_requests, friends};
|
|
||||||
|
|
||||||
#[derive(Serialize, Queryable, Selectable, Clone)]
|
|
||||||
#[diesel(table_name = friends)]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
|
||||||
pub struct Friend {
|
|
||||||
pub uuid1: Uuid,
|
|
||||||
pub uuid2: Uuid,
|
|
||||||
pub accepted_at: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Queryable, Selectable, Clone)]
|
|
||||||
#[diesel(table_name = friend_requests)]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
|
||||||
pub struct FriendRequest {
|
|
||||||
pub sender: Uuid,
|
|
||||||
pub receiver: Uuid,
|
|
||||||
pub requested_at: DateTime<Utc>,
|
|
||||||
}
|
|
|
@ -1,16 +1,16 @@
|
||||||
use axum::body::Bytes;
|
use actix_web::web::BytesMut;
|
||||||
use diesel::{
|
use diesel::{
|
||||||
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, insert_into,
|
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, insert_into,
|
||||||
update,
|
update,
|
||||||
};
|
};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::{RunQueryDsl, pooled_connection::AsyncDieselConnectionManager};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tokio::task;
|
use tokio::task;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, Conn,
|
Conn,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::{guild_members, guilds, invites},
|
schema::{guild_members, guilds, invites},
|
||||||
utils::image_check,
|
utils::image_check,
|
||||||
|
@ -26,6 +26,7 @@ pub struct GuildBuilder {
|
||||||
name: String,
|
name: String,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
icon: Option<String>,
|
icon: Option<String>,
|
||||||
|
owner_uuid: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GuildBuilder {
|
impl GuildBuilder {
|
||||||
|
@ -39,6 +40,7 @@ impl GuildBuilder {
|
||||||
name: self.name,
|
name: self.name,
|
||||||
description: self.description,
|
description: self.description,
|
||||||
icon: self.icon.and_then(|i| i.parse().ok()),
|
icon: self.icon.and_then(|i| i.parse().ok()),
|
||||||
|
owner_uuid: self.owner_uuid,
|
||||||
roles,
|
roles,
|
||||||
member_count,
|
member_count,
|
||||||
})
|
})
|
||||||
|
@ -51,6 +53,7 @@ pub struct Guild {
|
||||||
name: String,
|
name: String,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
icon: Option<Url>,
|
icon: Option<Url>,
|
||||||
|
owner_uuid: Uuid,
|
||||||
pub roles: Vec<Role>,
|
pub roles: Vec<Role>,
|
||||||
member_count: i64,
|
member_count: i64,
|
||||||
}
|
}
|
||||||
|
@ -68,11 +71,16 @@ impl Guild {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_amount(
|
pub async fn fetch_amount(
|
||||||
conn: &mut Conn,
|
pool: &deadpool::managed::Pool<
|
||||||
|
AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>,
|
||||||
|
Conn,
|
||||||
|
>,
|
||||||
offset: i64,
|
offset: i64,
|
||||||
amount: i64,
|
amount: i64,
|
||||||
) -> Result<Vec<Self>, Error> {
|
) -> Result<Vec<Self>, Error> {
|
||||||
// Fetch guild data from database
|
// Fetch guild data from database
|
||||||
|
let mut conn = pool.get().await?;
|
||||||
|
|
||||||
use guilds::dsl;
|
use guilds::dsl;
|
||||||
let guild_builders: Vec<GuildBuilder> = load_or_empty(
|
let guild_builders: Vec<GuildBuilder> = load_or_empty(
|
||||||
dsl::guilds
|
dsl::guilds
|
||||||
|
@ -80,17 +88,18 @@ impl Guild {
|
||||||
.order_by(dsl::uuid)
|
.order_by(dsl::uuid)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
.limit(amount)
|
.limit(amount)
|
||||||
.load(conn)
|
.load(&mut conn)
|
||||||
.await,
|
.await,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let mut guilds = vec![];
|
// Process each guild concurrently
|
||||||
|
let guild_futures = guild_builders.iter().map(async move |g| {
|
||||||
|
let mut conn = pool.get().await?;
|
||||||
|
g.clone().build(&mut conn).await
|
||||||
|
});
|
||||||
|
|
||||||
for builder in guild_builders {
|
// Execute all futures concurrently and collect results
|
||||||
guilds.push(builder.build(conn).await?);
|
futures::future::try_join_all(guild_futures).await
|
||||||
}
|
|
||||||
|
|
||||||
Ok(guilds)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn new(conn: &mut Conn, name: String, owner_uuid: Uuid) -> Result<Self, Error> {
|
pub async fn new(conn: &mut Conn, name: String, owner_uuid: Uuid) -> Result<Self, Error> {
|
||||||
|
@ -101,6 +110,7 @@ impl Guild {
|
||||||
name: name.clone(),
|
name: name.clone(),
|
||||||
description: None,
|
description: None,
|
||||||
icon: None,
|
icon: None,
|
||||||
|
owner_uuid,
|
||||||
};
|
};
|
||||||
|
|
||||||
insert_into(guilds::table)
|
insert_into(guilds::table)
|
||||||
|
@ -115,7 +125,6 @@ impl Guild {
|
||||||
nickname: None,
|
nickname: None,
|
||||||
user_uuid: owner_uuid,
|
user_uuid: owner_uuid,
|
||||||
guild_uuid,
|
guild_uuid,
|
||||||
is_owner: true,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
insert_into(guild_members::table)
|
insert_into(guild_members::table)
|
||||||
|
@ -128,6 +137,7 @@ impl Guild {
|
||||||
name,
|
name,
|
||||||
description: None,
|
description: None,
|
||||||
icon: None,
|
icon: None,
|
||||||
|
owner_uuid,
|
||||||
roles: vec![],
|
roles: vec![],
|
||||||
member_count: 1,
|
member_count: 1,
|
||||||
})
|
})
|
||||||
|
@ -182,9 +192,10 @@ impl Guild {
|
||||||
// FIXME: Horrible security
|
// FIXME: Horrible security
|
||||||
pub async fn set_icon(
|
pub async fn set_icon(
|
||||||
&mut self,
|
&mut self,
|
||||||
|
bunny_cdn: &bunny_api_tokio::Client,
|
||||||
conn: &mut Conn,
|
conn: &mut Conn,
|
||||||
app_state: &AppState,
|
cdn_url: Url,
|
||||||
icon: Bytes,
|
icon: BytesMut,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let icon_clone = icon.clone();
|
let icon_clone = icon.clone();
|
||||||
let image_type = task::spawn_blocking(move || image_check(icon_clone)).await??;
|
let image_type = task::spawn_blocking(move || image_check(icon_clone)).await??;
|
||||||
|
@ -192,14 +203,14 @@ impl Guild {
|
||||||
if let Some(icon) = &self.icon {
|
if let Some(icon) = &self.icon {
|
||||||
let relative_url = icon.path().trim_start_matches('/');
|
let relative_url = icon.path().trim_start_matches('/');
|
||||||
|
|
||||||
app_state.bunny_storage.delete(relative_url).await?;
|
bunny_cdn.storage.delete(relative_url).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let path = format!("icons/{}/{}.{}", self.uuid, Uuid::now_v7(), image_type);
|
let path = format!("icons/{}/icon.{}", self.uuid, image_type);
|
||||||
|
|
||||||
app_state.bunny_storage.upload(path.clone(), icon).await?;
|
bunny_cdn.storage.upload(path.clone(), icon.into()).await?;
|
||||||
|
|
||||||
let icon_url = app_state.config.bunny.cdn_url.join(&path)?;
|
let icon_url = cdn_url.join(&path)?;
|
||||||
|
|
||||||
use guilds::dsl;
|
use guilds::dsl;
|
||||||
update(guilds::table)
|
update(guilds::table)
|
||||||
|
|
|
@ -1,8 +1,5 @@
|
||||||
use axum::body::Bytes;
|
use actix_web::web::BytesMut;
|
||||||
use diesel::{
|
use diesel::{ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper, update};
|
||||||
ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper, delete, insert_into,
|
|
||||||
update,
|
|
||||||
};
|
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tokio::task;
|
use tokio::task;
|
||||||
|
@ -10,11 +7,10 @@ use url::Url;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, Conn,
|
Conn, Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{Friend, FriendRequest, User},
|
schema::{guild_members, guilds, users},
|
||||||
schema::{friend_requests, friends, guild_members, guilds, users},
|
utils::{EMAIL_REGEX, USERNAME_REGEX, image_check},
|
||||||
utils::{CacheFns, EMAIL_REGEX, USERNAME_REGEX, image_check},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{Guild, guild::GuildBuilder, load_or_empty, member::MemberBuilder};
|
use super::{Guild, guild::GuildBuilder, load_or_empty, member::MemberBuilder};
|
||||||
|
@ -29,7 +25,6 @@ pub struct Me {
|
||||||
avatar: Option<String>,
|
avatar: Option<String>,
|
||||||
pronouns: Option<String>,
|
pronouns: Option<String>,
|
||||||
about: Option<String>,
|
about: Option<String>,
|
||||||
online_status: i16,
|
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub email_verified: bool,
|
pub email_verified: bool,
|
||||||
}
|
}
|
||||||
|
@ -76,44 +71,41 @@ impl Me {
|
||||||
|
|
||||||
pub async fn set_avatar(
|
pub async fn set_avatar(
|
||||||
&mut self,
|
&mut self,
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
app_state: &AppState,
|
cdn_url: Url,
|
||||||
avatar: Bytes,
|
avatar: BytesMut,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let avatar_clone = avatar.clone();
|
let avatar_clone = avatar.clone();
|
||||||
let image_type = task::spawn_blocking(move || image_check(avatar_clone)).await??;
|
let image_type = task::spawn_blocking(move || image_check(avatar_clone)).await??;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
if let Some(avatar) = &self.avatar {
|
if let Some(avatar) = &self.avatar {
|
||||||
let avatar_url: Url = avatar.parse()?;
|
let avatar_url: Url = avatar.parse()?;
|
||||||
|
|
||||||
let relative_url = avatar_url.path().trim_start_matches('/');
|
let relative_url = avatar_url.path().trim_start_matches('/');
|
||||||
|
|
||||||
app_state.bunny_storage.delete(relative_url).await?;
|
data.bunny_cdn.storage.delete(relative_url).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let path = format!("avatar/{}/{}.{}", self.uuid, Uuid::now_v7(), image_type);
|
let path = format!("avatar/{}/avatar.{}", self.uuid, image_type);
|
||||||
|
|
||||||
app_state.bunny_storage.upload(path.clone(), avatar).await?;
|
data.bunny_cdn
|
||||||
|
.storage
|
||||||
|
.upload(path.clone(), avatar.into())
|
||||||
|
.await?;
|
||||||
|
|
||||||
let avatar_url = app_state.config.bunny.cdn_url.join(&path)?;
|
let avatar_url = cdn_url.join(&path)?;
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::avatar.eq(avatar_url.as_str()))
|
.set(dsl::avatar.eq(avatar_url.as_str()))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if app_state
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.cache_pool
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
app_state
|
|
||||||
.cache_pool
|
|
||||||
.del_cache_key(self.uuid.to_string())
|
|
||||||
.await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.avatar = Some(avatar_url.to_string());
|
self.avatar = Some(avatar_url.to_string());
|
||||||
|
@ -132,32 +124,22 @@ impl Me {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_username(
|
pub async fn set_username(&mut self, data: &Data, new_username: String) -> Result<(), Error> {
|
||||||
&mut self,
|
if !USERNAME_REGEX.is_match(&new_username) {
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_username: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !USERNAME_REGEX.is_match(&new_username)
|
|
||||||
|| new_username.len() < 3
|
|
||||||
|| new_username.len() > 32
|
|
||||||
{
|
|
||||||
return Err(Error::BadRequest("Invalid username".to_string()));
|
return Err(Error::BadRequest("Invalid username".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::username.eq(new_username.as_str()))
|
.set(dsl::username.eq(new_username.as_str()))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.username = new_username;
|
self.username = new_username;
|
||||||
|
@ -167,46 +149,34 @@ impl Me {
|
||||||
|
|
||||||
pub async fn set_display_name(
|
pub async fn set_display_name(
|
||||||
&mut self,
|
&mut self,
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_display_name: String,
|
new_display_name: String,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let new_display_name_option = if new_display_name.is_empty() {
|
let mut conn = data.pool.get().await?;
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(new_display_name)
|
|
||||||
};
|
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set(dsl::display_name.eq(&new_display_name_option))
|
.set(dsl::display_name.eq(new_display_name.as_str()))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.display_name = new_display_name_option;
|
self.display_name = Some(new_display_name);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_email(
|
pub async fn set_email(&mut self, data: &Data, new_email: String) -> Result<(), Error> {
|
||||||
&mut self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_email: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !EMAIL_REGEX.is_match(&new_email) {
|
if !EMAIL_REGEX.is_match(&new_email) {
|
||||||
return Err(Error::BadRequest("Invalid username".to_string()));
|
return Err(Error::BadRequest("Invalid username".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
|
@ -214,15 +184,11 @@ impl Me {
|
||||||
dsl::email.eq(new_email.as_str()),
|
dsl::email.eq(new_email.as_str()),
|
||||||
dsl::email_verified.eq(false),
|
dsl::email_verified.eq(false),
|
||||||
))
|
))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.email = new_email;
|
self.email = new_email;
|
||||||
|
@ -230,257 +196,37 @@ impl Me {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_pronouns(
|
pub async fn set_pronouns(&mut self, data: &Data, new_pronouns: String) -> Result<(), Error> {
|
||||||
&mut self,
|
let mut conn = data.pool.get().await?;
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_pronouns: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set((dsl::pronouns.eq(new_pronouns.as_str()),))
|
.set((dsl::pronouns.eq(new_pronouns.as_str()),))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_about(
|
pub async fn set_about(&mut self, data: &Data, new_about: String) -> Result<(), Error> {
|
||||||
&mut self,
|
let mut conn = data.pool.get().await?;
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_about: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
.filter(dsl::uuid.eq(self.uuid))
|
||||||
.set((dsl::about.eq(new_about.as_str()),))
|
.set((dsl::about.eq(new_about.as_str()),))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if cache_pool
|
if data.get_cache_key(self.uuid.to_string()).await.is_ok() {
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
data.del_cache_key(self.uuid.to_string()).await?
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_online_status(
|
|
||||||
&mut self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
new_status: i16,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !(0..=4).contains(&new_status) {
|
|
||||||
return Err(Error::BadRequest("Invalid status code".to_string()));
|
|
||||||
}
|
|
||||||
self.online_status = new_status;
|
|
||||||
|
|
||||||
use users::dsl;
|
|
||||||
update(users::table)
|
|
||||||
.filter(dsl::uuid.eq(self.uuid))
|
|
||||||
.set(dsl::online_status.eq(new_status))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if cache_pool
|
|
||||||
.get_cache_key::<User>(self.uuid.to_string())
|
|
||||||
.await
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
cache_pool.del_cache_key(self.uuid.to_string()).await?
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn friends_with(
|
|
||||||
&self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
user_uuid: Uuid,
|
|
||||||
) -> Result<Option<Friend>, Error> {
|
|
||||||
use friends::dsl;
|
|
||||||
|
|
||||||
let friends: Vec<Friend> = if self.uuid < user_uuid {
|
|
||||||
load_or_empty(
|
|
||||||
dsl::friends
|
|
||||||
.filter(dsl::uuid1.eq(self.uuid))
|
|
||||||
.filter(dsl::uuid2.eq(user_uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?
|
|
||||||
} else {
|
|
||||||
load_or_empty(
|
|
||||||
dsl::friends
|
|
||||||
.filter(dsl::uuid1.eq(user_uuid))
|
|
||||||
.filter(dsl::uuid2.eq(self.uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?
|
|
||||||
};
|
|
||||||
|
|
||||||
if friends.is_empty() {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Some(friends[0].clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn add_friend(&self, conn: &mut Conn, user_uuid: Uuid) -> Result<(), Error> {
|
|
||||||
if self.friends_with(conn, user_uuid).await?.is_some() {
|
|
||||||
// TODO: Check if another error should be used
|
|
||||||
return Err(Error::BadRequest("Already friends with user".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
use friend_requests::dsl;
|
|
||||||
|
|
||||||
let friend_request: Vec<FriendRequest> = load_or_empty(
|
|
||||||
dsl::friend_requests
|
|
||||||
.filter(dsl::sender.eq(user_uuid))
|
|
||||||
.filter(dsl::receiver.eq(self.uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
#[allow(clippy::get_first)]
|
|
||||||
if let Some(friend_request) = friend_request.get(0) {
|
|
||||||
use friends::dsl;
|
|
||||||
|
|
||||||
if self.uuid < user_uuid {
|
|
||||||
insert_into(friends::table)
|
|
||||||
.values((dsl::uuid1.eq(self.uuid), dsl::uuid2.eq(user_uuid)))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
insert_into(friends::table)
|
|
||||||
.values((dsl::uuid1.eq(user_uuid), dsl::uuid2.eq(self.uuid)))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
use friend_requests::dsl as frdsl;
|
|
||||||
|
|
||||||
delete(friend_requests::table)
|
|
||||||
.filter(frdsl::sender.eq(friend_request.sender))
|
|
||||||
.filter(frdsl::receiver.eq(friend_request.receiver))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
use friend_requests::dsl;
|
|
||||||
|
|
||||||
insert_into(friend_requests::table)
|
|
||||||
.values((dsl::sender.eq(self.uuid), dsl::receiver.eq(user_uuid)))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn remove_friend(&self, conn: &mut Conn, user_uuid: Uuid) -> Result<(), Error> {
|
|
||||||
if self.friends_with(conn, user_uuid).await?.is_none() {
|
|
||||||
// TODO: Check if another error should be used
|
|
||||||
return Err(Error::BadRequest("Not friends with user".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
use friends::dsl;
|
|
||||||
|
|
||||||
if self.uuid < user_uuid {
|
|
||||||
delete(friends::table)
|
|
||||||
.filter(dsl::uuid1.eq(self.uuid))
|
|
||||||
.filter(dsl::uuid2.eq(user_uuid))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
delete(friends::table)
|
|
||||||
.filter(dsl::uuid1.eq(user_uuid))
|
|
||||||
.filter(dsl::uuid2.eq(self.uuid))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_friends(
|
|
||||||
&self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
) -> Result<Vec<User>, Error> {
|
|
||||||
use friends::dsl;
|
|
||||||
|
|
||||||
let friends1 = load_or_empty(
|
|
||||||
dsl::friends
|
|
||||||
.filter(dsl::uuid1.eq(self.uuid))
|
|
||||||
.select(Friend::as_select())
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let friends2 = load_or_empty(
|
|
||||||
dsl::friends
|
|
||||||
.filter(dsl::uuid2.eq(self.uuid))
|
|
||||||
.select(Friend::as_select())
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let mut friends = vec![];
|
|
||||||
|
|
||||||
for friend in friends1 {
|
|
||||||
friends
|
|
||||||
.push(User::fetch_one_with_friendship(conn, cache_pool, self, friend.uuid2).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
for friend in friends2 {
|
|
||||||
friends
|
|
||||||
.push(User::fetch_one_with_friendship(conn, cache_pool, self, friend.uuid1).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(friends)
|
|
||||||
}
|
|
||||||
|
|
||||||
/* TODO
|
|
||||||
pub async fn get_friend_requests(&self, conn: &mut Conn) -> Result<Vec<FriendRequest>, Error> {
|
|
||||||
use friend_requests::dsl;
|
|
||||||
|
|
||||||
let friend_request: Vec<FriendRequest> = load_or_empty(
|
|
||||||
dsl::friend_requests
|
|
||||||
.filter(dsl::receiver.eq(self.uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn delete_friend_request(&self, conn: &mut Conn, user_uuid: Uuid) -> Result<Vec<FriendRequest>, Error> {
|
|
||||||
use friend_requests::dsl;
|
|
||||||
|
|
||||||
let friend_request: Vec<FriendRequest> = load_or_empty(
|
|
||||||
dsl::friend_requests
|
|
||||||
.filter(dsl::sender.eq(user_uuid))
|
|
||||||
.filter(dsl::receiver.eq(self.uuid))
|
|
||||||
.load(conn)
|
|
||||||
.await
|
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok()
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,122 +1,45 @@
|
||||||
use diesel::{
|
use diesel::{
|
||||||
Associations, BoolExpressionMethods, ExpressionMethods, Identifiable, Insertable, JoinOnDsl,
|
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, insert_into,
|
||||||
QueryDsl, Queryable, Selectable, SelectableHelper, define_sql_function, delete, insert_into,
|
|
||||||
sql_types::{Nullable, VarChar},
|
|
||||||
};
|
};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{Conn, Data, error::Error, schema::guild_members};
|
||||||
Conn,
|
|
||||||
error::Error,
|
|
||||||
objects::PaginationRequest,
|
|
||||||
schema::{friends, guild_bans, guild_members, users},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{
|
use super::{User, load_or_empty};
|
||||||
Friend, Guild, GuildBan, Me, Pagination, Permissions, Role, User, load_or_empty,
|
|
||||||
user::UserBuilder,
|
|
||||||
};
|
|
||||||
|
|
||||||
define_sql_function! { fn coalesce(x: Nullable<VarChar>, y: Nullable<VarChar>, z: VarChar) -> Text; }
|
#[derive(Serialize, Queryable, Selectable, Insertable)]
|
||||||
|
|
||||||
#[derive(Serialize, Queryable, Identifiable, Selectable, Insertable, Associations)]
|
|
||||||
#[diesel(table_name = guild_members)]
|
#[diesel(table_name = guild_members)]
|
||||||
#[diesel(belongs_to(UserBuilder, foreign_key = user_uuid))]
|
|
||||||
#[diesel(belongs_to(Guild, foreign_key = guild_uuid))]
|
|
||||||
#[diesel(primary_key(uuid))]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||||
pub struct MemberBuilder {
|
pub struct MemberBuilder {
|
||||||
pub uuid: Uuid,
|
pub uuid: Uuid,
|
||||||
pub nickname: Option<String>,
|
pub nickname: Option<String>,
|
||||||
pub user_uuid: Uuid,
|
pub user_uuid: Uuid,
|
||||||
pub guild_uuid: Uuid,
|
pub guild_uuid: Uuid,
|
||||||
pub is_owner: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MemberBuilder {
|
impl MemberBuilder {
|
||||||
pub async fn build(
|
async fn build(&self, data: &Data) -> Result<Member, Error> {
|
||||||
&self,
|
let user = User::fetch_one(data, self.user_uuid).await?;
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
me: Option<&Me>,
|
|
||||||
) -> Result<Member, Error> {
|
|
||||||
let user;
|
|
||||||
|
|
||||||
if let Some(me) = me {
|
|
||||||
user = User::fetch_one_with_friendship(conn, cache_pool, me, self.user_uuid).await?;
|
|
||||||
} else {
|
|
||||||
user = User::fetch_one(conn, cache_pool, self.user_uuid).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let roles = Role::fetch_from_member(conn, cache_pool, self).await?;
|
|
||||||
|
|
||||||
Ok(Member {
|
Ok(Member {
|
||||||
uuid: self.uuid,
|
uuid: self.uuid,
|
||||||
nickname: self.nickname.clone(),
|
nickname: self.nickname.clone(),
|
||||||
user_uuid: self.user_uuid,
|
user_uuid: self.user_uuid,
|
||||||
guild_uuid: self.guild_uuid,
|
guild_uuid: self.guild_uuid,
|
||||||
is_owner: self.is_owner,
|
|
||||||
user,
|
user,
|
||||||
roles,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn build_with_parts(
|
|
||||||
&self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
user_builder: UserBuilder,
|
|
||||||
friend: Option<Friend>,
|
|
||||||
) -> Result<Member, Error> {
|
|
||||||
let mut user = user_builder.build();
|
|
||||||
|
|
||||||
if let Some(friend) = friend {
|
|
||||||
user.friends_since = Some(friend.accepted_at);
|
|
||||||
}
|
|
||||||
|
|
||||||
let roles = Role::fetch_from_member(conn, cache_pool, self).await?;
|
|
||||||
|
|
||||||
Ok(Member {
|
|
||||||
uuid: self.uuid,
|
|
||||||
nickname: self.nickname.clone(),
|
|
||||||
user_uuid: self.user_uuid,
|
|
||||||
guild_uuid: self.guild_uuid,
|
|
||||||
is_owner: self.is_owner,
|
|
||||||
user,
|
|
||||||
roles,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn check_permission(
|
|
||||||
&self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
permission: Permissions,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !self.is_owner {
|
|
||||||
let roles = Role::fetch_from_member(conn, cache_pool, self).await?;
|
|
||||||
let allowed = roles.iter().any(|r| r.permissions & permission as i64 != 0);
|
|
||||||
if !allowed {
|
|
||||||
return Err(Error::Forbidden("Not allowed".to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone)]
|
#[derive(Serialize, Deserialize)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
pub uuid: Uuid,
|
pub uuid: Uuid,
|
||||||
pub nickname: Option<String>,
|
pub nickname: Option<String>,
|
||||||
#[serde(skip)]
|
|
||||||
pub user_uuid: Uuid,
|
pub user_uuid: Uuid,
|
||||||
pub guild_uuid: Uuid,
|
pub guild_uuid: Uuid,
|
||||||
pub is_owner: bool,
|
|
||||||
user: User,
|
user: User,
|
||||||
roles: Vec<Role>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Member {
|
impl Member {
|
||||||
|
@ -135,186 +58,53 @@ impl Member {
|
||||||
conn: &mut Conn,
|
conn: &mut Conn,
|
||||||
user_uuid: Uuid,
|
user_uuid: Uuid,
|
||||||
guild_uuid: Uuid,
|
guild_uuid: Uuid,
|
||||||
) -> Result<MemberBuilder, Error> {
|
) -> Result<(), Error> {
|
||||||
use guild_members::dsl;
|
use guild_members::dsl;
|
||||||
let member_builder = dsl::guild_members
|
dsl::guild_members
|
||||||
.filter(dsl::user_uuid.eq(user_uuid))
|
.filter(dsl::user_uuid.eq(user_uuid))
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
.filter(dsl::guild_uuid.eq(guild_uuid))
|
||||||
.select(MemberBuilder::as_select())
|
.select(MemberBuilder::as_select())
|
||||||
.get_result(conn)
|
.get_result(conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(member_builder)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_one(
|
pub async fn fetch_one(data: &Data, user_uuid: Uuid, guild_uuid: Uuid) -> Result<Self, Error> {
|
||||||
conn: &mut Conn,
|
let mut conn = data.pool.get().await?;
|
||||||
cache_pool: &redis::Client,
|
|
||||||
me: Option<&Me>,
|
|
||||||
user_uuid: Uuid,
|
|
||||||
guild_uuid: Uuid,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
let member: MemberBuilder;
|
|
||||||
let user: UserBuilder;
|
|
||||||
let friend: Option<Friend>;
|
|
||||||
use friends::dsl as fdsl;
|
|
||||||
use guild_members::dsl;
|
use guild_members::dsl;
|
||||||
if let Some(me) = me {
|
let member: MemberBuilder = dsl::guild_members
|
||||||
(member, user, friend) = dsl::guild_members
|
.filter(dsl::user_uuid.eq(user_uuid))
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
.filter(dsl::guild_uuid.eq(guild_uuid))
|
||||||
.filter(dsl::user_uuid.eq(user_uuid))
|
.select(MemberBuilder::as_select())
|
||||||
.inner_join(users::table)
|
.get_result(&mut conn)
|
||||||
.left_join(
|
.await?;
|
||||||
fdsl::friends.on(fdsl::uuid1
|
|
||||||
.eq(me.uuid)
|
|
||||||
.and(fdsl::uuid2.eq(users::uuid))
|
|
||||||
.or(fdsl::uuid2.eq(me.uuid).and(fdsl::uuid1.eq(users::uuid)))),
|
|
||||||
)
|
|
||||||
.select((
|
|
||||||
MemberBuilder::as_select(),
|
|
||||||
UserBuilder::as_select(),
|
|
||||||
Option::<Friend>::as_select(),
|
|
||||||
))
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
(member, user) = dsl::guild_members
|
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
|
||||||
.filter(dsl::user_uuid.eq(user_uuid))
|
|
||||||
.inner_join(users::table)
|
|
||||||
.select((MemberBuilder::as_select(), UserBuilder::as_select()))
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
friend = None;
|
member.build(data).await
|
||||||
}
|
|
||||||
|
|
||||||
member
|
|
||||||
.build_with_parts(conn, cache_pool, user, friend)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_one_with_uuid(
|
pub async fn fetch_all(data: &Data, guild_uuid: Uuid) -> Result<Vec<Self>, Error> {
|
||||||
conn: &mut Conn,
|
let mut conn = data.pool.get().await?;
|
||||||
cache_pool: &redis::Client,
|
|
||||||
me: Option<&Me>,
|
|
||||||
uuid: Uuid,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
let member: MemberBuilder;
|
|
||||||
let user: UserBuilder;
|
|
||||||
let friend: Option<Friend>;
|
|
||||||
use friends::dsl as fdsl;
|
|
||||||
use guild_members::dsl;
|
use guild_members::dsl;
|
||||||
if let Some(me) = me {
|
let member_builders: Vec<MemberBuilder> = load_or_empty(
|
||||||
(member, user, friend) = dsl::guild_members
|
|
||||||
.filter(dsl::uuid.eq(uuid))
|
|
||||||
.inner_join(users::table)
|
|
||||||
.left_join(
|
|
||||||
fdsl::friends.on(fdsl::uuid1
|
|
||||||
.eq(me.uuid)
|
|
||||||
.and(fdsl::uuid2.eq(users::uuid))
|
|
||||||
.or(fdsl::uuid2.eq(me.uuid).and(fdsl::uuid1.eq(users::uuid)))),
|
|
||||||
)
|
|
||||||
.select((
|
|
||||||
MemberBuilder::as_select(),
|
|
||||||
UserBuilder::as_select(),
|
|
||||||
Option::<Friend>::as_select(),
|
|
||||||
))
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
(member, user) = dsl::guild_members
|
|
||||||
.filter(dsl::uuid.eq(uuid))
|
|
||||||
.inner_join(users::table)
|
|
||||||
.select((MemberBuilder::as_select(), UserBuilder::as_select()))
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
friend = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
member
|
|
||||||
.build_with_parts(conn, cache_pool, user, friend)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_page(
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
me: &Me,
|
|
||||||
guild_uuid: Uuid,
|
|
||||||
pagination: PaginationRequest,
|
|
||||||
) -> Result<Pagination<Self>, Error> {
|
|
||||||
let per_page = pagination.per_page.unwrap_or(50);
|
|
||||||
let page_multiplier: i64 = ((pagination.page - 1) * per_page).into();
|
|
||||||
|
|
||||||
if !(10..=100).contains(&per_page) {
|
|
||||||
return Err(Error::BadRequest(
|
|
||||||
"Invalid amount per page requested".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
use friends::dsl as fdsl;
|
|
||||||
use guild_members::dsl;
|
|
||||||
let member_builders: Vec<(MemberBuilder, UserBuilder, Option<Friend>)> = load_or_empty(
|
|
||||||
dsl::guild_members
|
dsl::guild_members
|
||||||
.filter(dsl::guild_uuid.eq(guild_uuid))
|
.filter(dsl::guild_uuid.eq(guild_uuid))
|
||||||
.inner_join(users::table)
|
.select(MemberBuilder::as_select())
|
||||||
.left_join(
|
.load(&mut conn)
|
||||||
fdsl::friends.on(fdsl::uuid1
|
|
||||||
.eq(me.uuid)
|
|
||||||
.and(fdsl::uuid2.eq(users::uuid))
|
|
||||||
.or(fdsl::uuid2.eq(me.uuid).and(fdsl::uuid1.eq(users::uuid)))),
|
|
||||||
)
|
|
||||||
.limit(per_page.into())
|
|
||||||
.offset(page_multiplier)
|
|
||||||
.order_by(coalesce(
|
|
||||||
dsl::nickname,
|
|
||||||
users::display_name,
|
|
||||||
users::username,
|
|
||||||
))
|
|
||||||
.select((
|
|
||||||
MemberBuilder::as_select(),
|
|
||||||
UserBuilder::as_select(),
|
|
||||||
Option::<Friend>::as_select(),
|
|
||||||
))
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
.await,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let pages = Member::count(conn, guild_uuid).await? as f32 / per_page as f32;
|
let member_futures = member_builders
|
||||||
|
.iter()
|
||||||
|
.map(async move |m| m.build(data).await);
|
||||||
|
|
||||||
let mut members = Pagination::<Member> {
|
futures::future::try_join_all(member_futures).await
|
||||||
objects: Vec::with_capacity(member_builders.len()),
|
|
||||||
amount: member_builders.len() as i32,
|
|
||||||
pages: pages.ceil() as i32,
|
|
||||||
page: pagination.page,
|
|
||||||
};
|
|
||||||
|
|
||||||
for (member, user, friend) in member_builders {
|
|
||||||
members.objects.push(
|
|
||||||
member
|
|
||||||
.build_with_parts(conn, cache_pool, user, friend)
|
|
||||||
.await?,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(members)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn new(
|
pub async fn new(data: &Data, user_uuid: Uuid, guild_uuid: Uuid) -> Result<Self, Error> {
|
||||||
conn: &mut Conn,
|
let mut conn = data.pool.get().await?;
|
||||||
cache_pool: &redis::Client,
|
|
||||||
user_uuid: Uuid,
|
|
||||||
guild_uuid: Uuid,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
let banned = GuildBan::fetch_one(conn, guild_uuid, user_uuid).await;
|
|
||||||
|
|
||||||
match banned {
|
|
||||||
Ok(_) => Err(Error::Forbidden("User banned".to_string())),
|
|
||||||
Err(Error::SqlError(diesel::result::Error::NotFound)) => Ok(()),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}?;
|
|
||||||
|
|
||||||
let member_uuid = Uuid::now_v7();
|
let member_uuid = Uuid::now_v7();
|
||||||
|
|
||||||
|
@ -323,56 +113,13 @@ impl Member {
|
||||||
guild_uuid,
|
guild_uuid,
|
||||||
user_uuid,
|
user_uuid,
|
||||||
nickname: None,
|
nickname: None,
|
||||||
is_owner: false,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
insert_into(guild_members::table)
|
insert_into(guild_members::table)
|
||||||
.values(&member)
|
.values(&member)
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
member.build(conn, cache_pool, None).await
|
member.build(data).await
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn delete(self, conn: &mut Conn) -> Result<(), Error> {
|
|
||||||
if self.is_owner {
|
|
||||||
return Err(Error::Forbidden("Can not kick owner".to_string()));
|
|
||||||
}
|
|
||||||
delete(guild_members::table)
|
|
||||||
.filter(guild_members::uuid.eq(self.uuid))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn ban(self, conn: &mut Conn, reason: &String) -> Result<(), Error> {
|
|
||||||
if self.is_owner {
|
|
||||||
return Err(Error::Forbidden("Can not ban owner".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
use guild_bans::dsl;
|
|
||||||
insert_into(guild_bans::table)
|
|
||||||
.values((
|
|
||||||
dsl::guild_uuid.eq(self.guild_uuid),
|
|
||||||
dsl::user_uuid.eq(self.user_uuid),
|
|
||||||
dsl::reason.eq(reason),
|
|
||||||
))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
self.delete(conn).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn to_builder(&self) -> MemberBuilder {
|
|
||||||
MemberBuilder {
|
|
||||||
uuid: self.uuid,
|
|
||||||
nickname: self.nickname.clone(),
|
|
||||||
user_uuid: self.user_uuid,
|
|
||||||
guild_uuid: self.guild_uuid,
|
|
||||||
is_owner: self.is_owner,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +1,10 @@
|
||||||
use diesel::{ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable};
|
use diesel::{Insertable, Queryable, Selectable};
|
||||||
use diesel_async::RunQueryDsl;
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{Data, error::Error, schema::messages};
|
||||||
Conn,
|
|
||||||
error::Error,
|
|
||||||
schema::{channels, guilds, messages},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::Member;
|
use super::User;
|
||||||
|
|
||||||
#[derive(Clone, Queryable, Selectable, Insertable)]
|
#[derive(Clone, Queryable, Selectable, Insertable)]
|
||||||
#[diesel(table_name = messages)]
|
#[diesel(table_name = messages)]
|
||||||
|
@ -19,33 +14,18 @@ pub struct MessageBuilder {
|
||||||
pub channel_uuid: Uuid,
|
pub channel_uuid: Uuid,
|
||||||
pub user_uuid: Uuid,
|
pub user_uuid: Uuid,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
pub reply_to: Option<Uuid>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MessageBuilder {
|
impl MessageBuilder {
|
||||||
pub async fn build(
|
pub async fn build(&self, data: &Data) -> Result<Message, Error> {
|
||||||
&self,
|
let user = User::fetch_one(data, self.user_uuid).await?;
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
) -> Result<Message, Error> {
|
|
||||||
use channels::dsl;
|
|
||||||
|
|
||||||
let guild_uuid = dsl::channels
|
|
||||||
.filter(dsl::uuid.eq(self.channel_uuid))
|
|
||||||
.inner_join(guilds::table)
|
|
||||||
.select(guilds::uuid)
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let member = Member::fetch_one(conn, cache_pool, None, self.user_uuid, guild_uuid).await?;
|
|
||||||
|
|
||||||
Ok(Message {
|
Ok(Message {
|
||||||
uuid: self.uuid,
|
uuid: self.uuid,
|
||||||
channel_uuid: self.channel_uuid,
|
channel_uuid: self.channel_uuid,
|
||||||
user_uuid: self.user_uuid,
|
user_uuid: self.user_uuid,
|
||||||
message: self.message.clone(),
|
message: self.message.clone(),
|
||||||
reply_to: self.reply_to,
|
user,
|
||||||
member,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -56,6 +36,5 @@ pub struct Message {
|
||||||
channel_uuid: Uuid,
|
channel_uuid: Uuid,
|
||||||
user_uuid: Uuid,
|
user_uuid: Uuid,
|
||||||
message: String,
|
message: String,
|
||||||
reply_to: Option<Uuid>,
|
user: User,
|
||||||
member: Member,
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,13 +4,11 @@ use lettre::{
|
||||||
transport::smtp::authentication::Credentials,
|
transport::smtp::authentication::Credentials,
|
||||||
};
|
};
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Deserialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
mod bans;
|
|
||||||
mod channel;
|
mod channel;
|
||||||
mod email_token;
|
mod email_token;
|
||||||
mod friends;
|
|
||||||
mod guild;
|
mod guild;
|
||||||
mod invite;
|
mod invite;
|
||||||
mod me;
|
mod me;
|
||||||
|
@ -19,21 +17,19 @@ mod message;
|
||||||
mod password_reset_token;
|
mod password_reset_token;
|
||||||
mod role;
|
mod role;
|
||||||
mod user;
|
mod user;
|
||||||
|
mod signature;
|
||||||
|
|
||||||
pub use bans::GuildBan;
|
|
||||||
pub use channel::Channel;
|
pub use channel::Channel;
|
||||||
pub use email_token::EmailToken;
|
pub use email_token::EmailToken;
|
||||||
pub use friends::Friend;
|
|
||||||
pub use friends::FriendRequest;
|
|
||||||
pub use guild::Guild;
|
pub use guild::Guild;
|
||||||
pub use invite::Invite;
|
pub use invite::Invite;
|
||||||
pub use me::Me;
|
pub use me::Me;
|
||||||
pub use member::Member;
|
pub use member::Member;
|
||||||
pub use message::Message;
|
pub use message::Message;
|
||||||
pub use password_reset_token::PasswordResetToken;
|
pub use password_reset_token::PasswordResetToken;
|
||||||
pub use role::Permissions;
|
|
||||||
pub use role::Role;
|
pub use role::Role;
|
||||||
pub use user::User;
|
pub use user::User;
|
||||||
|
pub use signature::Signature;
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
|
@ -44,51 +40,6 @@ pub trait HasUuid {
|
||||||
pub trait HasIsAbove {
|
pub trait HasIsAbove {
|
||||||
fn is_above(&self) -> Option<&Uuid>;
|
fn is_above(&self) -> Option<&Uuid>;
|
||||||
}
|
}
|
||||||
/*
|
|
||||||
pub trait Cookies {
|
|
||||||
fn cookies(&self) -> CookieJar;
|
|
||||||
fn cookie<T: AsRef<str>>(&self, cookie: T) -> Option<Cookie>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Cookies for Request<Body> {
|
|
||||||
fn cookies(&self) -> CookieJar {
|
|
||||||
let cookies = self.headers()
|
|
||||||
.get(axum::http::header::COOKIE)
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.map(|s| Cookie::split_parse(s.to_string()))
|
|
||||||
.and_then(|c| c.collect::<Result<Vec<Cookie>, cookie::ParseError>>().ok())
|
|
||||||
.unwrap_or(vec![]);
|
|
||||||
|
|
||||||
let mut cookie_jar = CookieJar::new();
|
|
||||||
|
|
||||||
for cookie in cookies {
|
|
||||||
cookie_jar.add(cookie)
|
|
||||||
}
|
|
||||||
|
|
||||||
cookie_jar
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cookie<T: AsRef<str>>(&self, cookie: T) -> Option<Cookie> {
|
|
||||||
self.cookies()
|
|
||||||
.get(cookie.as_ref())
|
|
||||||
.and_then(|c| Some(c.to_owned()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
pub struct Pagination<T> {
|
|
||||||
objects: Vec<T>,
|
|
||||||
amount: i32,
|
|
||||||
pages: i32,
|
|
||||||
page: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
pub struct PaginationRequest {
|
|
||||||
pub page: i32,
|
|
||||||
pub per_page: Option<i32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load_or_empty<T>(
|
fn load_or_empty<T>(
|
||||||
query_result: Result<Vec<T>, diesel::result::Error>,
|
query_result: Result<Vec<T>, diesel::result::Error>,
|
||||||
|
@ -156,12 +107,50 @@ impl MailClient {
|
||||||
|
|
||||||
let response = mailer.send(email).await?;
|
let response = mailer.send(email).await?;
|
||||||
|
|
||||||
debug!("mail sending response: {response:?}");
|
debug!("mail sending response: {:?}", response);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub enum Permissions {
|
||||||
|
SendMessage = 1,
|
||||||
|
CreateChannel = 2,
|
||||||
|
DeleteChannel = 4,
|
||||||
|
ManageChannel = 8,
|
||||||
|
CreateRole = 16,
|
||||||
|
DeleteRole = 32,
|
||||||
|
ManageRole = 64,
|
||||||
|
CreateInvite = 128,
|
||||||
|
ManageInvite = 256,
|
||||||
|
ManageServer = 512,
|
||||||
|
ManageMember = 1024,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Permissions {
|
||||||
|
pub fn fetch_permissions(permissions: i64) -> Vec<Self> {
|
||||||
|
let all_perms = vec![
|
||||||
|
Self::SendMessage,
|
||||||
|
Self::CreateChannel,
|
||||||
|
Self::DeleteChannel,
|
||||||
|
Self::ManageChannel,
|
||||||
|
Self::CreateRole,
|
||||||
|
Self::DeleteRole,
|
||||||
|
Self::ManageRole,
|
||||||
|
Self::CreateInvite,
|
||||||
|
Self::ManageInvite,
|
||||||
|
Self::ManageServer,
|
||||||
|
Self::ManageMember,
|
||||||
|
];
|
||||||
|
|
||||||
|
all_perms
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| permissions & (*p as i64) != 0)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct StartAmountQuery {
|
pub struct StartAmountQuery {
|
||||||
pub start: Option<i64>,
|
pub start: Option<i64>,
|
||||||
|
|
|
@ -3,17 +3,19 @@ use argon2::{
|
||||||
password_hash::{SaltString, rand_core::OsRng},
|
password_hash::{SaltString, rand_core::OsRng},
|
||||||
};
|
};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use diesel::{ExpressionMethods, QueryDsl, update};
|
use diesel::{
|
||||||
|
ExpressionMethods, QueryDsl, update,
|
||||||
|
};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use lettre::message::MultiPart;
|
use lettre::message::MultiPart;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AppState, Conn,
|
Data,
|
||||||
error::Error,
|
error::Error,
|
||||||
schema::users,
|
schema::users,
|
||||||
utils::{CacheFns, PASSWORD_REGEX, generate_token, global_checks, user_uuid_from_identifier},
|
utils::{PASSWORD_REGEX, generate_refresh_token, global_checks, user_uuid_from_identifier},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
|
@ -24,49 +26,41 @@ pub struct PasswordResetToken {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PasswordResetToken {
|
impl PasswordResetToken {
|
||||||
pub async fn get(
|
pub async fn get(data: &Data, token: String) -> Result<PasswordResetToken, Error> {
|
||||||
cache_pool: &redis::Client,
|
let user_uuid: Uuid = serde_json::from_str(&data.get_cache_key(format!("{}", token)).await?)?;
|
||||||
token: String,
|
let password_reset_token = serde_json::from_str(&data.get_cache_key(format!("{}_password_reset", user_uuid)).await?)?;
|
||||||
) -> Result<PasswordResetToken, Error> {
|
|
||||||
let user_uuid: Uuid = cache_pool.get_cache_key(token.to_string()).await?;
|
|
||||||
let password_reset_token = cache_pool
|
|
||||||
.get_cache_key(format!("{user_uuid}_password_reset"))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(password_reset_token)
|
Ok(password_reset_token)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_with_identifier(
|
pub async fn get_with_identifier(
|
||||||
conn: &mut Conn,
|
data: &Data,
|
||||||
cache_pool: &redis::Client,
|
|
||||||
identifier: String,
|
identifier: String,
|
||||||
) -> Result<PasswordResetToken, Error> {
|
) -> Result<PasswordResetToken, Error> {
|
||||||
let user_uuid = user_uuid_from_identifier(conn, &identifier).await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
let password_reset_token = cache_pool
|
let user_uuid = user_uuid_from_identifier(&mut conn, &identifier).await?;
|
||||||
.get_cache_key(format!("{user_uuid}_password_reset"))
|
|
||||||
.await?;
|
let password_reset_token = serde_json::from_str(&data.get_cache_key(format!("{}_password_reset", user_uuid)).await?)?;
|
||||||
|
|
||||||
Ok(password_reset_token)
|
Ok(password_reset_token)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::new_ret_no_self)]
|
#[allow(clippy::new_ret_no_self)]
|
||||||
pub async fn new(
|
pub async fn new(data: &Data, identifier: String) -> Result<(), Error> {
|
||||||
conn: &mut Conn,
|
let token = generate_refresh_token()?;
|
||||||
app_state: &AppState,
|
|
||||||
identifier: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
let token = generate_token::<32>()?;
|
|
||||||
|
|
||||||
let user_uuid = user_uuid_from_identifier(conn, &identifier).await?;
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
global_checks(conn, &app_state.config, user_uuid).await?;
|
let user_uuid = user_uuid_from_identifier(&mut conn, &identifier).await?;
|
||||||
|
|
||||||
|
global_checks(data, user_uuid).await?;
|
||||||
|
|
||||||
use users::dsl as udsl;
|
use users::dsl as udsl;
|
||||||
let (username, email_address): (String, String) = udsl::users
|
let (username, email_address): (String, String) = udsl::users
|
||||||
.filter(udsl::uuid.eq(user_uuid))
|
.filter(udsl::uuid.eq(user_uuid))
|
||||||
.select((udsl::username, udsl::email))
|
.select((udsl::username, udsl::email))
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let password_reset_token = PasswordResetToken {
|
let password_reset_token = PasswordResetToken {
|
||||||
|
@ -75,44 +69,29 @@ impl PasswordResetToken {
|
||||||
created_at: Utc::now(),
|
created_at: Utc::now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
app_state
|
data.set_cache_key(format!("{}_password_reset", user_uuid), password_reset_token, 86400).await?;
|
||||||
.cache_pool
|
data.set_cache_key(token.clone(), user_uuid, 86400).await?;
|
||||||
.set_cache_key(
|
|
||||||
format!("{user_uuid}_password_reset"),
|
|
||||||
password_reset_token,
|
|
||||||
86400,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
app_state
|
|
||||||
.cache_pool
|
|
||||||
.set_cache_key(token.clone(), user_uuid, 86400)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut reset_endpoint = app_state.config.web.frontend_url.join("reset-password")?;
|
let mut reset_endpoint = data.config.web.frontend_url.join("reset-password")?;
|
||||||
|
|
||||||
reset_endpoint.set_query(Some(&format!("token={token}")));
|
reset_endpoint.set_query(Some(&format!("token={}", token)));
|
||||||
|
|
||||||
let email = app_state
|
let email = data
|
||||||
.mail_client
|
.mail_client
|
||||||
.message_builder()
|
.message_builder()
|
||||||
.to(email_address.parse()?)
|
.to(email_address.parse()?)
|
||||||
.subject(format!("{} Password Reset", app_state.config.instance.name))
|
.subject(format!("{} Password Reset", data.config.instance.name))
|
||||||
.multipart(MultiPart::alternative_plain_html(
|
.multipart(MultiPart::alternative_plain_html(
|
||||||
format!("{} Password Reset\n\nHello, {}!\nSomeone requested a password reset for your Gorb account.\nClick the button below within 24 hours to reset your password.\n\n{}\n\nIf you didn't request a password reset, don't worry, your account is safe and you can safely ignore this email.\n\nThanks, The gorb team.", app_state.config.instance.name, username, reset_endpoint),
|
format!("{} Password Reset\n\nHello, {}!\nSomeone requested a password reset for your Gorb account.\nClick the button below within 24 hours to reset your password.\n\n{}\n\nIf you didn't request a password reset, don't worry, your account is safe and you can safely ignore this email.\n\nThanks, The gorb team.", data.config.instance.name, username, reset_endpoint),
|
||||||
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root {{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark) {{:root {{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px) {{.container {{width: 100%;}}}}body {{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header {{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button {{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover {{background-color: var(--secondary-colour);}}.content {{padding: 20px 30px;}}.footer {{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>{} Password Reset</h1></div><div class="content"><h2>Hello, {}!</h2><p>Someone requested a password reset for your Gorb account.</p><p>Click the button below within 24 hours to reset your password.</p><a href="{}" class="verify-button">RESET PASSWORD</a><p>If you didn't request a password reset, don't worry, your account is safe and you can safely ignore this email.</p><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, app_state.config.instance.name, username, reset_endpoint)
|
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root {{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark) {{:root {{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px) {{.container {{width: 100%;}}}}body {{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header {{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button {{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover {{background-color: var(--secondary-colour);}}.content {{padding: 20px 30px;}}.footer {{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>{} Password Reset</h1></div><div class="content"><h2>Hello, {}!</h2><p>Someone requested a password reset for your Gorb account.</p><p>Click the button below within 24 hours to reset your password.</p><a href="{}" class="verify-button">RESET PASSWORD</a><p>If you didn't request a password reset, don't worry, your account is safe and you can safely ignore this email.</p><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, data.config.instance.name, username, reset_endpoint)
|
||||||
))?;
|
))?;
|
||||||
|
|
||||||
app_state.mail_client.send_mail(email).await?;
|
data.mail_client.send_mail(email).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_password(
|
pub async fn set_password(&self, data: &Data, password: String) -> Result<(), Error> {
|
||||||
&self,
|
|
||||||
conn: &mut Conn,
|
|
||||||
app_state: &AppState,
|
|
||||||
password: String,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if !PASSWORD_REGEX.is_match(&password) {
|
if !PASSWORD_REGEX.is_match(&password) {
|
||||||
return Err(Error::BadRequest(
|
return Err(Error::BadRequest(
|
||||||
"Please provide a valid password".to_string(),
|
"Please provide a valid password".to_string(),
|
||||||
|
@ -121,46 +100,46 @@ impl PasswordResetToken {
|
||||||
|
|
||||||
let salt = SaltString::generate(&mut OsRng);
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
|
||||||
let hashed_password = app_state
|
let hashed_password = data
|
||||||
.argon2
|
.argon2
|
||||||
.hash_password(password.as_bytes(), &salt)
|
.hash_password(password.as_bytes(), &salt)
|
||||||
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
|
||||||
|
|
||||||
|
let mut conn = data.pool.get().await?;
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
update(users::table)
|
update(users::table)
|
||||||
.filter(dsl::uuid.eq(self.user_uuid))
|
.filter(dsl::uuid.eq(self.user_uuid))
|
||||||
.set(dsl::password.eq(hashed_password.to_string()))
|
.set(dsl::password.eq(hashed_password.to_string()))
|
||||||
.execute(conn)
|
.execute(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let (username, email_address): (String, String) = dsl::users
|
let (username, email_address): (String, String) = dsl::users
|
||||||
.filter(dsl::uuid.eq(self.user_uuid))
|
.filter(dsl::uuid.eq(self.user_uuid))
|
||||||
.select((dsl::username, dsl::email))
|
.select((dsl::username, dsl::email))
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let login_page = app_state.config.web.frontend_url.join("login")?;
|
let login_page = data.config.web.frontend_url.join("login")?;
|
||||||
|
|
||||||
let email = app_state
|
let email = data
|
||||||
.mail_client
|
.mail_client
|
||||||
.message_builder()
|
.message_builder()
|
||||||
.to(email_address.parse()?)
|
.to(email_address.parse()?)
|
||||||
.subject(format!("Your {} Password has been Reset", app_state.config.instance.name))
|
.subject(format!("Your {} Password has been Reset", data.config.instance.name))
|
||||||
.multipart(MultiPart::alternative_plain_html(
|
.multipart(MultiPart::alternative_plain_html(
|
||||||
format!("{} Password Reset Confirmation\n\nHello, {}!\nYour password has been successfully reset for your Gorb account.\nIf you did not initiate this change, please click the link below to reset your password <strong>immediately</strong>.\n\n{}\n\nThanks, The gorb team.", app_state.config.instance.name, username, login_page),
|
format!("{} Password Reset Confirmation\n\nHello, {}!\nYour password has been successfully reset for your Gorb account.\nIf you did not initiate this change, please click the link below to reset your password <strong>immediately</strong>.\n\n{}\n\nThanks, The gorb team.", data.config.instance.name, username, login_page),
|
||||||
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root {{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark) {{:root {{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px) {{.container {{width: 100%;}}}}body {{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header {{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button {{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover {{background-color: var(--secondary-colour);}}.content {{padding: 20px 30px;}}.footer {{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>{} Password Reset Confirmation</h1></div><div class="content"><h2>Hello, {}!</h2><p>Your password has been successfully reset for your Gorb account.</p><p>If you did not initiate this change, please click the button below to reset your password <strong>immediately</strong>.</p><a href="{}" class="verify-button">RESET PASSWORD</a><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, app_state.config.instance.name, username, login_page)
|
format!(r#"<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style>:root {{--header-text-colour: #ffffff;--footer-text-colour: #7f7f7f;--button-text-colour: #170e08;--text-colour: #170e08;--background-colour: #fbf6f2;--primary-colour: #df5f0b;--secondary-colour: #e8ac84;--accent-colour: #e68b4e;}}@media (prefers-color-scheme: dark) {{:root {{--header-text-colour: #ffffff;--footer-text-colour: #585858;--button-text-colour: #ffffff;--text-colour: #f7eee8;--background-colour: #0c0704;--primary-colour: #f4741f;--secondary-colour: #7c4018;--accent-colour: #b35719;}}}}@media (max-width: 600px) {{.container {{width: 100%;}}}}body {{font-family: Arial, sans-serif;align-content: center;text-align: center;margin: 0;padding: 0;background-color: var(--background-colour);color: var(--text-colour);width: 100%;max-width: 600px;margin: 0 auto;border-radius: 5px;}}.header {{background-color: var(--primary-colour);color: var(--header-text-colour);padding: 20px;}}.verify-button {{background-color: var(--accent-colour);color: var(--button-text-colour);padding: 12px 30px;margin: 16px;font-size: 20px;transition: background-color 0.3s;cursor: pointer;border: none;border-radius: 14px;text-decoration: none;display: inline-block;}}.verify-button:hover {{background-color: var(--secondary-colour);}}.content {{padding: 20px 30px;}}.footer {{padding: 10px;font-size: 12px;color: var(--footer-text-colour);}}</style></head><body><div class="container"><div class="header"><h1>{} Password Reset Confirmation</h1></div><div class="content"><h2>Hello, {}!</h2><p>Your password has been successfully reset for your Gorb account.</p><p>If you did not initiate this change, please click the button below to reset your password <strong>immediately</strong>.</p><a href="{}" class="verify-button">RESET PASSWORD</a><div class="footer"><p>Thanks<br>The gorb team.</p></div></div></div></body></html>"#, data.config.instance.name, username, login_page)
|
||||||
))?;
|
))?;
|
||||||
|
|
||||||
app_state.mail_client.send_mail(email).await?;
|
data.mail_client.send_mail(email).await?;
|
||||||
|
|
||||||
self.delete(&app_state.cache_pool).await
|
self.delete(&data).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete(&self, cache_pool: &redis::Client) -> Result<(), Error> {
|
pub async fn delete(&self, data: &Data) -> Result<(), Error> {
|
||||||
cache_pool
|
data.del_cache_key(format!("{}_password_reset", &self.user_uuid)).await?;
|
||||||
.del_cache_key(format!("{}_password_reset", &self.user_uuid))
|
data.del_cache_key(format!("{}", &self.token)).await?;
|
||||||
.await?;
|
|
||||||
cache_pool.del_cache_key(self.token.to_string()).await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,17 @@
|
||||||
use diesel::query_dsl::BelongingToDsl;
|
|
||||||
use diesel::{
|
use diesel::{
|
||||||
Associations, ExpressionMethods, Identifiable, Insertable, QueryDsl, Queryable, Selectable,
|
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, insert_into,
|
||||||
SelectableHelper, insert_into, update,
|
update,
|
||||||
};
|
};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Serialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{Conn, error::Error, schema::roles, utils::order_by_is_above};
|
||||||
Conn,
|
|
||||||
error::Error,
|
|
||||||
schema::{role_members, roles},
|
|
||||||
utils::{CacheFns, order_by_is_above},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{HasIsAbove, HasUuid, load_or_empty, member::MemberBuilder};
|
use super::{HasIsAbove, HasUuid, load_or_empty};
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize, Clone, Identifiable, Queryable, Selectable, Insertable)]
|
#[derive(Serialize, Clone, Queryable, Selectable, Insertable)]
|
||||||
#[diesel(table_name = roles)]
|
#[diesel(table_name = roles)]
|
||||||
#[diesel(primary_key(uuid))]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||||
pub struct Role {
|
pub struct Role {
|
||||||
uuid: Uuid,
|
uuid: Uuid,
|
||||||
|
@ -26,18 +19,7 @@ pub struct Role {
|
||||||
name: String,
|
name: String,
|
||||||
color: i32,
|
color: i32,
|
||||||
is_above: Option<Uuid>,
|
is_above: Option<Uuid>,
|
||||||
pub permissions: i64,
|
permissions: i64,
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone, Identifiable, Queryable, Selectable, Insertable, Associations)]
|
|
||||||
#[diesel(table_name = role_members)]
|
|
||||||
#[diesel(belongs_to(MemberBuilder, foreign_key = member_uuid))]
|
|
||||||
#[diesel(belongs_to(Role, foreign_key = role_uuid))]
|
|
||||||
#[diesel(primary_key(role_uuid, member_uuid))]
|
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
|
||||||
pub struct RoleMember {
|
|
||||||
role_uuid: Uuid,
|
|
||||||
member_uuid: Uuid,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HasUuid for Role {
|
impl HasUuid for Role {
|
||||||
|
@ -66,33 +48,6 @@ impl Role {
|
||||||
Ok(roles)
|
Ok(roles)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_from_member(
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
member: &MemberBuilder,
|
|
||||||
) -> Result<Vec<Self>, Error> {
|
|
||||||
if let Ok(roles) = cache_pool
|
|
||||||
.get_cache_key(format!("{}_roles", member.uuid))
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
return Ok(roles);
|
|
||||||
}
|
|
||||||
|
|
||||||
let roles: Vec<Role> = load_or_empty(
|
|
||||||
RoleMember::belonging_to(member)
|
|
||||||
.inner_join(roles::table)
|
|
||||||
.select(Role::as_select())
|
|
||||||
.load(conn)
|
|
||||||
.await,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
cache_pool
|
|
||||||
.set_cache_key(format!("{}_roles", member.uuid), roles.clone(), 300)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(roles)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_one(conn: &mut Conn, role_uuid: Uuid) -> Result<Self, Error> {
|
pub async fn fetch_one(conn: &mut Conn, role_uuid: Uuid) -> Result<Self, Error> {
|
||||||
use roles::dsl;
|
use roles::dsl;
|
||||||
let role: Role = dsl::roles
|
let role: Role = dsl::roles
|
||||||
|
@ -104,10 +59,6 @@ impl Role {
|
||||||
Ok(role)
|
Ok(role)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_permissions(&self) -> Vec<Permissions> {
|
|
||||||
Permissions::fetch_permissions(self.permissions)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn new(conn: &mut Conn, guild_uuid: Uuid, name: String) -> Result<Self, Error> {
|
pub async fn new(conn: &mut Conn, guild_uuid: Uuid, name: String) -> Result<Self, Error> {
|
||||||
let role_uuid = Uuid::now_v7();
|
let role_uuid = Uuid::now_v7();
|
||||||
|
|
||||||
|
@ -143,46 +94,3 @@ impl Role {
|
||||||
Ok(new_role)
|
Ok(new_role)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum Permissions {
|
|
||||||
/// Lets users send messages in the guild or channel
|
|
||||||
SendMessage = 1,
|
|
||||||
/// Lets users create, delete and edit channels and categories or a singular channel depending on permission context
|
|
||||||
ManageChannel = 2,
|
|
||||||
/// Lets users manage roles in the guild
|
|
||||||
ManageRole = 4,
|
|
||||||
/// Lets users create invites in the guild
|
|
||||||
CreateInvite = 8,
|
|
||||||
/// Lets users manage invites in the guild
|
|
||||||
ManageInvite = 16,
|
|
||||||
/// Lets users change guild settings
|
|
||||||
ManageGuild = 32,
|
|
||||||
/// Lets users change member settings (nickname, etc)
|
|
||||||
ManageMember = 64,
|
|
||||||
/// Lets users ban members
|
|
||||||
BanMember = 128,
|
|
||||||
/// Lets users kick members
|
|
||||||
KickMember = 256,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Permissions {
|
|
||||||
pub fn fetch_permissions(permissions: i64) -> Vec<Self> {
|
|
||||||
let all_perms = vec![
|
|
||||||
Self::SendMessage,
|
|
||||||
Self::ManageChannel,
|
|
||||||
Self::ManageRole,
|
|
||||||
Self::CreateInvite,
|
|
||||||
Self::ManageInvite,
|
|
||||||
Self::ManageGuild,
|
|
||||||
Self::ManageMember,
|
|
||||||
Self::BanMember,
|
|
||||||
Self::KickMember,
|
|
||||||
];
|
|
||||||
|
|
||||||
all_perms
|
|
||||||
.into_iter()
|
|
||||||
.filter(|p| permissions & (*p as i64) != 0)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
68
src/objects/signature.rs
Normal file
68
src/objects/signature.rs
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use actix_web::http::header::HeaderMap;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub struct Signature {
|
||||||
|
pub url: Url,
|
||||||
|
pub signature: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Signature {
|
||||||
|
pub fn from_signature_header(headers: &HeaderMap) -> Result<Signature, Error> {
|
||||||
|
let signature_header = headers.get(actix_web::http::header::HeaderName::from_static("signature"));
|
||||||
|
|
||||||
|
if signature_header.is_none() {
|
||||||
|
return Err(Error::Unauthorized(
|
||||||
|
"No signature header provided".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let signature_raw = signature_header.unwrap().to_str()?;
|
||||||
|
|
||||||
|
let key_values = signature_raw.split_whitespace();
|
||||||
|
|
||||||
|
let mut hash_map = HashMap::new();
|
||||||
|
|
||||||
|
let results: Result<Vec<()>, Error> = key_values.map(|kv| {
|
||||||
|
let mut kv_split = kv.split('=');
|
||||||
|
let key = kv_split.next().unwrap().to_string();
|
||||||
|
let value = kv_split.next().ok_or(Error::BadRequest(format!(r#"Expected key="value", found {}"#, key)))?.trim_matches('"').to_string();
|
||||||
|
|
||||||
|
hash_map.insert(key, value);
|
||||||
|
|
||||||
|
Ok::<(), Error>(())
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
results?;
|
||||||
|
|
||||||
|
let key_id = hash_map.get("keyId");
|
||||||
|
let algorithm = hash_map.get("algorithm");
|
||||||
|
let signature = hash_map.get("signature");
|
||||||
|
|
||||||
|
if key_id.is_none() {
|
||||||
|
return Err(Error::BadRequest("No keyId was provided".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if algorithm.is_none() {
|
||||||
|
return Err(Error::BadRequest("No key algorithm was provided".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
if signature.is_none() {
|
||||||
|
return Err(Error::BadRequest("No signature was provided".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
let key_id = key_id.unwrap();
|
||||||
|
let algorithm = algorithm.unwrap();
|
||||||
|
let signature = signature.unwrap();
|
||||||
|
|
||||||
|
if algorithm != "ed25519" {
|
||||||
|
return Err(Error::BadRequest(format!("Unsupported signature {}, please use ed25519", algorithm)))
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Signature { url: key_id.parse()?, signature: signature.clone() })
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,111 +1,60 @@
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use diesel::{ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper};
|
use diesel::{ExpressionMethods, QueryDsl, Queryable, Selectable, SelectableHelper};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{Conn, error::Error, objects::Me, schema::users, utils::CacheFns};
|
use crate::{Conn, Data, error::Error, schema::users};
|
||||||
|
|
||||||
use super::load_or_empty;
|
use super::load_or_empty;
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize, Clone, Queryable, Selectable)]
|
#[derive(Deserialize, Serialize, Clone, Queryable, Selectable)]
|
||||||
#[diesel(table_name = users)]
|
#[diesel(table_name = users)]
|
||||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||||
pub struct UserBuilder {
|
pub struct User {
|
||||||
uuid: Uuid,
|
uuid: Uuid,
|
||||||
username: String,
|
username: String,
|
||||||
display_name: Option<String>,
|
display_name: Option<String>,
|
||||||
avatar: Option<String>,
|
avatar: Option<String>,
|
||||||
pronouns: Option<String>,
|
pronouns: Option<String>,
|
||||||
about: Option<String>,
|
about: Option<String>,
|
||||||
online_status: i16,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UserBuilder {
|
|
||||||
pub fn build(self) -> User {
|
|
||||||
User {
|
|
||||||
uuid: self.uuid,
|
|
||||||
username: self.username,
|
|
||||||
display_name: self.display_name,
|
|
||||||
avatar: self.avatar,
|
|
||||||
pronouns: self.pronouns,
|
|
||||||
about: self.about,
|
|
||||||
online_status: self.online_status,
|
|
||||||
friends_since: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize, Clone)]
|
|
||||||
pub struct User {
|
|
||||||
pub uuid: Uuid,
|
|
||||||
username: String,
|
|
||||||
display_name: Option<String>,
|
|
||||||
avatar: Option<String>,
|
|
||||||
pronouns: Option<String>,
|
|
||||||
about: Option<String>,
|
|
||||||
online_status: i16,
|
|
||||||
pub friends_since: Option<DateTime<Utc>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
pub async fn fetch_one(
|
pub async fn fetch_one(data: &Data, user_uuid: Uuid) -> Result<Self, Error> {
|
||||||
conn: &mut Conn,
|
let mut conn = data.pool.get().await?;
|
||||||
cache_pool: &redis::Client,
|
|
||||||
user_uuid: Uuid,
|
if let Ok(cache_hit) = data.get_cache_key(user_uuid.to_string()).await {
|
||||||
) -> Result<Self, Error> {
|
return Ok(serde_json::from_str(&cache_hit)?);
|
||||||
if let Ok(cache_hit) = cache_pool.get_cache_key(user_uuid.to_string()).await {
|
|
||||||
return Ok(cache_hit);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
let user_builder: UserBuilder = dsl::users
|
let user: User = dsl::users
|
||||||
.filter(dsl::uuid.eq(user_uuid))
|
.filter(dsl::uuid.eq(user_uuid))
|
||||||
.select(UserBuilder::as_select())
|
.select(User::as_select())
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let user = user_builder.build();
|
data.set_cache_key(user_uuid.to_string(), user.clone(), 1800)
|
||||||
|
|
||||||
cache_pool
|
|
||||||
.set_cache_key(user_uuid.to_string(), user.clone(), 1800)
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_one_with_friendship(
|
|
||||||
conn: &mut Conn,
|
|
||||||
cache_pool: &redis::Client,
|
|
||||||
me: &Me,
|
|
||||||
user_uuid: Uuid,
|
|
||||||
) -> Result<Self, Error> {
|
|
||||||
let mut user = Self::fetch_one(conn, cache_pool, user_uuid).await?;
|
|
||||||
|
|
||||||
if let Some(friend) = me.friends_with(conn, user_uuid).await? {
|
|
||||||
user.friends_since = Some(friend.accepted_at);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(user)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_amount(
|
pub async fn fetch_amount(
|
||||||
conn: &mut Conn,
|
conn: &mut Conn,
|
||||||
offset: i64,
|
offset: i64,
|
||||||
amount: i64,
|
amount: i64,
|
||||||
) -> Result<Vec<Self>, Error> {
|
) -> Result<Vec<Self>, Error> {
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
let user_builders: Vec<UserBuilder> = load_or_empty(
|
let users: Vec<User> = load_or_empty(
|
||||||
dsl::users
|
dsl::users
|
||||||
.limit(amount)
|
.limit(amount)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
.select(UserBuilder::as_select())
|
.select(User::as_select())
|
||||||
.load(conn)
|
.load(conn)
|
||||||
.await,
|
.await,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
let users: Vec<User> = user_builders.iter().map(|u| u.clone().build()).collect();
|
|
||||||
|
|
||||||
Ok(users)
|
Ok(users)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,28 +32,11 @@ diesel::table! {
|
||||||
}
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
friend_requests (sender, receiver) {
|
federated_users (uuid) {
|
||||||
sender -> Uuid,
|
uuid -> Uuid,
|
||||||
receiver -> Uuid,
|
email_verified -> Bool,
|
||||||
requested_at -> Timestamptz,
|
#[max_length = 8000]
|
||||||
}
|
instance_url -> Varchar,
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
friends (uuid1, uuid2) {
|
|
||||||
uuid1 -> Uuid,
|
|
||||||
uuid2 -> Uuid,
|
|
||||||
accepted_at -> Timestamptz,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
guild_bans (user_uuid, guild_uuid) {
|
|
||||||
guild_uuid -> Uuid,
|
|
||||||
user_uuid -> Uuid,
|
|
||||||
#[max_length = 200]
|
|
||||||
reason -> Nullable<Varchar>,
|
|
||||||
banned_since -> Timestamptz,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -64,18 +47,18 @@ diesel::table! {
|
||||||
user_uuid -> Uuid,
|
user_uuid -> Uuid,
|
||||||
#[max_length = 100]
|
#[max_length = 100]
|
||||||
nickname -> Nullable<Varchar>,
|
nickname -> Nullable<Varchar>,
|
||||||
is_owner -> Bool,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
guilds (uuid) {
|
guilds (uuid) {
|
||||||
uuid -> Uuid,
|
uuid -> Uuid,
|
||||||
|
owner_uuid -> Uuid,
|
||||||
#[max_length = 100]
|
#[max_length = 100]
|
||||||
name -> Varchar,
|
name -> Varchar,
|
||||||
#[max_length = 300]
|
#[max_length = 300]
|
||||||
description -> Nullable<Varchar>,
|
description -> Nullable<Varchar>,
|
||||||
#[max_length = 8000]
|
#[max_length = 100]
|
||||||
icon -> Nullable<Varchar>,
|
icon -> Nullable<Varchar>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -87,6 +70,15 @@ diesel::table! {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
instances (instance_url) {
|
||||||
|
#[max_length = 8000]
|
||||||
|
instance_url -> Varchar,
|
||||||
|
#[max_length = 500]
|
||||||
|
public_key -> Varchar,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
invites (id) {
|
invites (id) {
|
||||||
#[max_length = 32]
|
#[max_length = 32]
|
||||||
|
@ -103,7 +95,6 @@ diesel::table! {
|
||||||
user_uuid -> Uuid,
|
user_uuid -> Uuid,
|
||||||
#[max_length = 4000]
|
#[max_length = 4000]
|
||||||
message -> Varchar,
|
message -> Varchar,
|
||||||
reply_to -> Nullable<Uuid>,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -113,7 +104,7 @@ diesel::table! {
|
||||||
token -> Varchar,
|
token -> Varchar,
|
||||||
uuid -> Uuid,
|
uuid -> Uuid,
|
||||||
created_at -> Int8,
|
created_at -> Int8,
|
||||||
#[max_length = 64]
|
#[max_length = 16]
|
||||||
device_name -> Varchar,
|
device_name -> Varchar,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -126,7 +117,7 @@ diesel::table! {
|
||||||
}
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
roles (uuid) {
|
roles (uuid, guild_uuid) {
|
||||||
uuid -> Uuid,
|
uuid -> Uuid,
|
||||||
guild_uuid -> Uuid,
|
guild_uuid -> Uuid,
|
||||||
#[max_length = 50]
|
#[max_length = 50]
|
||||||
|
@ -151,25 +142,23 @@ diesel::table! {
|
||||||
email_verified -> Bool,
|
email_verified -> Bool,
|
||||||
is_deleted -> Bool,
|
is_deleted -> Bool,
|
||||||
deleted_at -> Nullable<Int8>,
|
deleted_at -> Nullable<Int8>,
|
||||||
#[max_length = 8000]
|
#[max_length = 100]
|
||||||
avatar -> Nullable<Varchar>,
|
avatar -> Nullable<Varchar>,
|
||||||
#[max_length = 32]
|
#[max_length = 32]
|
||||||
pronouns -> Nullable<Varchar>,
|
pronouns -> Nullable<Varchar>,
|
||||||
#[max_length = 200]
|
#[max_length = 200]
|
||||||
about -> Nullable<Varchar>,
|
about -> Nullable<Varchar>,
|
||||||
online_status -> Int2,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
diesel::joinable!(access_tokens -> refresh_tokens (refresh_token));
|
diesel::joinable!(access_tokens -> refresh_tokens (refresh_token));
|
||||||
diesel::joinable!(access_tokens -> users (uuid));
|
diesel::joinable!(access_tokens -> users (uuid));
|
||||||
diesel::joinable!(channel_permissions -> channels (channel_uuid));
|
diesel::joinable!(channel_permissions -> channels (channel_uuid));
|
||||||
diesel::joinable!(channel_permissions -> roles (role_uuid));
|
|
||||||
diesel::joinable!(channels -> guilds (guild_uuid));
|
diesel::joinable!(channels -> guilds (guild_uuid));
|
||||||
diesel::joinable!(guild_bans -> guilds (guild_uuid));
|
diesel::joinable!(federated_users -> instances (instance_url));
|
||||||
diesel::joinable!(guild_bans -> users (user_uuid));
|
|
||||||
diesel::joinable!(guild_members -> guilds (guild_uuid));
|
diesel::joinable!(guild_members -> guilds (guild_uuid));
|
||||||
diesel::joinable!(guild_members -> users (user_uuid));
|
diesel::joinable!(guild_members -> users (user_uuid));
|
||||||
|
diesel::joinable!(guilds -> users (owner_uuid));
|
||||||
diesel::joinable!(instance_permissions -> users (uuid));
|
diesel::joinable!(instance_permissions -> users (uuid));
|
||||||
diesel::joinable!(invites -> guilds (guild_uuid));
|
diesel::joinable!(invites -> guilds (guild_uuid));
|
||||||
diesel::joinable!(invites -> users (user_uuid));
|
diesel::joinable!(invites -> users (user_uuid));
|
||||||
|
@ -177,19 +166,17 @@ diesel::joinable!(messages -> channels (channel_uuid));
|
||||||
diesel::joinable!(messages -> users (user_uuid));
|
diesel::joinable!(messages -> users (user_uuid));
|
||||||
diesel::joinable!(refresh_tokens -> users (uuid));
|
diesel::joinable!(refresh_tokens -> users (uuid));
|
||||||
diesel::joinable!(role_members -> guild_members (member_uuid));
|
diesel::joinable!(role_members -> guild_members (member_uuid));
|
||||||
diesel::joinable!(role_members -> roles (role_uuid));
|
|
||||||
diesel::joinable!(roles -> guilds (guild_uuid));
|
diesel::joinable!(roles -> guilds (guild_uuid));
|
||||||
|
|
||||||
diesel::allow_tables_to_appear_in_same_query!(
|
diesel::allow_tables_to_appear_in_same_query!(
|
||||||
access_tokens,
|
access_tokens,
|
||||||
channel_permissions,
|
channel_permissions,
|
||||||
channels,
|
channels,
|
||||||
friend_requests,
|
federated_users,
|
||||||
friends,
|
|
||||||
guild_bans,
|
|
||||||
guild_members,
|
guild_members,
|
||||||
guilds,
|
guilds,
|
||||||
instance_permissions,
|
instance_permissions,
|
||||||
|
instances,
|
||||||
invites,
|
invites,
|
||||||
messages,
|
messages,
|
||||||
refresh_tokens,
|
refresh_tokens,
|
||||||
|
|
|
@ -1,28 +0,0 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use log::info;
|
|
||||||
use rmpv::Value;
|
|
||||||
use socketioxide::extract::{AckSender, Data, SocketRef, State};
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
pub async fn on_connect(
|
|
||||||
State(_app_state): State<Arc<AppState>>,
|
|
||||||
socket: SocketRef,
|
|
||||||
Data(data): Data<Value>,
|
|
||||||
) {
|
|
||||||
socket.emit("auth", &data).ok();
|
|
||||||
|
|
||||||
socket.on("message", async |socket: SocketRef, Data::<Value>(data)| {
|
|
||||||
info!("{data}");
|
|
||||||
socket.emit("message-back", &data).ok();
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on(
|
|
||||||
"message-with-ack",
|
|
||||||
async |Data::<Value>(data), ack: AckSender| {
|
|
||||||
info!("{data}");
|
|
||||||
ack.send(&data).ok();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
178
src/utils.rs
178
src/utils.rs
|
@ -1,25 +1,26 @@
|
||||||
use rand::seq::IndexedRandom;
|
use std::{collections::HashMap, sync::LazyLock};
|
||||||
use std::sync::LazyLock;
|
|
||||||
|
|
||||||
use axum::body::Bytes;
|
use actix_web::{
|
||||||
use axum_extra::extract::cookie::{Cookie, SameSite};
|
cookie::{Cookie, SameSite, time::Duration},
|
||||||
|
http::header::HeaderMap,
|
||||||
|
web::BytesMut,
|
||||||
|
};
|
||||||
use bindet::FileType;
|
use bindet::FileType;
|
||||||
use diesel::{ExpressionMethods, QueryDsl};
|
use diesel::{ExpressionMethods, QueryDsl};
|
||||||
use diesel_async::RunQueryDsl;
|
use diesel_async::RunQueryDsl;
|
||||||
use getrandom::fill;
|
use getrandom::fill;
|
||||||
use hex::encode;
|
use hex::encode;
|
||||||
|
use redis::RedisError;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde::{Serialize, de::DeserializeOwned};
|
use serde::Serialize;
|
||||||
use time::Duration;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Conn,
|
Conn, Data,
|
||||||
config::Config,
|
config::Config,
|
||||||
error::Error,
|
error::Error,
|
||||||
objects::{HasIsAbove, HasUuid},
|
objects::{HasIsAbove, HasUuid},
|
||||||
schema::users,
|
schema::users,
|
||||||
wordlist::{ADJECTIVES, ANIMALS},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
pub static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
||||||
|
@ -32,25 +33,101 @@ pub static USERNAME_REGEX: LazyLock<Regex> =
|
||||||
pub static CHANNEL_REGEX: LazyLock<Regex> =
|
pub static CHANNEL_REGEX: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"^[a-z0-9_.-]+$").unwrap());
|
LazyLock::new(|| Regex::new(r"^[a-z0-9_.-]+$").unwrap());
|
||||||
|
|
||||||
|
// Password is expected to be hashed using SHA3-384
|
||||||
pub static PASSWORD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[0-9a-f]{96}").unwrap());
|
pub static PASSWORD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[0-9a-f]{96}").unwrap());
|
||||||
|
|
||||||
pub fn new_refresh_token_cookie(config: &Config, refresh_token: String) -> Cookie {
|
pub fn get_auth_header(headers: &HeaderMap) -> Result<&str, Error> {
|
||||||
Cookie::build(("refresh_token", refresh_token))
|
let auth_token = headers.get(actix_web::http::header::AUTHORIZATION);
|
||||||
|
|
||||||
|
if auth_token.is_none() {
|
||||||
|
return Err(Error::Unauthorized(
|
||||||
|
"No authorization header provided".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth_raw = auth_token.unwrap().to_str()?;
|
||||||
|
|
||||||
|
let mut auth = auth_raw.split_whitespace();
|
||||||
|
|
||||||
|
let auth_type = auth.next();
|
||||||
|
|
||||||
|
let auth_value = auth.next();
|
||||||
|
|
||||||
|
if auth_type.is_none() {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
"Authorization header is empty".to_string(),
|
||||||
|
));
|
||||||
|
} else if auth_type.is_some_and(|at| at != "Bearer") {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
"Only token auth is supported".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if auth_value.is_none() {
|
||||||
|
return Err(Error::BadRequest("No token provided".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(auth_value.unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_ws_protocol_header(headers: &HeaderMap) -> Result<&str, Error> {
|
||||||
|
let auth_token = headers.get(actix_web::http::header::SEC_WEBSOCKET_PROTOCOL);
|
||||||
|
|
||||||
|
if auth_token.is_none() {
|
||||||
|
return Err(Error::Unauthorized(
|
||||||
|
"No authorization header provided".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth_raw = auth_token.unwrap().to_str()?;
|
||||||
|
|
||||||
|
let mut auth = auth_raw.split_whitespace();
|
||||||
|
|
||||||
|
let response_proto = auth.next();
|
||||||
|
|
||||||
|
let auth_value = auth.next();
|
||||||
|
|
||||||
|
if response_proto.is_none() {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
"Sec-WebSocket-Protocol header is empty".to_string(),
|
||||||
|
));
|
||||||
|
} else if response_proto.is_some_and(|rp| rp != "Authorization,") {
|
||||||
|
return Err(Error::BadRequest(
|
||||||
|
"First protocol should be Authorization".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if auth_value.is_none() {
|
||||||
|
return Err(Error::BadRequest("No token provided".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(auth_value.unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_refresh_token_cookie(config: &Config, refresh_token: String) -> Cookie<'static> {
|
||||||
|
Cookie::build("refresh_token", refresh_token)
|
||||||
.http_only(true)
|
.http_only(true)
|
||||||
.secure(true)
|
.secure(true)
|
||||||
.same_site(SameSite::None)
|
.same_site(SameSite::None)
|
||||||
|
//.domain(config.web.backend_url.domain().unwrap().to_string())
|
||||||
.path(config.web.backend_url.path().to_string())
|
.path(config.web.backend_url.path().to_string())
|
||||||
.max_age(Duration::days(30))
|
.max_age(Duration::days(30))
|
||||||
.build()
|
.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_token<const N: usize>() -> Result<String, getrandom::Error> {
|
pub fn generate_access_token() -> Result<String, getrandom::Error> {
|
||||||
let mut buf = [0u8; N];
|
let mut buf = [0u8; 16];
|
||||||
fill(&mut buf)?;
|
fill(&mut buf)?;
|
||||||
Ok(encode(buf))
|
Ok(encode(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn image_check(icon: Bytes) -> Result<String, Error> {
|
pub fn generate_refresh_token() -> Result<String, getrandom::Error> {
|
||||||
|
let mut buf = [0u8; 32];
|
||||||
|
fill(&mut buf)?;
|
||||||
|
Ok(encode(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn image_check(icon: BytesMut) -> Result<String, Error> {
|
||||||
let buf = std::io::Cursor::new(icon);
|
let buf = std::io::Cursor::new(icon);
|
||||||
|
|
||||||
let detect = bindet::detect(buf).map_err(|e| e.kind());
|
let detect = bindet::detect(buf).map_err(|e| e.kind());
|
||||||
|
@ -97,30 +174,15 @@ pub async fn user_uuid_from_identifier(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn user_uuid_from_username(conn: &mut Conn, username: &String) -> Result<Uuid, Error> {
|
pub async fn global_checks(data: &Data, user_uuid: Uuid) -> Result<(), Error> {
|
||||||
if USERNAME_REGEX.is_match(username) {
|
if data.config.instance.require_email_verification {
|
||||||
use users::dsl;
|
let mut conn = data.pool.get().await?;
|
||||||
let user_uuid = dsl::users
|
|
||||||
.filter(dsl::username.eq(username))
|
|
||||||
.select(dsl::uuid)
|
|
||||||
.get_result(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(user_uuid)
|
|
||||||
} else {
|
|
||||||
Err(Error::BadRequest(
|
|
||||||
"Please provide a valid username".to_string(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn global_checks(conn: &mut Conn, config: &Config, user_uuid: Uuid) -> Result<(), Error> {
|
|
||||||
if config.instance.require_email_verification {
|
|
||||||
use users::dsl;
|
use users::dsl;
|
||||||
let email_verified: bool = dsl::users
|
let email_verified: bool = dsl::users
|
||||||
.filter(dsl::uuid.eq(user_uuid))
|
.filter(dsl::uuid.eq(user_uuid))
|
||||||
.select(dsl::email_verified)
|
.select(dsl::email_verified)
|
||||||
.get_result(conn)
|
.get_result(&mut conn)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !email_verified {
|
if !email_verified {
|
||||||
|
@ -158,28 +220,14 @@ where
|
||||||
Ok(ordered)
|
Ok(ordered)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(async_fn_in_trait)]
|
impl Data {
|
||||||
pub trait CacheFns {
|
pub async fn set_cache_key(
|
||||||
async fn set_cache_key(
|
|
||||||
&self,
|
|
||||||
key: String,
|
|
||||||
value: impl Serialize,
|
|
||||||
expire: u32,
|
|
||||||
) -> Result<(), Error>;
|
|
||||||
async fn get_cache_key<T>(&self, key: String) -> Result<T, Error>
|
|
||||||
where
|
|
||||||
T: DeserializeOwned;
|
|
||||||
async fn del_cache_key(&self, key: String) -> Result<(), Error>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CacheFns for redis::Client {
|
|
||||||
async fn set_cache_key(
|
|
||||||
&self,
|
&self,
|
||||||
key: String,
|
key: String,
|
||||||
value: impl Serialize,
|
value: impl Serialize,
|
||||||
expire: u32,
|
expire: u32,
|
||||||
) -> Result<(), Error> {
|
) -> Result<(), Error> {
|
||||||
let mut conn = self.get_multiplexed_tokio_connection().await?;
|
let mut conn = self.cache_pool.get_multiplexed_tokio_connection().await?;
|
||||||
|
|
||||||
let key_encoded = encode(key);
|
let key_encoded = encode(key);
|
||||||
|
|
||||||
|
@ -198,39 +246,25 @@ impl CacheFns for redis::Client {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_cache_key<T>(&self, key: String) -> Result<T, Error>
|
pub async fn get_cache_key(&self, key: String) -> Result<String, RedisError> {
|
||||||
where
|
let mut conn = self.cache_pool.get_multiplexed_tokio_connection().await?;
|
||||||
T: DeserializeOwned,
|
|
||||||
{
|
|
||||||
let mut conn = self.get_multiplexed_tokio_connection().await?;
|
|
||||||
|
|
||||||
let key_encoded = encode(key);
|
let key_encoded = encode(key);
|
||||||
|
|
||||||
let res: String = redis::cmd("GET")
|
redis::cmd("GET")
|
||||||
.arg(key_encoded)
|
.arg(key_encoded)
|
||||||
.query_async(&mut conn)
|
.query_async(&mut conn)
|
||||||
.await?;
|
.await
|
||||||
|
|
||||||
Ok(serde_json::from_str(&res)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn del_cache_key(&self, key: String) -> Result<(), Error> {
|
pub async fn del_cache_key(&self, key: String) -> Result<(), RedisError> {
|
||||||
let mut conn = self.get_multiplexed_tokio_connection().await?;
|
let mut conn = self.cache_pool.get_multiplexed_tokio_connection().await?;
|
||||||
|
|
||||||
let key_encoded = encode(key);
|
let key_encoded = encode(key);
|
||||||
|
|
||||||
Ok(redis::cmd("DEL")
|
redis::cmd("DEL")
|
||||||
.arg(key_encoded)
|
.arg(key_encoded)
|
||||||
.query_async(&mut conn)
|
.query_async(&mut conn)
|
||||||
.await?)
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_device_name() -> String {
|
|
||||||
let mut rng = rand::rng();
|
|
||||||
|
|
||||||
let adjective = ADJECTIVES.choose(&mut rng).unwrap();
|
|
||||||
let animal = ANIMALS.choose(&mut rng).unwrap();
|
|
||||||
|
|
||||||
[*adjective, *animal].join(" ")
|
|
||||||
}
|
|
||||||
|
|
993
src/wordlist.rs
993
src/wordlist.rs
|
@ -1,993 +0,0 @@
|
||||||
pub const ANIMALS: [&str; 223] = [
|
|
||||||
"Aardvark",
|
|
||||||
"Albatross",
|
|
||||||
"Alligator",
|
|
||||||
"Alpaca",
|
|
||||||
"Ant",
|
|
||||||
"Anteater",
|
|
||||||
"Antelope",
|
|
||||||
"Ape",
|
|
||||||
"Armadillo",
|
|
||||||
"Donkey",
|
|
||||||
"Baboon",
|
|
||||||
"Badger",
|
|
||||||
"Barracuda",
|
|
||||||
"Bat",
|
|
||||||
"Bear",
|
|
||||||
"Beaver",
|
|
||||||
"Bee",
|
|
||||||
"Bison",
|
|
||||||
"Boar",
|
|
||||||
"Buffalo",
|
|
||||||
"Butterfly",
|
|
||||||
"Camel",
|
|
||||||
"Capybara",
|
|
||||||
"Caribou",
|
|
||||||
"Cassowary",
|
|
||||||
"Cat",
|
|
||||||
"Caterpillar",
|
|
||||||
"Cattle",
|
|
||||||
"Chamois",
|
|
||||||
"Cheetah",
|
|
||||||
"Chicken",
|
|
||||||
"Chimpanzee",
|
|
||||||
"Chinchilla",
|
|
||||||
"Chough",
|
|
||||||
"Clam",
|
|
||||||
"Cobra",
|
|
||||||
"Cockroach",
|
|
||||||
"Cod",
|
|
||||||
"Cormorant",
|
|
||||||
"Coyote",
|
|
||||||
"Crab",
|
|
||||||
"Crane",
|
|
||||||
"Crocodile",
|
|
||||||
"Crow",
|
|
||||||
"Curlew",
|
|
||||||
"Deer",
|
|
||||||
"Dinosaur",
|
|
||||||
"Dog",
|
|
||||||
"Dogfish",
|
|
||||||
"Dolphin",
|
|
||||||
"Dotterel",
|
|
||||||
"Dove",
|
|
||||||
"Dragonfly",
|
|
||||||
"Duck",
|
|
||||||
"Dugong",
|
|
||||||
"Dunlin",
|
|
||||||
"Eagle",
|
|
||||||
"Echidna",
|
|
||||||
"Eel",
|
|
||||||
"Eland",
|
|
||||||
"Elephant",
|
|
||||||
"Elk",
|
|
||||||
"Emu",
|
|
||||||
"Falcon",
|
|
||||||
"Ferret",
|
|
||||||
"Finch",
|
|
||||||
"Fish",
|
|
||||||
"Flamingo",
|
|
||||||
"Fly",
|
|
||||||
"Fox",
|
|
||||||
"Frog",
|
|
||||||
"Gaur",
|
|
||||||
"Gazelle",
|
|
||||||
"Gerbil",
|
|
||||||
"Giraffe",
|
|
||||||
"Gnat",
|
|
||||||
"Gnu",
|
|
||||||
"Goat",
|
|
||||||
"Goldfinch",
|
|
||||||
"Goldfish",
|
|
||||||
"Goose",
|
|
||||||
"Gorilla",
|
|
||||||
"Goshawk",
|
|
||||||
"Grasshopper",
|
|
||||||
"Grouse",
|
|
||||||
"Guanaco",
|
|
||||||
"Gull",
|
|
||||||
"Hamster",
|
|
||||||
"Hare",
|
|
||||||
"Hawk",
|
|
||||||
"Hedgehog",
|
|
||||||
"Heron",
|
|
||||||
"Herring",
|
|
||||||
"Hippopotamus",
|
|
||||||
"Hornet",
|
|
||||||
"Horse",
|
|
||||||
"Hummingbird",
|
|
||||||
"Hyena",
|
|
||||||
"Ibex",
|
|
||||||
"Ibis",
|
|
||||||
"Jackal",
|
|
||||||
"Jaguar",
|
|
||||||
"Jay",
|
|
||||||
"Jellyfish",
|
|
||||||
"Kangaroo",
|
|
||||||
"Kingfisher",
|
|
||||||
"Koala",
|
|
||||||
"Kookabura",
|
|
||||||
"Kouprey",
|
|
||||||
"Kudu",
|
|
||||||
"Lapwing",
|
|
||||||
"Lark",
|
|
||||||
"Lemur",
|
|
||||||
"Leopard",
|
|
||||||
"Lion",
|
|
||||||
"Llama",
|
|
||||||
"Lobster",
|
|
||||||
"Locust",
|
|
||||||
"Loris",
|
|
||||||
"Louse",
|
|
||||||
"Lyrebird",
|
|
||||||
"Magpie",
|
|
||||||
"Mallard",
|
|
||||||
"Manatee",
|
|
||||||
"Mandrill",
|
|
||||||
"Mantis",
|
|
||||||
"Marten",
|
|
||||||
"Meerkat",
|
|
||||||
"Mink",
|
|
||||||
"Mole",
|
|
||||||
"Mongoose",
|
|
||||||
"Monkey",
|
|
||||||
"Moose",
|
|
||||||
"Mosquito",
|
|
||||||
"Mouse",
|
|
||||||
"Mule",
|
|
||||||
"Narwhal",
|
|
||||||
"Newt",
|
|
||||||
"Nightingale",
|
|
||||||
"Octopus",
|
|
||||||
"Okapi",
|
|
||||||
"Opossum",
|
|
||||||
"Oryx",
|
|
||||||
"Ostrich",
|
|
||||||
"Otter",
|
|
||||||
"Owl",
|
|
||||||
"Oyster",
|
|
||||||
"Panther",
|
|
||||||
"Parrot",
|
|
||||||
"Partridge",
|
|
||||||
"Peafowl",
|
|
||||||
"Pelican",
|
|
||||||
"Penguin",
|
|
||||||
"Pheasant",
|
|
||||||
"Pig",
|
|
||||||
"Pigeon",
|
|
||||||
"Pony",
|
|
||||||
"Porcupine",
|
|
||||||
"Porpoise",
|
|
||||||
"Quail",
|
|
||||||
"Quelea",
|
|
||||||
"Quetzal",
|
|
||||||
"Rabbit",
|
|
||||||
"Raccoon",
|
|
||||||
"Rail",
|
|
||||||
"Ram",
|
|
||||||
"Rat",
|
|
||||||
"Raven",
|
|
||||||
"Red Deer",
|
|
||||||
"Red Panda",
|
|
||||||
"Reindeer",
|
|
||||||
"Rhinoceros",
|
|
||||||
"Rook",
|
|
||||||
"Salamander",
|
|
||||||
"Salmon",
|
|
||||||
"Sand Dollar",
|
|
||||||
"Sandpiper",
|
|
||||||
"Sardine",
|
|
||||||
"Scorpion",
|
|
||||||
"Seahorse",
|
|
||||||
"Seal",
|
|
||||||
"Shark",
|
|
||||||
"Sheep",
|
|
||||||
"Shrew",
|
|
||||||
"Skunk",
|
|
||||||
"Snail",
|
|
||||||
"Snake",
|
|
||||||
"Sparrow",
|
|
||||||
"Spider",
|
|
||||||
"Spoonbill",
|
|
||||||
"Squid",
|
|
||||||
"Squirrel",
|
|
||||||
"Starling",
|
|
||||||
"Stingray",
|
|
||||||
"Stinkbug",
|
|
||||||
"Stork",
|
|
||||||
"Swallow",
|
|
||||||
"Swan",
|
|
||||||
"Tapir",
|
|
||||||
"Tarsier",
|
|
||||||
"Termite",
|
|
||||||
"Tiger",
|
|
||||||
"Toad",
|
|
||||||
"Trout",
|
|
||||||
"Turkey",
|
|
||||||
"Turtle",
|
|
||||||
"Viper",
|
|
||||||
"Vulture",
|
|
||||||
"Wallaby",
|
|
||||||
"Walrus",
|
|
||||||
"Wasp",
|
|
||||||
"Weasel",
|
|
||||||
"Whale",
|
|
||||||
"Wildcat",
|
|
||||||
"Wolf",
|
|
||||||
"Wolverine",
|
|
||||||
"Wombat",
|
|
||||||
"Woodcock",
|
|
||||||
"Woodpecker",
|
|
||||||
"Worm",
|
|
||||||
"Wren",
|
|
||||||
"Yak",
|
|
||||||
"Zebra",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub const ADJECTIVES: [&str; 765] = [
|
|
||||||
"Other",
|
|
||||||
"Such",
|
|
||||||
"First",
|
|
||||||
"Many",
|
|
||||||
"New",
|
|
||||||
"More",
|
|
||||||
"Same",
|
|
||||||
"Own",
|
|
||||||
"Good",
|
|
||||||
"Different",
|
|
||||||
"Great",
|
|
||||||
"Long",
|
|
||||||
"High",
|
|
||||||
"Social",
|
|
||||||
"Little",
|
|
||||||
"Much",
|
|
||||||
"Important",
|
|
||||||
"Small",
|
|
||||||
"Most",
|
|
||||||
"Large",
|
|
||||||
"Old",
|
|
||||||
"Few",
|
|
||||||
"General",
|
|
||||||
"Second",
|
|
||||||
"Public",
|
|
||||||
"Last",
|
|
||||||
"Several",
|
|
||||||
"Early",
|
|
||||||
"Certain",
|
|
||||||
"Economic",
|
|
||||||
"Least",
|
|
||||||
"Common",
|
|
||||||
"Present",
|
|
||||||
"Next",
|
|
||||||
"Local",
|
|
||||||
"Best",
|
|
||||||
"Particular",
|
|
||||||
"Young",
|
|
||||||
"Various",
|
|
||||||
"Necessary",
|
|
||||||
"Whole",
|
|
||||||
"Only",
|
|
||||||
"True",
|
|
||||||
"Able",
|
|
||||||
"Major",
|
|
||||||
"Full",
|
|
||||||
"Low",
|
|
||||||
"Available",
|
|
||||||
"Real",
|
|
||||||
"Similar",
|
|
||||||
"Total",
|
|
||||||
"Special",
|
|
||||||
"Less",
|
|
||||||
"Short",
|
|
||||||
"Specific",
|
|
||||||
"Single",
|
|
||||||
"Self",
|
|
||||||
"National",
|
|
||||||
"Individual",
|
|
||||||
"Clear",
|
|
||||||
"Personal",
|
|
||||||
"Higher",
|
|
||||||
"Better",
|
|
||||||
"Third",
|
|
||||||
"Natural",
|
|
||||||
"Greater",
|
|
||||||
"Open",
|
|
||||||
"Difficult",
|
|
||||||
"Current",
|
|
||||||
"Further",
|
|
||||||
"Main",
|
|
||||||
"Physical",
|
|
||||||
"Foreign",
|
|
||||||
"Lower",
|
|
||||||
"Strong",
|
|
||||||
"Private",
|
|
||||||
"Likely",
|
|
||||||
"International",
|
|
||||||
"Significant",
|
|
||||||
"Late",
|
|
||||||
"Basic",
|
|
||||||
"Hard",
|
|
||||||
"Modern",
|
|
||||||
"Simple",
|
|
||||||
"Normal",
|
|
||||||
"Sure",
|
|
||||||
"Central",
|
|
||||||
"Original",
|
|
||||||
"Effective",
|
|
||||||
"Following",
|
|
||||||
"Direct",
|
|
||||||
"Final",
|
|
||||||
"Cultural",
|
|
||||||
"Big",
|
|
||||||
"Recent",
|
|
||||||
"Complete",
|
|
||||||
"Financial",
|
|
||||||
"Positive",
|
|
||||||
"Primary",
|
|
||||||
"Appropriate",
|
|
||||||
"Legal",
|
|
||||||
"European",
|
|
||||||
"Equal",
|
|
||||||
"Larger",
|
|
||||||
"Average",
|
|
||||||
"Historical",
|
|
||||||
"Critical",
|
|
||||||
"Wide",
|
|
||||||
"Traditional",
|
|
||||||
"Additional",
|
|
||||||
"Active",
|
|
||||||
"Complex",
|
|
||||||
"Former",
|
|
||||||
"Independent",
|
|
||||||
"Entire",
|
|
||||||
"Actual",
|
|
||||||
"Close",
|
|
||||||
"Constant",
|
|
||||||
"Previous",
|
|
||||||
"Easy",
|
|
||||||
"Serious",
|
|
||||||
"Potential",
|
|
||||||
"Fine",
|
|
||||||
"Industrial",
|
|
||||||
"Subject",
|
|
||||||
"Future",
|
|
||||||
"Internal",
|
|
||||||
"Initial",
|
|
||||||
"Well",
|
|
||||||
"Essential",
|
|
||||||
"Dark",
|
|
||||||
"Popular",
|
|
||||||
"Successful",
|
|
||||||
"Standard",
|
|
||||||
"Year",
|
|
||||||
"Past",
|
|
||||||
"Ready",
|
|
||||||
"Professional",
|
|
||||||
"Wrong",
|
|
||||||
"Very",
|
|
||||||
"Proper",
|
|
||||||
"Separate",
|
|
||||||
"Heavy",
|
|
||||||
"Civil",
|
|
||||||
"Responsible",
|
|
||||||
"Considerable",
|
|
||||||
"Light",
|
|
||||||
"Cold",
|
|
||||||
"Above",
|
|
||||||
"Older",
|
|
||||||
"Practical",
|
|
||||||
"External",
|
|
||||||
"Sufficient",
|
|
||||||
"Interesting",
|
|
||||||
"Upper",
|
|
||||||
"Scientific",
|
|
||||||
"Key",
|
|
||||||
"Annual",
|
|
||||||
"Limited",
|
|
||||||
"Smaller",
|
|
||||||
"Southern",
|
|
||||||
"Earlier",
|
|
||||||
"Commercial",
|
|
||||||
"Powerful",
|
|
||||||
"Later",
|
|
||||||
"Like",
|
|
||||||
"Clinical",
|
|
||||||
"Ancient",
|
|
||||||
"Educational",
|
|
||||||
"Typical",
|
|
||||||
"Technical",
|
|
||||||
"Environmental",
|
|
||||||
"Formal",
|
|
||||||
"Aware",
|
|
||||||
"Beautiful",
|
|
||||||
"Variable",
|
|
||||||
"Obvious",
|
|
||||||
"Secondary",
|
|
||||||
"Enough",
|
|
||||||
"Urban",
|
|
||||||
"Regular",
|
|
||||||
"Relevant",
|
|
||||||
"Greatest",
|
|
||||||
"Spiritual",
|
|
||||||
"Time",
|
|
||||||
"Double",
|
|
||||||
"Happy",
|
|
||||||
"Term",
|
|
||||||
"Multiple",
|
|
||||||
"Dependent",
|
|
||||||
"Correct",
|
|
||||||
"Northern",
|
|
||||||
"Middle",
|
|
||||||
"Rural",
|
|
||||||
"Official",
|
|
||||||
"Fundamental",
|
|
||||||
"Numerous",
|
|
||||||
"Overall",
|
|
||||||
"Usual",
|
|
||||||
"Native",
|
|
||||||
"Regional",
|
|
||||||
"Highest",
|
|
||||||
"North",
|
|
||||||
"Agricultural",
|
|
||||||
"Literary",
|
|
||||||
"Broad",
|
|
||||||
"Perfect",
|
|
||||||
"Experimental",
|
|
||||||
"Fourth",
|
|
||||||
"Global",
|
|
||||||
"Ordinary",
|
|
||||||
"Related",
|
|
||||||
"Apparent",
|
|
||||||
"Daily",
|
|
||||||
"Principal",
|
|
||||||
"Contemporary",
|
|
||||||
"Severe",
|
|
||||||
"Reasonable",
|
|
||||||
"Subsequent",
|
|
||||||
"Worth",
|
|
||||||
"Longer",
|
|
||||||
"Emotional",
|
|
||||||
"Intellectual",
|
|
||||||
"Unique",
|
|
||||||
"Pure",
|
|
||||||
"Familiar",
|
|
||||||
"American",
|
|
||||||
"Solid",
|
|
||||||
"Brief",
|
|
||||||
"Famous",
|
|
||||||
"Fresh",
|
|
||||||
"Day",
|
|
||||||
"Corresponding",
|
|
||||||
"Characteristic",
|
|
||||||
"Maximum",
|
|
||||||
"Detailed",
|
|
||||||
"Outside",
|
|
||||||
"Theoretical",
|
|
||||||
"Fair",
|
|
||||||
"Opposite",
|
|
||||||
"Capable",
|
|
||||||
"Visual",
|
|
||||||
"Interested",
|
|
||||||
"Joint",
|
|
||||||
"Adequate",
|
|
||||||
"Based",
|
|
||||||
"Substantial",
|
|
||||||
"Unable",
|
|
||||||
"Structural",
|
|
||||||
"Soft",
|
|
||||||
"False",
|
|
||||||
"Largest",
|
|
||||||
"Inner",
|
|
||||||
"Mean",
|
|
||||||
"Extensive",
|
|
||||||
"Excellent",
|
|
||||||
"Rapid",
|
|
||||||
"Absolute",
|
|
||||||
"Consistent",
|
|
||||||
"Continuous",
|
|
||||||
"Administrative",
|
|
||||||
"Strange",
|
|
||||||
"Willing",
|
|
||||||
"Alternative",
|
|
||||||
"Slow",
|
|
||||||
"Distinct",
|
|
||||||
"Safe",
|
|
||||||
"Permanent",
|
|
||||||
"Front",
|
|
||||||
"Corporate",
|
|
||||||
"Academic",
|
|
||||||
"Thin",
|
|
||||||
"Nineteenth",
|
|
||||||
"Universal",
|
|
||||||
"Functional",
|
|
||||||
"Unknown",
|
|
||||||
"Careful",
|
|
||||||
"Narrow",
|
|
||||||
"Evident",
|
|
||||||
"Sound",
|
|
||||||
"Classical",
|
|
||||||
"Minor",
|
|
||||||
"Weak",
|
|
||||||
"Suitable",
|
|
||||||
"Chief",
|
|
||||||
"Extreme",
|
|
||||||
"Yellow",
|
|
||||||
"Warm",
|
|
||||||
"Mixed",
|
|
||||||
"Flat",
|
|
||||||
"Huge",
|
|
||||||
"Vast",
|
|
||||||
"Stable",
|
|
||||||
"Valuable",
|
|
||||||
"Rare",
|
|
||||||
"Visible",
|
|
||||||
"Sensitive",
|
|
||||||
"Mechanical",
|
|
||||||
"State",
|
|
||||||
"Radical",
|
|
||||||
"Extra",
|
|
||||||
"Superior",
|
|
||||||
"Conventional",
|
|
||||||
"Thick",
|
|
||||||
"Dominant",
|
|
||||||
"Post",
|
|
||||||
"Collective",
|
|
||||||
"Younger",
|
|
||||||
"Efficient",
|
|
||||||
"Linear",
|
|
||||||
"Organic",
|
|
||||||
"Oral",
|
|
||||||
"Century",
|
|
||||||
"Creative",
|
|
||||||
"Vertical",
|
|
||||||
"Dynamic",
|
|
||||||
"Empty",
|
|
||||||
"Minimum",
|
|
||||||
"Cognitive",
|
|
||||||
"Logical",
|
|
||||||
"Afraid",
|
|
||||||
"Equivalent",
|
|
||||||
"Quick",
|
|
||||||
"Near",
|
|
||||||
"Concrete",
|
|
||||||
"Mass",
|
|
||||||
"Acute",
|
|
||||||
"Sharp",
|
|
||||||
"Easier",
|
|
||||||
"Quiet",
|
|
||||||
"Adult",
|
|
||||||
"Accurate",
|
|
||||||
"Ideal",
|
|
||||||
"Partial",
|
|
||||||
"Bright",
|
|
||||||
"Identical",
|
|
||||||
"Conservative",
|
|
||||||
"Magnetic",
|
|
||||||
"Frequent",
|
|
||||||
"Electronic",
|
|
||||||
"Fixed",
|
|
||||||
"Square",
|
|
||||||
"Cross",
|
|
||||||
"Clean",
|
|
||||||
"Back",
|
|
||||||
"Organizational",
|
|
||||||
"Constitutional",
|
|
||||||
"Genetic",
|
|
||||||
"Ultimate",
|
|
||||||
"Secret",
|
|
||||||
"Vital",
|
|
||||||
"Dramatic",
|
|
||||||
"Objective",
|
|
||||||
"Round",
|
|
||||||
"Alive",
|
|
||||||
"Straight",
|
|
||||||
"Unusual",
|
|
||||||
"Rational",
|
|
||||||
"Electric",
|
|
||||||
"Mutual",
|
|
||||||
"Class",
|
|
||||||
"Competitive",
|
|
||||||
"Revolutionary",
|
|
||||||
"Statistical",
|
|
||||||
"Random",
|
|
||||||
"Musical",
|
|
||||||
"Crucial",
|
|
||||||
"Racial",
|
|
||||||
"Sudden",
|
|
||||||
"Acid",
|
|
||||||
"Content",
|
|
||||||
"Temporary",
|
|
||||||
"Line",
|
|
||||||
"Remarkable",
|
|
||||||
"Exact",
|
|
||||||
"Valid",
|
|
||||||
"Helpful",
|
|
||||||
"Nice",
|
|
||||||
"Comprehensive",
|
|
||||||
"United",
|
|
||||||
"Level",
|
|
||||||
"Fifth",
|
|
||||||
"Nervous",
|
|
||||||
"Expensive",
|
|
||||||
"Prominent",
|
|
||||||
"Healthy",
|
|
||||||
"Liquid",
|
|
||||||
"Institutional",
|
|
||||||
"Silent",
|
|
||||||
"Sweet",
|
|
||||||
"Strategic",
|
|
||||||
"Molecular",
|
|
||||||
"Comparative",
|
|
||||||
"Called",
|
|
||||||
"Electrical",
|
|
||||||
"Raw",
|
|
||||||
"Acceptable",
|
|
||||||
"Scale",
|
|
||||||
"Violent",
|
|
||||||
"All",
|
|
||||||
"Desirable",
|
|
||||||
"Tall",
|
|
||||||
"Steady",
|
|
||||||
"Wonderful",
|
|
||||||
"Sub",
|
|
||||||
"Distant",
|
|
||||||
"Progressive",
|
|
||||||
"Enormous",
|
|
||||||
"Horizontal",
|
|
||||||
"And",
|
|
||||||
"Intense",
|
|
||||||
"Smooth",
|
|
||||||
"Applicable",
|
|
||||||
"Over",
|
|
||||||
"Animal",
|
|
||||||
"Abstract",
|
|
||||||
"Wise",
|
|
||||||
"Worst",
|
|
||||||
"Gold",
|
|
||||||
"Precise",
|
|
||||||
"Legislative",
|
|
||||||
"Remote",
|
|
||||||
"Technological",
|
|
||||||
"Outer",
|
|
||||||
"Uniform",
|
|
||||||
"Slight",
|
|
||||||
"Attractive",
|
|
||||||
"Evil",
|
|
||||||
"Tiny",
|
|
||||||
"Royal",
|
|
||||||
"Angry",
|
|
||||||
"Advanced",
|
|
||||||
"Friendly",
|
|
||||||
"Dear",
|
|
||||||
"Busy",
|
|
||||||
"Spatial",
|
|
||||||
"Rough",
|
|
||||||
"Primitive",
|
|
||||||
"Judicial",
|
|
||||||
"Systematic",
|
|
||||||
"Lateral",
|
|
||||||
"Sorry",
|
|
||||||
"Plain",
|
|
||||||
"Off",
|
|
||||||
"Comfortable",
|
|
||||||
"Definite",
|
|
||||||
"Massive",
|
|
||||||
"Firm",
|
|
||||||
"Widespread",
|
|
||||||
"Prior",
|
|
||||||
"Twentieth",
|
|
||||||
"Mathematical",
|
|
||||||
"Verbal",
|
|
||||||
"Marginal",
|
|
||||||
"Excessive",
|
|
||||||
"Stronger",
|
|
||||||
"Gross",
|
|
||||||
"World",
|
|
||||||
"Productive",
|
|
||||||
"Wider",
|
|
||||||
"Glad",
|
|
||||||
"Linguistic",
|
|
||||||
"Patient",
|
|
||||||
"Symbolic",
|
|
||||||
"Earliest",
|
|
||||||
"Plastic",
|
|
||||||
"Type",
|
|
||||||
"Prime",
|
|
||||||
"Eighteenth",
|
|
||||||
"Blind",
|
|
||||||
"Neutral",
|
|
||||||
"Guilty",
|
|
||||||
"Hand",
|
|
||||||
"Extraordinary",
|
|
||||||
"Metal",
|
|
||||||
"Surprising",
|
|
||||||
"Fellow",
|
|
||||||
"York",
|
|
||||||
"Grand",
|
|
||||||
"Thermal",
|
|
||||||
"Artificial",
|
|
||||||
"Five",
|
|
||||||
"Lowest",
|
|
||||||
"Genuine",
|
|
||||||
"Dimensional",
|
|
||||||
"Optical",
|
|
||||||
"Unlikely",
|
|
||||||
"Developmental",
|
|
||||||
"Reliable",
|
|
||||||
"Executive",
|
|
||||||
"Comparable",
|
|
||||||
"Satisfactory",
|
|
||||||
"Golden",
|
|
||||||
"Diverse",
|
|
||||||
"Preliminary",
|
|
||||||
"Wooden",
|
|
||||||
"Noble",
|
|
||||||
"Part",
|
|
||||||
"Striking",
|
|
||||||
"Cool",
|
|
||||||
"Classic",
|
|
||||||
"Elderly",
|
|
||||||
"Four",
|
|
||||||
"Temporal",
|
|
||||||
"Indirect",
|
|
||||||
"Romantic",
|
|
||||||
"Intermediate",
|
|
||||||
"Differential",
|
|
||||||
"Passive",
|
|
||||||
"Life",
|
|
||||||
"Voluntary",
|
|
||||||
"Out",
|
|
||||||
"Adjacent",
|
|
||||||
"Behavioral",
|
|
||||||
"Exclusive",
|
|
||||||
"Closed",
|
|
||||||
"Inherent",
|
|
||||||
"Inevitable",
|
|
||||||
"Complicated",
|
|
||||||
"Quantitative",
|
|
||||||
"Respective",
|
|
||||||
"Artistic",
|
|
||||||
"Probable",
|
|
||||||
"Anxious",
|
|
||||||
"Informal",
|
|
||||||
"Strict",
|
|
||||||
"Fiscal",
|
|
||||||
"Ideological",
|
|
||||||
"Profound",
|
|
||||||
"Extended",
|
|
||||||
"Eternal",
|
|
||||||
"Known",
|
|
||||||
"Infinite",
|
|
||||||
"Proud",
|
|
||||||
"Honest",
|
|
||||||
"Peculiar",
|
|
||||||
"Absent",
|
|
||||||
"Pleasant",
|
|
||||||
"Optimal",
|
|
||||||
"Renal",
|
|
||||||
"Static",
|
|
||||||
"Outstanding",
|
|
||||||
"Presidential",
|
|
||||||
"Digital",
|
|
||||||
"Integrated",
|
|
||||||
"Legitimate",
|
|
||||||
"Curious",
|
|
||||||
"Aggressive",
|
|
||||||
"Deeper",
|
|
||||||
"Elementary",
|
|
||||||
"History",
|
|
||||||
"Surgical",
|
|
||||||
"Occasional",
|
|
||||||
"Flexible",
|
|
||||||
"Convenient",
|
|
||||||
"Solar",
|
|
||||||
"Atomic",
|
|
||||||
"Isolated",
|
|
||||||
"Latest",
|
|
||||||
"Sad",
|
|
||||||
"Conceptual",
|
|
||||||
"Underlying",
|
|
||||||
"Everyday",
|
|
||||||
"Cost",
|
|
||||||
"Intensive",
|
|
||||||
"Odd",
|
|
||||||
"Subjective",
|
|
||||||
"Mid",
|
|
||||||
"Worthy",
|
|
||||||
"Pale",
|
|
||||||
"Meaningful",
|
|
||||||
"Therapeutic",
|
|
||||||
"Making",
|
|
||||||
"Circular",
|
|
||||||
"Realistic",
|
|
||||||
"Multi",
|
|
||||||
"Child",
|
|
||||||
"Sophisticated",
|
|
||||||
"Down",
|
|
||||||
"Leading",
|
|
||||||
"Intelligent",
|
|
||||||
"Governmental",
|
|
||||||
"Numerical",
|
|
||||||
"Minimal",
|
|
||||||
"Diagnostic",
|
|
||||||
"Indigenous",
|
|
||||||
"Aesthetic",
|
|
||||||
"Distinctive",
|
|
||||||
"Operational",
|
|
||||||
"Sole",
|
|
||||||
"Material",
|
|
||||||
"Fast",
|
|
||||||
"Bitter",
|
|
||||||
"Broader",
|
|
||||||
"Brilliant",
|
|
||||||
"Peripheral",
|
|
||||||
"Rigid",
|
|
||||||
"Automatic",
|
|
||||||
"Lesser",
|
|
||||||
"Routine",
|
|
||||||
"Favorable",
|
|
||||||
"Cooperative",
|
|
||||||
"Cardiac",
|
|
||||||
"Arbitrary",
|
|
||||||
"Loose",
|
|
||||||
"Favorite",
|
|
||||||
"Subtle",
|
|
||||||
"Uncertain",
|
|
||||||
"Hostile",
|
|
||||||
"Monthly",
|
|
||||||
"Naval",
|
|
||||||
"Physiological",
|
|
||||||
"Historic",
|
|
||||||
"Developed",
|
|
||||||
"Skilled",
|
|
||||||
"Anterior",
|
|
||||||
"Pro",
|
|
||||||
"Gentle",
|
|
||||||
"Loud",
|
|
||||||
"Pulmonary",
|
|
||||||
"Innocent",
|
|
||||||
"Provincial",
|
|
||||||
"Mild",
|
|
||||||
"Page",
|
|
||||||
"Specialized",
|
|
||||||
"Bare",
|
|
||||||
"Excess",
|
|
||||||
"Inter",
|
|
||||||
"Shaped",
|
|
||||||
"Theological",
|
|
||||||
"Sensory",
|
|
||||||
"The",
|
|
||||||
"Stress",
|
|
||||||
"Novel",
|
|
||||||
"Working",
|
|
||||||
"Shorter",
|
|
||||||
"Secular",
|
|
||||||
"Geographical",
|
|
||||||
"Intimate",
|
|
||||||
"Liable",
|
|
||||||
"Selective",
|
|
||||||
"Influential",
|
|
||||||
"Modest",
|
|
||||||
"Successive",
|
|
||||||
"Continued",
|
|
||||||
"Water",
|
|
||||||
"Expert",
|
|
||||||
"Municipal",
|
|
||||||
"Marine",
|
|
||||||
"Thirty",
|
|
||||||
"Adverse",
|
|
||||||
"Wacky",
|
|
||||||
"Closer",
|
|
||||||
"Virtual",
|
|
||||||
"Peaceful",
|
|
||||||
"Mobile",
|
|
||||||
"Sixth",
|
|
||||||
"Immune",
|
|
||||||
"Coastal",
|
|
||||||
"Representative",
|
|
||||||
"Lead",
|
|
||||||
"Forward",
|
|
||||||
"Faithful",
|
|
||||||
"Crystal",
|
|
||||||
"Protective",
|
|
||||||
"Elaborate",
|
|
||||||
"Tremendous",
|
|
||||||
"Welcoming",
|
|
||||||
"Abnormal",
|
|
||||||
"Grateful",
|
|
||||||
"Proportional",
|
|
||||||
"Dual",
|
|
||||||
"Operative",
|
|
||||||
"Precious",
|
|
||||||
"Sympathetic",
|
|
||||||
"Accessible",
|
|
||||||
"Lovely",
|
|
||||||
"Spinal",
|
|
||||||
"Even",
|
|
||||||
"Marked",
|
|
||||||
"Observed",
|
|
||||||
"Point",
|
|
||||||
"Mature",
|
|
||||||
"Competent",
|
|
||||||
"Residential",
|
|
||||||
"Impressive",
|
|
||||||
"Unexpected",
|
|
||||||
"Nearby",
|
|
||||||
"Unnecessary",
|
|
||||||
"Generous",
|
|
||||||
"Cerebral",
|
|
||||||
"Unpublished",
|
|
||||||
"Delicate",
|
|
||||||
"Analytical",
|
|
||||||
"Tropical",
|
|
||||||
"Statutory",
|
|
||||||
"Cell",
|
|
||||||
"Weekly",
|
|
||||||
"End",
|
|
||||||
"Online",
|
|
||||||
"Beneficial",
|
|
||||||
"Aged",
|
|
||||||
"Tough",
|
|
||||||
"Eager",
|
|
||||||
"Ongoing",
|
|
||||||
"Silver",
|
|
||||||
"Persistent",
|
|
||||||
"Calm",
|
|
||||||
"Nearest",
|
|
||||||
"Hidden",
|
|
||||||
"Magic",
|
|
||||||
"Pretty",
|
|
||||||
"Wealthy",
|
|
||||||
"Exciting",
|
|
||||||
"Decisive",
|
|
||||||
"Confident",
|
|
||||||
"Invisible",
|
|
||||||
"Notable",
|
|
||||||
"Medium",
|
|
||||||
"Manual",
|
|
||||||
"Select",
|
|
||||||
"Thorough",
|
|
||||||
"Causal",
|
|
||||||
"Giant",
|
|
||||||
"Bigger",
|
|
||||||
"Pink",
|
|
||||||
"Improved",
|
|
||||||
"Immense",
|
|
||||||
"Hour",
|
|
||||||
"Intact",
|
|
||||||
"Grade",
|
|
||||||
"Dense",
|
|
||||||
"Hungry",
|
|
||||||
"Biggest",
|
|
||||||
"Abundant",
|
|
||||||
"Handsome",
|
|
||||||
"Retail",
|
|
||||||
"Insufficient",
|
|
||||||
"Irregular",
|
|
||||||
"Intrinsic",
|
|
||||||
"Residual",
|
|
||||||
"Follow",
|
|
||||||
"Fluid",
|
|
||||||
"Mysterious",
|
|
||||||
"Descriptive",
|
|
||||||
"Elastic",
|
|
||||||
"Destructive",
|
|
||||||
"Architectural",
|
|
||||||
"Synthetic",
|
|
||||||
"Continental",
|
|
||||||
"Evolutionary",
|
|
||||||
"Lucky",
|
|
||||||
"Bold",
|
|
||||||
"Funny",
|
|
||||||
"Peak",
|
|
||||||
"Smallest",
|
|
||||||
"Reluctant",
|
|
||||||
"Suspicious",
|
|
||||||
"Smart",
|
|
||||||
"Mighty",
|
|
||||||
"Brave",
|
|
||||||
"Humble",
|
|
||||||
"Vocal",
|
|
||||||
"Obscure",
|
|
||||||
"Innovative",
|
|
||||||
];
|
|
Loading…
Add table
Add a link
Reference in a new issue