add: apps api

This commit is contained in:
trisua 2025-06-14 14:45:52 -04:00
parent 2a99d49c8a
commit ebded00fd3
33 changed files with 698 additions and 31 deletions

View file

@ -50,6 +50,10 @@ pub struct DirsConfig {
/// The markdown document files directory.
#[serde(default = "default_dir_docs")]
pub docs: String,
/// The directory which holds your `rustdoc` (`cargo doc`) output. The directory should
/// exist, but it isn't required to actually have anything in it.
#[serde(default = "default_dir_rustdoc")]
pub rustdoc: String,
}
fn default_dir_templates() -> String {
@ -72,6 +76,10 @@ fn default_dir_docs() -> String {
"docs".to_string()
}
fn default_dir_rustdoc() -> String {
"reference".to_string()
}
impl Default for DirsConfig {
fn default() -> Self {
Self {
@ -80,6 +88,7 @@ impl Default for DirsConfig {
media: default_dir_media(),
icons: default_dir_icons(),
docs: default_dir_docs(),
rustdoc: default_dir_rustdoc(),
}
}
}

View file

@ -0,0 +1,150 @@
use oiseau::cache::Cache;
use crate::model::{
Error, Result,
auth::User,
permissions::FinePermission,
apps::{AppQuota, ThirdPartyApp},
};
use crate::{auto_method, DataManager};
#[cfg(feature = "sqlite")]
use oiseau::SqliteRow;
#[cfg(feature = "postgres")]
use oiseau::PostgresRow;
use oiseau::{execute, get, query_rows, params};
impl DataManager {
/// Get a [`ThirdPartyApp`] from an SQL row.
pub(crate) fn get_app_from_row(
#[cfg(feature = "sqlite")] x: &SqliteRow<'_>,
#[cfg(feature = "postgres")] x: &PostgresRow,
) -> ThirdPartyApp {
ThirdPartyApp {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
title: get!(x->3(String)),
homepage: get!(x->4(String)),
redirect: get!(x->5(String)),
quota_status: serde_json::from_str(&get!(x->6(String))).unwrap(),
banned: get!(x->7(i32)) as i8 == 1,
grants: get!(x->8(i32)) as usize,
}
}
auto_method!(get_app_by_id(usize as i64)@get_app_from_row -> "SELECT * FROM apps WHERE id = $1" --name="app" --returns=ThirdPartyApp --cache-key-tmpl="atto.app:{}");
/// Get all apps by user.
///
/// # Arguments
/// * `id` - the ID of the user to fetch apps for
pub async fn get_apps_by_owner(&self, id: usize) -> Result<Vec<ThirdPartyApp>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM apps WHERE owner = $1 ORDER BY created DESC",
&[&(id as i64)],
|x| { Self::get_app_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("app".to_string()));
}
Ok(res.unwrap())
}
const MAXIMUM_FREE_APPS: usize = 1;
/// Create a new app in the database.
///
/// # Arguments
/// * `data` - a mock [`ThirdPartyApp`] object to insert
pub async fn create_app(&self, data: ThirdPartyApp) -> Result<ThirdPartyApp> {
// check values
if data.title.len() < 2 {
return Err(Error::DataTooShort("title".to_string()));
} else if data.title.len() > 32 {
return Err(Error::DataTooLong("title".to_string()));
}
// check number of apps
let owner = self.get_user_by_id(data.owner).await?;
if !owner.permissions.check(FinePermission::SUPPORTER) {
let apps = self.get_apps_by_owner(data.owner).await?;
if apps.len() >= Self::MAXIMUM_FREE_APPS {
return Err(Error::MiscError(
"You already have the maximum number of apps you can have".to_string(),
));
}
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO apps VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&data.title,
&data.homepage,
&data.redirect,
&serde_json::to_string(&data.quota_status).unwrap(),
&{ if data.banned { 1 } else { 0 } },
&(data.grants as i32)
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
Ok(data)
}
pub async fn delete_app(&self, id: usize, user: &User) -> Result<()> {
let app = self.get_app_by_id(id).await?;
// check user permission
if user.id != app.owner && !user.permissions.check(FinePermission::MANAGE_APPS) {
return Err(Error::NotAllowed);
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, "DELETE FROM apps WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.app:{}", id)).await;
Ok(())
}
auto_method!(update_app_title(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_homepage(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET homepage = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_redirect(&str)@get_app_by_id:MANAGE_APPS -> "UPDATE apps SET redirect = $1 WHERE id = $2" --cache-key-tmpl="atto.app:{}");
auto_method!(update_app_quota_status(AppQuota) -> "UPDATE apps SET quota_status = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.app:{}");
auto_method!(incr_app_grants() -> "UPDATE apps SET grants = grants + 1 WHERE id = $2" --cache-key-tmpl="atto.app:{}" --incr);
auto_method!(decr_app_grants()@get_app_by_id -> "UPDATE apps SET grants = grants - 1 WHERE id = $2" --cache-key-tmpl="atto.app:{}" --decr=grants);
}

View file

@ -34,6 +34,7 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_DRAFTS).unwrap();
execute!(&conn, common::CREATE_TABLE_POLLS).unwrap();
execute!(&conn, common::CREATE_TABLE_POLLVOTES).unwrap();
execute!(&conn, common::CREATE_TABLE_APPS).unwrap();
self.0
.1
@ -456,7 +457,7 @@ macro_rules! auto_method {
let res = execute!(
&conn,
$query,
&[&serde_json::to_string(&x).unwrap(), &(id as i64)]
params![&serde_json::to_string(&x).unwrap(), &(id as i64)]
);
if let Err(e) = res {
@ -507,6 +508,31 @@ macro_rules! auto_method {
}
};
($name:ident()@$select_fn:ident -> $query:literal --cache-key-tmpl=$cache_key_tmpl:literal --decr=$field:ident) => {
pub async fn $name(&self, id: usize) -> Result<()> {
let y = self.$select_fn(id).await?;
if (y.$field as isize) - 1 < 0 {
return Ok(());
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, $query, &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!($cache_key_tmpl, id)).await;
Ok(())
}
};
($name:ident()@$select_fn:ident:$permission:ident -> $query:literal --cache-key-tmpl=$cache_key_tmpl:ident) => {
pub async fn $name(&self, id: usize, user: &User) -> Result<()> {
let y = self.$select_fn(id).await?;

View file

@ -21,3 +21,4 @@ pub const CREATE_TABLE_STACKS: &str = include_str!("./sql/create_stacks.sql");
pub const CREATE_TABLE_DRAFTS: &str = include_str!("./sql/create_drafts.sql");
pub const CREATE_TABLE_POLLS: &str = include_str!("./sql/create_polls.sql");
pub const CREATE_TABLE_POLLVOTES: &str = include_str!("./sql/create_pollvotes.sql");
pub const CREATE_TABLE_APPS: &str = include_str!("./sql/create_apps.sql");

View file

@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS apps (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
title TEXT NOT NULL,
homepage TEXT NOT NULL,
redirect TEXT NOT NULL,
quota_status TEXT NOT NULL,
banned INT NOT NULL,
grants INT NOT NULL
)

View file

@ -1,3 +1,4 @@
mod apps;
mod audit_log;
mod auth;
mod common;

View file

@ -1,11 +1,10 @@
use oiseau::cache::Cache;
use crate::model::communities::{Community, Poll, Post, Question};
use crate::model::stacks::{StackMode, StackSort};
use crate::model::{
Error, Result,
auth::User,
permissions::FinePermission,
stacks::{StackPrivacy, UserStack},
stacks::{StackPrivacy, UserStack, StackMode, StackSort},
communities::{Community, Poll, Post, Question},
};
use crate::{auto_method, DataManager};

View file

@ -0,0 +1,60 @@
use serde::{Deserialize, Serialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum AppQuota {
/// The app is limited to 5 grants.
Limited,
/// The app is allowed to maintain an unlimited number of grants.
Unlimited,
}
impl Default for AppQuota {
fn default() -> Self {
Self::Limited
}
}
/// An app is required to request grants on user accounts.
///
/// Users must approve grants through a web portal.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ThirdPartyApp {
pub id: usize,
pub created: usize,
/// The ID of the owner of the app.
pub owner: usize,
/// The name of the app.
pub title: String,
/// The URL of the app's homepage.
pub homepage: String,
/// The redirect URL for the app.
///
/// Upon accepting a grant request, the user will be redirected to this URL
/// with a query parameter named `token`, which should be saved by the app
/// for future authentication.
pub redirect: String,
/// The app's quota status, which determines how many grants the app is allowed to maintain.
pub quota_status: AppQuota,
/// If the app is banned. A banned app cannot use any of its grants.
pub banned: bool,
/// The number of accepted grants the app maintains.
pub grants: usize,
}
impl ThirdPartyApp {
/// Create a new [`ThirdPartyApp`].
pub fn new(title: String, owner: usize, homepage: String, redirect: String) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp() as usize,
owner,
title,
homepage,
redirect,
quota_status: AppQuota::Limited,
banned: false,
grants: 0,
}
}
}

View file

@ -403,6 +403,14 @@ impl User {
self.stripe_id = String::new();
self.connections = HashMap::new();
}
/// Get a grant from the user given the grant's `app` ID.
///
/// Should be used **before** adding another grant (to ensure the app doesn't
/// already have a grant for this user).
pub fn get_grant_by_app_id(&self, id: usize) -> Option<&AuthGrant> {
self.grants.iter().find(|x| x.app == id)
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]

View file

@ -1,4 +1,5 @@
pub mod addr;
pub mod apps;
pub mod auth;
pub mod communities;
pub mod communities_permissions;

View file

@ -6,8 +6,8 @@ use super::{Result, Error};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthGrant {
pub id: usize,
/// The name of the application associated with this grant.
pub name: String,
/// The ID of the application associated with this grant.
pub app: usize,
/// The code challenge for PKCE verifiers associated with this grant.
///
/// This challenge is *all* that is required to refresh this grant's auth token.

View file

@ -36,6 +36,7 @@ bitflags! {
const MANAGE_EMOJIS = 1 << 25;
const MANAGE_STACKS = 1 << 26;
const STAFF_BADGE = 1 << 27;
const MANAGE_APPS = 1 << 28;
const _ = !0;
}