Compare commits

..

3 commits

112 changed files with 2116 additions and 6495 deletions

View file

@ -1,25 +1,8 @@
when:
- event: push
branch: main
steps:
- name: build-x86_64
image: rust:1.88-bookworm
commands:
- cargo build --release
when:
- event: push
- name: build-arm64
image: rust:1.88-bookworm
commands:
- dpkg --add-architecture arm64
- apt-get update -y && apt-get install -y crossbuild-essential-arm64 libssl-dev:arm64
- rustup target add aarch64-unknown-linux-gnu
- cargo build --target aarch64-unknown-linux-gnu --release
environment:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
PKG_CONFIG_ALLOW_CROSS: 1
PKG_CONFIG_PATH: /usr/aarch64-linux-gnu/lib/pkgconfig
when:
- event: push
- name: container-build-and-publish
image: docker
commands:
@ -30,20 +13,3 @@ steps:
from_secret: docker_password
volumes:
- /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

View file

@ -1,19 +0,0 @@
when:
- event: push
branch: main
steps:
- name: build-docs
image: rust:1.88-bookworm
commands:
- cargo doc --release --no-deps
- name: publish-docs
image: debian:12
commands:
- apt update -y && apt install -y rsync openssh-client
- printf "Host *\n StrictHostKeyChecking no" >> /etc/ssh/ssh_config
- ssh-agent bash -c "ssh-add <(echo '$KEY' | base64 -d) && rsync --archive --verbose --compress --hard-links --delete-during --partial --progress ./target/doc/ root@gorb.app:/var/www/docs.gorb.app/api && ssh root@gorb.app systemctl reload caddy.service"
environment:
KEY:
from_secret: ssh_key

View file

@ -8,56 +8,37 @@ strip = true
lto = true
codegen-units = 1
# Speed up compilation to make dev bearable
[profile.dev]
debug = 0
strip = "debuginfo"
codegen-units = 512
[dependencies]
thiserror = "2.0.12"
# 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
actix-cors = "0.7.1"
actix-web = "4.11"
argon2 = { version = "0.5.3", features = ["std"] }
clap = { version = "4.5", features = ["derive"] }
futures = "0.3"
getrandom = "0.3"
hex = "0.4"
log = "0.4"
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.16", features = ["serde", "v7"] }
random-string = "1.1"
lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls"] }
chrono = { version = "0.4.41", features = ["serde"] }
tracing-subscriber = "0.3.19"
rand = "0.9.1"
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"] }
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"
actix-files = "0.6.6"
[dependencies.tokio]
version = "1.44"
features = ["full"]

View file

@ -1,17 +1,16 @@
FROM --platform=linux/amd64 debian:12-slim AS prep
FROM rust:bookworm AS builder
WORKDIR /src
COPY target/release/backend backend-amd64
COPY target/aarch64-unknown-linux-gnu/release/backend backend-arm64
COPY . .
RUN cargo build --release
FROM debian:12-slim
ARG TARGETARCH
RUN apt update && apt install libssl3 && rm -rf /var/lib/apt/lists/* /var/cache/apt/* /tmp/*
RUN apt update -y && apt install libssl3 ca-certificates -y && rm -rf /var/lib/apt/lists/* /var/cache/apt/* /tmp/*
COPY --from=prep /src/backend-${TARGETARCH} /usr/bin/gorb-backend
COPY --from=builder /src/target/release/backend /usr/bin/gorb-backend
COPY entrypoint.sh /usr/bin/entrypoint.sh
@ -19,8 +18,7 @@ RUN useradd --create-home --home-dir /gorb gorb
USER gorb
ENV WEB_FRONTEND_URL=https://gorb.app/web/ \
WEB_BASE_PATH=/api \
ENV WEB_URL=http://localhost:8080 \
DATABASE_USERNAME=gorb \
DATABASE_PASSWORD=gorb \
DATABASE=gorb \
@ -28,14 +26,9 @@ DATABASE_HOST=database \
DATABASE_PORT=5432 \
CACHE_DB_HOST=valkey \
CACHE_DB_PORT=6379 \
BUNNY_API_KEY=your_storage_zone_password_here \
BUNNY_ENDPOINT=Frankfurt \
BUNNY_ZONE=gorb \
BUNNY_CDN_URL=https://cdn.gorb.app \
MAIL_ADDRESS=noreply@gorb.app \
MAIL_TLS=tls \
SMTP_SERVER=mail.gorb.app \
SMTP_USERNAME=your_smtp_username \
SMTP_PASSWORD=your_smtp_password
BUNNY_API_KEY= \
BUNNY_ENDPOINT= \
BUNNY_ZONE= \
BUNNY_CDN_URL=
ENTRYPOINT ["/usr/bin/entrypoint.sh"]

View file

@ -1,16 +1,3 @@
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=migrations");
let git_short_hash = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string()) // Trim newline
.unwrap_or_else(|| "UNKNOWN".to_string());
// Tell Cargo to set `GIT_SHORT_HASH` for the main compilation
println!("cargo:rustc-env=GIT_SHORT_HASH={git_short_hash}");
}

View file

@ -18,21 +18,18 @@ services:
- gorb-backend:/gorb
environment:
#- RUST_LOG=debug
- WEB_FRONTEND_URL=https://gorb.app/web/
# This should be changed to the public URL of the server!
- WEB_URL=http://localhost:8080
- DATABASE_USERNAME=gorb
- DATABASE_PASSWORD=gorb
- DATABASE=gorb
- DATABASE_HOST=database
- DATABASE_PORT=5432
- BUNNY_API_KEY=your_storage_zone_password_here
- BUNNY_ENDPOINT=Frankfurt
- BUNNY_ZONE=gorb
- BUNNY_CDN_URL=https://cdn.gorb.app
- MAIL_ADDRESS=Gorb <noreply@gorb.app>
- MAIL_TLS=tls
- SMTP_SERVER=mail.gorb.app
- SMTP_USERNAME=your_smtp_username
- SMTP_PASSWORD=your_smtp_password
# These can be set to use a CDN, if they are not set then files will be stored locally
#- BUNNY_API_KEY=your_storage_zone_password_here
#- BUNNY_ENDPOINT=Frankfurt
#- BUNNY_ZONE=gorb
#- BUNNY_CDN_URL=https://cdn.gorb.app
database:
image: postgres:16
restart: always

View file

@ -16,21 +16,18 @@ services:
- gorb-backend:/gorb
environment:
#- RUST_LOG=debug
- WEB_FRONTEND_URL=https://gorb.app/web/
# This should be changed to the public URL of the server!
- WEB_URL=http://localhost:8080
- DATABASE_USERNAME=gorb
- DATABASE_PASSWORD=gorb
- DATABASE=gorb
- DATABASE_HOST=database
- DATABASE_PORT=5432
- BUNNY_API_KEY=your_storage_zone_password_here
- BUNNY_ENDPOINT=Frankfurt
- BUNNY_ZONE=gorb
- BUNNY_CDN_URL=https://cdn.gorb.app
- MAIL_ADDRESS=Gorb <noreply@gorb.app>
- MAIL_TLS=tls
- SMTP_SERVER=mail.gorb.app
- SMTP_USERNAME=your_smtp_username
- SMTP_PASSWORD=your_smtp_password
# These can be set to use a CDN, if they are not set then files will be stored locally
#- BUNNY_API_KEY=your_storage_zone_password_here
#- BUNNY_ENDPOINT=Frankfurt
#- BUNNY_ZONE=gorb
#- BUNNY_CDN_URL=https://cdn.gorb.app
database:
image: postgres:16
restart: always

View file

@ -8,11 +8,14 @@ if [ ! -d "/gorb/logs" ]; then
mkdir /gorb/logs
fi
if [ ! -d "/gorb/data" ]; then
mkdir /gorb/data
fi
if [ ! -f "/gorb/config/config.toml" ]; then
cat > /gorb/config/config.toml <<EOF
[web]
frontend_url = "${WEB_FRONTEND_URL}"
base_path = "${WEB_BASE_PATH}"
url = "${WEB_URL}"
[database]
username = "${DATABASE_USERNAME}"
@ -25,21 +28,17 @@ port = ${DATABASE_PORT}
host = "${CACHE_DB_HOST}"
port = ${CACHE_DB_PORT}
EOF
fi
if [ -n "${BUNNY_API_KEY}" ] && ! grep -q "^\[bunny\]" "/gorb/config/config.toml"; then
cat >> "/gorb/config/config.toml" <<EOF
[bunny]
api_key = "${BUNNY_API_KEY}"
endpoint = "${BUNNY_ENDPOINT}"
storage_zone = "${BUNNY_ZONE}"
cdn_url = "${BUNNY_CDN_URL}"
[mail]
address = "${MAIL_ADDRESS}"
tls = "${MAIL_TLS}"
[mail.smtp]
server = "${SMTP_SERVER}"
username = "${SMTP_USERNAME}"
password = "${SMTP_PASSWORD}"
EOF
fi
@ -65,4 +64,4 @@ rotate_log "/gorb/logs/backend.log"
# Give the DB time to start up before connecting
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 --data-dir /gorb/data 2>&1 | tee /gorb/logs/backend.log

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE channels DROP COLUMN is_above;

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE channels ADD COLUMN is_above UUID UNIQUE REFERENCES channels(uuid) DEFAULT NULL;

View file

@ -1,3 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE roles ADD COLUMN position int NOT NULL DEFAULT 0;
ALTER TABLE roles DROP COLUMN is_above;

View file

@ -1,3 +0,0 @@
-- Your SQL goes here
ALTER TABLE roles DROP COLUMN position;
ALTER TABLE roles ADD COLUMN is_above UUID UNIQUE REFERENCES roles(uuid) DEFAULT NULL;

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE email_tokens;

View file

@ -1,7 +0,0 @@
-- Your SQL goes here
CREATE TABLE email_tokens (
token VARCHAR(64) NOT NULL,
user_uuid uuid UNIQUE NOT NULL REFERENCES users(uuid),
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (token, user_uuid)
);

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE password_reset_tokens;

View file

@ -1,7 +0,0 @@
-- Your SQL goes here
CREATE TABLE password_reset_tokens (
token VARCHAR(64) NOT NULL,
user_uuid uuid UNIQUE NOT NULL REFERENCES users(uuid),
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (token, user_uuid)
);

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE users DROP COLUMN pronouns;

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE users ADD COLUMN pronouns VARCHAR(32) DEFAULT NULL;

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE users DROP COLUMN about;

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE users ADD COLUMN about VARCHAR(200) DEFAULT NULL;

View file

@ -1,7 +0,0 @@
-- This file should undo anything in `up.sql`
CREATE TABLE email_tokens (
token VARCHAR(64) NOT NULL,
user_uuid uuid UNIQUE NOT NULL REFERENCES users(uuid),
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (token, user_uuid)
);

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
DROP TABLE email_tokens;

View file

@ -1,7 +0,0 @@
-- This file should undo anything in `up.sql`
CREATE TABLE password_reset_tokens (
token VARCHAR(64) NOT NULL,
user_uuid uuid UNIQUE NOT NULL REFERENCES users(uuid),
created_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (token, user_uuid)
);

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
DROP TABLE password_reset_tokens;

View file

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

View file

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

View file

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

View file

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

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE messages DROP COLUMN reply_to;

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE messages ADD COLUMN reply_to UUID REFERENCES messages(uuid) DEFAULT NULL;

View file

@ -1,4 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE friend_requests;
DROP FUNCTION check_friend_request;
DROP TABLE friends;

View file

@ -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();

View file

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

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE guild_members ADD UNIQUE (user_uuid, guild_uuid)

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE refresh_tokens ALTER COLUMN device_name TYPE varchar(16);

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE refresh_tokens ALTER COLUMN device_name TYPE varchar(64);

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
DROP TABLE guild_bans;

View file

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

View file

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

View file

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

View file

@ -1,2 +0,0 @@
-- This file should undo anything in `up.sql`
ALTER TABLE users DROP COLUMN online_status;

View file

@ -1,2 +0,0 @@
-- Your SQL goes here
ALTER TABLE users ADD COLUMN online_status INT2 NOT NULL DEFAULT 0;

View file

@ -1,16 +1,9 @@
//! `/api` Contains the entire API
use std::sync::Arc;
use axum::{Router, routing::get};
use crate::AppState;
use actix_web::Scope;
use actix_web::web;
mod v1;
mod versions;
pub fn router(path: &str, app_state: Arc<AppState>) -> Router<Arc<AppState>> {
Router::new()
.route(&format!("{path}/versions"), get(versions::versions))
.nest(&format!("{path}/v1"), v1::router(app_state))
pub fn web() -> Scope {
web::scope("/api").service(v1::web()).service(versions::res)
}

View file

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

View file

@ -1,62 +1,94 @@
use std::{
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use std::time::{SystemTime, UNIX_EPOCH};
use actix_web::{HttpResponse, post, web};
use argon2::{PasswordHash, PasswordVerifier};
use axum::{
Json,
extract::State,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use diesel::{ExpressionMethods, QueryDsl, dsl::insert_into};
use diesel_async::RunQueryDsl;
use serde::Deserialize;
use uuid::Uuid;
use super::Response;
use crate::{
AppState,
Data,
api::v1::auth::{EMAIL_REGEX, PASSWORD_REGEX, USERNAME_REGEX},
error::Error,
schema::*,
utils::{
PASSWORD_REGEX, generate_device_name, generate_token, new_refresh_token_cookie,
user_uuid_from_identifier,
},
utils::{generate_access_token, generate_refresh_token, refresh_token_cookie},
};
use super::Response;
#[derive(Deserialize)]
pub struct LoginInformation {
struct LoginInformation {
username: String,
password: String,
device_name: String,
}
#[post("/login")]
pub async fn response(
State(app_state): State<Arc<AppState>>,
Json(login_information): Json<LoginInformation>,
) -> Result<impl IntoResponse, Error> {
login_information: web::Json<LoginInformation>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
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;
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 database_password: String = dsl::users
.filter(dsl::uuid.eq(uuid))
.select(dsl::password)
if EMAIL_REGEX.is_match(&login_information.username) {
// FIXME: error handling, right now i just want this to work
let (uuid, password): (Uuid, String) = dsl::users
.filter(dsl::email.eq(&login_information.username))
.select((dsl::uuid, dsl::password))
.get_result(&mut conn)
.await?;
return login(
data.clone(),
uuid,
login_information.password.clone(),
password,
login_information.device_name.clone(),
)
.await;
} else if USERNAME_REGEX.is_match(&login_information.username) {
// FIXME: error handling, right now i just want this to work
let (uuid, password): (Uuid, String) = dsl::users
.filter(dsl::username.eq(&login_information.username))
.select((dsl::uuid, dsl::password))
.get_result(&mut conn)
.await?;
return login(
data.clone(),
uuid,
login_information.password.clone(),
password,
login_information.device_name.clone(),
)
.await;
}
Ok(HttpResponse::Unauthorized().finish())
}
async fn login(
data: actix_web::web::Data<Data>,
uuid: Uuid,
request_password: String,
database_password: String,
device_name: String,
) -> Result<HttpResponse, Error> {
let mut conn = data.pool.get().await?;
let parsed_hash = PasswordHash::new(&database_password)
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
if app_state
if data
.argon2
.verify_password(login_information.password.as_bytes(), &parsed_hash)
.verify_password(request_password.as_bytes(), &parsed_hash)
.is_err()
{
return Err(Error::Unauthorized(
@ -64,21 +96,19 @@ pub async fn response(
));
}
let refresh_token = generate_token::<32>()?;
let access_token = generate_token::<16>()?;
let refresh_token = generate_refresh_token()?;
let access_token = generate_access_token()?;
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
use refresh_tokens::dsl as rdsl;
let device_name = generate_device_name();
insert_into(refresh_tokens::table)
.values((
rdsl::token.eq(&refresh_token),
rdsl::uuid.eq(uuid),
rdsl::created_at.eq(current_time),
rdsl::device_name.eq(&device_name),
rdsl::device_name.eq(device_name),
))
.execute(&mut conn)
.await?;
@ -95,21 +125,7 @@ pub async fn response(
.execute(&mut conn)
.await?;
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(),
)?,
);
Ok(response)
Ok(HttpResponse::Ok()
.cookie(refresh_token_cookie(refresh_token))
.json(Response { access_token }))
}

View file

@ -1,65 +0,0 @@
use std::sync::Arc;
use axum::{
extract::State,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use axum_extra::extract::CookieJar;
use diesel::{ExpressionMethods, delete};
use diesel_async::RunQueryDsl;
use crate::{
AppState,
error::Error,
schema::refresh_tokens::{self, dsl},
};
/// `GET /api/v1/logout`
///
/// requires auth: kinda, needs refresh token set but no access token is technically required
///
/// ### Responses
///
/// 200 Logged out
///
/// 404 Refresh token is invalid
///
/// 401 Unauthorized (no refresh token found)
///
pub async fn res(
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 refresh_token = String::from(refresh_token_cookie.value_trimmed());
let mut conn = app_state.pool.get().await?;
let deleted = delete(refresh_tokens::table)
.filter(dsl::token.eq(refresh_token))
.execute(&mut conn)
.await?;
let mut response;
if deleted == 0 {
response = StatusCode::NOT_FOUND.into_response();
} else {
response = StatusCode::OK.into_response();
}
refresh_token_cookie.make_removal();
response.headers_mut().append(
"Set-Cookie",
HeaderValue::from_str(&refresh_token_cookie.to_string())?,
);
Ok(response)
}

View file

@ -1,57 +1,42 @@
use std::{
sync::Arc,
sync::LazyLock,
time::{SystemTime, UNIX_EPOCH},
};
use axum::{
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 actix_web::{Scope, web};
use diesel::{ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl;
use regex::Regex;
use serde::Serialize;
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 logout;
mod refresh;
mod register;
mod reset_password;
mod revoke;
mod verify_email;
#[derive(Serialize)]
pub struct Response {
struct Response {
access_token: String,
device_name: String,
}
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
let router_with_auth = Router::new()
.route("/verify-email", get(verify_email::get))
.route("/verify-email", post(verify_email::post))
.route("/revoke", post(revoke::post))
.route("/devices", get(devices::get))
.layer(from_fn_with_state(app_state, CurrentUser::check_auth_layer));
static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"[-A-Za-z0-9!#$%&'*+/=?^_`{|}~]+(?:\.[-A-Za-z0-9!#$%&'*+/=?^_`{|}~]+)*@(?:[A-Za-z0-9](?:[-A-Za-z0-9]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[-A-Za-z0-9]*[A-Za-z0-9])?").unwrap()
});
Router::new()
.route("/register", post(register::post))
.route("/login", post(login::response))
.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)
static USERNAME_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-z0-9_.-]+$").unwrap());
// Password is expected to be hashed using SHA3-384
static PASSWORD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[0-9a-f]{96}").unwrap());
pub fn web() -> Scope {
web::scope("/auth")
.service(register::res)
.service(login::response)
.service(refresh::res)
.service(revoke::res)
}
pub async fn check_access_token(access_token: &str, conn: &mut Conn) -> Result<Uuid, Error> {
@ -78,21 +63,3 @@ pub async fn check_access_token(access_token: &str, conn: &mut Conn) -> Result<U
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)
}
}

View file

@ -1,45 +1,34 @@
use axum::{
Json,
extract::State,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use axum_extra::extract::CookieJar;
use actix_web::{HttpRequest, HttpResponse, post, web};
use diesel::{ExpressionMethods, QueryDsl, delete, update};
use diesel_async::RunQueryDsl;
use log::error;
use std::{
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use std::time::{SystemTime, UNIX_EPOCH};
use super::Response;
use crate::{
AppState,
Data,
error::Error,
schema::{
access_tokens::{self, dsl},
refresh_tokens::{self, dsl as rdsl},
},
utils::{generate_token, new_refresh_token_cookie},
utils::{generate_access_token, generate_refresh_token, refresh_token_cookie},
};
pub async fn post(
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();
use super::Response;
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 recv_refresh_token_cookie = req.cookie("refresh_token");
if recv_refresh_token_cookie.is_none() {
return Ok(HttpResponse::Unauthorized().finish());
}
let mut refresh_token = String::from(recv_refresh_token_cookie.unwrap().value());
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
.filter(rdsl::token.eq(&refresh_token))
@ -55,25 +44,29 @@ pub async fn post(
.execute(&mut conn)
.await
{
error!("{error}");
error!("{}", error);
}
let mut response = StatusCode::UNAUTHORIZED.into_response();
let mut refresh_token_cookie = refresh_token_cookie(refresh_token);
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 mut device_name: String = String::new();
if lifetime > 1987200 {
let new_refresh_token = generate_token::<32>()?;
let new_refresh_token = generate_refresh_token();
if new_refresh_token.is_err() {
error!("{}", new_refresh_token.unwrap_err());
return Ok(HttpResponse::InternalServerError().finish());
}
let new_refresh_token = new_refresh_token.unwrap();
match update(refresh_tokens::table)
.filter(rdsl::token.eq(&refresh_token))
@ -81,21 +74,19 @@ pub async fn post(
rdsl::token.eq(&new_refresh_token),
rdsl::created_at.eq(current_time),
))
.returning(rdsl::device_name)
.get_result::<String>(&mut conn)
.execute(&mut conn)
.await
{
Ok(existing_device_name) => {
Ok(_) => {
refresh_token = new_refresh_token;
device_name = existing_device_name;
}
Err(error) => {
error!("{error}");
error!("{}", error);
}
}
}
let access_token = generate_token::<16>()?;
let access_token = generate_access_token()?;
update(access_tokens::table)
.filter(dsl::refresh_token.eq(&refresh_token))
@ -106,33 +97,16 @@ pub async fn post(
.execute(&mut conn)
.await?;
let mut response = (
StatusCode::OK,
Json(Response {
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);
return Ok(HttpResponse::Ok()
.cookie(refresh_token_cookie(refresh_token))
.json(Response { access_token }));
}
let mut response = StatusCode::UNAUTHORIZED.into_response();
let mut refresh_token_cookie = refresh_token_cookie(refresh_token);
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())
}

View file

@ -1,18 +1,10 @@
use std::{
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use std::time::{SystemTime, UNIX_EPOCH};
use actix_web::{HttpResponse, post, web};
use argon2::{
PasswordHasher,
password_hash::{SaltString, rand_core::OsRng},
};
use axum::{
Json,
extract::State,
http::{HeaderValue, StatusCode},
response::IntoResponse,
};
use diesel::{ExpressionMethods, dsl::insert_into};
use diesel_async::RunQueryDsl;
use serde::{Deserialize, Serialize};
@ -20,35 +12,37 @@ use uuid::Uuid;
use super::Response;
use crate::{
AppState,
Data,
api::v1::auth::{EMAIL_REGEX, PASSWORD_REGEX, USERNAME_REGEX},
error::Error,
objects::Member,
schema::{
access_tokens::{self, dsl as adsl},
refresh_tokens::{self, dsl as rdsl},
users::{self, dsl as udsl},
},
utils::{
EMAIL_REGEX, PASSWORD_REGEX, USERNAME_REGEX, generate_device_name, generate_token,
new_refresh_token_cookie,
},
utils::{generate_access_token, generate_refresh_token, refresh_token_cookie},
};
#[derive(Deserialize)]
pub struct AccountInformation {
struct AccountInformation {
identifier: String,
email: String,
password: String,
device_name: String,
}
#[derive(Serialize)]
pub struct ResponseError {
struct ResponseError {
signups_enabled: bool,
gorb_id_valid: bool,
gorb_id_available: bool,
email_valid: 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 {
@ -59,66 +53,53 @@ impl Default for ResponseError {
gorb_id_available: true,
email_valid: 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(
State(app_state): State<Arc<AppState>>,
Json(account_information): Json<AccountInformation>,
) -> Result<impl IntoResponse, Error> {
if !app_state.config.instance.registration {
return Err(Error::Forbidden(
"registration is disabled on this instance".to_string(),
));
}
#[post("/register")]
pub async fn res(
account_information: web::Json<AccountInformation>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let uuid = Uuid::now_v7();
if !EMAIL_REGEX.is_match(&account_information.email) {
return Ok((
StatusCode::FORBIDDEN,
Json(ResponseError {
return Ok(HttpResponse::Forbidden().json(ResponseError {
email_valid: false,
..Default::default()
}),
)
.into_response());
}));
}
if !USERNAME_REGEX.is_match(&account_information.identifier)
|| account_information.identifier.len() < 3
|| account_information.identifier.len() > 32
{
return Ok((
StatusCode::FORBIDDEN,
Json(ResponseError {
return Ok(HttpResponse::Forbidden().json(ResponseError {
gorb_id_valid: false,
..Default::default()
}),
)
.into_response());
}));
}
if !PASSWORD_REGEX.is_match(&account_information.password) {
return Ok((
StatusCode::FORBIDDEN,
Json(ResponseError {
password_strength: false,
return Ok(HttpResponse::Forbidden().json(ResponseError {
password_hashed: false,
..Default::default()
}),
)
.into_response());
}));
}
let salt = SaltString::generate(&mut OsRng);
if let Ok(hashed_password) = app_state
if let Ok(hashed_password) = data
.argon2
.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
insert_into(users::table)
@ -131,19 +112,17 @@ pub async fn post(
.execute(&mut conn)
.await?;
let refresh_token = generate_token::<32>()?;
let access_token = generate_token::<16>()?;
let refresh_token = generate_refresh_token()?;
let access_token = generate_access_token()?;
let current_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
let device_name = generate_device_name();
insert_into(refresh_tokens::table)
.values((
rdsl::token.eq(&refresh_token),
rdsl::uuid.eq(uuid),
rdsl::created_at.eq(current_time),
rdsl::device_name.eq(&device_name),
rdsl::device_name.eq(&account_information.device_name),
))
.execute(&mut conn)
.await?;
@ -158,28 +137,10 @@ pub async fn post(
.execute(&mut conn)
.await?;
if let Some(initial_guild) = app_state.config.instance.initial_guild {
Member::new(&mut conn, &app_state.cache_pool, uuid, initial_guild).await?;
return Ok(HttpResponse::Ok()
.cookie(refresh_token_cookie(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())
}

View file

@ -1,107 +0,0 @@
//! `/api/v1/auth/reset-password` Endpoints for resetting user password
use std::sync::Arc;
use axum::{
Json,
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
};
use chrono::{Duration, Utc};
use serde::Deserialize;
use crate::{AppState, error::Error, objects::PasswordResetToken};
#[derive(Deserialize)]
pub struct QueryParams {
identifier: String,
}
/// `GET /api/v1/auth/reset-password` Sends password reset email to user
///
/// requires auth? no
///
/// ### Query Parameters
/// identifier: Email or username
///
/// ### Responses
/// 200 Email sent
///
/// 429 Too Many Requests
///
/// 404 Not found
///
/// 400 Bad request
///
pub async fn get(
State(app_state): State<Arc<AppState>>,
query: Query<QueryParams>,
) -> Result<impl IntoResponse, Error> {
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) {
password_reset_token.delete(&app_state.cache_pool).await?;
} else {
return Err(Error::TooManyRequests(
"Please allow 1 hour before sending a new email".to_string(),
));
}
}
PasswordResetToken::new(&mut conn, &app_state, query.identifier.clone()).await?;
Ok(StatusCode::OK)
}
#[derive(Deserialize)]
pub struct ResetPassword {
password: String,
token: String,
}
/// `POST /api/v1/auth/reset-password` Resets user password
///
/// requires auth? no
///
/// ### Request Example:
/// ```
/// json!({
/// "password": "1608c17a27f6ae3891c23d680c73ae91528f20a54dcf4973e2c3126b9734f48b7253047f2395b51bb8a44a6daa188003",
/// "token": "a3f7e29c1b8d0456e2c9f83b7a1d6e4f5028c3b9a7e1f2d5c6b8a0d3e7f4a2b"
/// });
/// ```
///
/// ### Responses
/// 200 Success
///
/// 410 Token Expired
///
/// 404 Not Found
///
/// 400 Bad Request
///
pub async fn post(
State(app_state): State<Arc<AppState>>,
reset_password: Json<ResetPassword>,
) -> Result<impl IntoResponse, Error> {
let password_reset_token =
PasswordResetToken::get(&app_state.cache_pool, reset_password.token.clone()).await?;
password_reset_token
.set_password(
&mut app_state.pool.get().await?,
&app_state,
reset_password.password.clone(),
)
.await?;
Ok(StatusCode::OK)
}

View file

@ -1,35 +1,38 @@
use std::sync::Arc;
use actix_web::{HttpRequest, HttpResponse, post, web};
use argon2::{PasswordHash, PasswordVerifier};
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
use diesel::{ExpressionMethods, QueryDsl, delete};
use diesel_async::RunQueryDsl;
use serde::Deserialize;
use uuid::Uuid;
use crate::{
AppState,
api::v1::auth::CurrentUser,
Data,
api::v1::auth::check_access_token,
error::Error,
schema::{
refresh_tokens::{self, dsl as rdsl},
users::dsl as udsl,
},
schema::refresh_tokens::{self, dsl as rdsl},
schema::users::dsl as udsl,
utils::get_auth_header,
};
#[derive(Deserialize)]
pub struct RevokeRequest {
struct RevokeRequest {
password: String,
device_name: String,
}
// TODO: Should maybe be a delete request?
pub async fn post(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(revoke_request): Json<RevokeRequest>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
#[post("/revoke")]
pub async fn res(
req: HttpRequest,
revoke_request: web::Json<RevokeRequest>,
data: web::Data<Data>,
) -> 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
.filter(udsl::uuid.eq(uuid))
@ -40,7 +43,7 @@ pub async fn post(
let hashed_password = PasswordHash::new(&database_password)
.map_err(|e| Error::PasswordHashError(e.to_string()))?;
if app_state
if data
.argon2
.verify_password(revoke_request.password.as_bytes(), &hashed_password)
.is_err()
@ -56,5 +59,5 @@ pub async fn post(
.execute(&mut conn)
.await?;
Ok(StatusCode::OK)
Ok(HttpResponse::Ok().finish())
}

View file

@ -1,107 +0,0 @@
//! `/api/v1/auth/verify-email` Endpoints for verifying user emails
use std::sync::Arc;
use axum::{
Extension,
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
};
use chrono::{Duration, Utc};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{EmailToken, Me},
};
#[derive(Deserialize)]
pub struct QueryParams {
token: String,
}
/// `GET /api/v1/auth/verify-email` Verifies user email address
///
/// requires auth? yes
///
/// ### Query Parameters
/// token
///
/// ### Responses
/// 200 Success
///
/// 204 Already verified
///
/// 410 Token Expired
///
/// 404 Not Found
///
/// 401 Unauthorized
///
pub async fn get(
State(app_state): State<Arc<AppState>>,
Query(query): Query<QueryParams>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
let me = Me::get(&mut conn, uuid).await?;
if me.email_verified {
return Ok(StatusCode::NO_CONTENT);
}
let email_token = EmailToken::get(&app_state.cache_pool, me.uuid).await?;
if query.token != email_token.token {
return Ok(StatusCode::UNAUTHORIZED);
}
me.verify_email(&mut conn).await?;
email_token.delete(&app_state.cache_pool).await?;
Ok(StatusCode::OK)
}
/// `POST /api/v1/auth/verify-email` Sends user verification email
///
/// requires auth? yes
///
/// ### Responses
/// 200 Email sent
///
/// 204 Already verified
///
/// 429 Too Many Requests
///
/// 401 Unauthorized
///
pub async fn post(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
let me = Me::get(&mut app_state.pool.get().await?, uuid).await?;
if me.email_verified {
return Ok(StatusCode::NO_CONTENT);
}
if let Ok(email_token) = EmailToken::get(&app_state.cache_pool, me.uuid).await {
if Utc::now().signed_duration_since(email_token.created_at) > Duration::hours(1) {
email_token.delete(&app_state.cache_pool).await?;
} else {
return Err(Error::TooManyRequests(
"Please allow 1 hour before sending a new email".to_string(),
));
}
}
EmailToken::new(&app_state, me).await?;
Ok(StatusCode::OK)
}

View file

@ -1,25 +0,0 @@
use std::sync::Arc;
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;
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
let router_with_auth = Router::new()
.route("/{uuid}", get(uuid::get))
.route("/{uuid}", delete(uuid::delete))
.route("/{uuid}", patch(uuid::patch))
.route("/{uuid}/messages", get(uuid::messages::get))
.layer(from_fn_with_state(app_state, CurrentUser::check_auth_layer));
Router::new()
.route("/{uuid}/socket", any(uuid::socket::ws))
.merge(router_with_auth)
}

View file

@ -1,81 +0,0 @@
//! `/api/v1/channels/{uuid}/messages` Endpoints related to channel messages
use std::sync::Arc;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Channel, Member},
utils::global_checks,
};
use ::uuid::Uuid;
use axum::{
Extension, Json,
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct MessageRequest {
amount: i64,
offset: i64,
}
/// `GET /api/v1/channels/{uuid}/messages` Returns user with the given UUID
///
/// requires auth: yes
///
/// requires relation: yes
///
/// ### Request Example
/// ```
/// json!({
/// "amount": 100,
/// "offset": 0
/// })
/// ```
///
/// ### Response Example
/// ```
/// json!({
/// "uuid": "01971976-8618-74c0-b040-7ffbc44823f6",
/// "channel_uuid": "0196fcb1-e886-7de3-b685-0ee46def9a7b",
/// "user_uuid": "0196fc96-a822-76b0-b9bf-a9de232f54b7",
/// "message": "test",
/// "user": {
/// "uuid": "0196fc96-a822-76b0-b9bf-a9de232f54b7",
/// "username": "1234",
/// "display_name": null,
/// "avatar": "https://cdn.gorb.app/avatar/0196fc96-a822-76b0-b9bf-a9de232f54b7/avatar.jpg"
/// }
/// });
/// ```
///
pub async fn get(
State(app_state): State<Arc<AppState>>,
Path(channel_uuid): Path<Uuid>,
Query(message_request): Query<MessageRequest>,
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 channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
let messages = channel
.fetch_messages(
&mut conn,
&app_state.cache_pool,
message_request.amount,
message_request.offset,
)
.await?;
Ok((StatusCode::OK, Json(messages)))
}

View file

@ -1,142 +0,0 @@
//! `/api/v1/channels/{uuid}` Channel specific endpoints
pub mod messages;
pub mod socket;
use std::sync::Arc;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Channel, Member, Permissions},
utils::global_checks,
};
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use serde::Deserialize;
use uuid::Uuid;
pub async fn get(
State(app_state): State<Arc<AppState>>,
Path(channel_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 channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
Ok((StatusCode::OK, Json(channel)))
}
pub async fn delete(
State(app_state): State<Arc<AppState>>,
Path(channel_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 channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
let member = Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
member
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageChannel)
.await?;
channel.delete(&mut conn, &app_state.cache_pool).await?;
Ok(StatusCode::OK)
}
#[derive(Deserialize)]
pub struct NewInfo {
name: Option<String>,
description: Option<String>,
is_above: Option<String>,
}
/// `PATCH /api/v1/channels/{uuid}` Returns user with the given UUID
///
/// requires auth: yes
///
/// requires relation: yes
///
/// ### Request Example
/// All fields are optional and can be nulled/dropped if only changing 1 value
/// ```
/// json!({
/// "name": "gaming-chat",
/// "description": "Gaming related topics.",
/// "is_above": "398f6d7b-752c-4348-9771-fe6024adbfb1"
/// });
/// ```
///
/// ### Response Example
/// ```
/// json!({
/// uuid: "cdcac171-5add-4f88-9559-3a247c8bba2c",
/// guild_uuid: "383d2afa-082f-4dd3-9050-ca6ed91487b6",
/// name: "gaming-chat",
/// description: "Gaming related topics.",
/// is_above: "398f6d7b-752c-4348-9771-fe6024adbfb1",
/// permissions: {
/// role_uuid: "79cc0806-0f37-4a06-a468-6639c4311a2d",
/// permissions: 0
/// }
/// });
/// ```
/// 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 patch(
State(app_state): State<Arc<AppState>>,
Path(channel_uuid): Path<Uuid>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(new_info): Json<NewInfo>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
global_checks(&mut conn, &app_state.config, uuid).await?;
let mut channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
let member = Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
member
.check_permission(&mut conn, &app_state.cache_pool, Permissions::ManageChannel)
.await?;
if let Some(new_name) = &new_info.name {
channel
.set_name(&mut conn, &app_state.cache_pool, new_name.to_string())
.await?;
}
if let Some(new_description) = &new_info.description {
channel
.set_description(
&mut conn,
&app_state.cache_pool,
new_description.to_string(),
)
.await?;
}
if let Some(new_is_above) = &new_info.is_above {
channel
.set_description(&mut conn, &app_state.cache_pool, new_is_above.to_string())
.await?;
}
Ok((StatusCode::OK, Json(channel)))
}

View file

@ -1,139 +0,0 @@
use std::sync::Arc;
use axum::{
extract::{Path, State, WebSocketUpgrade, ws::Message},
http::HeaderMap,
response::IntoResponse,
};
use futures_util::{SinkExt, StreamExt};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
AppState,
api::v1::auth::check_access_token,
error::Error,
objects::{Channel, Member},
utils::global_checks,
};
#[derive(Deserialize)]
struct MessageBody {
message: String,
reply_to: Option<Uuid>,
}
pub async fn ws(
ws: WebSocketUpgrade,
State(app_state): State<Arc<AppState>>,
Path(channel_uuid): Path<Uuid>,
headers: HeaderMap,
) -> Result<impl IntoResponse, Error> {
// Retrieve auth header
let auth_token = headers.get(axum::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()));
}
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
let uuid = check_access_token(auth_header, &mut conn).await?;
global_checks(&mut conn, &app_state.config, uuid).await?;
let channel = Channel::fetch_one(&mut conn, &app_state.cache_pool, channel_uuid).await?;
Member::check_membership(&mut conn, uuid, channel.guild_uuid).await?;
let mut pubsub = app_state
.cache_pool
.get_async_pubsub()
.await
.map_err(crate::error::Error::from)?;
let mut res = ws.on_upgrade(async move |socket| {
let (mut sender, mut receiver) = socket.split();
tokio::spawn(async move {
pubsub.subscribe(channel_uuid.to_string()).await?;
while let Some(msg) = pubsub.on_message().next().await {
let payload: String = msg.get_payload()?;
sender.send(payload.into()).await?;
}
Ok::<(), crate::error::Error>(())
});
tokio::spawn(async move {
while let Some(msg) = receiver.next().await {
if let Ok(Message::Text(text)) = msg {
let message_body: MessageBody = serde_json::from_str(&text)?;
let message = channel
.new_message(
&mut conn,
&app_state.cache_pool,
uuid,
message_body.message,
message_body.reply_to,
)
.await?;
redis::cmd("PUBLISH")
.arg(&[channel_uuid.to_string(), serde_json::to_string(&message)?])
.exec_async(
&mut app_state
.cache_pool
.get_multiplexed_tokio_connection()
.await?,
)
.await?;
}
}
Ok::<(), crate::error::Error>(())
});
});
let headers = res.headers_mut();
headers.append(
axum::http::header::SEC_WEBSOCKET_PROTOCOL,
"Authorization".parse()?,
);
// respond immediately with response connected to WS session
Ok(res)
}

View file

@ -1,138 +0,0 @@
//! `/api/v1/guilds` Guild related endpoints
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json, Router,
extract::State,
http::StatusCode,
response::IntoResponse,
routing::{get, post},
};
use serde::Deserialize;
mod uuid;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Guild, StartAmountQuery},
utils::global_checks,
};
#[derive(Deserialize)]
pub struct GuildInfo {
name: String,
}
pub fn router() -> Router<Arc<AppState>> {
Router::new()
.route("/", post(new))
.route("/", get(get_guilds))
.nest("/{uuid}", uuid::router())
}
/// `POST /api/v1/guilds` Creates a new guild
///
/// requires auth: yes
///
/// ### Request Example
/// ```
/// json!({
/// "name": "My new server!"
/// });
/// ```
///
/// ### Response Example
/// ```
/// json!({
/// "uuid": "383d2afa-082f-4dd3-9050-ca6ed91487b6",
/// "name": "My new server!",
/// "description": null,
/// "icon": null,
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [],
/// "member_count": 1
/// });
/// ```
/// 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(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(guild_info): Json<GuildInfo>,
) -> Result<impl IntoResponse, Error> {
let guild = Guild::new(
&mut app_state.pool.get().await?,
guild_info.name.clone(),
uuid,
)
.await?;
Ok((StatusCode::OK, Json(guild)))
}
/// `GET /api/v1/servers` Fetches all guilds
///
/// requires auth: yes
///
/// requires admin: yes
///
/// ### Response Example
/// ```
/// json!([
/// {
/// "uuid": "383d2afa-082f-4dd3-9050-ca6ed91487b6",
/// "name": "My new server!",
/// "description": null,
/// "icon": null,
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [],
/// "member_count": 1
/// },
/// {
/// "uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "My first server!",
/// "description": "This is a cool and nullable description!",
/// "icon": "https://nullable-url/path/to/icon.png",
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [
/// {
/// "uuid": "be0e4da4-cf73-4f45-98f8-bb1c73d1ab8b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Cool people",
/// "color": 15650773,
/// "is_above": c7432f1c-f4ad-4ad3-8216-51388b6abb5b,
/// "permissions": 0
/// }
/// {
/// "uuid": "c7432f1c-f4ad-4ad3-8216-51388b6abb5b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Equally cool people",
/// "color": 16777215,
/// "is_above": null,
/// "permissions": 0
/// }
/// ],
/// "member_count": 20
/// }
/// ]);
/// ```
/// 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(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(request_query): Json<StartAmountQuery>,
) -> Result<impl IntoResponse, Error> {
let start = request_query.start.unwrap_or(0);
let amount = request_query.amount.unwrap_or(10);
let mut conn = app_state.pool.get().await?;
global_checks(&mut conn, &app_state.config, uuid).await?;
let guilds = Guild::fetch_amount(&mut conn, start, amount).await?;
Ok((StatusCode::OK, Json(guilds)))
}

View file

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

View file

@ -1,87 +0,0 @@
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
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)]
pub struct ChannelInfo {
name: String,
description: Option<String>,
}
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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = app_state
.cache_pool
.get_cache_key::<Vec<Channel>>(format!("{guild_uuid}_channels"))
.await
{
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
}
let channels = Channel::fetch_all(&mut conn, guild_uuid).await?;
let channels_ordered = order_by_is_above(channels).await?;
app_state
.cache_pool
.set_cache_key(
format!("{guild_uuid}_channels"),
channels_ordered.clone(),
1800,
)
.await?;
Ok((StatusCode::OK, Json(channels_ordered)).into_response())
}
pub async fn create(
State(app_state): State<Arc<AppState>>,
Path(guild_uuid): Path<Uuid>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(channel_info): Json<ChannelInfo>,
) -> 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::ManageChannel)
.await?;
let channel = Channel::new(
&mut conn,
&app_state.cache_pool,
guild_uuid,
channel_info.name.clone(),
channel_info.description.clone(),
)
.await?;
Ok((StatusCode::OK, Json(channel)))
}

View file

@ -1,66 +0,0 @@
use std::sync::Arc;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Guild, Member, Permissions},
utils::global_checks,
};
#[derive(Deserialize)]
pub struct InviteRequest {
custom_id: Option<String>,
}
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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
let invites = guild.get_invites(&mut conn).await?;
Ok((StatusCode::OK, Json(invites)))
}
pub async fn create(
State(app_state): State<Arc<AppState>>,
Path(guild_uuid): Path<Uuid>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(invite_request): Json<InviteRequest>,
) -> 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::CreateInvite)
.await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
let invite = guild
.create_invite(&mut conn, uuid, invite_request.custom_id.clone())
.await?;
Ok((StatusCode::OK, Json(invite)))
}

View file

@ -1,43 +0,0 @@
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json,
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
};
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Me, Member, PaginationRequest},
utils::global_checks,
};
pub async fn get(
State(app_state): State<Arc<AppState>>,
Path(guild_uuid): Path<Uuid>,
Query(pagination): Query<PaginationRequest>,
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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
let me = Me::get(&mut conn, uuid).await?;
let members = Member::fetch_page(
&mut conn,
&app_state.cache_pool,
&me,
guild_uuid,
pagination,
)
.await?;
Ok((StatusCode::OK, Json(members)))
}

View file

@ -1,138 +0,0 @@
//! `/api/v1/guilds/{uuid}` Specific server endpoints
use std::sync::Arc;
use axum::{
Extension, Json, Router,
extract::{Multipart, Path, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, patch, post},
};
use bytes::Bytes;
use uuid::Uuid;
mod bans;
mod channels;
mod invites;
mod members;
mod roles;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Guild, Member, Permissions},
utils::global_checks,
};
pub fn router() -> Router<Arc<AppState>> {
Router::new()
// Servers
.route("/", get(get_guild))
.route("/", patch(edit))
// Channels
.route("/channels", get(channels::get))
.route("/channels", post(channels::create))
// Roles
.route("/roles", get(roles::get))
.route("/roles", post(roles::create))
.route("/roles/{role_uuid}", get(roles::uuid::get))
// Invites
.route("/invites", get(invites::get))
.route("/invites", post(invites::create))
// Members
.route("/members", get(members::get))
// Bans
.route("/bans", get(bans::get))
.route("/bans/{uuid}", delete(bans::unban))
}
/// `GET /api/v1/guilds/{uuid}` DESCRIPTION
///
/// requires auth: yes
///
/// ### Response Example
/// ```
/// json!({
/// "uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "My first server!",
/// "description": "This is a cool and nullable description!",
/// "icon": "https://nullable-url/path/to/icon.png",
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [
/// {
/// "uuid": "be0e4da4-cf73-4f45-98f8-bb1c73d1ab8b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Cool people",
/// "color": 15650773,
/// "is_above": c7432f1c-f4ad-4ad3-8216-51388b6abb5b,
/// "permissions": 0
/// }
/// {
/// "uuid": "c7432f1c-f4ad-4ad3-8216-51388b6abb5b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Equally cool people",
/// "color": 16777215,
/// "is_above": null,
/// "permissions": 0
/// }
/// ],
/// "member_count": 20
/// });
/// ```
pub async fn get_guild(
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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
Ok((StatusCode::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)
}

View file

@ -1,77 +0,0 @@
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use serde::Deserialize;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Member, Permissions, Role},
utils::{CacheFns, global_checks, order_by_is_above},
};
pub mod uuid;
#[derive(Deserialize)]
pub struct RoleInfo {
name: String,
}
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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = app_state
.cache_pool
.get_cache_key::<Vec<Role>>(format!("{guild_uuid}_roles"))
.await
{
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
}
let roles = Role::fetch_all(&mut conn, guild_uuid).await?;
let roles_ordered = order_by_is_above(roles).await?;
app_state
.cache_pool
.set_cache_key(format!("{guild_uuid}_roles"), roles_ordered.clone(), 1800)
.await?;
Ok((StatusCode::OK, Json(roles_ordered)).into_response())
}
pub async fn create(
State(app_state): State<Arc<AppState>>,
Path(guild_uuid): Path<Uuid>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
Json(role_info): Json<RoleInfo>,
) -> 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::ManageRole)
.await?;
let role = Role::new(&mut conn, guild_uuid, role_info.name.clone()).await?;
Ok((StatusCode::OK, Json(role)).into_response())
}

View file

@ -1,46 +0,0 @@
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Member, Role},
utils::{CacheFns, global_checks},
};
pub async fn get(
State(app_state): State<Arc<AppState>>,
Path((guild_uuid, role_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?;
Member::check_membership(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = app_state
.cache_pool
.get_cache_key::<Role>(format!("{role_uuid}"))
.await
{
return Ok((StatusCode::OK, Json(cache_hit)).into_response());
}
let role = Role::fetch_one(&mut conn, role_uuid).await?;
app_state
.cache_pool
.set_cache_key(format!("{role_uuid}"), role.clone(), 60)
.await?;
Ok((StatusCode::OK, Json(role)).into_response())
}

View file

@ -1,48 +1,57 @@
use std::sync::Arc;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use uuid::Uuid;
use actix_web::{HttpRequest, HttpResponse, get, post, web};
use crate::{
AppState,
api::v1::auth::CurrentUser,
Data,
api::v1::auth::check_access_token,
error::Error,
objects::{Guild, Invite, Member},
utils::global_checks,
structs::{Guild, Invite, Member},
utils::get_auth_header,
};
#[get("{id}")]
pub async fn get(
State(app_state): State<Arc<AppState>>,
Path(invite_id): Path<String>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
req: HttpRequest,
path: web::Path<(String,)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
let auth_header = get_auth_header(headers)?;
let mut conn = data.pool.get().await?;
check_access_token(auth_header, &mut conn).await?;
let invite_id = path.into_inner().0;
let invite = Invite::fetch_one(&mut conn, invite_id).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(
State(app_state): State<Arc<AppState>>,
Path(invite_id): Path<String>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
req: HttpRequest,
path: web::Path<(String,)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
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?;
let invite = Invite::fetch_one(&mut conn, invite_id).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(&mut conn, uuid, guild.uuid).await?;
Ok((StatusCode::OK, Json(guild)))
Ok(HttpResponse::Ok().json(guild))
}

View file

@ -1,16 +1,7 @@
use std::sync::Arc;
use axum::{
Router,
routing::{get, post},
};
use crate::AppState;
use actix_web::{Scope, web};
mod id;
pub fn router() -> Router<Arc<AppState>> {
Router::new()
.route("/{id}", get(id::get))
.route("/{id}", post(id::join))
pub fn web() -> Scope {
web::scope("/invites").service(id::get).service(id::join)
}

View file

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

View file

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

View file

@ -1,70 +0,0 @@
//! `/api/v1/me/guilds` Contains endpoint related to guild memberships
use std::sync::Arc;
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
use uuid::Uuid;
use crate::{
AppState, api::v1::auth::CurrentUser, error::Error, objects::Me, utils::global_checks,
};
/// `GET /api/v1/me/guilds` Returns all guild memberships in a list
///
/// requires auth: yes
///
/// ### Example Response
/// ```
/// json!([
/// {
/// "uuid": "383d2afa-082f-4dd3-9050-ca6ed91487b6",
/// "name": "My new server!",
/// "description": null,
/// "icon": null,
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [],
/// "member_count": 1
/// },
/// {
/// "uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "My first server!",
/// "description": "This is a cool and nullable description!",
/// "icon": "https://nullable-url/path/to/icon.png",
/// "owner_uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "roles": [
/// {
/// "uuid": "be0e4da4-cf73-4f45-98f8-bb1c73d1ab8b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Cool people",
/// "color": 15650773,
/// "is_above": c7432f1c-f4ad-4ad3-8216-51388b6abb5b,
/// "permissions": 0
/// }
/// {
/// "uuid": "c7432f1c-f4ad-4ad3-8216-51388b6abb5b",
/// "guild_uuid": "5ba61ec7-5f97-43e1-89a5-d4693c155612",
/// "name": "Equally cool people",
/// "color": 16777215,
/// "is_above": null,
/// "permissions": 0
/// }
/// ],
/// "member_count": 20
/// }
/// ]);
/// ```
/// 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(
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 memberships = me.fetch_memberships(&mut conn).await?;
Ok((StatusCode::OK, Json(memberships)))
}

View file

@ -1,120 +0,0 @@
use std::sync::Arc;
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 uuid::Uuid;
use crate::{
AppState, api::v1::auth::CurrentUser, error::Error, objects::Me, utils::global_checks,
};
mod friends;
mod guilds;
pub fn router() -> Router<Arc<AppState>> {
Router::new()
.route("/", get(get_me))
.route(
"/",
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(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
let me = Me::get(&mut app_state.pool.get().await?, uuid).await?;
Ok((StatusCode::OK, Json(me)))
}
#[derive(Default, Debug, Deserialize, Clone)]
struct NewInfo {
username: Option<String>,
display_name: Option<String>,
email: Option<String>,
pronouns: Option<String>,
about: Option<String>,
online_status: Option<i16>,
}
pub async fn update(
State(app_state): State<Arc<AppState>>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
mut multipart: Multipart,
) -> Result<impl IntoResponse, Error> {
let mut json_raw: Option<NewInfo> = None;
let mut avatar: 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 == "avatar" {
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 mut conn = app_state.pool.get().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?;
if let Some(avatar) = avatar {
me.set_avatar(&mut conn, &app_state, avatar).await?;
}
if let Some(username) = &json.username {
me.set_username(&mut conn, &app_state.cache_pool, username.clone())
.await?;
}
if let Some(display_name) = &json.display_name {
me.set_display_name(&mut conn, &app_state.cache_pool, display_name.clone())
.await?;
}
if let Some(email) = &json.email {
me.set_email(&mut conn, &app_state.cache_pool, email.clone())
.await?;
}
if let Some(pronouns) = &json.pronouns {
me.set_pronouns(&mut conn, &app_state.cache_pool, pronouns.clone())
.await?;
}
if let Some(about) = &json.about {
me.set_about(&mut conn, &app_state.cache_pool, about.clone())
.await?;
}
if let Some(online_status) = &json.online_status {
me.set_online_status(&mut conn, &app_state.cache_pool, *online_status)
.await?;
}
Ok(StatusCode::OK)
}

View file

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

View file

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

View file

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

View file

@ -1,35 +1,16 @@
//! `/api/v1` Contains version 1 of the api
use std::sync::Arc;
use axum::{Router, middleware::from_fn_with_state, routing::get};
use crate::{AppState, api::v1::auth::CurrentUser};
use actix_web::{Scope, web};
mod auth;
mod channels;
mod guilds;
mod invites;
mod me;
mod members;
mod servers;
mod stats;
mod users;
pub fn router(app_state: Arc<AppState>) -> Router<Arc<AppState>> {
let router_with_auth = Router::new()
.nest("/users", users::router())
.nest("/guilds", guilds::router())
.nest("/invites", invites::router())
.nest("/members", members::router())
.nest("/me", me::router())
.layer(from_fn_with_state(
app_state.clone(),
CurrentUser::check_auth_layer,
));
Router::new()
.route("/stats", get(stats::res))
.nest("/auth", auth::router(app_state.clone()))
.nest("/channels", channels::router(app_state))
.merge(router_with_auth)
pub fn web() -> Scope {
web::scope("/v1")
.service(stats::res)
.service(auth::web())
.service(users::web())
.service(servers::web())
.service(invites::web())
}

71
src/api/v1/servers/mod.rs Normal file
View file

@ -0,0 +1,71 @@
use actix_web::{HttpRequest, HttpResponse, Scope, get, post, web};
use serde::Deserialize;
mod uuid;
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Guild, StartAmountQuery},
utils::get_auth_header,
};
#[derive(Deserialize)]
struct GuildInfo {
name: String,
description: Option<String>,
}
pub fn web() -> Scope {
web::scope("/servers")
.service(create)
.service(get)
.service(uuid::web())
}
#[post("")]
pub async fn create(
req: HttpRequest,
guild_info: web::Json<GuildInfo>,
data: web::Data<Data>,
) -> 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 guild = Guild::new(
&mut conn,
guild_info.name.clone(),
guild_info.description.clone(),
uuid,
)
.await?;
Ok(HttpResponse::Ok().json(guild))
}
#[get("")]
pub async fn get(
req: HttpRequest,
request_query: web::Query<StartAmountQuery>,
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 amount = request_query.amount.unwrap_or(10);
check_access_token(auth_header, &mut data.pool.get().await.unwrap()).await?;
let guilds = Guild::fetch_amount(&data.pool, start, amount).await?;
Ok(HttpResponse::Ok().json(guilds))
}

View file

@ -0,0 +1,82 @@
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Channel, Member},
utils::get_auth_header,
};
use ::uuid::Uuid;
use actix_web::{HttpRequest, HttpResponse, get, post, web};
use serde::Deserialize;
pub mod uuid;
#[derive(Deserialize)]
struct ChannelInfo {
name: String,
description: Option<String>,
}
#[get("{uuid}/channels")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid,)>,
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?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = data.get_cache_key(format!("{}_channels", guild_uuid)).await {
return Ok(HttpResponse::Ok()
.content_type("application/json")
.body(cache_hit));
}
let channels = Channel::fetch_all(&data.pool, guild_uuid).await?;
data.set_cache_key(format!("{}_channels", guild_uuid), channels.clone(), 1800)
.await?;
Ok(HttpResponse::Ok().json(channels))
}
#[post("{uuid}/channels")]
pub async fn create(
req: HttpRequest,
channel_info: web::Json<ChannelInfo>,
path: web::Path<(Uuid,)>,
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?;
Member::fetch_one(&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.unwrap()))
}

View file

@ -0,0 +1,53 @@
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Channel, Member},
utils::get_auth_header,
};
use ::uuid::Uuid;
use actix_web::{HttpRequest, HttpResponse, get, web};
use serde::Deserialize;
#[derive(Deserialize)]
struct MessageRequest {
amount: i64,
offset: i64,
}
#[get("{uuid}/channels/{channel_uuid}/messages")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid, Uuid)>,
message_request: web::Query<MessageRequest>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
let auth_header = get_auth_header(headers)?;
let (guild_uuid, channel_uuid) = path.into_inner();
let mut conn = data.pool.get().await?;
let uuid = check_access_token(auth_header, &mut conn).await?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let channel: Channel;
if let Ok(cache_hit) = data.get_cache_key(format!("{}", channel_uuid)).await {
channel = serde_json::from_str(&cache_hit)?
} else {
channel = Channel::fetch_one(&mut conn, channel_uuid).await?;
data.set_cache_key(format!("{}", channel_uuid), channel.clone(), 60)
.await?;
}
let messages = channel
.fetch_messages(&mut conn, message_request.amount, message_request.offset)
.await?;
Ok(HttpResponse::Ok().json(messages))
}

View file

@ -0,0 +1,77 @@
pub mod messages;
pub mod socket;
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Channel, Member},
utils::get_auth_header,
};
use actix_web::{HttpRequest, HttpResponse, delete, get, web};
use uuid::Uuid;
#[get("{uuid}/channels/{channel_uuid}")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid, Uuid)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
let auth_header = get_auth_header(headers)?;
let (guild_uuid, channel_uuid) = path.into_inner();
let mut conn = data.pool.get().await?;
let uuid = check_access_token(auth_header, &mut conn).await?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = data.get_cache_key(format!("{}", channel_uuid)).await {
return Ok(HttpResponse::Ok()
.content_type("application/json")
.body(cache_hit));
}
let channel = Channel::fetch_one(&mut conn, channel_uuid).await?;
data.set_cache_key(format!("{}", channel_uuid), channel.clone(), 60)
.await?;
Ok(HttpResponse::Ok().json(channel))
}
#[delete("{uuid}/channels/{channel_uuid}")]
pub async fn delete(
req: HttpRequest,
path: web::Path<(Uuid, Uuid)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
let auth_header = get_auth_header(headers)?;
let (guild_uuid, channel_uuid) = path.into_inner();
let mut conn = data.pool.get().await?;
let uuid = check_access_token(auth_header, &mut conn).await?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let channel: Channel;
if let Ok(cache_hit) = data.get_cache_key(format!("{}", channel_uuid)).await {
channel = serde_json::from_str(&cache_hit).unwrap();
data.del_cache_key(format!("{}", channel_uuid)).await?;
} else {
channel = Channel::fetch_one(&mut conn, channel_uuid).await?;
}
channel.delete(&mut conn).await?;
Ok(HttpResponse::Ok().finish())
}

View file

@ -0,0 +1,112 @@
use actix_web::{Error, HttpRequest, HttpResponse, get, rt, web};
use actix_ws::AggregatedMessage;
use futures_util::StreamExt as _;
use uuid::Uuid;
use crate::{
Data,
api::v1::auth::check_access_token,
structs::{Channel, Member},
utils::get_auth_header,
};
#[get("{uuid}/channels/{channel_uuid}/socket")]
pub async fn echo(
req: HttpRequest,
path: web::Path<(Uuid, Uuid)>,
stream: web::Payload,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
// Get all headers
let headers = req.headers();
// Retrieve auth header
let auth_header = get_auth_header(headers)?;
// Get uuids from path
let (guild_uuid, channel_uuid) = path.into_inner();
let mut conn = data.pool.get().await.map_err(crate::error::Error::from)?;
// Authorize client using auth header
let uuid = check_access_token(auth_header, &mut conn).await?;
// Get server member from psql
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let channel: Channel;
// Return channel cache or result from psql as `channel` variable
if let Ok(cache_hit) = data.get_cache_key(format!("{}", channel_uuid)).await {
channel = serde_json::from_str(&cache_hit).unwrap()
} else {
channel = Channel::fetch_one(&mut conn, channel_uuid).await?;
data.set_cache_key(format!("{}", channel_uuid), channel.clone(), 60)
.await?;
}
let (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
.get_async_pubsub()
.await
.map_err(crate::error::Error::from)?;
let mut session_2 = session_1.clone();
rt::spawn(async move {
pubsub.subscribe(channel_uuid.to_string()).await.unwrap();
while let Some(msg) = pubsub.on_message().next().await {
let payload: String = msg.get_payload().unwrap();
session_1.text(payload).await.unwrap();
}
});
// start task but don't wait for it
rt::spawn(async move {
let mut conn = data
.cache_pool
.get_multiplexed_tokio_connection()
.await
.unwrap();
// receive messages from websocket
while let Some(msg) = stream.next().await {
match msg {
Ok(AggregatedMessage::Text(text)) => {
// echo text message
redis::cmd("PUBLISH")
.arg(&[channel_uuid.to_string(), text.to_string()])
.exec_async(&mut conn)
.await
.unwrap();
channel
.new_message(&mut data.pool.get().await.unwrap(), uuid, text.to_string())
.await
.unwrap();
}
Ok(AggregatedMessage::Binary(bin)) => {
// echo binary message
session_2.binary(bin).await.unwrap();
}
Ok(AggregatedMessage::Ping(msg)) => {
// respond to PING frame with PONG frame
session_2.pong(&msg).await.unwrap();
}
_ => {}
}
}
});
// respond immediately with response connected to WS session
Ok(res)
}

View file

@ -0,0 +1,48 @@
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,
structs::{Guild, Member},
utils::get_auth_header,
};
#[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?;
Member::fetch_one(&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.storage,
&mut conn,
bytes,
)
.await?;
Ok(HttpResponse::Ok().finish())
}

View file

@ -0,0 +1,69 @@
use actix_web::{HttpRequest, HttpResponse, get, post, web};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Guild, Member},
utils::get_auth_header,
};
#[derive(Deserialize)]
struct InviteRequest {
custom_id: String,
}
#[get("{uuid}/invites")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid,)>,
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?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
let invites = guild.get_invites(&mut conn).await?;
Ok(HttpResponse::Ok().json(invites))
}
#[post("{uuid}/invites")]
pub async fn create(
req: HttpRequest,
path: web::Path<(Uuid,)>,
invite_request: web::Json<Option<InviteRequest>>,
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?;
let member = Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
let custom_id = invite_request.as_ref().map(|ir| ir.custom_id.clone());
let invite = guild.create_invite(&mut conn, &member, custom_id).await?;
Ok(HttpResponse::Ok().json(invite))
}

View file

@ -0,0 +1,60 @@
use actix_web::{HttpRequest, HttpResponse, Scope, get, web};
use uuid::Uuid;
mod channels;
mod icon;
mod invites;
mod roles;
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Guild, Member},
utils::get_auth_header,
};
pub fn web() -> Scope {
web::scope("")
// Servers
.service(res)
// Channels
.service(channels::get)
.service(channels::create)
.service(channels::uuid::get)
.service(channels::uuid::delete)
.service(channels::uuid::messages::get)
.service(channels::uuid::socket::echo)
// Roles
.service(roles::get)
.service(roles::create)
.service(roles::uuid::get)
// Invites
.service(invites::get)
.service(invites::create)
// Icon
.service(icon::upload)
}
#[get("/{uuid}")]
pub async fn res(
req: HttpRequest,
path: web::Path<(Uuid,)>,
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?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
let guild = Guild::fetch_one(&mut conn, guild_uuid).await?;
Ok(HttpResponse::Ok().json(guild))
}

View file

@ -0,0 +1,76 @@
use ::uuid::Uuid;
use actix_web::{HttpRequest, HttpResponse, get, post, web};
use serde::Deserialize;
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Member, Role},
utils::get_auth_header,
};
pub mod uuid;
#[derive(Deserialize)]
struct RoleInfo {
name: String,
}
#[get("{uuid}/roles")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid,)>,
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?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = data.get_cache_key(format!("{}_roles", guild_uuid)).await {
return Ok(HttpResponse::Ok()
.content_type("application/json")
.body(cache_hit));
}
let roles = Role::fetch_all(&mut conn, guild_uuid).await?;
data.set_cache_key(format!("{}_roles", guild_uuid), roles.clone(), 1800)
.await?;
Ok(HttpResponse::Ok().json(roles))
}
#[post("{uuid}/roles")]
pub async fn create(
req: HttpRequest,
role_info: web::Json<RoleInfo>,
path: web::Path<(Uuid,)>,
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.unwrap();
let uuid = check_access_token(auth_header, &mut conn).await?;
Member::fetch_one(&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?;
Ok(HttpResponse::Ok().json(role))
}

View file

@ -0,0 +1,41 @@
use crate::{
Data,
api::v1::auth::check_access_token,
error::Error,
structs::{Member, Role},
utils::get_auth_header,
};
use ::uuid::Uuid;
use actix_web::{HttpRequest, HttpResponse, get, web};
#[get("{uuid}/roles/{role_uuid}")]
pub async fn get(
req: HttpRequest,
path: web::Path<(Uuid, Uuid)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
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?;
Member::fetch_one(&mut conn, uuid, guild_uuid).await?;
if let Ok(cache_hit) = data.get_cache_key(format!("{}", role_uuid)).await {
return Ok(HttpResponse::Ok()
.content_type("application/json")
.body(cache_hit));
}
let role = Role::fetch_one(&mut conn, role_uuid).await?;
data.set_cache_key(format!("{}", role_uuid), role.clone(), 60)
.await?;
Ok(HttpResponse::Ok().json(role))
}

View file

@ -1,68 +1,43 @@
//! `/api/v1/stats` Returns stats about the server
use std::sync::Arc;
use std::time::SystemTime;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use actix_web::{HttpResponse, get, web};
use diesel::QueryDsl;
use diesel_async::RunQueryDsl;
use serde::Serialize;
use crate::AppState;
use crate::Data;
use crate::error::Error;
use crate::schema::users::dsl::{users, uuid};
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
const GIT_SHORT_HASH: &str = env!("GIT_SHORT_HASH");
#[derive(Serialize)]
struct Response {
accounts: i64,
uptime: u64,
version: String,
registration_enabled: bool,
email_verification_required: bool,
build_number: String,
}
/// `GET /api/v1/stats` Returns stats about the server
///
/// requires auth: no
///
/// ### Response Example
/// ```
/// json!({
/// "accounts": 3,
/// "uptime": 50000,
/// "version": "0.1.0",
/// "registration_enabled": true,
/// "email_verification_required": true,
/// "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
.select(uuid)
.count()
.get_result(&mut app_state.pool.get().await?)
.get_result(&mut data.pool.get().await?)
.await?;
let response = Response {
// TODO: Get number of accounts from db
accounts,
uptime: SystemTime::now()
.duration_since(app_state.start_time)
.duration_since(data.start_time)
.expect("Seriously why dont you have time??")
.as_secs(),
version: String::from(VERSION.unwrap_or("UNKNOWN")),
registration_enabled: app_state.config.instance.registration,
email_verification_required: app_state.config.instance.require_email_verification,
// TODO: Get build number from git hash or remove this from the spec
build_number: String::from(GIT_SHORT_HASH),
build_number: String::from("how do i implement this?"),
};
Ok((StatusCode::OK, Json(response)))
Ok(HttpResponse::Ok().json(response))
}

87
src/api/v1/users/me.rs Normal file
View file

@ -0,0 +1,87 @@
use actix_multipart::form::{MultipartForm, json::Json as MpJson, tempfile::TempFile};
use actix_web::{HttpRequest, HttpResponse, get, patch, web};
use serde::Deserialize;
use crate::{
Data, api::v1::auth::check_access_token, error::Error, structs::Me, utils::get_auth_header,
};
#[get("/me")]
pub async fn res(req: HttpRequest, data: web::Data<Data>) -> 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 me = Me::get(&mut conn, uuid).await?;
Ok(HttpResponse::Ok().json(me))
}
#[derive(Debug, Deserialize)]
struct NewInfo {
username: Option<String>,
display_name: Option<String>,
password: Option<String>,
email: Option<String>,
}
#[derive(Debug, MultipartForm)]
struct UploadForm {
#[multipart(limit = "100MB")]
avatar: Option<TempFile>,
json: Option<MpJson<NewInfo>>,
}
#[patch("/me")]
pub async fn update(
req: HttpRequest,
MultipartForm(form): MultipartForm<UploadForm>,
data: web::Data<Data>,
) -> 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 mut me = Me::get(&mut conn, uuid).await?;
if let Some(avatar) = form.avatar {
let bytes = tokio::fs::read(avatar.file).await?;
let byte_slice: &[u8] = &bytes;
me.set_avatar(
&data.storage,
&mut conn,
byte_slice.into(),
)
.await?;
}
if let Some(new_info) = form.json {
if let Some(username) = &new_info.username {
todo!();
}
if let Some(display_name) = &new_info.display_name {
todo!();
}
if let Some(password) = &new_info.password {
todo!();
}
if let Some(email) = &new_info.email {
todo!();
}
}
Ok(HttpResponse::Ok().finish())
}

View file

@ -1,80 +1,47 @@
//! `/api/v1/users` Contains endpoints related to all users
use std::sync::Arc;
use ::uuid::Uuid;
use axum::{
Extension, Json, Router,
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
routing::get,
};
use actix_web::{HttpRequest, HttpResponse, Scope, get, web};
use crate::{
AppState,
api::v1::auth::CurrentUser,
Data,
api::v1::auth::check_access_token,
error::Error,
objects::{StartAmountQuery, User},
utils::global_checks,
structs::{StartAmountQuery, User},
utils::get_auth_header,
};
mod me;
mod uuid;
pub fn router() -> Router<Arc<AppState>> {
Router::new()
.route("/", get(users))
.route("/{uuid}", get(uuid::get))
pub fn web() -> Scope {
web::scope("/users")
.service(res)
.service(me::res)
.service(me::update)
.service(uuid::res)
}
/// `GET /api/v1/users` Returns all users on this instance
///
/// requires auth: yes
///
/// requires admin: yes
///
/// ### Response Example
/// ```
/// json!([
/// {
/// "uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "username": "user1",
/// "display_name": "Nullable Name",
/// "avatar": "https://nullable-url.com/path/to/image.png"
/// },
/// {
/// "uuid": "d48a3317-7b4d-443f-a250-ea9ab2bb8661",
/// "username": "user2",
/// "display_name": "John User 2",
/// "avatar": "https://also-supports-jpg.com/path/to/image.jpg"
/// },
/// {
/// "uuid": "12c4b3f8-a25b-4b9b-8136-b275c855ed4a",
/// "username": "user3",
/// "display_name": null,
/// "avatar": null
/// }
/// ]);
/// ```
/// 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(
State(app_state): State<Arc<AppState>>,
Query(request_query): Query<StartAmountQuery>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
#[get("")]
pub async fn res(
req: HttpRequest,
request_query: web::Query<StartAmountQuery>,
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 amount = request_query.amount.unwrap_or(10);
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?;
check_access_token(auth_header, &mut conn).await?;
let users = User::fetch_amount(&mut conn, start, amount).await?;
Ok((StatusCode::OK, Json(users)).into_response())
Ok(HttpResponse::Ok().json(users))
}

View file

@ -1,52 +1,36 @@
//! `/api/v1/users/{uuid}` Specific user endpoints
use std::sync::Arc;
use axum::{
Extension, Json,
extract::{Path, State},
http::StatusCode,
response::IntoResponse,
};
use actix_web::{HttpRequest, HttpResponse, get, web};
use uuid::Uuid;
use crate::{
AppState,
api::v1::auth::CurrentUser,
error::Error,
objects::{Me, User},
utils::global_checks,
Data, api::v1::auth::check_access_token, error::Error, structs::User, utils::get_auth_header,
};
/// `GET /api/v1/users/{uuid}` Returns user with the given UUID
///
/// requires auth: yes
///
/// requires relation: yes
///
/// ### Response Example
/// ```
/// json!({
/// "uuid": "155d2291-fb23-46bd-a656-ae7c5d8218e6",
/// "username": "user1",
/// "display_name": "Nullable Name",
/// "avatar": "https://nullable-url.com/path/to/image.png"
/// });
/// ```
/// 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(
State(app_state): State<Arc<AppState>>,
Path(user_uuid): Path<Uuid>,
Extension(CurrentUser(uuid)): Extension<CurrentUser<Uuid>>,
) -> Result<impl IntoResponse, Error> {
let mut conn = app_state.pool.get().await?;
#[get("/{uuid}")]
pub async fn res(
req: HttpRequest,
path: web::Path<(Uuid,)>,
data: web::Data<Data>,
) -> Result<HttpResponse, Error> {
let headers = req.headers();
global_checks(&mut conn, &app_state.config, uuid).await?;
let uuid = path.into_inner().0;
let me = Me::get(&mut conn, uuid).await?;
let auth_header = get_auth_header(headers)?;
let user =
User::fetch_one_with_friendship(&mut conn, &app_state.cache_pool, &me, user_uuid).await?;
let mut conn = data.pool.get().await?;
Ok((StatusCode::OK, Json(user)))
check_access_token(auth_header, &mut conn).await?;
if let Ok(cache_hit) = data.get_cache_key(uuid.to_string()).await {
return Ok(HttpResponse::Ok()
.content_type("application/json")
.body(cache_hit));
}
let user = User::fetch_one(&mut conn, uuid).await?;
data.set_cache_key(uuid.to_string(), user.clone(), 1800)
.await?;
Ok(HttpResponse::Ok().json(user))
}

View file

@ -1,5 +1,4 @@
//! `/api/v1/versions` Returns info about api versions
use axum::{Json, http::StatusCode, response::IntoResponse};
use actix_web::{HttpResponse, Responder, get};
use serde::Serialize;
#[derive(Serialize)]
@ -11,25 +10,13 @@ struct Response {
#[derive(Serialize)]
struct UnstableFeatures;
/// `GET /api/versions` Returns info about api versions.
///
/// requires auth: no
///
/// ### Response Example
/// ```
/// json!({
/// "unstable_features": {},
/// "versions": [
/// "1"
/// ]
/// });
/// ```
pub async fn versions() -> impl IntoResponse {
#[get("/versions")]
pub async fn res() -> impl Responder {
let response = Response {
unstable_features: UnstableFeatures,
// TODO: Find a way to dynamically update this possibly?
versions: vec![String::from("1")],
};
(StatusCode::OK, Json(response))
HttpResponse::Ok().json(response)
}

View file

@ -1,20 +1,16 @@
use crate::error::Error;
use bunny_api_tokio::edge_storage::Endpoint;
use lettre::transport::smtp::authentication::Credentials;
use log::debug;
use serde::Deserialize;
use tokio::fs::read_to_string;
use url::Url;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub struct ConfigBuilder {
database: Database,
cache_database: CacheDatabase,
web: WebBuilder,
instance: Option<InstanceBuilder>,
bunny: BunnyBuilder,
mail: Mail,
bunny: Option<BunnyBuilder>,
}
#[derive(Debug, Deserialize, Clone)]
@ -39,19 +35,10 @@ pub struct CacheDatabase {
struct WebBuilder {
ip: Option<String>,
port: Option<u16>,
frontend_url: Url,
backend_url: Option<Url>,
url: Url,
_ssl: Option<bool>,
}
#[derive(Debug, Deserialize)]
struct InstanceBuilder {
name: Option<String>,
registration: Option<bool>,
require_email_verification: Option<bool>,
initial_guild: Option<Uuid>,
}
#[derive(Debug, Deserialize)]
struct BunnyBuilder {
api_key: String,
@ -60,23 +47,9 @@ struct BunnyBuilder {
cdn_url: Url,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Mail {
pub smtp: Smtp,
pub address: String,
pub tls: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Smtp {
pub server: String,
username: String,
password: String,
}
impl ConfigBuilder {
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 config = toml::from_str(&raw)?;
@ -88,15 +61,13 @@ impl ConfigBuilder {
let web = Web {
ip: self.web.ip.unwrap_or(String::from("0.0.0.0")),
port: self.web.port.unwrap_or(8080),
frontend_url: self.web.frontend_url.clone(),
backend_url: self
.web
.backend_url
.or_else(|| self.web.frontend_url.join("/api").ok())
.unwrap(),
url: self.web.url
};
let endpoint = match &*self.bunny.endpoint {
let bunny;
if let Some(bunny_builder) = self.bunny {
let endpoint = match &*bunny_builder.endpoint {
"Frankfurt" => Endpoint::Frankfurt,
"London" => Endpoint::London,
"New York" => Endpoint::NewYork,
@ -109,35 +80,21 @@ impl ConfigBuilder {
url => Endpoint::Custom(url.to_string()),
};
let bunny = Bunny {
api_key: self.bunny.api_key,
bunny = Some(Bunny {
api_key: bunny_builder.api_key,
endpoint,
storage_zone: self.bunny.storage_zone,
cdn_url: self.bunny.cdn_url,
};
let instance = match self.instance {
Some(instance) => Instance {
name: instance.name.unwrap_or("Gorb".to_string()),
registration: instance.registration.unwrap_or(true),
require_email_verification: instance.require_email_verification.unwrap_or(false),
initial_guild: instance.initial_guild,
},
None => Instance {
name: "Gorb".to_string(),
registration: true,
require_email_verification: false,
initial_guild: None,
},
};
storage_zone: bunny_builder.storage_zone,
cdn_url: bunny_builder.cdn_url,
});
} else {
bunny = None;
}
Config {
database: self.database,
cache_database: self.cache_database,
web,
instance,
bunny,
mail: self.mail,
}
}
}
@ -147,25 +104,14 @@ pub struct Config {
pub database: Database,
pub cache_database: CacheDatabase,
pub web: Web,
pub instance: Instance,
pub bunny: Bunny,
pub mail: Mail,
pub bunny: Option<Bunny>,
}
#[derive(Debug, Clone)]
pub struct Web {
pub ip: String,
pub port: u16,
pub frontend_url: Url,
pub backend_url: Url,
}
#[derive(Debug, Clone)]
pub struct Instance {
pub name: String,
pub registration: bool,
pub require_email_verification: bool,
pub initial_guild: Option<Uuid>,
pub url: Url,
}
#[derive(Debug, Clone)]
@ -227,9 +173,3 @@ impl CacheDatabase {
url
}
}
impl Smtp {
pub fn credentials(&self) -> Credentials {
Credentials::new(self.username.clone(), self.password.clone())
}
}

View file

@ -1,24 +1,17 @@
use std::{io, time::SystemTimeError};
use axum::{
Json,
extract::{
multipart::MultipartError,
rejection::{JsonRejection, QueryRejection},
},
use actix_web::{
HttpResponse,
error::{PayloadError, ResponseError},
http::{
StatusCode,
header::{InvalidHeaderValue, ToStrError},
header::{ContentType, ToStrError},
},
response::IntoResponse,
};
use bunny_api_tokio::error::Error as BunnyError;
use deadpool::managed::{BuildError, PoolError};
use diesel::{ConnectionError, result::Error as DieselError};
use diesel_async::pooled_connection::PoolError as DieselPoolError;
use lettre::{
address::AddressError, error::Error as EmailError, transport::smtp::Error as SmtpError,
};
use log::{debug, error};
use redis::RedisError;
use serde::Serialize;
@ -58,70 +51,35 @@ pub enum Error {
#[error(transparent)]
UrlParseError(#[from] url::ParseError),
#[error(transparent)]
JsonRejection(#[from] JsonRejection),
#[error(transparent)]
QueryRejection(#[from] QueryRejection),
#[error(transparent)]
MultipartError(#[from] MultipartError),
#[error(transparent)]
InvalidHeaderValue(#[from] InvalidHeaderValue),
#[error(transparent)]
EmailError(#[from] EmailError),
#[error(transparent)]
SmtpError(#[from] SmtpError),
#[error(transparent)]
SmtpAddressError(#[from] AddressError),
PayloadError(#[from] PayloadError),
#[error("{0}")]
PasswordHashError(String),
#[error("{0}")]
PathError(String),
#[error("{0}")]
BadRequest(String),
#[error("{0}")]
Unauthorized(String),
#[error("{0}")]
Forbidden(String),
#[error("{0}")]
TooManyRequests(String),
#[error("{0}")]
InternalServerError(String),
// TODO: remove when doing socket.io
#[error(transparent)]
AxumError(#[from] axum::Error),
}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
let error = match self {
Error::SqlError(DieselError::NotFound) => {
(StatusCode::NOT_FOUND, Json(WebError::new(self.to_string())))
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
debug!("{:?}", self);
error!("{}: {}", self.status_code(), self);
HttpResponse::build(self.status_code())
.insert_header(ContentType::json())
.json(WebError::new(self.to_string()))
}
Error::BunnyError(BunnyError::NotFound(_)) => {
(StatusCode::NOT_FOUND, Json(WebError::new(self.to_string())))
fn status_code(&self) -> StatusCode {
match *self {
Error::SqlError(DieselError::NotFound) => StatusCode::NOT_FOUND,
Error::BunnyError(BunnyError::NotFound(_)) => StatusCode::NOT_FOUND,
Error::BadRequest(_) => StatusCode::BAD_REQUEST,
Error::Unauthorized(_) => StatusCode::UNAUTHORIZED,
_ => StatusCode::INTERNAL_SERVER_ERROR,
}
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;
debug!("{self:?}");
error!("{code}: {self}");
error.into_response()
}
}

View file

@ -1,17 +1,17 @@
use actix_cors::Cors;
use actix_files::Files;
use actix_web::{App, HttpServer, web};
use argon2::Argon2;
use axum::{
Router,
http::{Method, header},
};
use clap::Parser;
use config::{Config, ConfigBuilder};
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::pooled_connection::deadpool::Pool;
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
use error::Error;
use objects::MailClient;
use std::{sync::Arc, time::SystemTime};
use tower_http::cors::{AllowOrigin, CorsLayer};
use simple_logger::SimpleLogger;
use structs::Storage;
use std::time::SystemTime;
mod config;
use config::{Config, ConfigBuilder};
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
@ -19,23 +19,22 @@ type Conn =
deadpool::managed::Object<AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>>;
mod api;
mod config;
pub mod error;
pub mod objects;
pub mod schema;
//mod socket;
pub mod structs;
pub mod utils;
mod wordlist;
#[derive(Parser, Debug)]
#[derive(Parser, Debug, Clone)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(short, long, default_value_t = String::from("/etc/gorb/config.toml"))]
config: String,
#[arg(short, long, default_value_t = String::from("/var/lib/gorb/"))]
data_dir: String,
}
#[derive(Clone)]
pub struct AppState {
pub struct Data {
pub pool: deadpool::managed::Pool<
AsyncDieselConnectionManager<diesel_async::AsyncPgConnection>,
Conn,
@ -44,14 +43,17 @@ pub struct AppState {
pub config: Config,
pub argon2: Argon2<'static>,
pub start_time: SystemTime,
pub bunny_storage: bunny_api_tokio::EdgeStorageClient,
pub mail_client: MailClient,
pub storage: Storage,
}
#[tokio::main]
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 config = ConfigBuilder::load(args.config).await?.build();
@ -65,20 +67,7 @@ async fn main() -> Result<(), Error> {
let cache_pool = redis::Client::open(config.cache_database.url())?;
let bunny = config.bunny.clone();
let bunny_storage =
bunny_api_tokio::EdgeStorageClient::new(bunny.api_key, bunny.endpoint, bunny.storage_zone)
.await?;
let mail = config.mail.clone();
let mail_client = MailClient::new(
mail.smtp.credentials(),
mail.smtp.server,
mail.address,
mail.tls,
)?;
let storage = Storage::new(config.clone(), args.data_dir.clone()).await?;
let database_url = config.database.url();
@ -112,65 +101,53 @@ async fn main() -> Result<(), Error> {
)
*/
let app_state = Arc::new(AppState {
let data = Data {
pool,
cache_pool,
config,
// TODO: Possibly implement "pepper" into this (thinking it could generate one if it doesnt exist and store it on disk)
argon2: Argon2::default(),
start_time: SystemTime::now(),
bunny_storage,
mail_client,
});
storage,
};
let cors = CorsLayer::new()
// Allow any origin (equivalent to allowed_origin_fn returning true)
.allow_origin(AllowOrigin::predicate(|_origin, _request_head| true))
.allow_methods(vec![
Method::GET,
Method::POST,
Method::PUT,
Method::DELETE,
Method::HEAD,
Method::OPTIONS,
Method::CONNECT,
Method::PATCH,
Method::TRACE,
])
.allow_headers(vec![
header::ACCEPT,
header::ACCEPT_LANGUAGE,
header::AUTHORIZATION,
header::CONTENT_LANGUAGE,
header::CONTENT_TYPE,
header::ORIGIN,
header::ACCEPT,
header::COOKIE,
"x-requested-with".parse().unwrap(),
])
// Allow credentials
.allow_credentials(true);
let data_dir = args.data_dir.clone();
/*let (socket_io, io) = SocketIo::builder()
.with_state(app_state.clone())
.build_layer();
io.ns("/", socket::on_connect);
HttpServer::new(move || {
// Set CORS headers
let cors = Cors::default()
/*
Set Allowed-Control-Allow-Origin header to whatever
the request's Origin header is. Must be done like this
rather than setting it to "*" due to CORS not allowing
sending of credentials (cookies) with wildcard origin.
*/
// build our application with a route
let app = Router::new()
// `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);
.allowed_origin_fn(|_origin, _req_head| true)
/*
Allows any request method in CORS preflight requests.
This will be restricted to only ones actually in use later.
*/
.allow_any_method()
/*
Allows any header(s) in request in CORS preflight requests.
This wll be restricted to only ones actually in use later.
*/
.allow_any_header()
/*
Allows browser to include cookies in requests.
This is needed for receiving the secure HttpOnly refresh_token cookie.
*/
.supports_credentials();
// 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?;
App::new()
.app_data(web::Data::new(data.clone()))
.wrap(cors)
.service(Files::new("/api/assets", &data_dir))
.service(api::web())
})
.bind((web.ip, web.port))?
.run()
.await?;
Ok(())
}

View file

@ -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(())
}
}

View file

@ -1,447 +0,0 @@
use diesel::{
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, delete,
insert_into, update,
};
use diesel_async::RunQueryDsl;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
Conn,
error::Error,
schema::{channel_permissions, channels, messages},
utils::{CHANNEL_REGEX, CacheFns, order_by_is_above},
};
use super::{HasIsAbove, HasUuid, Message, load_or_empty, message::MessageBuilder};
#[derive(Queryable, Selectable, Insertable, Clone, Debug)]
#[diesel(table_name = channels)]
#[diesel(check_for_backend(diesel::pg::Pg))]
struct ChannelBuilder {
uuid: Uuid,
guild_uuid: Uuid,
name: String,
description: Option<String>,
is_above: Option<Uuid>,
}
impl ChannelBuilder {
async fn build(self, conn: &mut Conn) -> Result<Channel, Error> {
use self::channel_permissions::dsl::*;
let channel_permission: Vec<ChannelPermission> = load_or_empty(
channel_permissions
.filter(channel_uuid.eq(self.uuid))
.select(ChannelPermission::as_select())
.load(conn)
.await,
)?;
Ok(Channel {
uuid: self.uuid,
guild_uuid: self.guild_uuid,
name: self.name,
description: self.description,
is_above: self.is_above,
permissions: channel_permission,
})
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Channel {
pub uuid: Uuid,
pub guild_uuid: Uuid,
name: String,
description: Option<String>,
pub is_above: Option<Uuid>,
pub permissions: Vec<ChannelPermission>,
}
#[derive(Serialize, Deserialize, Clone, Queryable, Selectable, Debug)]
#[diesel(table_name = channel_permissions)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct ChannelPermission {
pub role_uuid: Uuid,
pub permissions: i64,
}
impl HasUuid for Channel {
fn uuid(&self) -> &Uuid {
self.uuid.as_ref()
}
}
impl HasIsAbove for Channel {
fn is_above(&self) -> Option<&Uuid> {
self.is_above.as_ref()
}
}
impl Channel {
pub async fn fetch_all(conn: &mut Conn, guild_uuid: Uuid) -> Result<Vec<Self>, Error> {
use channels::dsl;
let channel_builders: Vec<ChannelBuilder> = load_or_empty(
dsl::channels
.filter(dsl::guild_uuid.eq(guild_uuid))
.select(ChannelBuilder::as_select())
.load(conn)
.await,
)?;
let mut channels = vec![];
for builder in channel_builders {
channels.push(builder.build(conn).await?);
}
Ok(channels)
}
pub async fn fetch_one(
conn: &mut Conn,
cache_pool: &redis::Client,
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);
}
use channels::dsl;
let channel_builder: ChannelBuilder = dsl::channels
.filter(dsl::uuid.eq(channel_uuid))
.select(ChannelBuilder::as_select())
.get_result(conn)
.await?;
let channel = channel_builder.build(conn).await?;
cache_pool
.set_cache_key(channel_uuid.to_string(), channel.clone(), 60)
.await?;
Ok(channel)
}
pub async fn new(
conn: &mut Conn,
cache_pool: &redis::Client,
guild_uuid: Uuid,
name: String,
description: Option<String>,
) -> Result<Self, Error> {
if !CHANNEL_REGEX.is_match(&name) {
return Err(Error::BadRequest("Channel name is invalid".to_string()));
}
let channel_uuid = Uuid::now_v7();
let channels = Self::fetch_all(conn, guild_uuid).await?;
let channels_ordered = order_by_is_above(channels).await?;
let last_channel = channels_ordered.last();
let new_channel = ChannelBuilder {
uuid: channel_uuid,
guild_uuid,
name: name.clone(),
description: description.clone(),
is_above: None,
};
insert_into(channels::table)
.values(new_channel.clone())
.execute(conn)
.await?;
if let Some(old_last_channel) = last_channel {
use channels::dsl;
update(channels::table)
.filter(dsl::uuid.eq(old_last_channel.uuid))
.set(dsl::is_above.eq(new_channel.uuid))
.execute(conn)
.await?;
}
// returns different object because there's no reason to build the channelbuilder (wastes 1 database request)
let channel = Self {
uuid: channel_uuid,
guild_uuid,
name,
description,
is_above: None,
permissions: vec![],
};
cache_pool
.set_cache_key(channel_uuid.to_string(), channel.clone(), 1800)
.await?;
if cache_pool
.get_cache_key::<Vec<Channel>>(format!("{guild_uuid}_channels"))
.await
.is_ok()
{
cache_pool
.del_cache_key(format!("{guild_uuid}_channels"))
.await?;
}
Ok(channel)
}
pub async fn delete(self, conn: &mut Conn, cache_pool: &redis::Client) -> Result<(), Error> {
use channels::dsl;
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),
}?;
delete(channels::table)
.filter(dsl::uuid.eq(self.uuid))
.execute(conn)
.await?;
match update(channels::table)
.filter(dsl::is_above.eq(self.uuid))
.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(())
}
pub async fn fetch_messages(
&self,
conn: &mut Conn,
cache_pool: &redis::Client,
amount: i64,
offset: i64,
) -> Result<Vec<Message>, Error> {
use messages::dsl;
let message_builders: Vec<MessageBuilder> = load_or_empty(
dsl::messages
.filter(dsl::channel_uuid.eq(self.uuid))
.select(MessageBuilder::as_select())
.order(dsl::uuid.desc())
.limit(amount)
.offset(offset)
.load(conn)
.await,
)?;
let mut messages = vec![];
for builder in message_builders {
messages.push(builder.build(conn, cache_pool).await?);
}
Ok(messages)
}
pub async fn new_message(
&self,
conn: &mut Conn,
cache_pool: &redis::Client,
user_uuid: Uuid,
message: String,
reply_to: Option<Uuid>,
) -> Result<Message, Error> {
let message_uuid = Uuid::now_v7();
let message = MessageBuilder {
uuid: message_uuid,
channel_uuid: self.uuid,
user_uuid,
message,
reply_to,
};
insert_into(messages::table)
.values(message.clone())
.execute(conn)
.await?;
message.build(conn, cache_pool).await
}
pub async fn set_name(
&mut self,
conn: &mut Conn,
cache_pool: &redis::Client,
new_name: String,
) -> Result<(), Error> {
if !CHANNEL_REGEX.is_match(&new_name) {
return Err(Error::BadRequest("Channel name is invalid".to_string()));
}
use channels::dsl;
update(channels::table)
.filter(dsl::uuid.eq(self.uuid))
.set(dsl::name.eq(&new_name))
.execute(conn)
.await?;
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(())
}
pub async fn set_description(
&mut self,
conn: &mut Conn,
cache_pool: &redis::Client,
new_description: String,
) -> Result<(), Error> {
use channels::dsl;
update(channels::table)
.filter(dsl::uuid.eq(self.uuid))
.set(dsl::description.eq(&new_description))
.execute(conn)
.await?;
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(())
}
pub async fn move_channel(
&mut self,
conn: &mut Conn,
cache_pool: &redis::Client,
new_is_above: Uuid,
) -> Result<(), Error> {
use channels::dsl;
let old_above_uuid: Option<Uuid> = match dsl::channels
.filter(dsl::is_above.eq(self.uuid))
.select(dsl::uuid)
.get_result(conn)
.await
{
Ok(r) => Ok(Some(r)),
Err(diesel::result::Error::NotFound) => Ok(None),
Err(e) => Err(e),
}?;
if let Some(uuid) = old_above_uuid {
update(channels::table)
.filter(dsl::uuid.eq(uuid))
.set(dsl::is_above.eq(None::<Uuid>))
.execute(conn)
.await?;
}
match update(channels::table)
.filter(dsl::is_above.eq(new_is_above))
.set(dsl::is_above.eq(self.uuid))
.execute(conn)
.await
{
Ok(r) => Ok(r),
Err(diesel::result::Error::NotFound) => Ok(0),
Err(e) => Err(e),
}?;
update(channels::table)
.filter(dsl::uuid.eq(self.uuid))
.set(dsl::is_above.eq(new_is_above))
.execute(conn)
.await?;
if let Some(uuid) = old_above_uuid {
update(channels::table)
.filter(dsl::uuid.eq(uuid))
.set(dsl::is_above.eq(self.is_above))
.execute(conn)
.await?;
}
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(())
}
}

View file

@ -1,72 +0,0 @@
use chrono::Utc;
use lettre::message::MultiPart;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
AppState,
error::Error,
utils::{CacheFns, generate_token},
};
use super::Me;
#[derive(Serialize, Deserialize)]
pub struct EmailToken {
user_uuid: Uuid,
pub token: String,
pub created_at: chrono::DateTime<Utc>,
}
impl EmailToken {
pub async fn get(cache_pool: &redis::Client, user_uuid: Uuid) -> Result<EmailToken, Error> {
let email_token = cache_pool
.get_cache_key(format!("{user_uuid}_email_verify"))
.await?;
Ok(email_token)
}
#[allow(clippy::new_ret_no_self)]
pub async fn new(app_state: &AppState, me: Me) -> Result<(), Error> {
let token = generate_token::<32>()?;
let email_token = EmailToken {
user_uuid: me.uuid,
token: token.clone(),
// TODO: Check if this can be replaced with something built into valkey
created_at: Utc::now(),
};
app_state
.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")?;
verify_endpoint.set_query(Some(&format!("token={token}")));
let email = app_state
.mail_client
.message_builder()
.to(me.email.parse()?)
.subject(format!("{} E-mail Verification", app_state.config.instance.name))
.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!(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)
))?;
app_state.mail_client.send_mail(email).await?;
Ok(())
}
pub async fn delete(&self, cache_pool: &redis::Client) -> Result<(), Error> {
cache_pool
.del_cache_key(format!("{}_email_verify", self.user_uuid))
.await?;
Ok(())
}
}

View file

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

View file

@ -1,215 +0,0 @@
use axum::body::Bytes;
use diesel::{
ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper, insert_into,
update,
};
use diesel_async::RunQueryDsl;
use serde::Serialize;
use tokio::task;
use url::Url;
use uuid::Uuid;
use crate::{
AppState, Conn,
error::Error,
schema::{guild_members, guilds, invites},
utils::image_check,
};
use super::{Invite, Member, Role, load_or_empty, member::MemberBuilder};
#[derive(Serialize, Queryable, Selectable, Insertable, Clone)]
#[diesel(table_name = guilds)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct GuildBuilder {
uuid: Uuid,
name: String,
description: Option<String>,
icon: Option<String>,
}
impl GuildBuilder {
pub async fn build(self, conn: &mut Conn) -> Result<Guild, Error> {
let member_count = Member::count(conn, self.uuid).await?;
let roles = Role::fetch_all(conn, self.uuid).await?;
Ok(Guild {
uuid: self.uuid,
name: self.name,
description: self.description,
icon: self.icon.and_then(|i| i.parse().ok()),
roles,
member_count,
})
}
}
#[derive(Serialize)]
pub struct Guild {
pub uuid: Uuid,
name: String,
description: Option<String>,
icon: Option<Url>,
pub roles: Vec<Role>,
member_count: i64,
}
impl Guild {
pub async fn fetch_one(conn: &mut Conn, guild_uuid: Uuid) -> Result<Self, Error> {
use guilds::dsl;
let guild_builder: GuildBuilder = dsl::guilds
.filter(dsl::uuid.eq(guild_uuid))
.select(GuildBuilder::as_select())
.get_result(conn)
.await?;
guild_builder.build(conn).await
}
pub async fn fetch_amount(
conn: &mut Conn,
offset: i64,
amount: i64,
) -> Result<Vec<Self>, Error> {
// Fetch guild data from database
use guilds::dsl;
let guild_builders: Vec<GuildBuilder> = load_or_empty(
dsl::guilds
.select(GuildBuilder::as_select())
.order_by(dsl::uuid)
.offset(offset)
.limit(amount)
.load(conn)
.await,
)?;
let mut guilds = vec![];
for builder in guild_builders {
guilds.push(builder.build(conn).await?);
}
Ok(guilds)
}
pub async fn new(conn: &mut Conn, name: String, owner_uuid: Uuid) -> Result<Self, Error> {
let guild_uuid = Uuid::now_v7();
let guild_builder = GuildBuilder {
uuid: guild_uuid,
name: name.clone(),
description: None,
icon: None,
};
insert_into(guilds::table)
.values(guild_builder)
.execute(conn)
.await?;
let member_uuid = Uuid::now_v7();
let member = MemberBuilder {
uuid: member_uuid,
nickname: None,
user_uuid: owner_uuid,
guild_uuid,
is_owner: true,
};
insert_into(guild_members::table)
.values(member)
.execute(conn)
.await?;
Ok(Guild {
uuid: guild_uuid,
name,
description: None,
icon: None,
roles: vec![],
member_count: 1,
})
}
pub async fn get_invites(&self, conn: &mut Conn) -> Result<Vec<Invite>, Error> {
use invites::dsl;
let invites = load_or_empty(
dsl::invites
.filter(dsl::guild_uuid.eq(self.uuid))
.select(Invite::as_select())
.load(conn)
.await,
)?;
Ok(invites)
}
pub async fn create_invite(
&self,
conn: &mut Conn,
user_uuid: Uuid,
custom_id: Option<String>,
) -> Result<Invite, Error> {
let invite_id;
if let Some(id) = custom_id {
invite_id = id;
if invite_id.len() > 32 {
return Err(Error::BadRequest("MAX LENGTH".to_string()));
}
} else {
let charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
invite_id = random_string::generate(8, charset);
}
let invite = Invite {
id: invite_id,
user_uuid,
guild_uuid: self.uuid,
};
insert_into(invites::table)
.values(invite.clone())
.execute(conn)
.await?;
Ok(invite)
}
// FIXME: Horrible security
pub async fn set_icon(
&mut self,
conn: &mut Conn,
app_state: &AppState,
icon: Bytes,
) -> Result<(), Error> {
let icon_clone = icon.clone();
let image_type = task::spawn_blocking(move || image_check(icon_clone)).await??;
if let Some(icon) = &self.icon {
let relative_url = icon.path().trim_start_matches('/');
app_state.bunny_storage.delete(relative_url).await?;
}
let path = format!("icons/{}/{}.{}", self.uuid, Uuid::now_v7(), image_type);
app_state.bunny_storage.upload(path.clone(), icon).await?;
let icon_url = app_state.config.bunny.cdn_url.join(&path)?;
use guilds::dsl;
update(guilds::table)
.filter(dsl::uuid.eq(self.uuid))
.set(dsl::icon.eq(icon_url.as_str()))
.execute(conn)
.await?;
self.icon = Some(icon_url);
Ok(())
}
}

View file

@ -1,30 +0,0 @@
use diesel::{ExpressionMethods, Insertable, QueryDsl, Queryable, Selectable, SelectableHelper};
use diesel_async::RunQueryDsl;
use serde::Serialize;
use uuid::Uuid;
use crate::{Conn, error::Error, schema::invites};
/// Server invite struct
#[derive(Clone, Serialize, Queryable, Selectable, Insertable)]
pub struct Invite {
/// case-sensitive alphanumeric string with a fixed length of 8 characters, can be up to 32 characters for custom invites
pub id: String,
/// User that created the invite
pub user_uuid: Uuid,
/// UUID of the guild that the invite belongs to
pub guild_uuid: Uuid,
}
impl Invite {
pub async fn fetch_one(conn: &mut Conn, invite_id: String) -> Result<Self, Error> {
use invites::dsl;
let invite: Invite = dsl::invites
.filter(dsl::id.eq(invite_id))
.select(Invite::as_select())
.get_result(conn)
.await?;
Ok(invite)
}
}

Some files were not shown because too many files have changed in this diff Show more