Compare commits
12 Commits
renovate/u
...
3de26c0fff
| Author | SHA1 | Date | |
|---|---|---|---|
| 3de26c0fff | |||
| 79b5a767f3 | |||
| fdcd565431 | |||
| d9c96e85f7 | |||
| 9ed711777c | |||
| 20a42f3c55 | |||
| d05747e60e | |||
| 1cdd3d9e60 | |||
| bc815a5cf1 | |||
| 830f47b61f | |||
| 602edaae79 | |||
| f7e1d1539f |
12
.drone.yml
12
.drone.yml
@@ -1,12 +0,0 @@
|
|||||||
---
|
|
||||||
kind: pipeline
|
|
||||||
type: docker
|
|
||||||
name: default
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: cargo_check
|
|
||||||
image: rust
|
|
||||||
commands:
|
|
||||||
- rustup component add clippy
|
|
||||||
- cargo clippy -- -D warnings
|
|
||||||
- cargo test
|
|
||||||
14
Makefile
14
Makefile
@@ -1,14 +0,0 @@
|
|||||||
DOCKER_TEMP_DIR=temp
|
|
||||||
|
|
||||||
all: gateway
|
|
||||||
|
|
||||||
gateway:
|
|
||||||
cargo clippy -- -D warnings && cargo build --release
|
|
||||||
|
|
||||||
gateway_docker: gateway
|
|
||||||
rm -rf $(DOCKER_TEMP_DIR)
|
|
||||||
mkdir $(DOCKER_TEMP_DIR)
|
|
||||||
cp target/release/matrix_gateway $(DOCKER_TEMP_DIR)
|
|
||||||
docker build -t pierre42100/matrix_gateway -f ./Dockerfile "$(DOCKER_TEMP_DIR)"
|
|
||||||
rm -rf $(DOCKER_TEMP_DIR)
|
|
||||||
|
|
||||||
22
README.md
22
README.md
@@ -6,10 +6,9 @@ Project that expose a simple API to make use of Matrix API. It acts as a Matrix
|
|||||||
**Known limitations**:
|
**Known limitations**:
|
||||||
|
|
||||||
- Supports only a limited subset of Matrix API
|
- Supports only a limited subset of Matrix API
|
||||||
- Does not support E2E encryption
|
|
||||||
- Does not support spaces
|
- Does not support spaces
|
||||||
|
|
||||||
Project written in Rust. Releases are published on Docker Hub.
|
Project written in Rust and TypeScript. Releases are published on Docker Hub.
|
||||||
|
|
||||||
## Docker image options
|
## Docker image options
|
||||||
```bash
|
```bash
|
||||||
@@ -17,8 +16,11 @@ docker run --rm -it docker.io/pierre42100/matrix_gateway --help
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Setup dev environment
|
## Setup dev environment
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
```
|
```
|
||||||
mkdir -p storage/maspostgres storage/synapse storage/minio
|
cd matrixgw_backend
|
||||||
|
mkdir -p storage/maspostgres storage/synapse
|
||||||
docker compose up
|
docker compose up
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -33,12 +35,22 @@ URLs:
|
|||||||
* Synapse: http://localhost:8448/
|
* Synapse: http://localhost:8448/
|
||||||
* Matrix Authentication Service: http://localhost:8778/
|
* Matrix Authentication Service: http://localhost:8778/
|
||||||
* OpenID configuration: http://127.0.0.1:9001/dex/.well-known/openid-configuration
|
* OpenID configuration: http://127.0.0.1:9001/dex/.well-known/openid-configuration
|
||||||
* Minio console: http://localhost:9002/
|
|
||||||
|
|
||||||
Auto-created Matrix accounts:
|
Auto-created Matrix accounts:
|
||||||
|
|
||||||
* `admin1` : `admin1`
|
* `admin1` : `admin1`
|
||||||
* `user1` : `user1`
|
* `user1` : `user1`
|
||||||
|
|
||||||
Minio administration credentials: `minioadmin` : `minioadmin`
|
|
||||||
|
|
||||||
|
### Backend
|
||||||
|
```bash
|
||||||
|
cd matrixgw_backend
|
||||||
|
cargo fmt && cargo clippy && cargo run --
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
```bash
|
||||||
|
cd matrixgw_frontend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
12199
assets/bootstrap.css
vendored
12199
assets/bootstrap.css
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,30 +0,0 @@
|
|||||||
/**
|
|
||||||
* Delete a client referenced by its ID
|
|
||||||
*
|
|
||||||
* @param clientID The ID of the client to delete
|
|
||||||
*/
|
|
||||||
async function deleteClient(clientID) {
|
|
||||||
if(!confirm("Do you really want to remove client " + clientID + "? The operation cannot be reverted!"))
|
|
||||||
return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch("/", {
|
|
||||||
method: "POST",
|
|
||||||
headers:{
|
|
||||||
'Content-Type': 'application/x-www-form-urlencoded'
|
|
||||||
},
|
|
||||||
body: new URLSearchParams({
|
|
||||||
"delete_client_id": clientID
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if(res.status !== 200)
|
|
||||||
throw new Error(`Invalid status code: ${res.status}`);
|
|
||||||
|
|
||||||
alert("The client was successfully deleted!");
|
|
||||||
location.reload();
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Failed to delete client: ${e}`);
|
|
||||||
alert("Failed to delete client!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
.body-content {
|
|
||||||
max-width: 900px;
|
|
||||||
margin: 50px auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.body-content .card-header {
|
|
||||||
font-weight: bold;
|
|
||||||
}
|
|
||||||
|
|
||||||
#user_id_container {
|
|
||||||
margin: 20px auto;
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
let ws;
|
|
||||||
|
|
||||||
const JS_MESSAGE = "JS code";
|
|
||||||
const IN_MESSAGE = "Incoming";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Log message
|
|
||||||
*/
|
|
||||||
function log(src, txt) {
|
|
||||||
const target = document.getElementById("ws_log");
|
|
||||||
const msg = document.createElement("div");
|
|
||||||
msg.className = "message";
|
|
||||||
msg.innerHTML = `<div class='type'>${src}</div><div>${txt}</div>`
|
|
||||||
target.insertBefore(msg, target.firstChild);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the state of the WebSocket
|
|
||||||
*/
|
|
||||||
function setState(state) {
|
|
||||||
document.getElementById("state").innerText = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Initialize WebSocket connection
|
|
||||||
*/
|
|
||||||
function connect() {
|
|
||||||
disconnect();
|
|
||||||
log(JS_MESSAGE, "Initialize connection...");
|
|
||||||
ws = new WebSocket("/api/ws");
|
|
||||||
setState("Connecting...");
|
|
||||||
ws.onopen = function () {
|
|
||||||
log(JS_MESSAGE, "Connected to WebSocket !");
|
|
||||||
setState("Connected");
|
|
||||||
}
|
|
||||||
ws.onmessage = function (event) {
|
|
||||||
log(IN_MESSAGE, event.data);
|
|
||||||
}
|
|
||||||
ws.onclose = function () {
|
|
||||||
log(JS_MESSAGE, "Disconnected from WebSocket !");
|
|
||||||
setState("Disconnected");
|
|
||||||
}
|
|
||||||
ws.onerror = function (event) {
|
|
||||||
console.error("WS Error!", event);
|
|
||||||
log(JS_MESSAGE, `Error with websocket! ${event}`);
|
|
||||||
setState("Error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Close WebSocket connection
|
|
||||||
*/
|
|
||||||
function disconnect() {
|
|
||||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
||||||
log(JS_MESSAGE, "Close connection...");
|
|
||||||
ws.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
setState("Disconnected");
|
|
||||||
ws = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear WS logs
|
|
||||||
*/
|
|
||||||
function clearLogs() {
|
|
||||||
document.getElementById("ws_log").innerHTML = "";
|
|
||||||
}
|
|
||||||
1
.gitignore → matrixgw_backend/.gitignore
vendored
1
.gitignore → matrixgw_backend/.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
storage
|
storage
|
||||||
|
app_storage
|
||||||
.idea
|
.idea
|
||||||
target
|
target
|
||||||
2037
Cargo.lock → matrixgw_backend/Cargo.lock
generated
2037
Cargo.lock → matrixgw_backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,35 +1,30 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "matrix_gateway"
|
name = "matrixgw_backend"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
log = "0.4.28"
|
|
||||||
env_logger = "0.11.8"
|
env_logger = "0.11.8"
|
||||||
|
log = "0.4.28"
|
||||||
clap = { version = "4.5.51", features = ["derive", "env"] }
|
clap = { version = "4.5.51", features = ["derive", "env"] }
|
||||||
lazy_static = "1.5.0"
|
lazy_static = "1.5.0"
|
||||||
anyhow = "1.0.100"
|
anyhow = "1.0.100"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
serde_json = "1.0.143"
|
tokio = { version = "1.48.0", features = ["full"] }
|
||||||
rust-s3 = { version = "0.37.0", features = ["tokio"] }
|
|
||||||
actix-web = "4.11.0"
|
actix-web = "4.11.0"
|
||||||
actix-session = { version = "0.11.0", features = ["redis-session"] }
|
actix-session = { version = "0.11.0", features = ["redis-session"] }
|
||||||
light-openid = "1.0.4"
|
|
||||||
thiserror = "2.0.17"
|
|
||||||
rand = "0.9.2"
|
|
||||||
rust-embed = "8.8.0"
|
|
||||||
mime_guess = "2.0.5"
|
|
||||||
askama = "0.14.0"
|
|
||||||
urlencoding = "2.1.3"
|
|
||||||
uuid = { version = "1.18.0", features = ["v4", "serde"] }
|
|
||||||
ipnet = { version = "2.11.0", features = ["serde"] }
|
|
||||||
chrono = "0.4.42"
|
|
||||||
futures-util = { version = "0.3.31", features = ["sink"] }
|
|
||||||
jwt-simple = { version = "0.12.13", default-features = false, features = ["pure-rust"] }
|
|
||||||
actix-remote-ip = "0.1.0"
|
actix-remote-ip = "0.1.0"
|
||||||
|
actix-cors = "0.7.1"
|
||||||
|
light-openid = "1.0.4"
|
||||||
bytes = "1.10.1"
|
bytes = "1.10.1"
|
||||||
sha2 = "0.11.0-rc.2"
|
sha2 = "0.10.9"
|
||||||
|
urlencoding = "2.1.3"
|
||||||
base16ct = { version = "0.3.0", features = ["alloc"] }
|
base16ct = { version = "0.3.0", features = ["alloc"] }
|
||||||
ruma = { version = "0.13.0", features = ["client-api-c", "client-ext-client-api", "client-hyper-native-tls", "rand"] }
|
futures-util = "0.3.31"
|
||||||
actix-ws = "0.3.0"
|
jwt-simple = { version = "0.12.13", default-features = false, features = ["pure-rust"] }
|
||||||
tokio = { version = "1.48.0", features = ["rt", "time", "macros", "rt-multi-thread"] }
|
thiserror = "2.0.17"
|
||||||
|
uuid = { version = "1.18.1", features = ["v4", "serde"] }
|
||||||
|
ipnet = { version = "2.11.0", features = ["serde"] }
|
||||||
|
rand = "0.9.2"
|
||||||
|
hex = "0.4.3"
|
||||||
|
mailchecker = "6.0.19"
|
||||||
2
matrixgw_backend/README.md
Normal file
2
matrixgw_backend/README.md
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# Matrix Gateway backend
|
||||||
|
Backend component, written in Rust using Actix.
|
||||||
@@ -80,36 +80,23 @@ services:
|
|||||||
element:
|
element:
|
||||||
image: docker.io/vectorim/element-web
|
image: docker.io/vectorim/element-web
|
||||||
ports:
|
ports:
|
||||||
- 8080:80/tcp
|
- "8080:80/tcp"
|
||||||
volumes:
|
volumes:
|
||||||
- ./docker/element/config.json:/app/config.json:ro
|
- ./docker/element/config.json:/app/config.json:ro
|
||||||
|
|
||||||
oidc:
|
oidc:
|
||||||
image: dexidp/dex
|
image: dexidp/dex
|
||||||
ports:
|
ports:
|
||||||
- 9001:9001
|
- "9001:9001"
|
||||||
volumes:
|
volumes:
|
||||||
- ./docker/dex:/conf:ro
|
- ./docker/dex:/conf:ro
|
||||||
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
||||||
|
|
||||||
minio:
|
|
||||||
image: quay.io/minio/minio
|
|
||||||
command: minio server --console-address ":9002" /data
|
|
||||||
ports:
|
|
||||||
- 9000:9000/tcp
|
|
||||||
- 9002:9002/tcp
|
|
||||||
environment:
|
|
||||||
MINIO_ROOT_USER: minioadmin
|
|
||||||
MINIO_ROOT_PASSWORD: minioadmin
|
|
||||||
volumes:
|
|
||||||
# You may store the database tables in a local folder..
|
|
||||||
- ./storage/minio:/data
|
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:alpine
|
image: redis:alpine
|
||||||
command: redis-server --requirepass ${REDIS_PASS:-secretredis}
|
command: redis-server --requirepass ${REDIS_PASS:-secretredis}
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- "6379:6379"
|
||||||
volumes:
|
volumes:
|
||||||
- ./storage/redis-data:/data
|
- ./storage/redis-data:/data
|
||||||
- ./storage/redis-conf:/usr/local/etc/redis/redis.conf
|
- ./storage/redis-conf:/usr/local/etc/redis/redis.conf
|
||||||
@@ -22,5 +22,5 @@ staticClients:
|
|||||||
- id: foo
|
- id: foo
|
||||||
secret: bar
|
secret: bar
|
||||||
redirectURIs:
|
redirectURIs:
|
||||||
- http://localhost:8000/oidc_cb
|
- http://localhost:5173/oidc_cb
|
||||||
name: Project
|
name: Project
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use jwt_simple::algorithms::HS256Key;
|
use jwt_simple::algorithms::HS256Key;
|
||||||
use jwt_simple::prelude::{Clock, Duration, JWTClaims, MACLike};
|
use jwt_simple::prelude::{Clock, Duration, JWTClaims, MACLike};
|
||||||
use matrix_gateway::extractors::client_auth::TokenClaims;
|
use matrixgw_backend::constants;
|
||||||
use matrix_gateway::utils::base_utils::rand_str;
|
use matrixgw_backend::extractors::auth_extractor::TokenClaims;
|
||||||
|
use matrixgw_backend::utils::rand_utils::rand_string;
|
||||||
use std::ops::Add;
|
use std::ops::Add;
|
||||||
use std::os::unix::prelude::CommandExt;
|
use std::os::unix::prelude::CommandExt;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
@@ -59,7 +60,7 @@ fn main() {
|
|||||||
subject: None,
|
subject: None,
|
||||||
audiences: None,
|
audiences: None,
|
||||||
jwt_id: None,
|
jwt_id: None,
|
||||||
nonce: Some(rand_str(10)),
|
nonce: Some(rand_string(10)),
|
||||||
custom: TokenClaims {
|
custom: TokenClaims {
|
||||||
method: args.method.to_string(),
|
method: args.method.to_string(),
|
||||||
uri: args.uri,
|
uri: args.uri,
|
||||||
@@ -78,7 +79,7 @@ fn main() {
|
|||||||
|
|
||||||
let _ = Command::new("curl")
|
let _ = Command::new("curl")
|
||||||
.args(["-X", &args.method])
|
.args(["-X", &args.method])
|
||||||
.args(["-H", &format!("x-client-auth: {jwt}")])
|
.args(["-H", &format!("{}: {jwt}", constants::API_AUTH_HEADER)])
|
||||||
.args(args.run)
|
.args(args.run)
|
||||||
.arg(full_url)
|
.arg(full_url)
|
||||||
.exec();
|
.exec();
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
|
use crate::users::{APITokenID, UserEmail};
|
||||||
|
use crate::utils::crypt_utils::sha256str;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use s3::creds::Credentials;
|
use std::path::{Path, PathBuf};
|
||||||
use s3::{Bucket, Region};
|
|
||||||
|
|
||||||
/// Matrix gateway backend API
|
/// Matrix gateway backend API
|
||||||
#[derive(Parser, Debug, Clone)]
|
#[derive(Parser, Debug, Clone)]
|
||||||
@@ -11,18 +12,23 @@ pub struct AppConfig {
|
|||||||
pub listen_address: String,
|
pub listen_address: String,
|
||||||
|
|
||||||
/// Website origin
|
/// Website origin
|
||||||
#[clap(short, long, env, default_value = "http://localhost:8000")]
|
#[clap(short, long, env, default_value = "http://localhost:5173")]
|
||||||
pub website_origin: String,
|
pub website_origin: String,
|
||||||
|
|
||||||
/// Proxy IP, might end with a star "*"
|
/// Proxy IP, might end with a star "*"
|
||||||
#[clap(short, long, env)]
|
#[clap(short, long, env)]
|
||||||
pub proxy_ip: Option<String>,
|
pub proxy_ip: Option<String>,
|
||||||
|
|
||||||
/// Secret key, used to sign some resources. Must be randomly generated
|
/// Unsecure : for development, bypass authentication, using the account with the given
|
||||||
|
/// email address by default
|
||||||
|
#[clap(long, env)]
|
||||||
|
unsecure_auto_login_email: Option<String>,
|
||||||
|
|
||||||
|
/// Secret key, used to secure some resources. Must be randomly generated
|
||||||
#[clap(short = 'S', long, env, default_value = "")]
|
#[clap(short = 'S', long, env, default_value = "")]
|
||||||
secret: String,
|
secret: String,
|
||||||
|
|
||||||
/// Matrix API origin
|
/// Matrix homeserver origin
|
||||||
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
|
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
|
||||||
pub matrix_homeserver: String,
|
pub matrix_homeserver: String,
|
||||||
|
|
||||||
@@ -54,6 +60,10 @@ pub struct AppConfig {
|
|||||||
)]
|
)]
|
||||||
pub oidc_configuration_url: String,
|
pub oidc_configuration_url: String,
|
||||||
|
|
||||||
|
/// OpenID provider name
|
||||||
|
#[arg(long, env, default_value = "3rd party provider")]
|
||||||
|
pub oidc_provider_name: String,
|
||||||
|
|
||||||
/// OpenID client ID
|
/// OpenID client ID
|
||||||
#[arg(long, env, default_value = "foo")]
|
#[arg(long, env, default_value = "foo")]
|
||||||
pub oidc_client_id: String,
|
pub oidc_client_id: String,
|
||||||
@@ -66,29 +76,9 @@ pub struct AppConfig {
|
|||||||
#[arg(long, env, default_value = "APP_ORIGIN/oidc_cb")]
|
#[arg(long, env, default_value = "APP_ORIGIN/oidc_cb")]
|
||||||
oidc_redirect_url: String,
|
oidc_redirect_url: String,
|
||||||
|
|
||||||
/// S3 Bucket name
|
/// Application storage path
|
||||||
#[arg(long, env, default_value = "matrix-gw")]
|
#[arg(long, env, default_value = "app_storage")]
|
||||||
s3_bucket_name: String,
|
storage_path: String,
|
||||||
|
|
||||||
/// S3 region (if not using Minio)
|
|
||||||
#[arg(long, env, default_value = "eu-central-1")]
|
|
||||||
s3_region: String,
|
|
||||||
|
|
||||||
/// S3 API endpoint
|
|
||||||
#[arg(long, env, default_value = "http://localhost:9000")]
|
|
||||||
s3_endpoint: String,
|
|
||||||
|
|
||||||
/// S3 access key
|
|
||||||
#[arg(long, env, default_value = "minioadmin")]
|
|
||||||
s3_access_key: String,
|
|
||||||
|
|
||||||
/// S3 secret key
|
|
||||||
#[arg(long, env, default_value = "minioadmin")]
|
|
||||||
s3_secret_key: String,
|
|
||||||
|
|
||||||
/// S3 skip auto create bucket if not existing
|
|
||||||
#[arg(long, env)]
|
|
||||||
pub s3_skip_auto_create_bucket: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@@ -103,6 +93,14 @@ impl AppConfig {
|
|||||||
&ARGS
|
&ARGS
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get auto login email (if not empty)
|
||||||
|
pub fn unsecure_auto_login_email(&self) -> Option<UserEmail> {
|
||||||
|
match self.unsecure_auto_login_email.as_deref() {
|
||||||
|
None | Some("") => None,
|
||||||
|
Some(s) => Some(UserEmail(s.to_owned())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Get app secret
|
/// Get app secret
|
||||||
pub fn secret(&self) -> &str {
|
pub fn secret(&self) -> &str {
|
||||||
let mut secret = self.secret.as_str();
|
let mut secret = self.secret.as_str();
|
||||||
@@ -118,6 +116,11 @@ impl AppConfig {
|
|||||||
secret
|
secret
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if auth is disabled
|
||||||
|
pub fn is_auth_disabled(&self) -> bool {
|
||||||
|
self.unsecure_auto_login_email().is_some()
|
||||||
|
}
|
||||||
|
|
||||||
/// Get Redis connection configuration
|
/// Get Redis connection configuration
|
||||||
pub fn redis_connection_string(&self) -> String {
|
pub fn redis_connection_string(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
@@ -136,39 +139,42 @@ impl AppConfig {
|
|||||||
client_id: self.oidc_client_id.as_str(),
|
client_id: self.oidc_client_id.as_str(),
|
||||||
client_secret: self.oidc_client_secret.as_str(),
|
client_secret: self.oidc_client_secret.as_str(),
|
||||||
configuration_url: self.oidc_configuration_url.as_str(),
|
configuration_url: self.oidc_configuration_url.as_str(),
|
||||||
|
name: self.oidc_provider_name.as_str(),
|
||||||
redirect_url: self
|
redirect_url: self
|
||||||
.oidc_redirect_url
|
.oidc_redirect_url
|
||||||
.replace("APP_ORIGIN", &self.website_origin),
|
.replace("APP_ORIGIN", &self.website_origin),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get s3 bucket credentials
|
/// Get storage path
|
||||||
pub fn s3_credentials(&self) -> anyhow::Result<Credentials> {
|
pub fn storage_path(&self) -> &Path {
|
||||||
Ok(Credentials::new(
|
Path::new(self.storage_path.as_str())
|
||||||
Some(&self.s3_access_key),
|
|
||||||
Some(&self.s3_secret_key),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get S3 bucket
|
/// User storage directory
|
||||||
pub fn s3_bucket(&self) -> anyhow::Result<Box<Bucket>> {
|
pub fn user_directory(&self, mail: &UserEmail) -> PathBuf {
|
||||||
Ok(Bucket::new(
|
self.storage_path().join("users").join(sha256str(&mail.0))
|
||||||
&self.s3_bucket_name,
|
}
|
||||||
Region::Custom {
|
|
||||||
region: self.s3_region.to_string(),
|
/// User metadata file
|
||||||
endpoint: self.s3_endpoint.to_string(),
|
pub fn user_metadata_file_path(&self, mail: &UserEmail) -> PathBuf {
|
||||||
},
|
self.user_directory(mail).join("metadata.json")
|
||||||
self.s3_credentials()?,
|
}
|
||||||
)?
|
|
||||||
.with_path_style())
|
/// User API tokens directory
|
||||||
|
pub fn user_api_token_directory(&self, mail: &UserEmail) -> PathBuf {
|
||||||
|
self.user_directory(mail).join("api-tokens")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User API token metadata file
|
||||||
|
pub fn user_api_token_metadata_file(&self, mail: &UserEmail, id: &APITokenID) -> PathBuf {
|
||||||
|
self.user_api_token_directory(mail).join(id.0.to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
pub struct OIDCProvider<'a> {
|
pub struct OIDCProvider<'a> {
|
||||||
|
pub name: &'a str,
|
||||||
pub client_id: &'a str,
|
pub client_id: &'a str,
|
||||||
pub client_secret: &'a str,
|
pub client_secret: &'a str,
|
||||||
pub configuration_url: &'a str,
|
pub configuration_url: &'a str,
|
||||||
15
matrixgw_backend/src/constants.rs
Normal file
15
matrixgw_backend/src/constants.rs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/// Auth header
|
||||||
|
pub const API_AUTH_HEADER: &str = "x-client-auth";
|
||||||
|
|
||||||
|
/// Max token validity, in seconds
|
||||||
|
pub const API_TOKEN_JWT_MAX_DURATION: u64 = 15 * 60;
|
||||||
|
|
||||||
|
/// Session-specific constants
|
||||||
|
pub mod sessions {
|
||||||
|
/// OpenID auth session state key
|
||||||
|
pub const OIDC_STATE_KEY: &str = "oidc-state";
|
||||||
|
/// OpenID auth remote IP address
|
||||||
|
pub const OIDC_REMOTE_IP: &str = "oidc-remote-ip";
|
||||||
|
/// Authenticated ID
|
||||||
|
pub const USER_ID: &str = "uid";
|
||||||
|
}
|
||||||
131
matrixgw_backend/src/controllers/auth_controller.rs
Normal file
131
matrixgw_backend/src/controllers/auth_controller.rs
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::controllers::{HttpFailure, HttpResult};
|
||||||
|
use crate::extractors::auth_extractor::{AuthExtractor, AuthenticatedMethod};
|
||||||
|
use crate::extractors::session_extractor::MatrixGWSession;
|
||||||
|
use crate::users::{User, UserEmail};
|
||||||
|
use actix_remote_ip::RemoteIP;
|
||||||
|
use actix_web::{HttpResponse, web};
|
||||||
|
use light_openid::primitives::OpenIDConfig;
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct StartOIDCResponse {
|
||||||
|
url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start OIDC authentication
|
||||||
|
pub async fn start_oidc(session: MatrixGWSession, remote_ip: RemoteIP) -> HttpResult {
|
||||||
|
let prov = AppConfig::get().openid_provider();
|
||||||
|
|
||||||
|
let conf = match OpenIDConfig::load_from_url(prov.configuration_url).await {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to fetch OpenID provider configuration! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError()
|
||||||
|
.json("Failed to fetch OpenID provider configuration!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let state = match session.gen_oidc_state(remote_ip.0) {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to generate auth state! {e}");
|
||||||
|
return Ok(HttpResponse::InternalServerError().json("Failed to generate auth state!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().json(StartOIDCResponse {
|
||||||
|
url: conf.gen_authorization_url(
|
||||||
|
prov.client_id,
|
||||||
|
&state,
|
||||||
|
&AppConfig::get().openid_provider().redirect_url,
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct FinishOpenIDLoginQuery {
|
||||||
|
code: String,
|
||||||
|
state: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish OIDC authentication
|
||||||
|
pub async fn finish_oidc(
|
||||||
|
session: MatrixGWSession,
|
||||||
|
remote_ip: RemoteIP,
|
||||||
|
req: web::Json<FinishOpenIDLoginQuery>,
|
||||||
|
) -> HttpResult {
|
||||||
|
if let Err(e) = session.validate_state(&req.state, remote_ip.0) {
|
||||||
|
log::error!("Failed to validate OIDC CB state! {e}");
|
||||||
|
return Ok(HttpResponse::BadRequest().json("Invalid state!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let prov = AppConfig::get().openid_provider();
|
||||||
|
|
||||||
|
let conf = OpenIDConfig::load_from_url(prov.configuration_url)
|
||||||
|
.await
|
||||||
|
.map_err(HttpFailure::OpenID)?;
|
||||||
|
|
||||||
|
let (token, _) = conf
|
||||||
|
.request_token(
|
||||||
|
prov.client_id,
|
||||||
|
prov.client_secret,
|
||||||
|
&req.code,
|
||||||
|
&AppConfig::get().openid_provider().redirect_url,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(HttpFailure::OpenID)?;
|
||||||
|
let (user_info, _) = conf
|
||||||
|
.request_user_info(&token)
|
||||||
|
.await
|
||||||
|
.map_err(HttpFailure::OpenID)?;
|
||||||
|
|
||||||
|
if user_info.email_verified != Some(true) {
|
||||||
|
log::error!("Email is not verified!");
|
||||||
|
return Ok(HttpResponse::Unauthorized().json("Email unverified by IDP!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mail = match user_info.email {
|
||||||
|
Some(m) => m,
|
||||||
|
None => {
|
||||||
|
return Ok(HttpResponse::Unauthorized().json("Email not provided by the IDP!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let user_name = user_info.name.unwrap_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"{} {}",
|
||||||
|
user_info.given_name.as_deref().unwrap_or(""),
|
||||||
|
user_info.family_name.as_deref().unwrap_or("")
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
let user = User::create_or_update_user(&UserEmail(mail), &user_name).await?;
|
||||||
|
|
||||||
|
session.set_user(&user)?;
|
||||||
|
|
||||||
|
Ok(HttpResponse::Ok().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get current user information
|
||||||
|
pub async fn auth_info(auth: AuthExtractor) -> HttpResult {
|
||||||
|
Ok(HttpResponse::Ok().json(auth.user))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sign out user
|
||||||
|
pub async fn sign_out(auth: AuthExtractor, session: MatrixGWSession) -> HttpResult {
|
||||||
|
match auth.method {
|
||||||
|
AuthenticatedMethod::Cookie => {
|
||||||
|
session.unset_current_user()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
AuthenticatedMethod::Token(token) => {
|
||||||
|
token.delete(&auth.user.email).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
AuthenticatedMethod::Dev => {
|
||||||
|
// Nothing to be done, user is always authenticated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::NoContent().finish())
|
||||||
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::{HttpResponse, ResponseError};
|
use actix_web::{HttpResponse, ResponseError};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt::Debug;
|
|
||||||
|
|
||||||
pub mod api;
|
pub mod auth_controller;
|
||||||
pub mod web_ui;
|
pub mod server_controller;
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum HttpFailure {
|
pub enum HttpFailure {
|
||||||
@@ -12,24 +11,10 @@ pub enum HttpFailure {
|
|||||||
Forbidden,
|
Forbidden,
|
||||||
#[error("this resource was not found")]
|
#[error("this resource was not found")]
|
||||||
NotFound,
|
NotFound,
|
||||||
#[error("Actix web error")]
|
|
||||||
ActixError(#[from] actix_web::Error),
|
|
||||||
#[error("an unhandled session insert error occurred")]
|
|
||||||
SessionInsertError(#[from] actix_session::SessionInsertError),
|
|
||||||
#[error("an unhandled session error occurred")]
|
|
||||||
SessionError(#[from] actix_session::SessionGetError),
|
|
||||||
#[error("an unspecified open id error occurred: {0}")]
|
#[error("an unspecified open id error occurred: {0}")]
|
||||||
OpenID(Box<dyn Error>),
|
OpenID(Box<dyn Error>),
|
||||||
#[error("an error occurred while fetching user configuration: {0}")]
|
|
||||||
FetchUserConfig(anyhow::Error),
|
|
||||||
#[error("an unspecified internal error occurred: {0}")]
|
#[error("an unspecified internal error occurred: {0}")]
|
||||||
InternalError(#[from] anyhow::Error),
|
InternalError(#[from] anyhow::Error),
|
||||||
#[error("a matrix api client error occurred: {0}")]
|
|
||||||
MatrixApiClientError(#[from] ruma::api::client::Error),
|
|
||||||
#[error("a matrix client error occurred: {0}")]
|
|
||||||
MatrixClientError(String),
|
|
||||||
#[error("a serde_json error occurred: {0}")]
|
|
||||||
SerdeJsonError(#[from] serde_json::error::Error),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ResponseError for HttpFailure {
|
impl ResponseError for HttpFailure {
|
||||||
74
matrixgw_backend/src/controllers/server_controller.rs
Normal file
74
matrixgw_backend/src/controllers/server_controller.rs
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use actix_web::HttpResponse;
|
||||||
|
|
||||||
|
/// Serve robots.txt (disallow ranking)
|
||||||
|
pub async fn robots_txt() -> HttpResponse {
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.content_type("text/plain")
|
||||||
|
.body("User-agent: *\nDisallow: /\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub struct LenConstraints {
|
||||||
|
min: usize,
|
||||||
|
max: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LenConstraints {
|
||||||
|
pub fn new(min: usize, max: usize) -> Self {
|
||||||
|
Self { min, max }
|
||||||
|
}
|
||||||
|
pub fn not_empty(max: usize) -> Self {
|
||||||
|
Self { min: 1, max }
|
||||||
|
}
|
||||||
|
pub fn max_only(max: usize) -> Self {
|
||||||
|
Self { min: 0, max }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_str(&self, s: &str) -> bool {
|
||||||
|
s.len() >= self.min && s.len() <= self.max
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_u32(&self, v: u32) -> bool {
|
||||||
|
v >= self.min as u32 && v <= self.max as u32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
pub struct ServerConstraints {
|
||||||
|
pub token_name: LenConstraints,
|
||||||
|
pub token_ip_net: LenConstraints,
|
||||||
|
pub token_max_inactivity: LenConstraints,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ServerConstraints {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
token_name: LenConstraints::new(5, 255),
|
||||||
|
token_ip_net: LenConstraints::max_only(44),
|
||||||
|
token_max_inactivity: LenConstraints::new(3600, 3600 * 24 * 365),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct ServerConfig {
|
||||||
|
auth_disabled: bool,
|
||||||
|
oidc_provider_name: &'static str,
|
||||||
|
constraints: ServerConstraints,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ServerConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
auth_disabled: AppConfig::get().is_auth_disabled(),
|
||||||
|
oidc_provider_name: AppConfig::get().openid_provider().name,
|
||||||
|
constraints: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get server static configuration
|
||||||
|
pub async fn config() -> HttpResponse {
|
||||||
|
HttpResponse::Ok().json(ServerConfig::default())
|
||||||
|
}
|
||||||
305
matrixgw_backend/src/extractors/auth_extractor.rs
Normal file
305
matrixgw_backend/src/extractors/auth_extractor.rs
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::constants;
|
||||||
|
use crate::extractors::session_extractor::MatrixGWSession;
|
||||||
|
use crate::users::{APIToken, APITokenID, User, UserEmail};
|
||||||
|
use crate::utils::time_utils::time_secs;
|
||||||
|
use actix_remote_ip::RemoteIP;
|
||||||
|
use actix_web::dev::Payload;
|
||||||
|
use actix_web::error::ErrorPreconditionFailed;
|
||||||
|
use actix_web::{FromRequest, HttpRequest};
|
||||||
|
use anyhow::Context;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use jwt_simple::common::VerificationOptions;
|
||||||
|
use jwt_simple::prelude::{Duration, HS256Key, MACLike};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum AuthenticatedMethod {
|
||||||
|
/// User is authenticated using a cookie
|
||||||
|
Cookie,
|
||||||
|
/// User is authenticated through command line, for debugging purposes only
|
||||||
|
Dev,
|
||||||
|
/// User is authenticated using an API token
|
||||||
|
Token(APIToken),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AuthExtractor {
|
||||||
|
pub user: User,
|
||||||
|
pub method: AuthenticatedMethod,
|
||||||
|
pub payload: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Eq, PartialEq)]
|
||||||
|
pub struct MatrixJWTKID {
|
||||||
|
pub user_email: UserEmail,
|
||||||
|
pub id: APITokenID,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for MatrixJWTKID {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}#{}", self.user_email.0, self.id.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for MatrixJWTKID {
|
||||||
|
type Err = anyhow::Error;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
let (mail, token_id) = s
|
||||||
|
.split_once("#")
|
||||||
|
.context("Failed to decode KID in two parts!")?;
|
||||||
|
|
||||||
|
let mail = UserEmail(mail.to_string());
|
||||||
|
|
||||||
|
if !mail.is_valid() {
|
||||||
|
anyhow::bail!("Given email is invalid!")
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
user_email: mail,
|
||||||
|
id: token_id.parse().context("Failed to parse API token ID")?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct TokenClaims {
|
||||||
|
#[serde(rename = "met")]
|
||||||
|
pub method: String,
|
||||||
|
pub uri: String,
|
||||||
|
#[serde(rename = "pay", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub payload_sha256: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthExtractor {
|
||||||
|
async fn extract_auth(
|
||||||
|
req: &HttpRequest,
|
||||||
|
remote_ip: IpAddr,
|
||||||
|
payload_bytes: Option<Bytes>,
|
||||||
|
) -> Result<Self, actix_web::Error> {
|
||||||
|
// Check for authentication using API token
|
||||||
|
if let Some(token) = req.headers().get(constants::API_AUTH_HEADER) {
|
||||||
|
let Ok(jwt_token) = token.to_str() else {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Failed to decode token as string!",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
let metadata = match jwt_simple::token::Token::decode_metadata(jwt_token) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to decode JWT header metadata! {e}");
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Failed to decode JWT header metadata!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Extract token ID
|
||||||
|
let Some(kid) = metadata.key_id() else {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Missing key id in request!",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
let jwt_kid = match MatrixJWTKID::from_str(kid) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to parse token id! {e}");
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Failed to parse token id!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get token information
|
||||||
|
let Ok(mut token) = APIToken::load(&jwt_kid.user_email, &jwt_kid.id).await else {
|
||||||
|
log::error!("Token not found!");
|
||||||
|
return Err(actix_web::error::ErrorForbidden("Token not found!"));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Decode JWT
|
||||||
|
let key = HS256Key::from_bytes(token.secret.as_ref());
|
||||||
|
let verif = VerificationOptions {
|
||||||
|
max_validity: Some(Duration::from_secs(constants::API_TOKEN_JWT_MAX_DURATION)),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let claims = match key.verify_token::<TokenClaims>(jwt_token, Some(verif)) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("JWT validation failed! {e}");
|
||||||
|
return Err(actix_web::error::ErrorForbidden("JWT validation failed!"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check for nonce
|
||||||
|
if claims.nonce.is_none() {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"A nonce is required in auth JWT!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check IP restriction
|
||||||
|
if let Some(net) = token.network
|
||||||
|
&& !net.contains(&remote_ip)
|
||||||
|
{
|
||||||
|
log::error!(
|
||||||
|
"Trying to use token {:?} from unauthorized IP address: {remote_ip:?}",
|
||||||
|
token.id
|
||||||
|
);
|
||||||
|
return Err(actix_web::error::ErrorForbidden(
|
||||||
|
"This token cannot be used from this IP address!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for write access
|
||||||
|
if token.read_only && !req.method().is_safe() {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Read only token cannot perform write operations!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user information
|
||||||
|
let Ok(user) = User::get_by_mail(&jwt_kid.user_email).await else {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Failed to get user information from token!",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update last use (if needed)
|
||||||
|
if token.shall_update_time_used() {
|
||||||
|
token.last_used = time_secs();
|
||||||
|
if let Err(e) = token.write(&jwt_kid.user_email).await {
|
||||||
|
log::error!("Failed to refresh last usage of token! {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle tokens expiration
|
||||||
|
if token.is_expired() {
|
||||||
|
log::error!("Attempted to use expired token! {token:?}");
|
||||||
|
return Err(actix_web::error::ErrorBadRequest("Token has expired!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check payload
|
||||||
|
let payload = match (payload_bytes, claims.custom.payload_sha256) {
|
||||||
|
(None, _) => None,
|
||||||
|
(Some(_), None) => {
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"A payload digest must be included in the JWT when the request has a payload!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(Some(payload), Some(provided_digest)) => {
|
||||||
|
let computed_digest = base16ct::lower::encode_string(&Sha256::digest(&payload));
|
||||||
|
if computed_digest != provided_digest {
|
||||||
|
log::error!(
|
||||||
|
"Expected digest {provided_digest} for payload but computed {computed_digest}!"
|
||||||
|
);
|
||||||
|
return Err(actix_web::error::ErrorBadRequest(
|
||||||
|
"Computed digest is different from the one provided in the JWT!",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(payload.to_vec())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return Ok(Self {
|
||||||
|
method: AuthenticatedMethod::Token(token),
|
||||||
|
user,
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if login is hard-coded as program argument
|
||||||
|
if let Some(email) = &AppConfig::get().unsecure_auto_login_email() {
|
||||||
|
let user = User::get_by_mail(email).await.map_err(|e| {
|
||||||
|
log::error!("Failed to retrieve dev user: {e}");
|
||||||
|
ErrorPreconditionFailed("Unable to retrieve dev user!")
|
||||||
|
})?;
|
||||||
|
return Ok(Self {
|
||||||
|
method: AuthenticatedMethod::Dev,
|
||||||
|
user,
|
||||||
|
payload: payload_bytes.map(|bytes| bytes.to_vec()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for cookie authentication
|
||||||
|
let session = MatrixGWSession::extract(req).await?;
|
||||||
|
if let Some(mail) = session.current_user().map_err(|e| {
|
||||||
|
log::error!("Failed to retrieve user id: {e}");
|
||||||
|
ErrorPreconditionFailed("Failed to read session information!")
|
||||||
|
})? {
|
||||||
|
let user = User::get_by_mail(&mail).await.map_err(|e| {
|
||||||
|
log::error!("Failed to retrieve user from cookie session: {e}");
|
||||||
|
ErrorPreconditionFailed("Failed to retrieve user information!")
|
||||||
|
})?;
|
||||||
|
return Ok(Self {
|
||||||
|
method: AuthenticatedMethod::Cookie,
|
||||||
|
user,
|
||||||
|
payload: payload_bytes.map(|bytes| bytes.to_vec()),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Err(ErrorPreconditionFailed("Authentication required!"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for AuthExtractor {
|
||||||
|
type Error = actix_web::Error;
|
||||||
|
type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
||||||
|
|
||||||
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
|
let req = req.clone();
|
||||||
|
|
||||||
|
let remote_ip = match RemoteIP::from_request(&req, &mut Payload::None).into_inner() {
|
||||||
|
Ok(ip) => ip,
|
||||||
|
Err(e) => return Box::pin(async { Err(e) }),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut payload = payload.take();
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let payload_bytes = match Bytes::from_request(&req, &mut payload).await {
|
||||||
|
Ok(b) => {
|
||||||
|
if b.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to extract request payload! {e}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Self::extract_auth(&req, remote_ip.0, payload_bytes).await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::extractors::auth_extractor::MatrixJWTKID;
|
||||||
|
use crate::users::{APITokenID, UserEmail};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_decode_jwt_kid() {
|
||||||
|
let src = MatrixJWTKID {
|
||||||
|
user_email: UserEmail("test@mail.com".to_string()),
|
||||||
|
id: APITokenID::default(),
|
||||||
|
};
|
||||||
|
let encoded = src.to_string();
|
||||||
|
let decoded = encoded.parse::<MatrixJWTKID>().unwrap();
|
||||||
|
assert_eq!(src, decoded);
|
||||||
|
|
||||||
|
MatrixJWTKID::from_str("bad").unwrap_err();
|
||||||
|
MatrixJWTKID::from_str("ba#d").unwrap_err();
|
||||||
|
MatrixJWTKID::from_str("test@valid.com#d").unwrap_err();
|
||||||
|
}
|
||||||
|
}
|
||||||
2
matrixgw_backend/src/extractors/mod.rs
Normal file
2
matrixgw_backend/src/extractors/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod auth_extractor;
|
||||||
|
pub mod session_extractor;
|
||||||
91
matrixgw_backend/src/extractors/session_extractor.rs
Normal file
91
matrixgw_backend/src/extractors/session_extractor.rs
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
use crate::constants;
|
||||||
|
use crate::users::{User, UserEmail};
|
||||||
|
use crate::utils::rand_utils::rand_string;
|
||||||
|
use actix_session::Session;
|
||||||
|
use actix_web::dev::Payload;
|
||||||
|
use actix_web::{Error, FromRequest, HttpRequest};
|
||||||
|
use futures_util::future::{Ready, ready};
|
||||||
|
use std::net::IpAddr;
|
||||||
|
|
||||||
|
/// Matrix Gateway session errors
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum MatrixGWSessionError {
|
||||||
|
#[error("Missing state!")]
|
||||||
|
OIDCMissingState,
|
||||||
|
#[error("Missing IP address!")]
|
||||||
|
OIDCMissingIP,
|
||||||
|
#[error("Invalid state!")]
|
||||||
|
OIDCInvalidState,
|
||||||
|
#[error("Invalid IP address!")]
|
||||||
|
OIDCInvalidIP,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Matrix Gateway session
|
||||||
|
///
|
||||||
|
/// Basic wrapper around actix-session extractor
|
||||||
|
pub struct MatrixGWSession(Session);
|
||||||
|
|
||||||
|
impl MatrixGWSession {
|
||||||
|
/// Generate OpenID state for this session
|
||||||
|
pub fn gen_oidc_state(&self, ip: IpAddr) -> anyhow::Result<String> {
|
||||||
|
let random_string = rand_string(50);
|
||||||
|
self.0
|
||||||
|
.insert(constants::sessions::OIDC_STATE_KEY, random_string.clone())?;
|
||||||
|
self.0.insert(constants::sessions::OIDC_REMOTE_IP, ip)?;
|
||||||
|
Ok(random_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate OpenID state
|
||||||
|
pub fn validate_state(&self, state: &str, ip: IpAddr) -> anyhow::Result<()> {
|
||||||
|
let session_state: String = self
|
||||||
|
.0
|
||||||
|
.get(constants::sessions::OIDC_STATE_KEY)?
|
||||||
|
.ok_or(MatrixGWSessionError::OIDCMissingState)?;
|
||||||
|
|
||||||
|
let session_ip: IpAddr = self
|
||||||
|
.0
|
||||||
|
.get(constants::sessions::OIDC_REMOTE_IP)?
|
||||||
|
.ok_or(MatrixGWSessionError::OIDCMissingIP)?;
|
||||||
|
|
||||||
|
if session_state != state {
|
||||||
|
return Err(anyhow::anyhow!(MatrixGWSessionError::OIDCInvalidState));
|
||||||
|
}
|
||||||
|
|
||||||
|
if session_ip != ip {
|
||||||
|
return Err(anyhow::anyhow!(MatrixGWSessionError::OIDCInvalidIP));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set current user
|
||||||
|
pub fn set_user(&self, user: &User) -> anyhow::Result<()> {
|
||||||
|
self.0.insert(constants::sessions::USER_ID, &user.email)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get current user
|
||||||
|
pub fn current_user(&self) -> anyhow::Result<Option<UserEmail>> {
|
||||||
|
Ok(self.0.get(constants::sessions::USER_ID)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove defined user
|
||||||
|
pub fn unset_current_user(&self) -> anyhow::Result<()> {
|
||||||
|
self.0.remove(constants::sessions::USER_ID);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequest for MatrixGWSession {
|
||||||
|
type Error = Error;
|
||||||
|
type Future = Ready<Result<Self, Error>>;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
|
ready(
|
||||||
|
Session::from_request(req, &mut Payload::None)
|
||||||
|
.into_inner()
|
||||||
|
.map(MatrixGWSession),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
6
matrixgw_backend/src/lib.rs
Normal file
6
matrixgw_backend/src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
pub mod app_config;
|
||||||
|
pub mod constants;
|
||||||
|
pub mod controllers;
|
||||||
|
pub mod extractors;
|
||||||
|
pub mod users;
|
||||||
|
pub mod utils;
|
||||||
83
matrixgw_backend/src/main.rs
Normal file
83
matrixgw_backend/src/main.rs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
use actix_cors::Cors;
|
||||||
|
use actix_remote_ip::RemoteIPConfig;
|
||||||
|
use actix_session::SessionMiddleware;
|
||||||
|
use actix_session::config::SessionLifecycle;
|
||||||
|
use actix_session::storage::RedisSessionStore;
|
||||||
|
use actix_web::cookie::Key;
|
||||||
|
use actix_web::middleware::Logger;
|
||||||
|
use actix_web::{App, HttpServer, web};
|
||||||
|
use matrixgw_backend::app_config::AppConfig;
|
||||||
|
use matrixgw_backend::constants;
|
||||||
|
use matrixgw_backend::controllers::{auth_controller, server_controller};
|
||||||
|
use matrixgw_backend::users::User;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
|
|
||||||
|
let secret_key = Key::from(AppConfig::get().secret().as_bytes());
|
||||||
|
|
||||||
|
let redis_store = RedisSessionStore::new(AppConfig::get().redis_connection_string())
|
||||||
|
.await
|
||||||
|
.expect("Failed to connect to Redis!");
|
||||||
|
|
||||||
|
// Auto create default account, if requested
|
||||||
|
if let Some(mail) = &AppConfig::get().unsecure_auto_login_email() {
|
||||||
|
User::create_or_update_user(mail, "Anonymous")
|
||||||
|
.await
|
||||||
|
.expect("Failed to create auto-login account!");
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"Starting to listen on {} for {}",
|
||||||
|
AppConfig::get().listen_address,
|
||||||
|
AppConfig::get().website_origin
|
||||||
|
);
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
let session_mw = SessionMiddleware::builder(redis_store.clone(), secret_key.clone())
|
||||||
|
.cookie_name("matrixgw-session".to_string())
|
||||||
|
.session_lifecycle(SessionLifecycle::BrowserSession(Default::default()))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
let cors = Cors::default()
|
||||||
|
.allowed_origin(&AppConfig::get().website_origin)
|
||||||
|
.allowed_methods(vec!["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
|
||||||
|
.allowed_header(constants::API_AUTH_HEADER)
|
||||||
|
.allow_any_header()
|
||||||
|
.supports_credentials()
|
||||||
|
.max_age(3600);
|
||||||
|
|
||||||
|
App::new()
|
||||||
|
.wrap(Logger::default())
|
||||||
|
.wrap(session_mw)
|
||||||
|
.wrap(cors)
|
||||||
|
.app_data(web::Data::new(RemoteIPConfig {
|
||||||
|
proxy: AppConfig::get().proxy_ip.clone(),
|
||||||
|
}))
|
||||||
|
// Server controller
|
||||||
|
.route("/robots.txt", web::get().to(server_controller::robots_txt))
|
||||||
|
.route(
|
||||||
|
"/api/server/config",
|
||||||
|
web::get().to(server_controller::config),
|
||||||
|
)
|
||||||
|
// Auth controller
|
||||||
|
.route(
|
||||||
|
"/api/auth/start_oidc",
|
||||||
|
web::get().to(auth_controller::start_oidc),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/api/auth/finish_oidc",
|
||||||
|
web::post().to(auth_controller::finish_oidc),
|
||||||
|
)
|
||||||
|
.route("/api/auth/info", web::get().to(auth_controller::auth_info))
|
||||||
|
.route(
|
||||||
|
"/api/auth/sign_out",
|
||||||
|
web::get().to(auth_controller::sign_out),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.workers(4)
|
||||||
|
.bind(&AppConfig::get().listen_address)?
|
||||||
|
.run()
|
||||||
|
.await
|
||||||
|
}
|
||||||
168
matrixgw_backend/src/users.rs
Normal file
168
matrixgw_backend/src/users.rs
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
use crate::app_config::AppConfig;
|
||||||
|
use crate::utils::time_utils::time_secs;
|
||||||
|
use jwt_simple::reexports::serde_json;
|
||||||
|
use std::cmp::min;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// Matrix Gateway user errors
|
||||||
|
#[derive(thiserror::Error, Debug)]
|
||||||
|
enum MatrixGWUserError {
|
||||||
|
#[error("Failed to load user metadata: {0}")]
|
||||||
|
LoadUserMetadata(std::io::Error),
|
||||||
|
#[error("Failed to decode user metadata: {0}")]
|
||||||
|
DecodeUserMetadata(serde_json::Error),
|
||||||
|
#[error("Failed to save user metadata: {0}")]
|
||||||
|
SaveUserMetadata(std::io::Error),
|
||||||
|
#[error("Failed to delete API token: {0}")]
|
||||||
|
DeleteToken(std::io::Error),
|
||||||
|
#[error("Failed to load API token: {0}")]
|
||||||
|
LoadApiToken(std::io::Error),
|
||||||
|
#[error("Failed to decode API token: {0}")]
|
||||||
|
DecodeApiToken(serde_json::Error),
|
||||||
|
#[error("API Token does not exists!")]
|
||||||
|
ApiTokenDoesNotExists,
|
||||||
|
#[error("Failed to save API token: {0}")]
|
||||||
|
SaveAPIToken(std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct UserEmail(pub String);
|
||||||
|
|
||||||
|
impl UserEmail {
|
||||||
|
pub fn is_valid(&self) -> bool {
|
||||||
|
mailchecker::is_valid(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
||||||
|
pub struct APITokenID(pub uuid::Uuid);
|
||||||
|
|
||||||
|
impl Default for APITokenID {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(uuid::Uuid::new_v4())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromStr for APITokenID {
|
||||||
|
type Err = uuid::Error;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
Ok(Self(uuid::Uuid::from_str(s)?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct User {
|
||||||
|
pub email: UserEmail,
|
||||||
|
pub name: String,
|
||||||
|
pub time_create: u64,
|
||||||
|
pub last_login: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
/// Get a user by its mail
|
||||||
|
pub async fn get_by_mail(mail: &UserEmail) -> anyhow::Result<Self> {
|
||||||
|
let path = AppConfig::get().user_metadata_file_path(mail);
|
||||||
|
let data = std::fs::read_to_string(path).map_err(MatrixGWUserError::LoadUserMetadata)?;
|
||||||
|
Ok(serde_json::from_str(&data).map_err(MatrixGWUserError::DecodeUserMetadata)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update user metadata on disk
|
||||||
|
pub async fn write(&self) -> anyhow::Result<()> {
|
||||||
|
let path = AppConfig::get().user_metadata_file_path(&self.email);
|
||||||
|
std::fs::write(&path, serde_json::to_string(&self)?)
|
||||||
|
.map_err(MatrixGWUserError::SaveUserMetadata)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create or update user information
|
||||||
|
pub async fn create_or_update_user(mail: &UserEmail, name: &str) -> anyhow::Result<User> {
|
||||||
|
let storage_dir = AppConfig::get().user_directory(mail);
|
||||||
|
let mut user = if !storage_dir.exists() {
|
||||||
|
std::fs::create_dir_all(storage_dir)?;
|
||||||
|
|
||||||
|
User {
|
||||||
|
email: mail.clone(),
|
||||||
|
name: name.to_string(),
|
||||||
|
time_create: time_secs(),
|
||||||
|
last_login: time_secs(),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Self::get_by_mail(mail).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update some user information
|
||||||
|
user.name = name.to_string();
|
||||||
|
user.last_login = time_secs();
|
||||||
|
user.write().await?;
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single API client information
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
||||||
|
pub struct APIToken {
|
||||||
|
/// Token unique ID
|
||||||
|
pub id: APITokenID,
|
||||||
|
|
||||||
|
/// Client description
|
||||||
|
pub description: String,
|
||||||
|
|
||||||
|
/// Restricted API network for token
|
||||||
|
pub network: Option<ipnet::IpNet>,
|
||||||
|
|
||||||
|
/// Client secret
|
||||||
|
pub secret: String,
|
||||||
|
|
||||||
|
/// Client creation time
|
||||||
|
pub created: u64,
|
||||||
|
|
||||||
|
/// Client last usage time
|
||||||
|
pub last_used: u64,
|
||||||
|
|
||||||
|
/// Read only access
|
||||||
|
pub read_only: bool,
|
||||||
|
|
||||||
|
/// Token max inactivity
|
||||||
|
pub max_inactivity: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl APIToken {
|
||||||
|
/// Get a token information
|
||||||
|
pub async fn load(email: &UserEmail, id: &APITokenID) -> anyhow::Result<Self> {
|
||||||
|
let token_file = AppConfig::get().user_api_token_metadata_file(email, id);
|
||||||
|
match token_file.exists() {
|
||||||
|
true => Ok(serde_json::from_str::<Self>(
|
||||||
|
&std::fs::read_to_string(&token_file).map_err(MatrixGWUserError::LoadApiToken)?,
|
||||||
|
)
|
||||||
|
.map_err(MatrixGWUserError::DecodeApiToken)?),
|
||||||
|
false => Err(MatrixGWUserError::ApiTokenDoesNotExists.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write this token information
|
||||||
|
pub async fn write(&self, mail: &UserEmail) -> anyhow::Result<()> {
|
||||||
|
let path = AppConfig::get().user_api_token_metadata_file(mail, &self.id);
|
||||||
|
std::fs::write(&path, serde_json::to_string(&self)?)
|
||||||
|
.map_err(MatrixGWUserError::SaveAPIToken)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete this token
|
||||||
|
pub async fn delete(self, email: &UserEmail) -> anyhow::Result<()> {
|
||||||
|
let token_file = AppConfig::get().user_api_token_metadata_file(email, &self.id);
|
||||||
|
std::fs::remove_file(&token_file).map_err(MatrixGWUserError::DeleteToken)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shall_update_time_used(&self) -> bool {
|
||||||
|
let refresh_interval = min(600, self.max_inactivity / 10);
|
||||||
|
|
||||||
|
(self.last_used) < time_secs() - refresh_interval
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_expired(&self) -> bool {
|
||||||
|
(self.last_used + self.max_inactivity) < time_secs()
|
||||||
|
}
|
||||||
|
}
|
||||||
6
matrixgw_backend/src/utils/crypt_utils.rs
Normal file
6
matrixgw_backend/src/utils/crypt_utils.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// Compute SHA256sum of a given string
|
||||||
|
pub fn sha256str(input: &str) -> String {
|
||||||
|
hex::encode(Sha256::digest(input.as_bytes()))
|
||||||
|
}
|
||||||
3
matrixgw_backend/src/utils/mod.rs
Normal file
3
matrixgw_backend/src/utils/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod crypt_utils;
|
||||||
|
pub mod rand_utils;
|
||||||
|
pub mod time_utils;
|
||||||
6
matrixgw_backend/src/utils/rand_utils.rs
Normal file
6
matrixgw_backend/src/utils/rand_utils.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
use rand::distr::{Alphanumeric, SampleString};
|
||||||
|
|
||||||
|
/// Generate a random string of a given length
|
||||||
|
pub fn rand_string(len: usize) -> String {
|
||||||
|
Alphanumeric.sample_string(&mut rand::rng(), len)
|
||||||
|
}
|
||||||
9
matrixgw_backend/src/utils/time_utils.rs
Normal file
9
matrixgw_backend/src/utils/time_utils.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
/// Get the current time since epoch
|
||||||
|
pub fn time_secs() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs()
|
||||||
|
}
|
||||||
1
matrixgw_frontend/.env
Normal file
1
matrixgw_frontend/.env
Normal file
@@ -0,0 +1 @@
|
|||||||
|
VITE_APP_BACKEND=http://localhost:8000/api
|
||||||
1
matrixgw_frontend/.env.production
Normal file
1
matrixgw_frontend/.env.production
Normal file
@@ -0,0 +1 @@
|
|||||||
|
VITE_APP_BACKEND=/api
|
||||||
24
matrixgw_frontend/.gitignore
vendored
Normal file
24
matrixgw_frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
73
matrixgw_frontend/README.md
Normal file
73
matrixgw_frontend/README.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## React Compiler
|
||||||
|
|
||||||
|
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
23
matrixgw_frontend/eslint.config.js
Normal file
23
matrixgw_frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs['recommended-latest'],
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
Before Width: | Height: | Size: 4.6 KiB After Width: | Height: | Size: 4.6 KiB |
13
matrixgw_frontend/index.html
Normal file
13
matrixgw_frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>MatrixGW</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
4031
matrixgw_frontend/package-lock.json
generated
Normal file
4031
matrixgw_frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
41
matrixgw_frontend/package.json
Normal file
41
matrixgw_frontend/package.json
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"name": "matrixgw_frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@emotion/react": "^11.14.0",
|
||||||
|
"@emotion/styled": "^11.14.1",
|
||||||
|
"@fontsource/roboto": "^5.2.8",
|
||||||
|
"@mdi/js": "^7.4.47",
|
||||||
|
"@mdi/react": "^1.6.1",
|
||||||
|
"@mui/icons-material": "^7.3.5",
|
||||||
|
"@mui/material": "^7.3.5",
|
||||||
|
"react": "^19.1.1",
|
||||||
|
"react-dom": "^19.1.1",
|
||||||
|
"react-router": "^7.9.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.36.0",
|
||||||
|
"@types/node": "^24.6.0",
|
||||||
|
"@types/react": "^19.1.16",
|
||||||
|
"@types/react-dom": "^19.1.9",
|
||||||
|
"@vitejs/plugin-react": "^5.0.4",
|
||||||
|
"eslint": "^9.36.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.22",
|
||||||
|
"globals": "^16.4.0",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"typescript-eslint": "^8.45.0",
|
||||||
|
"vite": "npm:rolldown-vite@7.1.14"
|
||||||
|
},
|
||||||
|
"overrides": {
|
||||||
|
"vite": "npm:rolldown-vite@7.1.14"
|
||||||
|
}
|
||||||
|
}
|
||||||
1
matrixgw_frontend/public/vite.svg
Normal file
1
matrixgw_frontend/public/vite.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
61
matrixgw_frontend/src/App.tsx
Normal file
61
matrixgw_frontend/src/App.tsx
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import React from "react";
|
||||||
|
import {
|
||||||
|
createBrowserRouter,
|
||||||
|
createRoutesFromElements,
|
||||||
|
Route,
|
||||||
|
RouterProvider,
|
||||||
|
} from "react-router";
|
||||||
|
import { AuthApi } from "./api/AuthApi";
|
||||||
|
import { ServerApi } from "./api/ServerApi";
|
||||||
|
import { LoginRoute } from "./routes/auth/LoginRoute";
|
||||||
|
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
|
||||||
|
import { HomeRoute } from "./routes/HomeRoute";
|
||||||
|
import { NotFoundRoute } from "./routes/NotFoundRoute";
|
||||||
|
import { BaseLoginPage } from "./widgets/auth/BaseLoginPage";
|
||||||
|
import BaseAuthenticatedPage from "./widgets/dashboard/BaseAuthenticatedPage";
|
||||||
|
|
||||||
|
interface AuthContext {
|
||||||
|
signedIn: boolean;
|
||||||
|
setSignedIn: (signedIn: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContextK = React.createContext<AuthContext | null>(null);
|
||||||
|
|
||||||
|
export function App(): React.ReactElement {
|
||||||
|
const [signedIn, setSignedIn] = React.useState(AuthApi.SignedIn);
|
||||||
|
|
||||||
|
const context: AuthContext = {
|
||||||
|
signedIn: signedIn,
|
||||||
|
setSignedIn: (s) => {
|
||||||
|
setSignedIn(s);
|
||||||
|
location.reload();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const router = createBrowserRouter(
|
||||||
|
createRoutesFromElements(
|
||||||
|
signedIn || ServerApi.Config.auth_disabled ? (
|
||||||
|
<Route path="*" element={<BaseAuthenticatedPage />}>
|
||||||
|
<Route path="" element={<HomeRoute />} />
|
||||||
|
<Route path="*" element={<NotFoundRoute />} />
|
||||||
|
</Route>
|
||||||
|
) : (
|
||||||
|
<Route path="*" element={<BaseLoginPage />}>
|
||||||
|
<Route path="" element={<LoginRoute />} />
|
||||||
|
<Route path="oidc_cb" element={<OIDCCbRoute />} />
|
||||||
|
<Route path="*" element={<NotFoundRoute />} />
|
||||||
|
</Route>
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContextK value={context}>
|
||||||
|
<RouterProvider router={router} />
|
||||||
|
</AuthContextK>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth(): AuthContext {
|
||||||
|
return React.use(AuthContextK)!;
|
||||||
|
}
|
||||||
192
matrixgw_frontend/src/api/ApiClient.ts
Normal file
192
matrixgw_frontend/src/api/ApiClient.ts
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
import { AuthApi } from "./AuthApi";
|
||||||
|
|
||||||
|
interface RequestParams {
|
||||||
|
uri: string;
|
||||||
|
method: "GET" | "POST" | "DELETE" | "PATCH" | "PUT";
|
||||||
|
allowFail?: boolean;
|
||||||
|
jsonData?: any;
|
||||||
|
formData?: FormData;
|
||||||
|
upProgress?: (progress: number) => void;
|
||||||
|
downProgress?: (e: { progress: number; total: number }) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface APIResponse {
|
||||||
|
data: any;
|
||||||
|
status: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
public code: number;
|
||||||
|
public data: number;
|
||||||
|
constructor(message: string, code: number, data: any) {
|
||||||
|
super(`HTTP status: ${code}\nMessage: ${message}\nData=${data}`);
|
||||||
|
this.code = code;
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class APIClient {
|
||||||
|
/**
|
||||||
|
* Get backend URL
|
||||||
|
*/
|
||||||
|
static backendURL(): string {
|
||||||
|
const URL = import.meta.env.VITE_APP_BACKEND ?? "";
|
||||||
|
if (URL.length === 0) throw new Error("Backend URL undefined!");
|
||||||
|
return URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the full URL at which the backend can be contacted
|
||||||
|
*/
|
||||||
|
static ActualBackendURL(): string {
|
||||||
|
const backendURL = this.backendURL();
|
||||||
|
if (backendURL.startsWith("/")) return `${location.origin}${backendURL}`;
|
||||||
|
else return backendURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check out whether the backend is accessed through
|
||||||
|
* HTTPS or not
|
||||||
|
*/
|
||||||
|
static IsBackendSecure(): boolean {
|
||||||
|
return this.ActualBackendURL().startsWith("https");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform a request on the backend
|
||||||
|
*/
|
||||||
|
static async exec(args: RequestParams): Promise<APIResponse> {
|
||||||
|
let body: string | undefined | FormData = undefined;
|
||||||
|
const headers: any = {};
|
||||||
|
|
||||||
|
// JSON request
|
||||||
|
if (args.jsonData) {
|
||||||
|
headers["Content-Type"] = "application/json";
|
||||||
|
body = JSON.stringify(args.jsonData);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Form data request
|
||||||
|
else if (args.formData) {
|
||||||
|
body = args.formData;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = this.backendURL() + args.uri;
|
||||||
|
|
||||||
|
let data;
|
||||||
|
let status: number;
|
||||||
|
|
||||||
|
// Make the request with XMLHttpRequest
|
||||||
|
if (args.upProgress) {
|
||||||
|
const res: XMLHttpRequest = await new Promise((resolve, reject) => {
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
xhr.upload.addEventListener("progress", (e) => {
|
||||||
|
args.upProgress!(e.loaded / e.total);
|
||||||
|
});
|
||||||
|
xhr.addEventListener("load", () => {
|
||||||
|
resolve(xhr);
|
||||||
|
});
|
||||||
|
xhr.addEventListener("error", () => {
|
||||||
|
reject(new Error("File upload failed"));
|
||||||
|
});
|
||||||
|
xhr.addEventListener("abort", () => {
|
||||||
|
reject(new Error("File upload aborted"));
|
||||||
|
});
|
||||||
|
xhr.addEventListener("timeout", () => {
|
||||||
|
reject(new Error("File upload timeout"));
|
||||||
|
});
|
||||||
|
xhr.open(args.method, url, true);
|
||||||
|
xhr.withCredentials = true;
|
||||||
|
for (const key in headers) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(headers, key))
|
||||||
|
xhr.setRequestHeader(key, headers[key]);
|
||||||
|
}
|
||||||
|
xhr.send(body);
|
||||||
|
});
|
||||||
|
|
||||||
|
status = res.status;
|
||||||
|
if (res.responseType === "json") data = JSON.parse(res.responseText);
|
||||||
|
else data = res.response;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make the request with fetch
|
||||||
|
else {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: args.method,
|
||||||
|
body: body,
|
||||||
|
headers: headers,
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Process response
|
||||||
|
// JSON response
|
||||||
|
if (res.headers.get("content-type") === "application/json")
|
||||||
|
data = await res.json();
|
||||||
|
// Text / XML response
|
||||||
|
else if (
|
||||||
|
["application/xml", "text/plain"].includes(
|
||||||
|
res.headers.get("content-type") ?? ""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
data = await res.text();
|
||||||
|
// Binary file, tracking download progress
|
||||||
|
else if (res.body !== null && args.downProgress) {
|
||||||
|
// Track download progress
|
||||||
|
const contentEncoding = res.headers.get("content-encoding");
|
||||||
|
const contentLength = contentEncoding
|
||||||
|
? null
|
||||||
|
: res.headers.get("content-length");
|
||||||
|
|
||||||
|
const total = parseInt(contentLength ?? "0", 10);
|
||||||
|
let loaded = 0;
|
||||||
|
|
||||||
|
const resInt = new Response(
|
||||||
|
new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
|
||||||
|
const read = async () => {
|
||||||
|
try {
|
||||||
|
const ret = await reader.read();
|
||||||
|
if (ret.done) {
|
||||||
|
controller.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loaded += ret.value.byteLength;
|
||||||
|
args.downProgress!({ progress: loaded, total });
|
||||||
|
controller.enqueue(ret.value);
|
||||||
|
read();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
controller.error(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
read();
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
data = await resInt.blob();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not track progress (binary file)
|
||||||
|
else data = await res.blob();
|
||||||
|
|
||||||
|
status = res.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle expired tokens
|
||||||
|
if (status === 412) {
|
||||||
|
AuthApi.UnsetAuthenticated();
|
||||||
|
window.location.href = "/";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!args.allowFail && (status < 200 || status > 299))
|
||||||
|
throw new ApiError("Request failed!", status, data);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: data,
|
||||||
|
status: status,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
87
matrixgw_frontend/src/api/AuthApi.ts
Normal file
87
matrixgw_frontend/src/api/AuthApi.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export interface AuthInfo {
|
||||||
|
id: number;
|
||||||
|
time_create: number;
|
||||||
|
time_update: number;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TokenStateKey = "auth-state";
|
||||||
|
|
||||||
|
export class AuthApi {
|
||||||
|
/**
|
||||||
|
* Check out whether user is signed in or not
|
||||||
|
*/
|
||||||
|
static get SignedIn(): boolean {
|
||||||
|
return localStorage.getItem(TokenStateKey) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark user as authenticated
|
||||||
|
*/
|
||||||
|
static SetAuthenticated() {
|
||||||
|
localStorage.setItem(TokenStateKey, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un-mark user as authenticated
|
||||||
|
*/
|
||||||
|
static UnsetAuthenticated() {
|
||||||
|
localStorage.removeItem(TokenStateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start OpenID login
|
||||||
|
*/
|
||||||
|
static async StartOpenIDLogin(): Promise<{ url: string }> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: "/auth/start_oidc",
|
||||||
|
method: "GET",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finish OpenID login
|
||||||
|
*/
|
||||||
|
static async FinishOpenIDLogin(code: string, state: string): Promise<void> {
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: "/auth/finish_oidc",
|
||||||
|
method: "POST",
|
||||||
|
jsonData: { code: code, state: state },
|
||||||
|
});
|
||||||
|
|
||||||
|
this.SetAuthenticated();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get auth information
|
||||||
|
*/
|
||||||
|
static async GetAuthInfo(): Promise<AuthInfo> {
|
||||||
|
return (
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: "/auth/info",
|
||||||
|
method: "GET",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign out
|
||||||
|
*/
|
||||||
|
static async SignOut(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: "/auth/sign_out",
|
||||||
|
method: "GET",
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to sign out user on API!", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.UnsetAuthenticated();
|
||||||
|
}
|
||||||
|
}
|
||||||
48
matrixgw_frontend/src/api/ServerApi.ts
Normal file
48
matrixgw_frontend/src/api/ServerApi.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { APIClient } from "./ApiClient";
|
||||||
|
|
||||||
|
export interface ServerConfig {
|
||||||
|
auth_disabled: boolean;
|
||||||
|
oidc_provider_name: string;
|
||||||
|
constraints: ServerConstraints;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccountType {
|
||||||
|
label: string;
|
||||||
|
code: string;
|
||||||
|
icon: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerConstraints {
|
||||||
|
token_name: LenConstraint;
|
||||||
|
token_ip_net: LenConstraint;
|
||||||
|
token_max_inactivity: LenConstraint;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LenConstraint {
|
||||||
|
min: number;
|
||||||
|
max: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
let config: ServerConfig | null = null;
|
||||||
|
|
||||||
|
export class ServerApi {
|
||||||
|
/**
|
||||||
|
* Get server configuration
|
||||||
|
*/
|
||||||
|
static async LoadConfig(): Promise<void> {
|
||||||
|
config = (
|
||||||
|
await APIClient.exec({
|
||||||
|
uri: "/server/config",
|
||||||
|
method: "GET",
|
||||||
|
})
|
||||||
|
).data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get cached configuration
|
||||||
|
*/
|
||||||
|
static get Config(): ServerConfig {
|
||||||
|
if (config === null) throw new Error("Missing configuration!");
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React, { type PropsWithChildren } from "react";
|
||||||
|
|
||||||
|
type AlertContext = (message: string, title?: string) => Promise<void>;
|
||||||
|
|
||||||
|
const AlertContextK = React.createContext<AlertContext | null>(null);
|
||||||
|
|
||||||
|
export function AlertDialogProvider(p: PropsWithChildren): React.ReactElement {
|
||||||
|
const [open, setOpen] = React.useState(false);
|
||||||
|
|
||||||
|
const [title, setTitle] = React.useState<string | undefined>(undefined);
|
||||||
|
const [message, setMessage] = React.useState("");
|
||||||
|
|
||||||
|
const cb = React.useRef<null | (() => void)>(null);
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setOpen(false);
|
||||||
|
|
||||||
|
if (cb.current !== null) cb.current();
|
||||||
|
cb.current = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const hook: AlertContext = (message, title) => {
|
||||||
|
setTitle(title);
|
||||||
|
setMessage(message);
|
||||||
|
setOpen(true);
|
||||||
|
|
||||||
|
return new Promise((res) => {
|
||||||
|
cb.current = res;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<AlertContextK value={hook}>{p.children}</AlertContextK>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={handleClose}
|
||||||
|
aria-labelledby="alert-dialog-title"
|
||||||
|
aria-describedby="alert-dialog-description"
|
||||||
|
>
|
||||||
|
{title && <DialogTitle id="alert-dialog-title">{title}</DialogTitle>}
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id="alert-dialog-description">
|
||||||
|
{message}
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button onClick={handleClose} autoFocus>
|
||||||
|
Ok
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAlert(): AlertContext {
|
||||||
|
return React.use(AlertContextK)!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Dialog,
|
||||||
|
DialogActions,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React, { type PropsWithChildren } from "react";
|
||||||
|
|
||||||
|
type ConfirmContext = (
|
||||||
|
message: string | React.ReactElement,
|
||||||
|
title?: string,
|
||||||
|
confirmButton?: string
|
||||||
|
) => Promise<boolean>;
|
||||||
|
|
||||||
|
const ConfirmContextK = React.createContext<ConfirmContext | null>(null);
|
||||||
|
|
||||||
|
export function ConfirmDialogProvider(
|
||||||
|
p: PropsWithChildren
|
||||||
|
): React.ReactElement {
|
||||||
|
const [open, setOpen] = React.useState(false);
|
||||||
|
|
||||||
|
const [title, setTitle] = React.useState<string | undefined>(undefined);
|
||||||
|
const [message, setMessage] = React.useState<string | React.ReactElement>("");
|
||||||
|
const [confirmButton, setConfirmButton] = React.useState<string | undefined>(
|
||||||
|
undefined
|
||||||
|
);
|
||||||
|
|
||||||
|
const cb = React.useRef<null | ((a: boolean) => void)>(null);
|
||||||
|
|
||||||
|
const handleClose = (confirm: boolean) => {
|
||||||
|
setOpen(false);
|
||||||
|
|
||||||
|
if (cb.current !== null) cb.current(confirm);
|
||||||
|
cb.current = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const hook: ConfirmContext = (message, title, confirmButton) => {
|
||||||
|
setTitle(title);
|
||||||
|
setMessage(message);
|
||||||
|
setConfirmButton(confirmButton);
|
||||||
|
setOpen(true);
|
||||||
|
|
||||||
|
return new Promise((res) => {
|
||||||
|
cb.current = res;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const keyUp = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.code === "Enter") handleClose(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<ConfirmContextK value={hook}>{p.children}</ConfirmContextK>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onClose={() => {
|
||||||
|
handleClose(false);
|
||||||
|
}}
|
||||||
|
aria-labelledby="alert-dialog-title"
|
||||||
|
aria-describedby="alert-dialog-description"
|
||||||
|
onKeyUp={keyUp}
|
||||||
|
>
|
||||||
|
{title && <DialogTitle id="alert-dialog-title">{title}</DialogTitle>}
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText id="alert-dialog-description">
|
||||||
|
{message}
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
<DialogActions>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
handleClose(false);
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
handleClose(true);
|
||||||
|
}}
|
||||||
|
color="error"
|
||||||
|
>
|
||||||
|
{confirmButton ?? "Confirm"}
|
||||||
|
</Button>
|
||||||
|
</DialogActions>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useConfirm(): ConfirmContext {
|
||||||
|
return React.use(ConfirmContextK)!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import {
|
||||||
|
CircularProgress,
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogContentText,
|
||||||
|
} from "@mui/material";
|
||||||
|
import React, { type PropsWithChildren } from "react";
|
||||||
|
|
||||||
|
interface LoadingMessageContext {
|
||||||
|
show: (message: string) => void;
|
||||||
|
hide: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LoadingMessageContextK =
|
||||||
|
React.createContext<LoadingMessageContext | null>(null);
|
||||||
|
|
||||||
|
export function LoadingMessageProvider(
|
||||||
|
p: PropsWithChildren
|
||||||
|
): React.ReactElement {
|
||||||
|
const [open, setOpen] = React.useState(false);
|
||||||
|
|
||||||
|
const [message, setMessage] = React.useState("");
|
||||||
|
|
||||||
|
const hook: LoadingMessageContext = {
|
||||||
|
show(message) {
|
||||||
|
setMessage(message);
|
||||||
|
setOpen(true);
|
||||||
|
},
|
||||||
|
hide() {
|
||||||
|
setMessage("");
|
||||||
|
setOpen(false);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<LoadingMessageContextK value={hook}>{p.children}</LoadingMessageContextK>
|
||||||
|
|
||||||
|
<Dialog open={open}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogContentText>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CircularProgress style={{ marginRight: "15px" }} />
|
||||||
|
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
</DialogContentText>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLoadingMessage(): LoadingMessageContext {
|
||||||
|
return React.use(LoadingMessageContextK)!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { Snackbar } from "@mui/material";
|
||||||
|
|
||||||
|
import React, { type PropsWithChildren } from "react";
|
||||||
|
|
||||||
|
type SnackbarContext = (message: string, duration?: number) => void;
|
||||||
|
|
||||||
|
const SnackbarContextK = React.createContext<SnackbarContext | null>(null);
|
||||||
|
|
||||||
|
export function SnackbarProvider(p: PropsWithChildren): React.ReactElement {
|
||||||
|
const [open, setOpen] = React.useState(false);
|
||||||
|
|
||||||
|
const [message, setMessage] = React.useState("");
|
||||||
|
const [duration, setDuration] = React.useState(0);
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const hook: SnackbarContext = (message, duration) => {
|
||||||
|
setMessage(message);
|
||||||
|
setDuration(duration ?? 6000);
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<SnackbarContextK value={hook}>{p.children}</SnackbarContextK>
|
||||||
|
|
||||||
|
<Snackbar
|
||||||
|
open={open}
|
||||||
|
autoHideDuration={duration}
|
||||||
|
onClose={handleClose}
|
||||||
|
message={message}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSnackbar(): SnackbarContext {
|
||||||
|
return React.use(SnackbarContextK)!;
|
||||||
|
}
|
||||||
9
matrixgw_frontend/src/index.css
Normal file
9
matrixgw_frontend/src/index.css
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
#root {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
41
matrixgw_frontend/src/main.tsx
Normal file
41
matrixgw_frontend/src/main.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import "@fontsource/roboto/300.css";
|
||||||
|
import "@fontsource/roboto/400.css";
|
||||||
|
import "@fontsource/roboto/500.css";
|
||||||
|
import "@fontsource/roboto/700.css";
|
||||||
|
|
||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import "./index.css";
|
||||||
|
import { App } from "./App";
|
||||||
|
import { AlertDialogProvider } from "./hooks/contexts_provider/AlertDialogProvider";
|
||||||
|
import { ConfirmDialogProvider } from "./hooks/contexts_provider/ConfirmDialogProvider";
|
||||||
|
import { SnackbarProvider } from "./hooks/contexts_provider/SnackbarProvider";
|
||||||
|
import { LoadingMessageProvider } from "./hooks/contexts_provider/LoadingMessageProvider";
|
||||||
|
import { AsyncWidget } from "./widgets/AsyncWidget";
|
||||||
|
import { ServerApi } from "./api/ServerApi";
|
||||||
|
import { AppTheme } from "./theme/AppTheme";
|
||||||
|
import { CssBaseline } from "@mui/material";
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<AppTheme>
|
||||||
|
<CssBaseline enableColorScheme />
|
||||||
|
<AlertDialogProvider>
|
||||||
|
<ConfirmDialogProvider>
|
||||||
|
<SnackbarProvider>
|
||||||
|
<LoadingMessageProvider>
|
||||||
|
<AsyncWidget
|
||||||
|
loadKey={1}
|
||||||
|
load={async () => {
|
||||||
|
await ServerApi.LoadConfig();
|
||||||
|
}}
|
||||||
|
errMsg="Failed to load static server configuration!"
|
||||||
|
build={() => <App />}
|
||||||
|
/>
|
||||||
|
</LoadingMessageProvider>
|
||||||
|
</SnackbarProvider>
|
||||||
|
</ConfirmDialogProvider>
|
||||||
|
</AlertDialogProvider>
|
||||||
|
</AppTheme>
|
||||||
|
</StrictMode>
|
||||||
|
);
|
||||||
3
matrixgw_frontend/src/routes/HomeRoute.tsx
Normal file
3
matrixgw_frontend/src/routes/HomeRoute.tsx
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export function HomeRoute(): React.ReactElement {
|
||||||
|
return <p>Todo home route</p>;
|
||||||
|
}
|
||||||
23
matrixgw_frontend/src/routes/NotFoundRoute.tsx
Normal file
23
matrixgw_frontend/src/routes/NotFoundRoute.tsx
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { Button } from "@mui/material";
|
||||||
|
import { RouterLink } from "../widgets/RouterLink";
|
||||||
|
|
||||||
|
export function NotFoundRoute(): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
textAlign: "center",
|
||||||
|
flex: "1",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h1>404 Not found</h1>
|
||||||
|
<p>The page you requested was not found!</p>
|
||||||
|
<RouterLink to="/">
|
||||||
|
<Button>Go back home</Button>
|
||||||
|
</RouterLink>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
50
matrixgw_frontend/src/routes/auth/LoginRoute.tsx
Normal file
50
matrixgw_frontend/src/routes/auth/LoginRoute.tsx
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { Alert, Box, Button, CircularProgress } from "@mui/material";
|
||||||
|
import Icon from "@mdi/react";
|
||||||
|
import { mdiOpenid } from "@mdi/js";
|
||||||
|
import { ServerApi } from "../../api/ServerApi";
|
||||||
|
import React from "react";
|
||||||
|
import { AuthApi } from "../../api/AuthApi";
|
||||||
|
|
||||||
|
export function LoginRoute(): React.ReactElement {
|
||||||
|
const [loading, setLoading] = React.useState(false);
|
||||||
|
const [error, setError] = React.useState<string | null>(null);
|
||||||
|
|
||||||
|
const authWithOpenID = async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
const res = await AuthApi.StartOpenIDLogin();
|
||||||
|
window.location.href = res.url;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setError("Failed to initialize OpenID login");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading)
|
||||||
|
return (
|
||||||
|
<div style={{ textAlign: "center" }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{error && (
|
||||||
|
<Alert style={{ width: "100%" }} severity="error">
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||||
|
<Button
|
||||||
|
fullWidth
|
||||||
|
variant="outlined"
|
||||||
|
onClick={authWithOpenID}
|
||||||
|
startIcon={<Icon path={mdiOpenid} size={1} />}
|
||||||
|
>
|
||||||
|
Sign in with {ServerApi.Config.oidc_provider_name}
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
53
matrixgw_frontend/src/routes/auth/OIDCCbRoute.tsx
Normal file
53
matrixgw_frontend/src/routes/auth/OIDCCbRoute.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { CircularProgress } from "@mui/material";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useNavigate, useSearchParams } from "react-router";
|
||||||
|
import { AuthApi } from "../../api/AuthApi";
|
||||||
|
import { useAuth } from "../../App";
|
||||||
|
import { AuthSingleMessage } from "../../widgets/auth/AuthSingleMessage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OpenID login callback route
|
||||||
|
*/
|
||||||
|
export function OIDCCbRoute(): React.ReactElement {
|
||||||
|
const auth = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [error, setError] = useState(false);
|
||||||
|
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const code = searchParams.get("code");
|
||||||
|
const state = searchParams.get("state");
|
||||||
|
|
||||||
|
const count = useRef("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const load = async () => {
|
||||||
|
try {
|
||||||
|
if (count.current === code) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
count.current = code!;
|
||||||
|
|
||||||
|
await AuthApi.FinishOpenIDLogin(code!, state!);
|
||||||
|
navigate("/");
|
||||||
|
auth.setSignedIn(true);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setError(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
load();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error)
|
||||||
|
return (
|
||||||
|
<AuthSingleMessage message="Failed to finalize OpenID authentication!" />
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ textAlign: "center" }}>
|
||||||
|
<CircularProgress />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
46
matrixgw_frontend/src/theme/AppTheme.tsx
Normal file
46
matrixgw_frontend/src/theme/AppTheme.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { ThemeProvider, createTheme } from "@mui/material/styles";
|
||||||
|
import type { ThemeOptions } from "@mui/material/styles";
|
||||||
|
import { inputsCustomizations } from "./customizations/inputs";
|
||||||
|
import { dataDisplayCustomizations } from "./customizations/dataDisplay";
|
||||||
|
import { feedbackCustomizations } from "./customizations/feedback";
|
||||||
|
import { navigationCustomizations } from "./customizations/navigation";
|
||||||
|
import { surfacesCustomizations } from "./customizations/surfaces";
|
||||||
|
import { colorSchemes, typography, shadows, shape } from "./themePrimitives";
|
||||||
|
|
||||||
|
interface AppThemeProps {
|
||||||
|
themeComponents?: ThemeOptions["components"];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppTheme(
|
||||||
|
props: React.PropsWithChildren<AppThemeProps>
|
||||||
|
): React.ReactElement {
|
||||||
|
const { children, themeComponents } = props;
|
||||||
|
const theme = React.useMemo(() => {
|
||||||
|
return createTheme({
|
||||||
|
// For more details about CSS variables configuration, see https://mui.com/material-ui/customization/css-theme-variables/configuration/
|
||||||
|
cssVariables: {
|
||||||
|
colorSchemeSelector: "data-mui-color-scheme",
|
||||||
|
cssVarPrefix: "template",
|
||||||
|
},
|
||||||
|
colorSchemes, // Recently added in v6 for building light & dark mode app, see https://mui.com/material-ui/customization/palette/#color-schemes
|
||||||
|
typography,
|
||||||
|
shadows,
|
||||||
|
shape,
|
||||||
|
components: {
|
||||||
|
...inputsCustomizations,
|
||||||
|
...dataDisplayCustomizations,
|
||||||
|
...feedbackCustomizations,
|
||||||
|
...navigationCustomizations,
|
||||||
|
...surfacesCustomizations,
|
||||||
|
...themeComponents,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}, [themeComponents]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ThemeProvider theme={theme} disableTransitionOnChange>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
matrixgw_frontend/src/theme/README.md
Normal file
2
matrixgw_frontend/src/theme/README.md
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# Application Theme
|
||||||
|
Taken from https://github.com/mui/material-ui/tree/v7.3.4/docs/data/material/getting-started/templates/shared-theme
|
||||||
233
matrixgw_frontend/src/theme/customizations/dataDisplay.tsx
Normal file
233
matrixgw_frontend/src/theme/customizations/dataDisplay.tsx
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
import { buttonBaseClasses } from "@mui/material/ButtonBase";
|
||||||
|
import { chipClasses } from "@mui/material/Chip";
|
||||||
|
import { iconButtonClasses } from "@mui/material/IconButton";
|
||||||
|
import { alpha, type Components, type Theme } from "@mui/material/styles";
|
||||||
|
import { svgIconClasses } from "@mui/material/SvgIcon";
|
||||||
|
import { typographyClasses } from "@mui/material/Typography";
|
||||||
|
import { gray, green, red } from "../themePrimitives";
|
||||||
|
|
||||||
|
/* eslint-disable import/prefer-default-export */
|
||||||
|
export const dataDisplayCustomizations: Components<Theme> = {
|
||||||
|
MuiList: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
padding: "8px",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiListItem: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
[`& .${svgIconClasses.root}`]: {
|
||||||
|
width: "1rem",
|
||||||
|
height: "1rem",
|
||||||
|
color: (theme.vars || theme).palette.text.secondary,
|
||||||
|
},
|
||||||
|
[`& .${typographyClasses.root}`]: {
|
||||||
|
fontWeight: 500,
|
||||||
|
},
|
||||||
|
[`& .${buttonBaseClasses.root}`]: {
|
||||||
|
display: "flex",
|
||||||
|
gap: 8,
|
||||||
|
padding: "2px 8px",
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
opacity: 0.7,
|
||||||
|
"&.Mui-selected": {
|
||||||
|
opacity: 1,
|
||||||
|
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||||
|
[`& .${svgIconClasses.root}`]: {
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
},
|
||||||
|
"&:focus-visible": {
|
||||||
|
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||||
|
},
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: alpha(theme.palette.action.selected, 0.5),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"&:focus-visible": {
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiListItemText: {
|
||||||
|
styleOverrides: {
|
||||||
|
primary: ({ theme }) => ({
|
||||||
|
fontSize: theme.typography.body2.fontSize,
|
||||||
|
fontWeight: 500,
|
||||||
|
lineHeight: theme.typography.body2.lineHeight,
|
||||||
|
}),
|
||||||
|
secondary: ({ theme }) => ({
|
||||||
|
fontSize: theme.typography.caption.fontSize,
|
||||||
|
lineHeight: theme.typography.caption.lineHeight,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiListSubheader: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
padding: "4px 8px",
|
||||||
|
fontSize: theme.typography.caption.fontSize,
|
||||||
|
fontWeight: 500,
|
||||||
|
lineHeight: theme.typography.caption.lineHeight,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiListItemIcon: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
minWidth: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiChip: {
|
||||||
|
defaultProps: {
|
||||||
|
size: "small",
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
border: "1px solid",
|
||||||
|
borderRadius: "999px",
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "default",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
borderColor: gray[200],
|
||||||
|
backgroundColor: gray[100],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: gray[500],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: gray[500],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
borderColor: gray[700],
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: gray[300],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: gray[300],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "success",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
borderColor: green[200],
|
||||||
|
backgroundColor: green[50],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: green[500],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: green[500],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
borderColor: green[800],
|
||||||
|
backgroundColor: green[900],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: green[300],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: green[300],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "error",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
borderColor: red[100],
|
||||||
|
backgroundColor: red[50],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: red[500],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: red[500],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
borderColor: red[800],
|
||||||
|
backgroundColor: red[900],
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
color: red[200],
|
||||||
|
},
|
||||||
|
[`& .${chipClasses.icon}`]: {
|
||||||
|
color: red[300],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: { size: "small" },
|
||||||
|
style: {
|
||||||
|
maxHeight: 20,
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
fontSize: theme.typography.caption.fontSize,
|
||||||
|
},
|
||||||
|
[`& .${svgIconClasses.root}`]: {
|
||||||
|
fontSize: theme.typography.caption.fontSize,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: { size: "medium" },
|
||||||
|
style: {
|
||||||
|
[`& .${chipClasses.label}`]: {
|
||||||
|
fontSize: theme.typography.caption.fontSize,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiTablePagination: {
|
||||||
|
styleOverrides: {
|
||||||
|
actions: {
|
||||||
|
display: "flex",
|
||||||
|
gap: 8,
|
||||||
|
marginRight: 6,
|
||||||
|
[`& .${iconButtonClasses.root}`]: {
|
||||||
|
minWidth: 0,
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiIcon: {
|
||||||
|
defaultProps: {
|
||||||
|
fontSize: "small",
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
fontSize: "small",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
fontSize: "1rem",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
46
matrixgw_frontend/src/theme/customizations/feedback.tsx
Normal file
46
matrixgw_frontend/src/theme/customizations/feedback.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { type Theme, alpha, type Components } from "@mui/material/styles";
|
||||||
|
import { gray, orange } from "../themePrimitives";
|
||||||
|
|
||||||
|
/* eslint-disable import/prefer-default-export */
|
||||||
|
export const feedbackCustomizations: Components<Theme> = {
|
||||||
|
MuiAlert: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
borderRadius: 10,
|
||||||
|
backgroundColor: orange[100],
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
border: `1px solid ${alpha(orange[300], 0.5)}`,
|
||||||
|
"& .MuiAlert-icon": {
|
||||||
|
color: orange[500],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: `${alpha(orange[900], 0.5)}`,
|
||||||
|
border: `1px solid ${alpha(orange[800], 0.5)}`,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiDialog: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
"& .MuiDialog-paper": {
|
||||||
|
borderRadius: "10px",
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: (theme.vars || theme).palette.divider,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiLinearProgress: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
height: 8,
|
||||||
|
borderRadius: 8,
|
||||||
|
backgroundColor: gray[200],
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
452
matrixgw_frontend/src/theme/customizations/inputs.tsx
Normal file
452
matrixgw_frontend/src/theme/customizations/inputs.tsx
Normal file
@@ -0,0 +1,452 @@
|
|||||||
|
import { alpha, type Theme, type Components } from "@mui/material/styles";
|
||||||
|
import { outlinedInputClasses } from "@mui/material/OutlinedInput";
|
||||||
|
import { svgIconClasses } from "@mui/material/SvgIcon";
|
||||||
|
import { toggleButtonGroupClasses } from "@mui/material/ToggleButtonGroup";
|
||||||
|
import { toggleButtonClasses } from "@mui/material/ToggleButton";
|
||||||
|
import CheckBoxOutlineBlankRoundedIcon from "@mui/icons-material/CheckBoxOutlineBlankRounded";
|
||||||
|
import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
|
||||||
|
import RemoveRoundedIcon from "@mui/icons-material/RemoveRounded";
|
||||||
|
import { gray, brand } from "../themePrimitives";
|
||||||
|
|
||||||
|
/* eslint-disable import/prefer-default-export */
|
||||||
|
export const inputsCustomizations: Components<Theme> = {
|
||||||
|
MuiButtonBase: {
|
||||||
|
defaultProps: {
|
||||||
|
disableTouchRipple: true,
|
||||||
|
disableRipple: true,
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
boxSizing: "border-box",
|
||||||
|
transition: "all 100ms ease-in",
|
||||||
|
"&:focus-visible": {
|
||||||
|
outline: `3px solid ${alpha(theme.palette.primary.main, 0.5)}`,
|
||||||
|
outlineOffset: "2px",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiButton: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
boxShadow: "none",
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
textTransform: "none",
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "small",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
height: "2.25rem",
|
||||||
|
padding: "8px 12px",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "medium",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
height: "2.5rem", // 40px
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "primary",
|
||||||
|
variant: "contained",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: "white",
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
backgroundImage: `linear-gradient(to bottom, ${gray[700]}, ${gray[800]})`,
|
||||||
|
boxShadow: `inset 0 1px 0 ${gray[600]}, inset 0 -1px 0 1px hsl(220, 0%, 0%)`,
|
||||||
|
border: `1px solid ${gray[700]}`,
|
||||||
|
"&:hover": {
|
||||||
|
backgroundImage: "none",
|
||||||
|
backgroundColor: gray[700],
|
||||||
|
boxShadow: "none",
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: "black",
|
||||||
|
backgroundColor: gray[50],
|
||||||
|
backgroundImage: `linear-gradient(to bottom, ${gray[100]}, ${gray[50]})`,
|
||||||
|
boxShadow: "inset 0 -1px 0 hsl(220, 30%, 80%)",
|
||||||
|
border: `1px solid ${gray[50]}`,
|
||||||
|
"&:hover": {
|
||||||
|
backgroundImage: "none",
|
||||||
|
backgroundColor: gray[300],
|
||||||
|
boxShadow: "none",
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[400],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "secondary",
|
||||||
|
variant: "contained",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: "white",
|
||||||
|
backgroundColor: brand[300],
|
||||||
|
backgroundImage: `linear-gradient(to bottom, ${alpha(
|
||||||
|
brand[400],
|
||||||
|
0.8
|
||||||
|
)}, ${brand[500]})`,
|
||||||
|
boxShadow: `inset 0 2px 0 ${alpha(
|
||||||
|
brand[200],
|
||||||
|
0.2
|
||||||
|
)}, inset 0 -2px 0 ${alpha(brand[700], 0.4)}`,
|
||||||
|
border: `1px solid ${brand[500]}`,
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: brand[700],
|
||||||
|
boxShadow: "none",
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: brand[700],
|
||||||
|
backgroundImage: "none",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
variant: "outlined",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: gray[200],
|
||||||
|
backgroundColor: alpha(gray[50], 0.3),
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[100],
|
||||||
|
borderColor: gray[300],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[200],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
borderColor: gray[700],
|
||||||
|
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
borderColor: gray[600],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "secondary",
|
||||||
|
variant: "outlined",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: brand[700],
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: brand[200],
|
||||||
|
backgroundColor: brand[50],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: brand[100],
|
||||||
|
borderColor: brand[400],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: alpha(brand[200], 0.7),
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: brand[50],
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: brand[900],
|
||||||
|
backgroundColor: alpha(brand[900], 0.3),
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: brand[700],
|
||||||
|
backgroundColor: alpha(brand[900], 0.6),
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: alpha(brand[900], 0.5),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
variant: "text",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: gray[600],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[100],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[200],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: gray[50],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[700],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: alpha(gray[700], 0.7),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
color: "secondary",
|
||||||
|
variant: "text",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
color: brand[700],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: alpha(brand[100], 0.5),
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: alpha(brand[200], 0.7),
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: brand[100],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: alpha(brand[900], 0.5),
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: alpha(brand[900], 0.3),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiIconButton: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
boxShadow: "none",
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
textTransform: "none",
|
||||||
|
fontWeight: theme.typography.fontWeightMedium,
|
||||||
|
letterSpacing: 0,
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
border: "1px solid ",
|
||||||
|
borderColor: gray[200],
|
||||||
|
backgroundColor: alpha(gray[50], 0.3),
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[100],
|
||||||
|
borderColor: gray[300],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[200],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
borderColor: gray[700],
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
borderColor: gray[600],
|
||||||
|
},
|
||||||
|
"&:active": {
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "small",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
width: "2.25rem",
|
||||||
|
height: "2.25rem",
|
||||||
|
padding: "0.25rem",
|
||||||
|
[`& .${svgIconClasses.root}`]: { fontSize: "1rem" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "medium",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
width: "2.5rem",
|
||||||
|
height: "2.5rem",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiToggleButtonGroup: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
borderRadius: "10px",
|
||||||
|
boxShadow: `0 4px 16px ${alpha(gray[400], 0.2)}`,
|
||||||
|
[`& .${toggleButtonGroupClasses.selected}`]: {
|
||||||
|
color: brand[500],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
[`& .${toggleButtonGroupClasses.selected}`]: {
|
||||||
|
color: "#fff",
|
||||||
|
},
|
||||||
|
boxShadow: `0 4px 16px ${alpha(brand[700], 0.5)}`,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiToggleButton: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
padding: "12px 16px",
|
||||||
|
textTransform: "none",
|
||||||
|
borderRadius: "10px",
|
||||||
|
fontWeight: 500,
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: gray[400],
|
||||||
|
boxShadow: "0 4px 16px rgba(0, 0, 0, 0.5)",
|
||||||
|
[`&.${toggleButtonClasses.selected}`]: {
|
||||||
|
color: brand[300],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiCheckbox: {
|
||||||
|
defaultProps: {
|
||||||
|
disableRipple: true,
|
||||||
|
icon: (
|
||||||
|
<CheckBoxOutlineBlankRoundedIcon
|
||||||
|
sx={{ color: "hsla(210, 0%, 0%, 0.0)" }}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
checkedIcon: <CheckRoundedIcon sx={{ height: 14, width: 14 }} />,
|
||||||
|
indeterminateIcon: <RemoveRoundedIcon sx={{ height: 14, width: 14 }} />,
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
margin: 10,
|
||||||
|
height: 16,
|
||||||
|
width: 16,
|
||||||
|
borderRadius: 5,
|
||||||
|
border: "1px solid ",
|
||||||
|
borderColor: alpha(gray[300], 0.8),
|
||||||
|
boxShadow: "0 0 0 1.5px hsla(210, 0%, 0%, 0.04) inset",
|
||||||
|
backgroundColor: alpha(gray[100], 0.4),
|
||||||
|
transition: "border-color, background-color, 120ms ease-in",
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: brand[300],
|
||||||
|
},
|
||||||
|
"&.Mui-focusVisible": {
|
||||||
|
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||||
|
outlineOffset: "2px",
|
||||||
|
borderColor: brand[400],
|
||||||
|
},
|
||||||
|
"&.Mui-checked": {
|
||||||
|
color: "white",
|
||||||
|
backgroundColor: brand[500],
|
||||||
|
borderColor: brand[500],
|
||||||
|
boxShadow: `none`,
|
||||||
|
"&:hover": {
|
||||||
|
backgroundColor: brand[600],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
borderColor: alpha(gray[700], 0.8),
|
||||||
|
boxShadow: "0 0 0 1.5px hsl(210, 0%, 0%) inset",
|
||||||
|
backgroundColor: alpha(gray[900], 0.8),
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: brand[300],
|
||||||
|
},
|
||||||
|
"&.Mui-focusVisible": {
|
||||||
|
borderColor: brand[400],
|
||||||
|
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||||
|
outlineOffset: "2px",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiInputBase: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
border: "none",
|
||||||
|
},
|
||||||
|
input: {
|
||||||
|
"&::placeholder": {
|
||||||
|
opacity: 0.7,
|
||||||
|
color: gray[500],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiOutlinedInput: {
|
||||||
|
styleOverrides: {
|
||||||
|
input: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
padding: "8px 12px",
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||||
|
transition: "border 120ms ease-in",
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: gray[400],
|
||||||
|
},
|
||||||
|
[`&.${outlinedInputClasses.focused}`]: {
|
||||||
|
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||||
|
borderColor: brand[400],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: gray[500],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "small",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
height: "2.25rem",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
size: "medium",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
height: "2.5rem",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
notchedOutline: {
|
||||||
|
border: "none",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiInputAdornment: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
color: (theme.vars || theme).palette.grey[500],
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
color: (theme.vars || theme).palette.grey[400],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiFormLabel: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
typography: theme.typography.caption,
|
||||||
|
marginBottom: 8,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
284
matrixgw_frontend/src/theme/customizations/navigation.tsx
Normal file
284
matrixgw_frontend/src/theme/customizations/navigation.tsx
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { type Theme, alpha, type Components } from "@mui/material/styles";
|
||||||
|
import { type SvgIconProps } from "@mui/material/SvgIcon";
|
||||||
|
import { buttonBaseClasses } from "@mui/material/ButtonBase";
|
||||||
|
import { dividerClasses } from "@mui/material/Divider";
|
||||||
|
import { menuItemClasses } from "@mui/material/MenuItem";
|
||||||
|
import { selectClasses } from "@mui/material/Select";
|
||||||
|
import { tabClasses } from "@mui/material/Tab";
|
||||||
|
import UnfoldMoreRoundedIcon from "@mui/icons-material/UnfoldMoreRounded";
|
||||||
|
import { gray, brand } from "../themePrimitives";
|
||||||
|
|
||||||
|
/* eslint-disable import/prefer-default-export */
|
||||||
|
export const navigationCustomizations: Components<Theme> = {
|
||||||
|
MuiMenuItem: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
padding: "6px 8px",
|
||||||
|
[`&.${menuItemClasses.focusVisible}`]: {
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
},
|
||||||
|
[`&.${menuItemClasses.selected}`]: {
|
||||||
|
[`&.${menuItemClasses.focusVisible}`]: {
|
||||||
|
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiMenu: {
|
||||||
|
styleOverrides: {
|
||||||
|
list: {
|
||||||
|
gap: "0px",
|
||||||
|
[`&.${dividerClasses.root}`]: {
|
||||||
|
margin: "0 -8px",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
paper: ({ theme }) => ({
|
||||||
|
marginTop: "4px",
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||||
|
backgroundImage: "none",
|
||||||
|
background: "hsl(0, 0%, 100%)",
|
||||||
|
boxShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px",
|
||||||
|
[`& .${buttonBaseClasses.root}`]: {
|
||||||
|
"&.Mui-selected": {
|
||||||
|
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
background: gray[900],
|
||||||
|
boxShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiSelect: {
|
||||||
|
defaultProps: {
|
||||||
|
IconComponent: React.forwardRef<SVGSVGElement, SvgIconProps>(
|
||||||
|
(props, ref) => (
|
||||||
|
<UnfoldMoreRoundedIcon fontSize="small" {...props} ref={ref} />
|
||||||
|
)
|
||||||
|
),
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: gray[200],
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||||
|
boxShadow: `inset 0 1px 0 1px hsla(220, 0%, 100%, 0.6), inset 0 -1px 0 1px hsla(220, 35%, 90%, 0.5)`,
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: gray[300],
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||||
|
boxShadow: "none",
|
||||||
|
},
|
||||||
|
[`&.${selectClasses.focused}`]: {
|
||||||
|
outlineOffset: 0,
|
||||||
|
borderColor: gray[400],
|
||||||
|
},
|
||||||
|
"&:before, &:after": {
|
||||||
|
display: "none",
|
||||||
|
},
|
||||||
|
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
borderColor: gray[700],
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||||
|
boxShadow: `inset 0 1px 0 1px ${alpha(
|
||||||
|
gray[700],
|
||||||
|
0.15
|
||||||
|
)}, inset 0 -1px 0 1px hsla(220, 0%, 0%, 0.7)`,
|
||||||
|
"&:hover": {
|
||||||
|
borderColor: alpha(gray[700], 0.7),
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||||
|
boxShadow: "none",
|
||||||
|
},
|
||||||
|
[`&.${selectClasses.focused}`]: {
|
||||||
|
outlineOffset: 0,
|
||||||
|
borderColor: gray[900],
|
||||||
|
},
|
||||||
|
"&:before, &:after": {
|
||||||
|
display: "none",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
select: ({ theme }) => ({
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
"&:focus-visible": {
|
||||||
|
backgroundColor: gray[900],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiLink: {
|
||||||
|
defaultProps: {
|
||||||
|
underline: "none",
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
fontWeight: 500,
|
||||||
|
position: "relative",
|
||||||
|
textDecoration: "none",
|
||||||
|
width: "fit-content",
|
||||||
|
"&::before": {
|
||||||
|
content: '""',
|
||||||
|
position: "absolute",
|
||||||
|
width: "100%",
|
||||||
|
height: "1px",
|
||||||
|
bottom: 0,
|
||||||
|
left: 0,
|
||||||
|
backgroundColor: (theme.vars || theme).palette.text.secondary,
|
||||||
|
opacity: 0.3,
|
||||||
|
transition: "width 0.3s ease, opacity 0.3s ease",
|
||||||
|
},
|
||||||
|
"&:hover::before": {
|
||||||
|
width: 0,
|
||||||
|
},
|
||||||
|
"&:focus-visible": {
|
||||||
|
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||||
|
outlineOffset: "4px",
|
||||||
|
borderRadius: "2px",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiDrawer: {
|
||||||
|
styleOverrides: {
|
||||||
|
paper: ({ theme }) => ({
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiPaginationItem: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
"&.Mui-selected": {
|
||||||
|
color: "white",
|
||||||
|
backgroundColor: (theme.vars || theme).palette.grey[900],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
"&.Mui-selected": {
|
||||||
|
color: "black",
|
||||||
|
backgroundColor: (theme.vars || theme).palette.grey[50],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiTabs: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: { minHeight: "fit-content" },
|
||||||
|
indicator: ({ theme }) => ({
|
||||||
|
backgroundColor: (theme.vars || theme).palette.grey[800],
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: (theme.vars || theme).palette.grey[200],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiTab: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
padding: "6px 8px",
|
||||||
|
marginBottom: "8px",
|
||||||
|
textTransform: "none",
|
||||||
|
minWidth: "fit-content",
|
||||||
|
minHeight: "fit-content",
|
||||||
|
color: (theme.vars || theme).palette.text.secondary,
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: "transparent",
|
||||||
|
":hover": {
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
backgroundColor: gray[100],
|
||||||
|
borderColor: gray[200],
|
||||||
|
},
|
||||||
|
[`&.${tabClasses.selected}`]: {
|
||||||
|
color: gray[900],
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
":hover": {
|
||||||
|
color: (theme.vars || theme).palette.text.primary,
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
borderColor: gray[700],
|
||||||
|
},
|
||||||
|
[`&.${tabClasses.selected}`]: {
|
||||||
|
color: "#fff",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiStepConnector: {
|
||||||
|
styleOverrides: {
|
||||||
|
line: ({ theme }) => ({
|
||||||
|
borderTop: "1px solid",
|
||||||
|
borderColor: (theme.vars || theme).palette.divider,
|
||||||
|
flex: 1,
|
||||||
|
borderRadius: "99px",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiStepIcon: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
color: "transparent",
|
||||||
|
border: `1px solid ${gray[400]}`,
|
||||||
|
width: 12,
|
||||||
|
height: 12,
|
||||||
|
borderRadius: "50%",
|
||||||
|
"& text": {
|
||||||
|
display: "none",
|
||||||
|
},
|
||||||
|
"&.Mui-active": {
|
||||||
|
border: "none",
|
||||||
|
color: (theme.vars || theme).palette.primary.main,
|
||||||
|
},
|
||||||
|
"&.Mui-completed": {
|
||||||
|
border: "none",
|
||||||
|
color: (theme.vars || theme).palette.success.main,
|
||||||
|
},
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
border: `1px solid ${gray[700]}`,
|
||||||
|
"&.Mui-active": {
|
||||||
|
border: "none",
|
||||||
|
color: (theme.vars || theme).palette.primary.light,
|
||||||
|
},
|
||||||
|
"&.Mui-completed": {
|
||||||
|
border: "none",
|
||||||
|
color: (theme.vars || theme).palette.success.light,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: { completed: true },
|
||||||
|
style: {
|
||||||
|
width: 12,
|
||||||
|
height: 12,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiStepLabel: {
|
||||||
|
styleOverrides: {
|
||||||
|
label: ({ theme }) => ({
|
||||||
|
"&.Mui-completed": {
|
||||||
|
opacity: 0.6,
|
||||||
|
...theme.applyStyles("dark", { opacity: 0.5 }),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
113
matrixgw_frontend/src/theme/customizations/surfaces.ts
Normal file
113
matrixgw_frontend/src/theme/customizations/surfaces.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import { alpha, type Theme, type Components } from "@mui/material/styles";
|
||||||
|
import { gray } from "../themePrimitives";
|
||||||
|
|
||||||
|
/* eslint-disable import/prefer-default-export */
|
||||||
|
export const surfacesCustomizations: Components<Theme> = {
|
||||||
|
MuiAccordion: {
|
||||||
|
defaultProps: {
|
||||||
|
elevation: 0,
|
||||||
|
disableGutters: true,
|
||||||
|
},
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
padding: 4,
|
||||||
|
overflow: "clip",
|
||||||
|
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||||
|
border: "1px solid",
|
||||||
|
borderColor: (theme.vars || theme).palette.divider,
|
||||||
|
":before": {
|
||||||
|
backgroundColor: "transparent",
|
||||||
|
},
|
||||||
|
"&:not(:last-of-type)": {
|
||||||
|
borderBottom: "none",
|
||||||
|
},
|
||||||
|
"&:first-of-type": {
|
||||||
|
borderTopLeftRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
borderTopRightRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
},
|
||||||
|
"&:last-of-type": {
|
||||||
|
borderBottomLeftRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
borderBottomRightRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiAccordionSummary: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => ({
|
||||||
|
border: "none",
|
||||||
|
borderRadius: 8,
|
||||||
|
"&:hover": { backgroundColor: gray[50] },
|
||||||
|
"&:focus-visible": { backgroundColor: "transparent" },
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
"&:hover": { backgroundColor: gray[800] },
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiAccordionDetails: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: { mb: 20, border: "none" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiPaper: {
|
||||||
|
defaultProps: {
|
||||||
|
elevation: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiCard: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: ({ theme }) => {
|
||||||
|
return {
|
||||||
|
padding: 16,
|
||||||
|
gap: 16,
|
||||||
|
transition: "all 100ms ease",
|
||||||
|
backgroundColor: gray[50],
|
||||||
|
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||||
|
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||||
|
boxShadow: "none",
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundColor: gray[800],
|
||||||
|
}),
|
||||||
|
variants: [
|
||||||
|
{
|
||||||
|
props: {
|
||||||
|
variant: "outlined",
|
||||||
|
},
|
||||||
|
style: {
|
||||||
|
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||||
|
boxShadow: "none",
|
||||||
|
background: "hsl(0, 0%, 100%)",
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
background: alpha(gray[900], 0.4),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiCardContent: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
padding: 0,
|
||||||
|
"&:last-child": { paddingBottom: 0 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiCardHeader: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
MuiCardActions: {
|
||||||
|
styleOverrides: {
|
||||||
|
root: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
414
matrixgw_frontend/src/theme/themePrimitives.ts
Normal file
414
matrixgw_frontend/src/theme/themePrimitives.ts
Normal file
@@ -0,0 +1,414 @@
|
|||||||
|
import {
|
||||||
|
createTheme,
|
||||||
|
alpha,
|
||||||
|
type PaletteMode,
|
||||||
|
type Shadows,
|
||||||
|
} from "@mui/material/styles";
|
||||||
|
|
||||||
|
declare module "@mui/material/Paper" {
|
||||||
|
interface PaperPropsVariantOverrides {
|
||||||
|
highlighted: true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
declare module "@mui/material/styles" {
|
||||||
|
interface ColorRange {
|
||||||
|
50: string;
|
||||||
|
100: string;
|
||||||
|
200: string;
|
||||||
|
300: string;
|
||||||
|
400: string;
|
||||||
|
500: string;
|
||||||
|
600: string;
|
||||||
|
700: string;
|
||||||
|
800: string;
|
||||||
|
900: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PaletteColor extends ColorRange {}
|
||||||
|
|
||||||
|
interface Palette {
|
||||||
|
baseShadow: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultTheme = createTheme();
|
||||||
|
|
||||||
|
const customShadows: Shadows = [...defaultTheme.shadows];
|
||||||
|
|
||||||
|
export const brand = {
|
||||||
|
50: "hsl(210, 100%, 95%)",
|
||||||
|
100: "hsl(210, 100%, 92%)",
|
||||||
|
200: "hsl(210, 100%, 80%)",
|
||||||
|
300: "hsl(210, 100%, 65%)",
|
||||||
|
400: "hsl(210, 98%, 48%)",
|
||||||
|
500: "hsl(210, 98%, 42%)",
|
||||||
|
600: "hsl(210, 98%, 55%)",
|
||||||
|
700: "hsl(210, 100%, 35%)",
|
||||||
|
800: "hsl(210, 100%, 16%)",
|
||||||
|
900: "hsl(210, 100%, 21%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const gray = {
|
||||||
|
50: "hsl(220, 35%, 97%)",
|
||||||
|
100: "hsl(220, 30%, 94%)",
|
||||||
|
200: "hsl(220, 20%, 88%)",
|
||||||
|
300: "hsl(220, 20%, 80%)",
|
||||||
|
400: "hsl(220, 20%, 65%)",
|
||||||
|
500: "hsl(220, 20%, 42%)",
|
||||||
|
600: "hsl(220, 20%, 35%)",
|
||||||
|
700: "hsl(220, 20%, 25%)",
|
||||||
|
800: "hsl(220, 30%, 6%)",
|
||||||
|
900: "hsl(220, 35%, 3%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const green = {
|
||||||
|
50: "hsl(120, 80%, 98%)",
|
||||||
|
100: "hsl(120, 75%, 94%)",
|
||||||
|
200: "hsl(120, 75%, 87%)",
|
||||||
|
300: "hsl(120, 61%, 77%)",
|
||||||
|
400: "hsl(120, 44%, 53%)",
|
||||||
|
500: "hsl(120, 59%, 30%)",
|
||||||
|
600: "hsl(120, 70%, 25%)",
|
||||||
|
700: "hsl(120, 75%, 16%)",
|
||||||
|
800: "hsl(120, 84%, 10%)",
|
||||||
|
900: "hsl(120, 87%, 6%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const orange = {
|
||||||
|
50: "hsl(45, 100%, 97%)",
|
||||||
|
100: "hsl(45, 92%, 90%)",
|
||||||
|
200: "hsl(45, 94%, 80%)",
|
||||||
|
300: "hsl(45, 90%, 65%)",
|
||||||
|
400: "hsl(45, 90%, 40%)",
|
||||||
|
500: "hsl(45, 90%, 35%)",
|
||||||
|
600: "hsl(45, 91%, 25%)",
|
||||||
|
700: "hsl(45, 94%, 20%)",
|
||||||
|
800: "hsl(45, 95%, 16%)",
|
||||||
|
900: "hsl(45, 93%, 12%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const red = {
|
||||||
|
50: "hsl(0, 100%, 97%)",
|
||||||
|
100: "hsl(0, 92%, 90%)",
|
||||||
|
200: "hsl(0, 94%, 80%)",
|
||||||
|
300: "hsl(0, 90%, 65%)",
|
||||||
|
400: "hsl(0, 90%, 40%)",
|
||||||
|
500: "hsl(0, 90%, 30%)",
|
||||||
|
600: "hsl(0, 91%, 25%)",
|
||||||
|
700: "hsl(0, 94%, 18%)",
|
||||||
|
800: "hsl(0, 95%, 12%)",
|
||||||
|
900: "hsl(0, 93%, 6%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getDesignTokens = (mode: PaletteMode) => {
|
||||||
|
customShadows[1] =
|
||||||
|
mode === "dark"
|
||||||
|
? "hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px"
|
||||||
|
: "hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px";
|
||||||
|
|
||||||
|
return {
|
||||||
|
palette: {
|
||||||
|
mode,
|
||||||
|
primary: {
|
||||||
|
light: brand[200],
|
||||||
|
main: brand[400],
|
||||||
|
dark: brand[700],
|
||||||
|
contrastText: brand[50],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
contrastText: brand[50],
|
||||||
|
light: brand[300],
|
||||||
|
main: brand[400],
|
||||||
|
dark: brand[700],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
light: brand[100],
|
||||||
|
main: brand[300],
|
||||||
|
dark: brand[600],
|
||||||
|
contrastText: gray[50],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
contrastText: brand[300],
|
||||||
|
light: brand[500],
|
||||||
|
main: brand[700],
|
||||||
|
dark: brand[900],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
light: orange[300],
|
||||||
|
main: orange[400],
|
||||||
|
dark: orange[800],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
light: orange[400],
|
||||||
|
main: orange[500],
|
||||||
|
dark: orange[700],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
error: {
|
||||||
|
light: red[300],
|
||||||
|
main: red[400],
|
||||||
|
dark: red[800],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
light: red[400],
|
||||||
|
main: red[500],
|
||||||
|
dark: red[700],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
light: green[300],
|
||||||
|
main: green[400],
|
||||||
|
dark: green[800],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
light: green[400],
|
||||||
|
main: green[500],
|
||||||
|
dark: green[700],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
grey: {
|
||||||
|
...gray,
|
||||||
|
},
|
||||||
|
divider: mode === "dark" ? alpha(gray[700], 0.6) : alpha(gray[300], 0.4),
|
||||||
|
background: {
|
||||||
|
default: "hsl(0, 0%, 99%)",
|
||||||
|
paper: "hsl(220, 35%, 97%)",
|
||||||
|
...(mode === "dark" && {
|
||||||
|
default: gray[900],
|
||||||
|
paper: "hsl(220, 30%, 7%)",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
text: {
|
||||||
|
primary: gray[800],
|
||||||
|
secondary: gray[600],
|
||||||
|
warning: orange[400],
|
||||||
|
...(mode === "dark" && {
|
||||||
|
primary: "hsl(0, 0%, 100%)",
|
||||||
|
secondary: gray[400],
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
action: {
|
||||||
|
hover: alpha(gray[200], 0.2),
|
||||||
|
selected: `${alpha(gray[200], 0.3)}`,
|
||||||
|
...(mode === "dark" && {
|
||||||
|
hover: alpha(gray[600], 0.2),
|
||||||
|
selected: alpha(gray[600], 0.3),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
typography: {
|
||||||
|
fontFamily: "Inter, sans-serif",
|
||||||
|
h1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(48),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
letterSpacing: -0.5,
|
||||||
|
},
|
||||||
|
h2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(36),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
},
|
||||||
|
h3: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(30),
|
||||||
|
lineHeight: 1.2,
|
||||||
|
},
|
||||||
|
h4: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(24),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.5,
|
||||||
|
},
|
||||||
|
h5: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(20),
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
h6: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(18),
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
subtitle1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(18),
|
||||||
|
},
|
||||||
|
subtitle2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
fontWeight: 500,
|
||||||
|
},
|
||||||
|
body1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
},
|
||||||
|
body2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
fontWeight: 400,
|
||||||
|
},
|
||||||
|
caption: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(12),
|
||||||
|
fontWeight: 400,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
shape: {
|
||||||
|
borderRadius: 8,
|
||||||
|
},
|
||||||
|
shadows: customShadows,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const colorSchemes = {
|
||||||
|
light: {
|
||||||
|
palette: {
|
||||||
|
primary: {
|
||||||
|
light: brand[200],
|
||||||
|
main: brand[400],
|
||||||
|
dark: brand[700],
|
||||||
|
contrastText: brand[50],
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
light: brand[100],
|
||||||
|
main: brand[300],
|
||||||
|
dark: brand[600],
|
||||||
|
contrastText: gray[50],
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
light: orange[300],
|
||||||
|
main: orange[400],
|
||||||
|
dark: orange[800],
|
||||||
|
},
|
||||||
|
error: {
|
||||||
|
light: red[300],
|
||||||
|
main: red[400],
|
||||||
|
dark: red[800],
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
light: green[300],
|
||||||
|
main: green[400],
|
||||||
|
dark: green[800],
|
||||||
|
},
|
||||||
|
grey: {
|
||||||
|
...gray,
|
||||||
|
},
|
||||||
|
divider: alpha(gray[300], 0.4),
|
||||||
|
background: {
|
||||||
|
default: "hsl(0, 0%, 99%)",
|
||||||
|
paper: "hsl(220, 35%, 97%)",
|
||||||
|
},
|
||||||
|
text: {
|
||||||
|
primary: gray[800],
|
||||||
|
secondary: gray[600],
|
||||||
|
warning: orange[400],
|
||||||
|
},
|
||||||
|
action: {
|
||||||
|
hover: alpha(gray[200], 0.2),
|
||||||
|
selected: `${alpha(gray[200], 0.3)}`,
|
||||||
|
},
|
||||||
|
baseShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
dark: {
|
||||||
|
palette: {
|
||||||
|
primary: {
|
||||||
|
contrastText: brand[50],
|
||||||
|
light: brand[300],
|
||||||
|
main: brand[400],
|
||||||
|
dark: brand[700],
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
contrastText: brand[300],
|
||||||
|
light: brand[500],
|
||||||
|
main: brand[700],
|
||||||
|
dark: brand[900],
|
||||||
|
},
|
||||||
|
warning: {
|
||||||
|
light: orange[400],
|
||||||
|
main: orange[500],
|
||||||
|
dark: orange[700],
|
||||||
|
},
|
||||||
|
error: {
|
||||||
|
light: red[400],
|
||||||
|
main: red[500],
|
||||||
|
dark: red[700],
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
light: green[400],
|
||||||
|
main: green[500],
|
||||||
|
dark: green[700],
|
||||||
|
},
|
||||||
|
grey: {
|
||||||
|
...gray,
|
||||||
|
},
|
||||||
|
divider: alpha(gray[700], 0.6),
|
||||||
|
background: {
|
||||||
|
default: gray[900],
|
||||||
|
paper: "hsl(220, 30%, 7%)",
|
||||||
|
},
|
||||||
|
text: {
|
||||||
|
primary: "hsl(0, 0%, 100%)",
|
||||||
|
secondary: gray[400],
|
||||||
|
},
|
||||||
|
action: {
|
||||||
|
hover: alpha(gray[600], 0.2),
|
||||||
|
selected: alpha(gray[600], 0.3),
|
||||||
|
},
|
||||||
|
baseShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const typography = {
|
||||||
|
fontFamily: "Inter, sans-serif",
|
||||||
|
h1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(48),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
letterSpacing: -0.5,
|
||||||
|
},
|
||||||
|
h2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(36),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
},
|
||||||
|
h3: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(30),
|
||||||
|
lineHeight: 1.2,
|
||||||
|
},
|
||||||
|
h4: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(24),
|
||||||
|
fontWeight: 600,
|
||||||
|
lineHeight: 1.5,
|
||||||
|
},
|
||||||
|
h5: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(20),
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
h6: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(18),
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
subtitle1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(18),
|
||||||
|
},
|
||||||
|
subtitle2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
fontWeight: 500,
|
||||||
|
},
|
||||||
|
body1: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
},
|
||||||
|
body2: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(14),
|
||||||
|
fontWeight: 400,
|
||||||
|
},
|
||||||
|
caption: {
|
||||||
|
fontSize: defaultTheme.typography.pxToRem(12),
|
||||||
|
fontWeight: 400,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const shape = {
|
||||||
|
borderRadius: 8,
|
||||||
|
};
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
const defaultShadows: Shadows = [
|
||||||
|
"none",
|
||||||
|
"var(--template-palette-baseShadow)",
|
||||||
|
...defaultTheme.shadows.slice(2),
|
||||||
|
];
|
||||||
|
export const shadows = defaultShadows;
|
||||||
86
matrixgw_frontend/src/widgets/AsyncWidget.tsx
Normal file
86
matrixgw_frontend/src/widgets/AsyncWidget.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { Alert, Box, Button, CircularProgress } from "@mui/material";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
const State = {
|
||||||
|
Loading: 0,
|
||||||
|
Ready: 1,
|
||||||
|
Error: 2,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type State = keyof typeof State;
|
||||||
|
|
||||||
|
export function AsyncWidget(p: {
|
||||||
|
loadKey: any;
|
||||||
|
load: () => Promise<void>;
|
||||||
|
errMsg: string;
|
||||||
|
build: () => React.ReactElement;
|
||||||
|
ready?: boolean;
|
||||||
|
errAdditionalElement?: () => React.ReactElement;
|
||||||
|
}): React.ReactElement {
|
||||||
|
const [state, setState] = useState<number>(State.Loading);
|
||||||
|
|
||||||
|
const counter = useRef<any>(null);
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
try {
|
||||||
|
setState(State.Loading);
|
||||||
|
await p.load();
|
||||||
|
setState(State.Ready);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setState(State.Error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (counter.current === p.loadKey) return;
|
||||||
|
counter.current = p.loadKey;
|
||||||
|
|
||||||
|
load();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (state === State.Error)
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
component="div"
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
height: "100%",
|
||||||
|
flex: "1",
|
||||||
|
flexDirection: "column",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Alert
|
||||||
|
variant="outlined"
|
||||||
|
severity="error"
|
||||||
|
style={{ margin: "0px 15px 15px 15px" }}
|
||||||
|
>
|
||||||
|
{p.errMsg}
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<Button onClick={load}>Try again</Button>
|
||||||
|
|
||||||
|
{p.errAdditionalElement?.()}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (state === State.Loading || p.ready === false)
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
component="div"
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "center",
|
||||||
|
alignItems: "center",
|
||||||
|
height: "100%",
|
||||||
|
flex: "1",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<CircularProgress />
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
|
||||||
|
return p.build();
|
||||||
|
}
|
||||||
16
matrixgw_frontend/src/widgets/RouterLink.tsx
Normal file
16
matrixgw_frontend/src/widgets/RouterLink.tsx
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { type PropsWithChildren } from "react";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
|
||||||
|
export function RouterLink(
|
||||||
|
p: PropsWithChildren<{ to: string; target?: React.HTMLAttributeAnchorTarget }>
|
||||||
|
): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
to={p.to}
|
||||||
|
target={p.target}
|
||||||
|
style={{ color: "inherit", textDecoration: "inherit" }}
|
||||||
|
>
|
||||||
|
{p.children}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
13
matrixgw_frontend/src/widgets/auth/AuthSingleMessage.tsx
Normal file
13
matrixgw_frontend/src/widgets/auth/AuthSingleMessage.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Button } from "@mui/material";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
|
||||||
|
export function AuthSingleMessage(p: { message: string }): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<p style={{ textAlign: "center" }}>{p.message}</p>
|
||||||
|
<Link to={"/"}>
|
||||||
|
<Button>Go back home</Button>
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
71
matrixgw_frontend/src/widgets/auth/BaseLoginPage.tsx
Normal file
71
matrixgw_frontend/src/widgets/auth/BaseLoginPage.tsx
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import { mdiMessageTextFast } from "@mdi/js";
|
||||||
|
import Icon from "@mdi/react";
|
||||||
|
import { Typography } from "@mui/material";
|
||||||
|
import MuiCard from "@mui/material/Card";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { styled } from "@mui/material/styles";
|
||||||
|
import { Outlet } from "react-router";
|
||||||
|
|
||||||
|
const Card = styled(MuiCard)(({ theme }) => ({
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
alignSelf: "center",
|
||||||
|
width: "100%",
|
||||||
|
padding: theme.spacing(4),
|
||||||
|
gap: theme.spacing(2),
|
||||||
|
margin: "auto",
|
||||||
|
[theme.breakpoints.up("sm")]: {
|
||||||
|
maxWidth: "450px",
|
||||||
|
},
|
||||||
|
boxShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px",
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
boxShadow:
|
||||||
|
"hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const SignInContainer = styled(Stack)(({ theme }) => ({
|
||||||
|
height: "calc((1 - var(--template-frame-height, 0)) * 100dvh)",
|
||||||
|
minHeight: "100%",
|
||||||
|
padding: theme.spacing(2),
|
||||||
|
[theme.breakpoints.up("sm")]: {
|
||||||
|
padding: theme.spacing(4),
|
||||||
|
},
|
||||||
|
"&::before": {
|
||||||
|
content: '""',
|
||||||
|
display: "block",
|
||||||
|
position: "absolute",
|
||||||
|
zIndex: -1,
|
||||||
|
inset: 0,
|
||||||
|
backgroundImage:
|
||||||
|
"radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))",
|
||||||
|
backgroundRepeat: "no-repeat",
|
||||||
|
...theme.applyStyles("dark", {
|
||||||
|
backgroundImage:
|
||||||
|
"radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))",
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
export function BaseLoginPage(): React.ReactElement {
|
||||||
|
return (
|
||||||
|
<SignInContainer direction="column" justifyContent="space-between">
|
||||||
|
<Card variant="outlined">
|
||||||
|
<Typography
|
||||||
|
component="h1"
|
||||||
|
variant="h4"
|
||||||
|
sx={{ width: "100%", fontSize: "clamp(2rem, 10vw, 2.15rem)" }}
|
||||||
|
>
|
||||||
|
<Icon
|
||||||
|
path={mdiMessageTextFast}
|
||||||
|
size={"1em"}
|
||||||
|
style={{ display: "inline-table" }}
|
||||||
|
/>{" "}
|
||||||
|
MatrixGW
|
||||||
|
</Typography>
|
||||||
|
<Outlet />
|
||||||
|
</Card>
|
||||||
|
</SignInContainer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import { useTheme } from "@mui/material/styles";
|
||||||
|
import Toolbar from "@mui/material/Toolbar";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
import * as React from "react";
|
||||||
|
import { Outlet } from "react-router";
|
||||||
|
import DashboardHeader from "./DashboardHeader";
|
||||||
|
import DashboardSidebar from "./DashboardSidebar";
|
||||||
|
|
||||||
|
export default function BaseAuthenticatedPage(): React.ReactElement {
|
||||||
|
const theme = useTheme();
|
||||||
|
|
||||||
|
const [isDesktopNavigationExpanded, setIsDesktopNavigationExpanded] =
|
||||||
|
React.useState(false);
|
||||||
|
const [isMobileNavigationExpanded, setIsMobileNavigationExpanded] =
|
||||||
|
React.useState(false);
|
||||||
|
|
||||||
|
const isOverMdViewport = useMediaQuery(theme.breakpoints.up("md"));
|
||||||
|
|
||||||
|
const isNavigationExpanded = isOverMdViewport
|
||||||
|
? isDesktopNavigationExpanded
|
||||||
|
: isMobileNavigationExpanded;
|
||||||
|
|
||||||
|
const setIsNavigationExpanded = React.useCallback(
|
||||||
|
(newExpanded: boolean) => {
|
||||||
|
if (isOverMdViewport) {
|
||||||
|
setIsDesktopNavigationExpanded(newExpanded);
|
||||||
|
} else {
|
||||||
|
setIsMobileNavigationExpanded(newExpanded);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[
|
||||||
|
isOverMdViewport,
|
||||||
|
setIsDesktopNavigationExpanded,
|
||||||
|
setIsMobileNavigationExpanded,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleToggleHeaderMenu = React.useCallback(
|
||||||
|
(isExpanded: boolean) => {
|
||||||
|
setIsNavigationExpanded(isExpanded);
|
||||||
|
},
|
||||||
|
[setIsNavigationExpanded]
|
||||||
|
);
|
||||||
|
|
||||||
|
const layoutRef = React.useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
ref={layoutRef}
|
||||||
|
sx={{
|
||||||
|
position: "relative",
|
||||||
|
display: "flex",
|
||||||
|
overflow: "hidden",
|
||||||
|
height: "100%",
|
||||||
|
width: "100%",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DashboardHeader
|
||||||
|
menuOpen={isNavigationExpanded}
|
||||||
|
onToggleMenu={handleToggleHeaderMenu}
|
||||||
|
/>
|
||||||
|
<DashboardSidebar
|
||||||
|
expanded={isNavigationExpanded}
|
||||||
|
setExpanded={setIsNavigationExpanded}
|
||||||
|
container={layoutRef?.current ?? undefined}
|
||||||
|
/>
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
flex: 1,
|
||||||
|
minWidth: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Toolbar sx={{ displayPrint: "none" }} />
|
||||||
|
<Box
|
||||||
|
component="main"
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
flex: 1,
|
||||||
|
overflow: "auto",
|
||||||
|
padding: "50px",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Outlet />
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
}
|
||||||
125
matrixgw_frontend/src/widgets/dashboard/DashboardHeader.tsx
Normal file
125
matrixgw_frontend/src/widgets/dashboard/DashboardHeader.tsx
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import { mdiMessageTextFast } from "@mdi/js";
|
||||||
|
import Icon from "@mdi/react";
|
||||||
|
import MenuIcon from "@mui/icons-material/Menu";
|
||||||
|
import MenuOpenIcon from "@mui/icons-material/MenuOpen";
|
||||||
|
import MuiAppBar from "@mui/material/AppBar";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import Stack from "@mui/material/Stack";
|
||||||
|
import { styled } from "@mui/material/styles";
|
||||||
|
import Toolbar from "@mui/material/Toolbar";
|
||||||
|
import Tooltip from "@mui/material/Tooltip";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import * as React from "react";
|
||||||
|
import { RouterLink } from "../RouterLink";
|
||||||
|
import ThemeSwitcher from "./ThemeSwitcher";
|
||||||
|
|
||||||
|
const AppBar = styled(MuiAppBar)(({ theme }) => ({
|
||||||
|
borderWidth: 0,
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
borderStyle: "solid",
|
||||||
|
borderColor: (theme.vars ?? theme).palette.divider,
|
||||||
|
boxShadow: "none",
|
||||||
|
zIndex: theme.zIndex.drawer + 1,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const LogoContainer = styled("div")({
|
||||||
|
position: "relative",
|
||||||
|
height: 40,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
"& img": {
|
||||||
|
maxHeight: 40,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export interface DashboardHeaderProps {
|
||||||
|
menuOpen: boolean;
|
||||||
|
onToggleMenu: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardHeader({
|
||||||
|
menuOpen,
|
||||||
|
onToggleMenu,
|
||||||
|
}: DashboardHeaderProps) {
|
||||||
|
const handleMenuOpen = React.useCallback(() => {
|
||||||
|
onToggleMenu(!menuOpen);
|
||||||
|
}, [menuOpen, onToggleMenu]);
|
||||||
|
|
||||||
|
const getMenuIcon = React.useCallback(
|
||||||
|
(isExpanded: boolean) => {
|
||||||
|
const expandMenuActionText = "Expand";
|
||||||
|
const collapseMenuActionText = "Collapse";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
title={`${
|
||||||
|
isExpanded ? collapseMenuActionText : expandMenuActionText
|
||||||
|
} menu`}
|
||||||
|
enterDelay={200}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label={`${
|
||||||
|
isExpanded ? collapseMenuActionText : expandMenuActionText
|
||||||
|
} navigation menu`}
|
||||||
|
onClick={handleMenuOpen}
|
||||||
|
>
|
||||||
|
{isExpanded ? <MenuOpenIcon /> : <MenuIcon />}
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
[handleMenuOpen]
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AppBar color="inherit" position="absolute" sx={{ displayPrint: "none" }}>
|
||||||
|
<Toolbar sx={{ backgroundColor: "inherit", mx: { xs: -0.75, sm: -1 } }}>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
justifyContent="space-between"
|
||||||
|
alignItems="center"
|
||||||
|
sx={{
|
||||||
|
flexWrap: "wrap",
|
||||||
|
width: "100%",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Stack direction="row" alignItems="center">
|
||||||
|
<Box sx={{ mr: 3 }}>{getMenuIcon(menuOpen)}</Box>
|
||||||
|
<RouterLink to="/">
|
||||||
|
<Stack direction="row" alignItems="center">
|
||||||
|
<LogoContainer>
|
||||||
|
<Icon path={mdiMessageTextFast} size="2em" />
|
||||||
|
</LogoContainer>
|
||||||
|
<Typography
|
||||||
|
variant="h6"
|
||||||
|
sx={{
|
||||||
|
fontWeight: "700",
|
||||||
|
ml: 1,
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
lineHeight: 1,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
MatrixGW
|
||||||
|
</Typography>
|
||||||
|
</Stack>
|
||||||
|
</RouterLink>
|
||||||
|
</Stack>
|
||||||
|
<Stack
|
||||||
|
direction="row"
|
||||||
|
alignItems="center"
|
||||||
|
spacing={1}
|
||||||
|
sx={{ marginLeft: "auto" }}
|
||||||
|
>
|
||||||
|
<Stack direction="row" alignItems="center">
|
||||||
|
<ThemeSwitcher />
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
</Toolbar>
|
||||||
|
</AppBar>
|
||||||
|
);
|
||||||
|
}
|
||||||
205
matrixgw_frontend/src/widgets/dashboard/DashboardSidebar.tsx
Normal file
205
matrixgw_frontend/src/widgets/dashboard/DashboardSidebar.tsx
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
import { mdiBug, mdiForum, mdiKeyVariant, mdiLinkLock } from "@mdi/js";
|
||||||
|
import Icon from "@mdi/react";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import Drawer from "@mui/material/Drawer";
|
||||||
|
import List from "@mui/material/List";
|
||||||
|
import Toolbar from "@mui/material/Toolbar";
|
||||||
|
import { useTheme } from "@mui/material/styles";
|
||||||
|
import type {} from "@mui/material/themeCssVarsAugmentation";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
import * as React from "react";
|
||||||
|
import DashboardSidebarContext from "./DashboardSidebarContext";
|
||||||
|
import DashboardSidebarDividerItem from "./DashboardSidebarDividerItem";
|
||||||
|
import DashboardSidebarPageItem from "./DashboardSidebarPageItem";
|
||||||
|
import { DRAWER_WIDTH, MINI_DRAWER_WIDTH } from "./constants";
|
||||||
|
import {
|
||||||
|
getDrawerSxTransitionMixin,
|
||||||
|
getDrawerWidthTransitionMixin,
|
||||||
|
} from "./mixins";
|
||||||
|
|
||||||
|
export interface DashboardSidebarProps {
|
||||||
|
expanded?: boolean;
|
||||||
|
setExpanded: (expanded: boolean) => void;
|
||||||
|
disableCollapsibleSidebar?: boolean;
|
||||||
|
container?: Element;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardSidebar({
|
||||||
|
expanded = true,
|
||||||
|
setExpanded,
|
||||||
|
disableCollapsibleSidebar = false,
|
||||||
|
container,
|
||||||
|
}: DashboardSidebarProps) {
|
||||||
|
const theme = useTheme();
|
||||||
|
|
||||||
|
const isOverSmViewport = useMediaQuery(theme.breakpoints.up("sm"));
|
||||||
|
const isOverMdViewport = useMediaQuery(theme.breakpoints.up("md"));
|
||||||
|
|
||||||
|
const [isFullyExpanded, setIsFullyExpanded] = React.useState(expanded);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (expanded) {
|
||||||
|
const drawerWidthTransitionTimeout = setTimeout(() => {
|
||||||
|
setIsFullyExpanded(true);
|
||||||
|
}, theme.transitions.duration.enteringScreen);
|
||||||
|
|
||||||
|
return () => clearTimeout(drawerWidthTransitionTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsFullyExpanded(false);
|
||||||
|
|
||||||
|
return () => {};
|
||||||
|
}, [expanded, theme.transitions.duration.enteringScreen]);
|
||||||
|
|
||||||
|
const mini = !disableCollapsibleSidebar && !expanded;
|
||||||
|
|
||||||
|
const handleSetSidebarExpanded = React.useCallback(
|
||||||
|
(newExpanded: boolean) => () => {
|
||||||
|
setExpanded(newExpanded);
|
||||||
|
},
|
||||||
|
[setExpanded]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handlePageItemClick = React.useCallback(() => {
|
||||||
|
if (!isOverSmViewport) {
|
||||||
|
setExpanded(false);
|
||||||
|
}
|
||||||
|
}, [mini, setExpanded, isOverSmViewport]);
|
||||||
|
|
||||||
|
const hasDrawerTransitions =
|
||||||
|
isOverSmViewport && (!disableCollapsibleSidebar || isOverMdViewport);
|
||||||
|
|
||||||
|
const getDrawerContent = React.useCallback(
|
||||||
|
(viewport: "phone" | "tablet" | "desktop") => (
|
||||||
|
<React.Fragment>
|
||||||
|
<Toolbar />
|
||||||
|
<Box
|
||||||
|
component="nav"
|
||||||
|
aria-label={`${viewport.charAt(0).toUpperCase()}${viewport.slice(1)}`}
|
||||||
|
sx={{
|
||||||
|
height: "100%",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
overflow: "auto",
|
||||||
|
scrollbarGutter: mini ? "stable" : "auto",
|
||||||
|
overflowX: "hidden",
|
||||||
|
pt: !mini ? 0 : 2,
|
||||||
|
...(hasDrawerTransitions
|
||||||
|
? getDrawerSxTransitionMixin(isFullyExpanded, "padding")
|
||||||
|
: {}),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<List
|
||||||
|
dense
|
||||||
|
sx={{
|
||||||
|
padding: mini ? 0 : 0.5,
|
||||||
|
mb: 4,
|
||||||
|
width: mini ? MINI_DRAWER_WIDTH : "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DashboardSidebarPageItem
|
||||||
|
title="Messages"
|
||||||
|
icon={<Icon path={mdiForum} size={"1.5em"} />}
|
||||||
|
href="/"
|
||||||
|
/>
|
||||||
|
<DashboardSidebarDividerItem />
|
||||||
|
<DashboardSidebarPageItem
|
||||||
|
title="Matrix link"
|
||||||
|
icon={<Icon path={mdiLinkLock} size={"1.5em"} />}
|
||||||
|
href="/matrixlink"
|
||||||
|
/>
|
||||||
|
<DashboardSidebarPageItem
|
||||||
|
title="API tokens"
|
||||||
|
icon={<Icon path={mdiKeyVariant} size={"1.5em"} />}
|
||||||
|
href="/tokens"
|
||||||
|
/>
|
||||||
|
<DashboardSidebarPageItem
|
||||||
|
title="WS Debug"
|
||||||
|
icon={<Icon path={mdiBug} size={"1.5em"} />}
|
||||||
|
href="/wsdebug"
|
||||||
|
/>
|
||||||
|
</List>
|
||||||
|
</Box>
|
||||||
|
</React.Fragment>
|
||||||
|
),
|
||||||
|
[mini, hasDrawerTransitions, isFullyExpanded]
|
||||||
|
);
|
||||||
|
|
||||||
|
const getDrawerSharedSx = React.useCallback(
|
||||||
|
(isTemporary: boolean) => {
|
||||||
|
const drawerWidth = mini ? MINI_DRAWER_WIDTH : DRAWER_WIDTH;
|
||||||
|
|
||||||
|
return {
|
||||||
|
displayPrint: "none",
|
||||||
|
width: drawerWidth,
|
||||||
|
flexShrink: 0,
|
||||||
|
...getDrawerWidthTransitionMixin(expanded),
|
||||||
|
...(isTemporary ? { position: "absolute" } : {}),
|
||||||
|
[`& .MuiDrawer-paper`]: {
|
||||||
|
position: "absolute",
|
||||||
|
width: drawerWidth,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
backgroundImage: "none",
|
||||||
|
...getDrawerWidthTransitionMixin(expanded),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
[expanded, mini]
|
||||||
|
);
|
||||||
|
|
||||||
|
const sidebarContextValue = React.useMemo(() => {
|
||||||
|
return {
|
||||||
|
onPageItemClick: handlePageItemClick,
|
||||||
|
mini,
|
||||||
|
fullyExpanded: isFullyExpanded,
|
||||||
|
hasDrawerTransitions,
|
||||||
|
};
|
||||||
|
}, [handlePageItemClick, mini, isFullyExpanded, hasDrawerTransitions]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DashboardSidebarContext.Provider value={sidebarContextValue}>
|
||||||
|
<Drawer
|
||||||
|
container={container}
|
||||||
|
variant="temporary"
|
||||||
|
open={expanded}
|
||||||
|
onClose={handleSetSidebarExpanded(false)}
|
||||||
|
ModalProps={{
|
||||||
|
keepMounted: true, // Better open performance on mobile.
|
||||||
|
}}
|
||||||
|
sx={{
|
||||||
|
display: {
|
||||||
|
xs: "block",
|
||||||
|
sm: disableCollapsibleSidebar ? "block" : "none",
|
||||||
|
md: "none",
|
||||||
|
},
|
||||||
|
...getDrawerSharedSx(true),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{getDrawerContent("phone")}
|
||||||
|
</Drawer>
|
||||||
|
<Drawer
|
||||||
|
variant="permanent"
|
||||||
|
sx={{
|
||||||
|
display: {
|
||||||
|
xs: "none",
|
||||||
|
sm: disableCollapsibleSidebar ? "none" : "block",
|
||||||
|
md: "none",
|
||||||
|
},
|
||||||
|
...getDrawerSharedSx(false),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{getDrawerContent("tablet")}
|
||||||
|
</Drawer>
|
||||||
|
<Drawer
|
||||||
|
variant="permanent"
|
||||||
|
sx={{
|
||||||
|
display: { xs: "none", md: "block" },
|
||||||
|
...getDrawerSharedSx(false),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{getDrawerContent("desktop")}
|
||||||
|
</Drawer>
|
||||||
|
</DashboardSidebarContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
const DashboardSidebarContext = React.createContext<{
|
||||||
|
onPageItemClick: () => void;
|
||||||
|
mini: boolean;
|
||||||
|
fullyExpanded: boolean;
|
||||||
|
hasDrawerTransitions: boolean;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
export default DashboardSidebarContext;
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
import type {} from "@mui/material/themeCssVarsAugmentation";
|
||||||
|
import DashboardSidebarContext from "./DashboardSidebarContext";
|
||||||
|
import { getDrawerSxTransitionMixin } from "./mixins";
|
||||||
|
|
||||||
|
export default function DashboardSidebarDividerItem() {
|
||||||
|
const sidebarContext = React.useContext(DashboardSidebarContext);
|
||||||
|
if (!sidebarContext) {
|
||||||
|
throw new Error("Sidebar context was used without a provider.");
|
||||||
|
}
|
||||||
|
const { fullyExpanded = true, hasDrawerTransitions } = sidebarContext;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<Divider
|
||||||
|
sx={{
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
my: 1,
|
||||||
|
mx: -0.5,
|
||||||
|
...(hasDrawerTransitions
|
||||||
|
? getDrawerSxTransitionMixin(fullyExpanded, "margin")
|
||||||
|
: {}),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import Avatar from "@mui/material/Avatar";
|
||||||
|
import Box from "@mui/material/Box";
|
||||||
|
import ListItem from "@mui/material/ListItem";
|
||||||
|
import ListItemButton from "@mui/material/ListItemButton";
|
||||||
|
import ListItemIcon from "@mui/material/ListItemIcon";
|
||||||
|
import ListItemText from "@mui/material/ListItemText";
|
||||||
|
import Typography from "@mui/material/Typography";
|
||||||
|
import type {} from "@mui/material/themeCssVarsAugmentation";
|
||||||
|
import * as React from "react";
|
||||||
|
import { Link, matchPath, useLocation } from "react-router";
|
||||||
|
import DashboardSidebarContext from "./DashboardSidebarContext";
|
||||||
|
import { MINI_DRAWER_WIDTH } from "./constants";
|
||||||
|
|
||||||
|
export interface DashboardSidebarPageItemProps {
|
||||||
|
title: string;
|
||||||
|
icon?: React.ReactNode;
|
||||||
|
href: string;
|
||||||
|
action?: React.ReactNode;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardSidebarPageItem({
|
||||||
|
title,
|
||||||
|
icon,
|
||||||
|
href,
|
||||||
|
action,
|
||||||
|
disabled = false,
|
||||||
|
}: DashboardSidebarPageItemProps) {
|
||||||
|
const { pathname } = useLocation();
|
||||||
|
|
||||||
|
const sidebarContext = React.useContext(DashboardSidebarContext);
|
||||||
|
if (!sidebarContext) {
|
||||||
|
throw new Error("Sidebar context was used without a provider.");
|
||||||
|
}
|
||||||
|
const {
|
||||||
|
onPageItemClick,
|
||||||
|
mini = false,
|
||||||
|
fullyExpanded = true,
|
||||||
|
} = sidebarContext;
|
||||||
|
|
||||||
|
const hasExternalHref = href
|
||||||
|
? href.startsWith("http://") || href.startsWith("https://")
|
||||||
|
: false;
|
||||||
|
|
||||||
|
const LinkComponent = hasExternalHref ? "a" : Link;
|
||||||
|
|
||||||
|
const selected = !!matchPath(href, pathname);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<React.Fragment>
|
||||||
|
<ListItem disablePadding style={{ padding: "5px" }}>
|
||||||
|
<ListItemButton
|
||||||
|
selected={selected}
|
||||||
|
disabled={disabled}
|
||||||
|
sx={{
|
||||||
|
height: mini ? 50 : "auto",
|
||||||
|
}}
|
||||||
|
{...{
|
||||||
|
LinkComponent,
|
||||||
|
...(hasExternalHref
|
||||||
|
? {
|
||||||
|
target: "_blank",
|
||||||
|
rel: "noopener noreferrer",
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
to: href,
|
||||||
|
onClick: onPageItemClick,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon || mini ? (
|
||||||
|
<Box
|
||||||
|
sx={
|
||||||
|
mini
|
||||||
|
? {
|
||||||
|
position: "absolute",
|
||||||
|
left: "50%",
|
||||||
|
top: "calc(50% - 6px)",
|
||||||
|
transform: "translate(-50%, -50%)",
|
||||||
|
}
|
||||||
|
: {}
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ListItemIcon
|
||||||
|
sx={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: mini ? "center" : "auto",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon ?? null}
|
||||||
|
{!icon && mini ? (
|
||||||
|
<Avatar
|
||||||
|
sx={{
|
||||||
|
fontSize: 10,
|
||||||
|
height: 16,
|
||||||
|
width: 16,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{title
|
||||||
|
.split(" ")
|
||||||
|
.slice(0, 2)
|
||||||
|
.map((titleWord) => titleWord.charAt(0).toUpperCase())}
|
||||||
|
</Avatar>
|
||||||
|
) : null}
|
||||||
|
</ListItemIcon>
|
||||||
|
{mini ? (
|
||||||
|
<Typography
|
||||||
|
variant="caption"
|
||||||
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
|
bottom: -18,
|
||||||
|
left: "50%",
|
||||||
|
transform: "translateX(-50%)",
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: 500,
|
||||||
|
textAlign: "center",
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
overflow: "hidden",
|
||||||
|
textOverflow: "ellipsis",
|
||||||
|
maxWidth: MINI_DRAWER_WIDTH - 28,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</Typography>
|
||||||
|
) : null}
|
||||||
|
</Box>
|
||||||
|
) : null}
|
||||||
|
{!mini ? (
|
||||||
|
<ListItemText
|
||||||
|
primary={title}
|
||||||
|
sx={{
|
||||||
|
whiteSpace: "nowrap",
|
||||||
|
zIndex: 1,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
{action && !mini && fullyExpanded ? action : null}
|
||||||
|
</ListItemButton>
|
||||||
|
</ListItem>
|
||||||
|
</React.Fragment>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import Divider from "@mui/material/Divider";
|
||||||
|
import type {} from "@mui/material/themeCssVarsAugmentation";
|
||||||
|
import DashboardSidebarContext from "./DashboardSidebarContext";
|
||||||
|
import { getDrawerSxTransitionMixin } from "./mixins";
|
||||||
|
|
||||||
|
export default function DashboardSidebarDividerItem() {
|
||||||
|
const sidebarContext = React.useContext(DashboardSidebarContext);
|
||||||
|
if (!sidebarContext) {
|
||||||
|
throw new Error("Sidebar context was used without a provider.");
|
||||||
|
}
|
||||||
|
const { fullyExpanded = true, hasDrawerTransitions } = sidebarContext;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<Divider
|
||||||
|
sx={{
|
||||||
|
borderBottomWidth: 1,
|
||||||
|
my: 1,
|
||||||
|
mx: -0.5,
|
||||||
|
...(hasDrawerTransitions
|
||||||
|
? getDrawerSxTransitionMixin(fullyExpanded, "margin")
|
||||||
|
: {}),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
59
matrixgw_frontend/src/widgets/dashboard/ThemeSwitcher.tsx
Normal file
59
matrixgw_frontend/src/widgets/dashboard/ThemeSwitcher.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { useTheme, useColorScheme } from "@mui/material/styles";
|
||||||
|
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||||
|
import IconButton from "@mui/material/IconButton";
|
||||||
|
import Tooltip from "@mui/material/Tooltip";
|
||||||
|
import DarkModeIcon from "@mui/icons-material/DarkMode";
|
||||||
|
import LightModeIcon from "@mui/icons-material/LightMode";
|
||||||
|
import type {} from "@mui/material/themeCssVarsAugmentation";
|
||||||
|
|
||||||
|
export default function ThemeSwitcher() {
|
||||||
|
const theme = useTheme();
|
||||||
|
|
||||||
|
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
|
||||||
|
const preferredMode = prefersDarkMode ? "dark" : "light";
|
||||||
|
|
||||||
|
const { mode, setMode } = useColorScheme();
|
||||||
|
|
||||||
|
const paletteMode = !mode || mode === "system" ? preferredMode : mode;
|
||||||
|
|
||||||
|
const toggleMode = React.useCallback(() => {
|
||||||
|
setMode(paletteMode === "dark" ? "light" : "dark");
|
||||||
|
}, [setMode, paletteMode]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
title={`${paletteMode === "dark" ? "Light" : "Dark"} mode`}
|
||||||
|
enterDelay={1000}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
aria-label={`Switch to ${
|
||||||
|
paletteMode === "dark" ? "light" : "dark"
|
||||||
|
} mode`}
|
||||||
|
onClick={toggleMode}
|
||||||
|
>
|
||||||
|
<React.Fragment>
|
||||||
|
<LightModeIcon
|
||||||
|
sx={{
|
||||||
|
display: "inline",
|
||||||
|
[theme.getColorSchemeSelector("dark")]: {
|
||||||
|
display: "none",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<DarkModeIcon
|
||||||
|
sx={{
|
||||||
|
display: "none",
|
||||||
|
[theme.getColorSchemeSelector("dark")]: {
|
||||||
|
display: "inline",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</React.Fragment>
|
||||||
|
</IconButton>
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
2
matrixgw_frontend/src/widgets/dashboard/constants.ts
Normal file
2
matrixgw_frontend/src/widgets/dashboard/constants.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export const DRAWER_WIDTH = 240; // px
|
||||||
|
export const MINI_DRAWER_WIDTH = 90; // px
|
||||||
23
matrixgw_frontend/src/widgets/dashboard/mixins.ts
Normal file
23
matrixgw_frontend/src/widgets/dashboard/mixins.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { type Theme } from "@mui/material/styles";
|
||||||
|
|
||||||
|
export function getDrawerSxTransitionMixin(
|
||||||
|
isExpanded: boolean,
|
||||||
|
property: string
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
transition: (theme: Theme) =>
|
||||||
|
theme.transitions.create(property, {
|
||||||
|
easing: theme.transitions.easing.sharp,
|
||||||
|
duration: isExpanded
|
||||||
|
? theme.transitions.duration.enteringScreen
|
||||||
|
: theme.transitions.duration.leavingScreen,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDrawerWidthTransitionMixin(isExpanded: boolean) {
|
||||||
|
return {
|
||||||
|
...getDrawerSxTransitionMixin(isExpanded, "width"),
|
||||||
|
overflowX: "hidden",
|
||||||
|
};
|
||||||
|
}
|
||||||
28
matrixgw_frontend/tsconfig.app.json
Normal file
28
matrixgw_frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["vite/client"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
7
matrixgw_frontend/tsconfig.json
Normal file
7
matrixgw_frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
26
matrixgw_frontend/tsconfig.node.json
Normal file
26
matrixgw_frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"types": ["node"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
7
matrixgw_frontend/vite.config.ts
Normal file
7
matrixgw_frontend/vite.config.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
})
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
use crate::sync_client::SyncClientID;
|
|
||||||
use crate::user::{APIClientID, UserID};
|
|
||||||
use ruma::api::client::sync::sync_events::v3::{GlobalAccountData, Presence, Rooms, ToDevice};
|
|
||||||
use ruma::api::client::sync::sync_events::DeviceLists;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
|
||||||
pub struct SyncEvent {
|
|
||||||
/// Updates to rooms.
|
|
||||||
#[serde(default, skip_serializing_if = "Rooms::is_empty")]
|
|
||||||
pub rooms: Rooms,
|
|
||||||
|
|
||||||
/// Updates to the presence status of other users.
|
|
||||||
#[serde(default, skip_serializing_if = "Presence::is_empty")]
|
|
||||||
pub presence: Presence,
|
|
||||||
|
|
||||||
/// The global private data created by this user.
|
|
||||||
#[serde(default, skip_serializing_if = "GlobalAccountData::is_empty")]
|
|
||||||
pub account_data: GlobalAccountData,
|
|
||||||
|
|
||||||
/// Messages sent directly between devices.
|
|
||||||
#[serde(default, skip_serializing_if = "ToDevice::is_empty")]
|
|
||||||
pub to_device: ToDevice,
|
|
||||||
|
|
||||||
/// Information on E2E device updates.
|
|
||||||
///
|
|
||||||
/// Only present on an incremental sync.
|
|
||||||
#[serde(default, skip_serializing_if = "DeviceLists::is_empty")]
|
|
||||||
pub device_lists: DeviceLists,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Broadcast messages
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum BroadcastMessage {
|
|
||||||
/// Request to close the session of a specific client
|
|
||||||
CloseClientSession(APIClientID),
|
|
||||||
/// Close all the sessions of a given user
|
|
||||||
CloseAllUserSessions(UserID),
|
|
||||||
/// Stop sync client for a given user
|
|
||||||
StopSyncTaskForUser(UserID),
|
|
||||||
/// Start sync client for a given user (if not already running)
|
|
||||||
StartSyncTaskForUser(UserID),
|
|
||||||
/// Stop a client with a given client ID
|
|
||||||
StopSyncClient(SyncClientID),
|
|
||||||
/// Propagate a new sync event
|
|
||||||
SyncEvent(UserID, Box<SyncEvent>),
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
/// Session key for OpenID login state
|
|
||||||
pub const STATE_KEY: &str = "oidc-state";
|
|
||||||
|
|
||||||
/// Session key for user information
|
|
||||||
pub const USER_SESSION_KEY: &str = "user";
|
|
||||||
|
|
||||||
/// Token length
|
|
||||||
pub const TOKEN_LEN: usize = 20;
|
|
||||||
|
|
||||||
/// How often heartbeat pings are sent.
|
|
||||||
///
|
|
||||||
/// Should be half (or less) of the acceptable client timeout.
|
|
||||||
pub const WS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
|
|
||||||
|
|
||||||
/// How long before lack of client response causes a timeout.
|
|
||||||
pub const WS_CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
|
|
||||||
@@ -1,256 +0,0 @@
|
|||||||
use crate::constants::USER_SESSION_KEY;
|
|
||||||
use crate::server::HttpFailure;
|
|
||||||
use crate::user::{APIClient, APIClientID, RumaClient, User, UserConfig, UserID};
|
|
||||||
use crate::utils::base_utils::curr_time;
|
|
||||||
use actix_remote_ip::RemoteIP;
|
|
||||||
use actix_session::Session;
|
|
||||||
use actix_web::dev::Payload;
|
|
||||||
use actix_web::{FromRequest, HttpRequest};
|
|
||||||
use bytes::Bytes;
|
|
||||||
use jwt_simple::common::VerificationOptions;
|
|
||||||
use jwt_simple::prelude::{Duration, HS256Key, MACLike};
|
|
||||||
use ruma::api::{IncomingResponse, OutgoingRequest};
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use std::net::IpAddr;
|
|
||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
pub struct APIClientAuth {
|
|
||||||
pub user: UserConfig,
|
|
||||||
pub client: Option<APIClient>,
|
|
||||||
pub payload: Option<Vec<u8>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
|
||||||
pub struct TokenClaims {
|
|
||||||
#[serde(rename = "met")]
|
|
||||||
pub method: String,
|
|
||||||
pub uri: String,
|
|
||||||
#[serde(rename = "pay", skip_serializing_if = "Option::is_none")]
|
|
||||||
pub payload_sha256: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl APIClientAuth {
|
|
||||||
async fn extract_auth(
|
|
||||||
req: &HttpRequest,
|
|
||||||
remote_ip: IpAddr,
|
|
||||||
payload_bytes: Option<Bytes>,
|
|
||||||
) -> Result<Self, actix_web::Error> {
|
|
||||||
// Check if user is authenticated using Web UI
|
|
||||||
let session = Session::from_request(req, &mut Payload::None).await?;
|
|
||||||
|
|
||||||
if let Some(user) = session.get::<User>(USER_SESSION_KEY)? {
|
|
||||||
match UserConfig::load(&user.id, false).await {
|
|
||||||
Ok(config) => {
|
|
||||||
return Ok(Self {
|
|
||||||
user: config,
|
|
||||||
client: None,
|
|
||||||
payload: payload_bytes.map(|bytes| bytes.to_vec()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to fetch user information for authentication using cookie token! {e}");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(token) = req.headers().get("x-client-auth") else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Missing authentication header!",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
let Ok(jwt_token) = token.to_str() else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Failed to decode token as string!",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
let metadata = match jwt_simple::token::Token::decode_metadata(jwt_token) {
|
|
||||||
Ok(m) => m,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to decode JWT header metadata! {e}");
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Failed to decode JWT header metadata!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(kid) = metadata.key_id() else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Missing key id in request!",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some((user_id, client_id)) = kid.split_once("#") else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Invalid key format (missing part)!",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
let (Ok(user_id), Ok(client_id)) =
|
|
||||||
(urlencoding::decode(user_id), urlencoding::decode(client_id))
|
|
||||||
else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Invalid key format (decoding failed)!",
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Fetch user
|
|
||||||
const USER_NOT_FOUND_ERROR: &str = "User not found!";
|
|
||||||
let user = match UserConfig::load(&UserID(user_id.to_string()), false).await {
|
|
||||||
Ok(u) => u,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to get user information! {e}");
|
|
||||||
return Err(actix_web::error::ErrorForbidden(USER_NOT_FOUND_ERROR));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Find client
|
|
||||||
let Ok(client_id) = APIClientID::from_str(&client_id) else {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest("Invalid token format!"));
|
|
||||||
};
|
|
||||||
let Some(client) = user.find_client_by_id(&client_id) else {
|
|
||||||
log::error!("Client not found for user!");
|
|
||||||
return Err(actix_web::error::ErrorForbidden(USER_NOT_FOUND_ERROR));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Decode JWT
|
|
||||||
let key = HS256Key::from_bytes(client.secret.as_bytes());
|
|
||||||
let verif = VerificationOptions {
|
|
||||||
max_validity: Some(Duration::from_mins(15)),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let claims = match key.verify_token::<TokenClaims>(jwt_token, Some(verif)) {
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("JWT validation failed! {e}");
|
|
||||||
return Err(actix_web::error::ErrorForbidden("JWT validation failed!"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check for nonce
|
|
||||||
if claims.nonce.is_none() {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"A nonce is required in JWT!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check IP restriction
|
|
||||||
if let Some(net) = client.network {
|
|
||||||
if !net.contains(&remote_ip) {
|
|
||||||
log::error!(
|
|
||||||
"Trying to use client {} from unauthorized IP address: {remote_ip}",
|
|
||||||
client.id.0
|
|
||||||
);
|
|
||||||
return Err(actix_web::error::ErrorForbidden(
|
|
||||||
"This client cannot be used from this IP address!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check URI & verb
|
|
||||||
if claims.custom.uri != req.uri().to_string() {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest("URI mismatch!"));
|
|
||||||
}
|
|
||||||
if claims.custom.method != req.method().to_string() {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest("Method mismatch!"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for write access
|
|
||||||
if client.readonly_client && !req.method().is_safe() {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Read only client cannot perform write operations!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let payload = match (payload_bytes, claims.custom.payload_sha256) {
|
|
||||||
(None, _) => None,
|
|
||||||
(Some(_), None) => {
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"A payload digest must be included in the JWT when the request has a payload!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
(Some(payload), Some(provided_digest)) => {
|
|
||||||
let computed_digest = base16ct::lower::encode_string(&Sha256::digest(&payload));
|
|
||||||
if computed_digest != provided_digest {
|
|
||||||
log::error!(
|
|
||||||
"Expected digest {provided_digest} but computed {computed_digest}!"
|
|
||||||
);
|
|
||||||
return Err(actix_web::error::ErrorBadRequest(
|
|
||||||
"Computed digest is different from the one provided in the JWT!",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(payload.to_vec())
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Update last use (if needed)
|
|
||||||
if client.need_update_last_used() {
|
|
||||||
let mut user_up = user.clone();
|
|
||||||
match user_up.find_client_by_id_mut(&client.id) {
|
|
||||||
None => log::error!("Client ID disappeared!!!"),
|
|
||||||
Some(u) => u.used = curr_time().unwrap(),
|
|
||||||
}
|
|
||||||
if let Err(e) = user_up.save().await {
|
|
||||||
log::error!("Failed to update last token usage! {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
client: Some(client.clone()),
|
|
||||||
payload,
|
|
||||||
user,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get an instance of Matrix client
|
|
||||||
pub async fn client(&self) -> anyhow::Result<RumaClient> {
|
|
||||||
self.user.matrix_client().await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send request to matrix server
|
|
||||||
pub async fn send_request<R: OutgoingRequest<IncomingResponse = E>, E: IncomingResponse>(
|
|
||||||
&self,
|
|
||||||
request: R,
|
|
||||||
) -> anyhow::Result<E, HttpFailure> {
|
|
||||||
match self.client().await?.send_request(request).await {
|
|
||||||
Ok(e) => Ok(e),
|
|
||||||
Err(e) => Err(HttpFailure::MatrixClientError(e.to_string())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromRequest for APIClientAuth {
|
|
||||||
type Error = actix_web::Error;
|
|
||||||
type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
|
||||||
|
|
||||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
|
||||||
let req = req.clone();
|
|
||||||
|
|
||||||
let remote_ip = match RemoteIP::from_request(&req, &mut Payload::None).into_inner() {
|
|
||||||
Ok(ip) => ip,
|
|
||||||
Err(e) => return Box::pin(async { Err(e) }),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut payload = payload.take();
|
|
||||||
|
|
||||||
Box::pin(async move {
|
|
||||||
let payload_bytes = match Bytes::from_request(&req, &mut payload).await {
|
|
||||||
Ok(b) => {
|
|
||||||
if b.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(b)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to extract request payload! {e}");
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Self::extract_auth(&req, remote_ip.0, payload_bytes).await
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
pub mod client_auth;
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
pub mod app_config;
|
|
||||||
pub mod broadcast_messages;
|
|
||||||
pub mod constants;
|
|
||||||
pub mod extractors;
|
|
||||||
pub mod server;
|
|
||||||
pub mod sync_client;
|
|
||||||
pub mod user;
|
|
||||||
pub mod utils;
|
|
||||||
80
src/main.rs
80
src/main.rs
@@ -1,80 +0,0 @@
|
|||||||
use actix_remote_ip::RemoteIPConfig;
|
|
||||||
use actix_session::config::SessionLifecycle;
|
|
||||||
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
|
|
||||||
use actix_web::cookie::Key;
|
|
||||||
use actix_web::{web, App, HttpServer};
|
|
||||||
use matrix_gateway::app_config::AppConfig;
|
|
||||||
use matrix_gateway::broadcast_messages::BroadcastMessage;
|
|
||||||
use matrix_gateway::server::{api, web_ui};
|
|
||||||
use matrix_gateway::sync_client;
|
|
||||||
use matrix_gateway::user::UserConfig;
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
|
||||||
|
|
||||||
UserConfig::create_bucket_if_required()
|
|
||||||
.await
|
|
||||||
.expect("Failed to create bucket!");
|
|
||||||
|
|
||||||
let secret_key = Key::from(AppConfig::get().secret().as_bytes());
|
|
||||||
|
|
||||||
let redis_store = RedisSessionStore::new(AppConfig::get().redis_connection_string())
|
|
||||||
.await
|
|
||||||
.expect("Failed to connect to Redis!");
|
|
||||||
|
|
||||||
let (ws_tx, _) = tokio::sync::broadcast::channel::<BroadcastMessage>(16);
|
|
||||||
|
|
||||||
// Launch sync manager
|
|
||||||
tokio::spawn(sync_client::sync_client_manager(ws_tx.clone()));
|
|
||||||
|
|
||||||
log::info!(
|
|
||||||
"Starting to listen on {} for {}",
|
|
||||||
AppConfig::get().listen_address,
|
|
||||||
AppConfig::get().website_origin
|
|
||||||
);
|
|
||||||
HttpServer::new(move || {
|
|
||||||
App::new()
|
|
||||||
// Add session management to your application using Redis for session state storage
|
|
||||||
.wrap(
|
|
||||||
SessionMiddleware::builder(redis_store.clone(), secret_key.clone())
|
|
||||||
.cookie_name("matrixgw-session".to_string())
|
|
||||||
.session_lifecycle(SessionLifecycle::BrowserSession(Default::default()))
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.app_data(web::Data::new(RemoteIPConfig {
|
|
||||||
proxy: AppConfig::get().proxy_ip.clone(),
|
|
||||||
}))
|
|
||||||
.app_data(web::Data::new(ws_tx.clone()))
|
|
||||||
// Web configuration routes
|
|
||||||
.route("/assets/{tail:.*}", web::get().to(web_ui::static_file))
|
|
||||||
.route("/", web::get().to(web_ui::home))
|
|
||||||
.route("/", web::post().to(web_ui::home))
|
|
||||||
.route("/oidc_cb", web::get().to(web_ui::oidc_cb))
|
|
||||||
.route("/sign_out", web::get().to(web_ui::sign_out))
|
|
||||||
.route("/ws_debug", web::get().to(web_ui::ws_debug))
|
|
||||||
// API routes
|
|
||||||
.route("/api", web::get().to(api::api_home))
|
|
||||||
.route("/api", web::post().to(api::api_home))
|
|
||||||
.route("/api/account/whoami", web::get().to(api::account::who_am_i))
|
|
||||||
.route("/api/room/joined", web::get().to(api::room::joined_rooms))
|
|
||||||
.route("/api/room/{room_id}", web::get().to(api::room::info))
|
|
||||||
.route(
|
|
||||||
"/api/media/{server_name}/{media_id}/download",
|
|
||||||
web::get().to(api::media::download),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/media/{server_name}/{media_id}/thumbnail",
|
|
||||||
web::get().to(api::media::thumbnail),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/api/profile/{user_id}",
|
|
||||||
web::get().to(api::profile::get_profile),
|
|
||||||
)
|
|
||||||
.service(web::resource("/api/ws").route(web::get().to(api::ws::ws)))
|
|
||||||
})
|
|
||||||
.workers(4)
|
|
||||||
.bind(&AppConfig::get().listen_address)?
|
|
||||||
.run()
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::HttpResult;
|
|
||||||
use actix_web::HttpResponse;
|
|
||||||
use ruma::api::client::account;
|
|
||||||
use ruma::DeviceId;
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct WhoAmIResponse {
|
|
||||||
user_id: String,
|
|
||||||
device_id: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get current user identity
|
|
||||||
pub async fn who_am_i(auth: APIClientAuth) -> HttpResult {
|
|
||||||
let res = auth
|
|
||||||
.send_request(account::whoami::v3::Request::default())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(WhoAmIResponse {
|
|
||||||
user_id: res.user_id.to_string(),
|
|
||||||
device_id: res.device_id.as_deref().map(DeviceId::to_string),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::HttpResult;
|
|
||||||
use actix_web::{web, HttpResponse};
|
|
||||||
use ruma::api::client::media;
|
|
||||||
use ruma::{OwnedServerName, UInt};
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct MediaInfoInPath {
|
|
||||||
server_name: OwnedServerName,
|
|
||||||
media_id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Download a media
|
|
||||||
#[allow(deprecated)]
|
|
||||||
pub async fn download(auth: APIClientAuth, path: web::Path<MediaInfoInPath>) -> HttpResult {
|
|
||||||
let res = auth
|
|
||||||
.send_request(media::get_content::v3::Request::new(
|
|
||||||
path.media_id.clone(),
|
|
||||||
path.server_name.clone(),
|
|
||||||
))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut http_res = HttpResponse::Ok();
|
|
||||||
if let Some(content_type) = res.content_type {
|
|
||||||
http_res.content_type(content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(http_res.body(res.file))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct MediaThumbnailQuery {
|
|
||||||
width: Option<UInt>,
|
|
||||||
height: Option<UInt>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get a media thumbnail
|
|
||||||
#[allow(deprecated)]
|
|
||||||
pub async fn thumbnail(
|
|
||||||
auth: APIClientAuth,
|
|
||||||
path: web::Path<MediaInfoInPath>,
|
|
||||||
query: web::Query<MediaThumbnailQuery>,
|
|
||||||
) -> HttpResult {
|
|
||||||
let res = auth
|
|
||||||
.send_request(media::get_content_thumbnail::v3::Request::new(
|
|
||||||
path.media_id.clone(),
|
|
||||||
path.server_name.clone(),
|
|
||||||
query.width.unwrap_or(UInt::new(500).unwrap()),
|
|
||||||
query.height.unwrap_or(UInt::new(500).unwrap()),
|
|
||||||
))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut http_res = HttpResponse::Ok();
|
|
||||||
if let Some(content_type) = res.content_type {
|
|
||||||
http_res.content_type(content_type);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(http_res.body(res.file))
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::HttpResult;
|
|
||||||
use actix_web::HttpResponse;
|
|
||||||
|
|
||||||
pub mod account;
|
|
||||||
pub mod media;
|
|
||||||
pub mod profile;
|
|
||||||
pub mod room;
|
|
||||||
pub mod ws;
|
|
||||||
|
|
||||||
/// API Home route
|
|
||||||
pub async fn api_home(auth: APIClientAuth) -> HttpResult {
|
|
||||||
Ok(HttpResponse::Ok().body(format!("Welcome user {}!", auth.user.user_id.0)))
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::HttpResult;
|
|
||||||
use crate::utils::matrix_utils::ApiMxcURI;
|
|
||||||
use actix_web::{web, HttpResponse};
|
|
||||||
use ruma::api::client::profile;
|
|
||||||
use ruma::OwnedUserId;
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct UserIDInPath {
|
|
||||||
user_id: OwnedUserId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct ProfileResponse {
|
|
||||||
display_name: Option<String>,
|
|
||||||
avatar: Option<ApiMxcURI>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get user profile
|
|
||||||
pub async fn get_profile(auth: APIClientAuth, path: web::Path<UserIDInPath>) -> HttpResult {
|
|
||||||
let res = auth
|
|
||||||
.send_request(profile::get_profile::v3::Request::new(path.user_id.clone()))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(ProfileResponse {
|
|
||||||
display_name: res.displayname,
|
|
||||||
avatar: res.avatar_url.map(ApiMxcURI),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::{HttpFailure, HttpResult};
|
|
||||||
use crate::utils::matrix_utils::ApiMxcURI;
|
|
||||||
use actix_web::{web, HttpResponse};
|
|
||||||
use ruma::api::client::{membership, state};
|
|
||||||
use ruma::events::StateEventType;
|
|
||||||
use ruma::{OwnedMxcUri, OwnedRoomId};
|
|
||||||
use serde::de::DeserializeOwned;
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct GetRoomsMembershipsResponse {
|
|
||||||
rooms: Vec<OwnedRoomId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the list of rooms the user has joined
|
|
||||||
pub async fn joined_rooms(auth: APIClientAuth) -> HttpResult {
|
|
||||||
let res = auth
|
|
||||||
.send_request(membership::joined_rooms::v3::Request::default())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(GetRoomsMembershipsResponse {
|
|
||||||
rooms: res.joined_rooms,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct RoomIDInPath {
|
|
||||||
room_id: OwnedRoomId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct GetRoomInfoResponse {
|
|
||||||
name: Option<String>,
|
|
||||||
avatar: Option<ApiMxcURI>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get a room information
|
|
||||||
async fn get_room_info<E: DeserializeOwned>(
|
|
||||||
auth: &APIClientAuth,
|
|
||||||
room_id: OwnedRoomId,
|
|
||||||
event_type: StateEventType,
|
|
||||||
field: &str,
|
|
||||||
) -> anyhow::Result<Option<E>, HttpFailure> {
|
|
||||||
let res = auth
|
|
||||||
.send_request(state::get_state_events_for_key::v3::Request::new(
|
|
||||||
room_id,
|
|
||||||
event_type,
|
|
||||||
String::default(),
|
|
||||||
))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(res.content.get_field(field)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get room information
|
|
||||||
pub async fn info(auth: APIClientAuth, path: web::Path<RoomIDInPath>) -> HttpResult {
|
|
||||||
let room_name: Option<String> = get_room_info(
|
|
||||||
&auth,
|
|
||||||
path.room_id.clone(),
|
|
||||||
StateEventType::RoomName,
|
|
||||||
"name",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten();
|
|
||||||
|
|
||||||
let room_avatar: Option<OwnedMxcUri> = get_room_info(
|
|
||||||
&auth,
|
|
||||||
path.room_id.clone(),
|
|
||||||
StateEventType::RoomAvatar,
|
|
||||||
"url",
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten();
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(GetRoomInfoResponse {
|
|
||||||
name: room_name,
|
|
||||||
avatar: room_avatar.map(ApiMxcURI),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
use crate::broadcast_messages::{BroadcastMessage, SyncEvent};
|
|
||||||
use crate::constants::{WS_CLIENT_TIMEOUT, WS_HEARTBEAT_INTERVAL};
|
|
||||||
use crate::extractors::client_auth::APIClientAuth;
|
|
||||||
use crate::server::HttpResult;
|
|
||||||
use actix_web::dev::Payload;
|
|
||||||
use actix_web::{web, FromRequest, HttpRequest};
|
|
||||||
use actix_ws::Message;
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
use std::time::Instant;
|
|
||||||
use tokio::select;
|
|
||||||
use tokio::sync::broadcast;
|
|
||||||
use tokio::sync::broadcast::Receiver;
|
|
||||||
use tokio::time::interval;
|
|
||||||
|
|
||||||
/// Messages send to the client
|
|
||||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
|
||||||
#[serde(tag = "type")]
|
|
||||||
pub enum WsMessage {
|
|
||||||
Sync(SyncEvent),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Main WS route
|
|
||||||
pub async fn ws(
|
|
||||||
req: HttpRequest,
|
|
||||||
stream: web::Payload,
|
|
||||||
tx: web::Data<broadcast::Sender<BroadcastMessage>>,
|
|
||||||
) -> HttpResult {
|
|
||||||
// Forcefully ignore request payload by manually extracting authentication information
|
|
||||||
let auth = APIClientAuth::from_request(&req, &mut Payload::None).await?;
|
|
||||||
|
|
||||||
let (res, session, msg_stream) = actix_ws::handle(&req, stream)?;
|
|
||||||
|
|
||||||
// Ask for sync client to be started
|
|
||||||
if let Err(e) = tx.send(BroadcastMessage::StartSyncTaskForUser(
|
|
||||||
auth.user.user_id.clone(),
|
|
||||||
)) {
|
|
||||||
log::error!("Failed to send StartSyncTaskForUser: {e}");
|
|
||||||
}
|
|
||||||
|
|
||||||
let rx = tx.subscribe();
|
|
||||||
|
|
||||||
// spawn websocket handler (and don't await it) so that the response is returned immediately
|
|
||||||
actix_web::rt::spawn(ws_handler(session, msg_stream, auth, rx));
|
|
||||||
|
|
||||||
Ok(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn ws_handler(
|
|
||||||
mut session: actix_ws::Session,
|
|
||||||
mut msg_stream: actix_ws::MessageStream,
|
|
||||||
auth: APIClientAuth,
|
|
||||||
mut rx: Receiver<BroadcastMessage>,
|
|
||||||
) {
|
|
||||||
log::info!("WS connected");
|
|
||||||
|
|
||||||
let mut last_heartbeat = Instant::now();
|
|
||||||
let mut interval = interval(WS_HEARTBEAT_INTERVAL);
|
|
||||||
|
|
||||||
let reason = loop {
|
|
||||||
// waits for either `msg_stream` to receive a message from the client, the broadcast channel
|
|
||||||
// to send a message, or the heartbeat interval timer to tick, yielding the value of
|
|
||||||
// whichever one is ready first
|
|
||||||
select! {
|
|
||||||
ws_msg = rx.recv() => {
|
|
||||||
let msg = match ws_msg {
|
|
||||||
Ok(msg) => msg,
|
|
||||||
Err(broadcast::error::RecvError::Closed) => break None,
|
|
||||||
Err(broadcast::error::RecvError::Lagged(_)) => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
match msg {
|
|
||||||
BroadcastMessage::CloseClientSession(id) => {
|
|
||||||
if let Some(client) = &auth.client {
|
|
||||||
if client.id == id {
|
|
||||||
log::info!(
|
|
||||||
"closing client session {id:?} of user {:?} as requested", auth.user.user_id
|
|
||||||
);
|
|
||||||
break None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
BroadcastMessage::CloseAllUserSessions(userid) => {
|
|
||||||
if userid == auth.user.user_id {
|
|
||||||
log::info!(
|
|
||||||
"closing WS session of user {userid:?} as requested"
|
|
||||||
);
|
|
||||||
break None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
BroadcastMessage::SyncEvent(userid, event) => {
|
|
||||||
if userid != auth.user.user_id {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the message to the websocket
|
|
||||||
if let Ok(msg) = serde_json::to_string(&WsMessage::Sync(*event)) {
|
|
||||||
if let Err(e) = session.text(msg).await {
|
|
||||||
log::error!("Failed to send SyncEvent: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}};
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// heartbeat interval ticked
|
|
||||||
_tick = interval.tick() => {
|
|
||||||
// if no heartbeat ping/pong received recently, close the connection
|
|
||||||
if Instant::now().duration_since(last_heartbeat) > WS_CLIENT_TIMEOUT {
|
|
||||||
log::info!(
|
|
||||||
"client has not sent heartbeat in over {WS_CLIENT_TIMEOUT:?}; disconnecting"
|
|
||||||
);
|
|
||||||
|
|
||||||
break None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// send heartbeat ping
|
|
||||||
let _ = session.ping(b"").await;
|
|
||||||
},
|
|
||||||
|
|
||||||
msg = msg_stream.next() => {
|
|
||||||
let msg = match msg {
|
|
||||||
// received message from WebSocket client
|
|
||||||
Some(Ok(msg)) => msg,
|
|
||||||
|
|
||||||
// client WebSocket stream error
|
|
||||||
Some(Err(err)) => {
|
|
||||||
log::error!("{err}");
|
|
||||||
break None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// client WebSocket stream ended
|
|
||||||
None => break None
|
|
||||||
};
|
|
||||||
|
|
||||||
log::debug!("msg: {msg:?}");
|
|
||||||
|
|
||||||
match msg {
|
|
||||||
Message::Text(s) => {
|
|
||||||
log::info!("Text message: {s}");
|
|
||||||
}
|
|
||||||
|
|
||||||
Message::Binary(_) => {
|
|
||||||
// drop client's binary messages
|
|
||||||
}
|
|
||||||
|
|
||||||
Message::Close(reason) => {
|
|
||||||
break reason;
|
|
||||||
}
|
|
||||||
|
|
||||||
Message::Ping(bytes) => {
|
|
||||||
last_heartbeat = Instant::now();
|
|
||||||
let _ = session.pong(&bytes).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
Message::Pong(_) => {
|
|
||||||
last_heartbeat = Instant::now();
|
|
||||||
}
|
|
||||||
|
|
||||||
Message::Continuation(_) => {
|
|
||||||
log::warn!("no support for continuation frames");
|
|
||||||
}
|
|
||||||
|
|
||||||
// no-op; ignore
|
|
||||||
Message::Nop => {}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// attempt to close connection gracefully
|
|
||||||
let _ = session.close(reason).await;
|
|
||||||
|
|
||||||
log::info!("WS disconnected");
|
|
||||||
}
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
use crate::app_config::AppConfig;
|
|
||||||
use crate::broadcast_messages::BroadcastMessage;
|
|
||||||
use crate::constants::{STATE_KEY, USER_SESSION_KEY};
|
|
||||||
use crate::server::{HttpFailure, HttpResult};
|
|
||||||
use crate::user::{APIClient, APIClientID, User, UserConfig, UserID};
|
|
||||||
use crate::utils::base_utils;
|
|
||||||
use actix_session::Session;
|
|
||||||
use actix_web::{web, HttpResponse};
|
|
||||||
use askama::Template;
|
|
||||||
use ipnet::IpNet;
|
|
||||||
use light_openid::primitives::OpenIDConfig;
|
|
||||||
use std::str::FromStr;
|
|
||||||
use tokio::sync::broadcast;
|
|
||||||
|
|
||||||
/// Static assets
|
|
||||||
#[derive(rust_embed::Embed)]
|
|
||||||
#[folder = "assets/"]
|
|
||||||
struct Assets;
|
|
||||||
|
|
||||||
/// Serve static file
|
|
||||||
pub async fn static_file(path: web::Path<String>) -> HttpResult {
|
|
||||||
match Assets::get(path.as_ref()) {
|
|
||||||
Some(content) => Ok(HttpResponse::Ok()
|
|
||||||
.content_type(
|
|
||||||
mime_guess::from_path(path.as_str())
|
|
||||||
.first_or_octet_stream()
|
|
||||||
.as_ref(),
|
|
||||||
)
|
|
||||||
.body(content.data.into_owned())),
|
|
||||||
None => Ok(HttpResponse::NotFound().body("404 Not Found")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(askama::Template)]
|
|
||||||
#[template(path = "index.html")]
|
|
||||||
struct HomeTemplate {
|
|
||||||
name: String,
|
|
||||||
user_id: UserID,
|
|
||||||
matrix_token: String,
|
|
||||||
clients: Vec<APIClient>,
|
|
||||||
success_message: Option<String>,
|
|
||||||
error_message: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// HTTP form request
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct FormRequest {
|
|
||||||
/// Update matrix token
|
|
||||||
new_matrix_token: Option<String>,
|
|
||||||
|
|
||||||
/// Create a new client
|
|
||||||
new_client_desc: Option<String>,
|
|
||||||
|
|
||||||
/// Restrict new client to a given network
|
|
||||||
ip_network: Option<String>,
|
|
||||||
|
|
||||||
/// Grant read only access to client
|
|
||||||
readonly_client: Option<String>,
|
|
||||||
|
|
||||||
/// Delete a specified client id
|
|
||||||
delete_client_id: Option<APIClientID>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Main route
|
|
||||||
pub async fn home(
|
|
||||||
session: Session,
|
|
||||||
form_req: Option<web::Form<FormRequest>>,
|
|
||||||
tx: web::Data<broadcast::Sender<BroadcastMessage>>,
|
|
||||||
) -> HttpResult {
|
|
||||||
// Get user information, requesting authentication if information is missing
|
|
||||||
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
|
|
||||||
// Generate auth state
|
|
||||||
let state = base_utils::rand_str(50);
|
|
||||||
session.insert(STATE_KEY, &state)?;
|
|
||||||
|
|
||||||
let oidc = AppConfig::get().openid_provider();
|
|
||||||
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
|
|
||||||
.await
|
|
||||||
.map_err(HttpFailure::OpenID)?;
|
|
||||||
|
|
||||||
let auth_url = config.gen_authorization_url(oidc.client_id, &state, &oidc.redirect_url);
|
|
||||||
|
|
||||||
return Ok(HttpResponse::Found()
|
|
||||||
.append_header(("location", auth_url))
|
|
||||||
.finish());
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut success_message = None;
|
|
||||||
let mut error_message = None;
|
|
||||||
|
|
||||||
// Retrieve user configuration
|
|
||||||
let mut config = UserConfig::load(&user.id, true)
|
|
||||||
.await
|
|
||||||
.map_err(HttpFailure::FetchUserConfig)?;
|
|
||||||
|
|
||||||
if let Some(form_req) = form_req {
|
|
||||||
// Update matrix token, if requested
|
|
||||||
if let Some(t) = form_req.0.new_matrix_token {
|
|
||||||
if t.len() < 3 {
|
|
||||||
error_message = Some("Specified Matrix token is too short!".to_string());
|
|
||||||
} else {
|
|
||||||
config.matrix_token = t;
|
|
||||||
config.save().await?;
|
|
||||||
success_message = Some("Matrix token was successfully updated!".to_string());
|
|
||||||
|
|
||||||
// Close sync task
|
|
||||||
if let Err(e) = tx.send(BroadcastMessage::StopSyncTaskForUser(user.id.clone())) {
|
|
||||||
log::error!("Failed to send StopSyncClientForUser: {e}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Invalidate all Ws connections
|
|
||||||
if let Err(e) = tx.send(BroadcastMessage::CloseAllUserSessions(user.id.clone())) {
|
|
||||||
log::error!("Failed to send CloseAllUserSessions: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new client, if requested
|
|
||||||
if let Some(new_token_desc) = form_req.0.new_client_desc {
|
|
||||||
let ip_net = match form_req.0.ip_network.as_deref() {
|
|
||||||
None | Some("") => None,
|
|
||||||
Some(e) => match IpNet::from_str(e) {
|
|
||||||
Ok(n) => Some(n),
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to parse IP network provided by user: {e}");
|
|
||||||
error_message = Some(format!("Failed to parse restricted IP network: {e}"));
|
|
||||||
None
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if error_message.is_none() {
|
|
||||||
let mut token = APIClient::generate(new_token_desc, ip_net);
|
|
||||||
token.readonly_client = form_req.0.readonly_client.is_some();
|
|
||||||
success_message = Some(format!("The secret of your new token is '{}'. Be sure to write it somewhere as you will not be able to recover it later!", token.secret));
|
|
||||||
config.clients.push(token);
|
|
||||||
config.save().await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete a client
|
|
||||||
if let Some(delete_client_id) = form_req.0.delete_client_id {
|
|
||||||
config.clients.retain(|c| c.id != delete_client_id);
|
|
||||||
config.save().await?;
|
|
||||||
success_message = Some("The client was successfully deleted!".to_string());
|
|
||||||
|
|
||||||
if let Err(e) = tx.send(BroadcastMessage::CloseClientSession(delete_client_id)) {
|
|
||||||
log::error!("Failed to send CloseClientSession: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Render page
|
|
||||||
Ok(HttpResponse::Ok()
|
|
||||||
.insert_header(("content-type", "text/html"))
|
|
||||||
.body(
|
|
||||||
HomeTemplate {
|
|
||||||
name: user.name,
|
|
||||||
user_id: user.id,
|
|
||||||
matrix_token: config.obfuscated_matrix_token(),
|
|
||||||
clients: config.clients,
|
|
||||||
success_message,
|
|
||||||
error_message,
|
|
||||||
}
|
|
||||||
.render()
|
|
||||||
.unwrap(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
pub struct AuthCallbackQuery {
|
|
||||||
code: String,
|
|
||||||
state: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Authenticate user callback
|
|
||||||
pub async fn oidc_cb(session: Session, query: web::Query<AuthCallbackQuery>) -> HttpResult {
|
|
||||||
if session.get(STATE_KEY)? != Some(query.state.to_string()) {
|
|
||||||
return Ok(HttpResponse::BadRequest()
|
|
||||||
.append_header(("content-type", "text/html"))
|
|
||||||
.body("State mismatch! <a href='/'>Try again</a>"));
|
|
||||||
}
|
|
||||||
|
|
||||||
let oidc = AppConfig::get().openid_provider();
|
|
||||||
let config = OpenIDConfig::load_from_url(oidc.configuration_url)
|
|
||||||
.await
|
|
||||||
.map_err(HttpFailure::OpenID)?;
|
|
||||||
|
|
||||||
let (token, _) = match config
|
|
||||||
.request_token(
|
|
||||||
oidc.client_id,
|
|
||||||
oidc.client_secret,
|
|
||||||
&query.code,
|
|
||||||
&oidc.redirect_url,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(t) => t,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to request user token! {e}");
|
|
||||||
|
|
||||||
return Ok(HttpResponse::BadRequest()
|
|
||||||
.append_header(("content-type", "text/html"))
|
|
||||||
.body("Authentication failed! <a href='/'>Try again</a>"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let (user, _) = config
|
|
||||||
.request_user_info(&token)
|
|
||||||
.await
|
|
||||||
.map_err(HttpFailure::OpenID)?;
|
|
||||||
|
|
||||||
let user = User {
|
|
||||||
id: UserID(user.sub),
|
|
||||||
name: user.name.unwrap_or("no_name".to_string()),
|
|
||||||
email: user.email.unwrap_or("no@mail.com".to_string()),
|
|
||||||
};
|
|
||||||
log::info!("Successful authentication as {user:?}");
|
|
||||||
session.insert(USER_SESSION_KEY, user)?;
|
|
||||||
|
|
||||||
Ok(HttpResponse::Found()
|
|
||||||
.insert_header(("location", "/"))
|
|
||||||
.finish())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// De-authenticate user
|
|
||||||
pub async fn sign_out(session: Session) -> HttpResult {
|
|
||||||
session.remove(USER_SESSION_KEY);
|
|
||||||
|
|
||||||
Ok(HttpResponse::Found()
|
|
||||||
.insert_header(("location", "/"))
|
|
||||||
.finish())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(askama::Template)]
|
|
||||||
#[template(path = "ws_debug.html")]
|
|
||||||
struct WsDebugTemplate {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// WebSocket debug
|
|
||||||
pub async fn ws_debug(session: Session) -> HttpResult {
|
|
||||||
let Some(user): Option<User> = session.get(USER_SESSION_KEY)? else {
|
|
||||||
return Ok(HttpResponse::Found()
|
|
||||||
.insert_header(("location", "/"))
|
|
||||||
.finish());
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(HttpResponse::Ok()
|
|
||||||
.content_type("text/html")
|
|
||||||
.body(WsDebugTemplate { name: user.name }.render().unwrap()))
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
use crate::broadcast_messages::{BroadcastMessage, SyncEvent};
|
|
||||||
use crate::user::{UserConfig, UserID};
|
|
||||||
use futures_util::TryStreamExt;
|
|
||||||
use ruma::api::client::sync::sync_events;
|
|
||||||
use ruma::assign;
|
|
||||||
use ruma::presence::PresenceState;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
use tokio::sync::broadcast;
|
|
||||||
|
|
||||||
/// ID of sync client
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
|
||||||
pub struct SyncClientID(uuid::Uuid);
|
|
||||||
|
|
||||||
/// Sync client launcher loop
|
|
||||||
pub async fn sync_client_manager(tx: broadcast::Sender<BroadcastMessage>) -> ! {
|
|
||||||
let mut rx = tx.subscribe();
|
|
||||||
let tx = Arc::new(tx.clone());
|
|
||||||
|
|
||||||
let mut running_tasks = HashMap::new();
|
|
||||||
|
|
||||||
while let Ok(msg) = rx.recv().await {
|
|
||||||
match msg {
|
|
||||||
BroadcastMessage::StartSyncTaskForUser(user_id) => {
|
|
||||||
if running_tasks.contains_key(&user_id) {
|
|
||||||
log::info!("Won't start sync task for user {user_id:?} because a task is already running for this user!");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
log::info!("Start sync task for user {user_id:?}");
|
|
||||||
let task_id = SyncClientID(uuid::Uuid::new_v4());
|
|
||||||
running_tasks.insert(user_id.clone(), task_id.clone());
|
|
||||||
|
|
||||||
let tx = tx.clone();
|
|
||||||
tokio::task::spawn(async move {
|
|
||||||
sync_task(task_id, user_id, tx).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
BroadcastMessage::StopSyncTaskForUser(user_id) => {
|
|
||||||
// Check if a task is running for this user
|
|
||||||
if let Some(task_id) = running_tasks.remove(&user_id) {
|
|
||||||
log::info!("Stop sync task for user {user_id:?}");
|
|
||||||
tx.send(BroadcastMessage::StopSyncClient(task_id)).unwrap();
|
|
||||||
} else {
|
|
||||||
log::info!("Not stopping sync task for user {user_id:?}: not running");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
panic!("Sync client manager stopped unexpectedly!");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sync task for a single user
|
|
||||||
async fn sync_task(
|
|
||||||
id: SyncClientID,
|
|
||||||
user_id: UserID,
|
|
||||||
tx: Arc<broadcast::Sender<BroadcastMessage>>,
|
|
||||||
) {
|
|
||||||
let mut rx = tx.subscribe();
|
|
||||||
|
|
||||||
let Ok(user_config) = UserConfig::load(&user_id, false).await else {
|
|
||||||
log::error!("Failed to load user config in sync thread!");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let client = match user_config.matrix_client().await {
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to load matrix client for user {user_id:?}: {e}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Ok(client) => client,
|
|
||||||
};
|
|
||||||
|
|
||||||
let initial_sync_response = match client
|
|
||||||
.send_request(assign!(sync_events::v3::Request::new(), {
|
|
||||||
filter: None,
|
|
||||||
}))
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to perform initial sync request for user {user_id:?}! {e}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut sync_stream = Box::pin(client.sync(
|
|
||||||
None,
|
|
||||||
initial_sync_response.next_batch,
|
|
||||||
PresenceState::Offline,
|
|
||||||
Some(Duration::from_secs(30)),
|
|
||||||
));
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
// Message from tokio broadcast
|
|
||||||
msg = rx.recv() => {
|
|
||||||
match msg {
|
|
||||||
Ok(BroadcastMessage::StopSyncClient(client_id)) => {
|
|
||||||
if client_id == id {
|
|
||||||
log::info!("A request was received to stop this client! {id:?} for user {user_id:?}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to receive a message from broadcast! {e}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Message from Matrix
|
|
||||||
msg_stream = sync_stream.try_next() => {
|
|
||||||
match msg_stream {
|
|
||||||
Ok(Some(msg)) => {
|
|
||||||
log::debug!("Received new message from Matrix: {msg:#?}");
|
|
||||||
if let Err(e) = tx.send(BroadcastMessage::SyncEvent(user_id.clone(), Box::new(SyncEvent {
|
|
||||||
rooms: msg.rooms,presence: msg.presence,
|
|
||||||
account_data: msg.account_data,
|
|
||||||
to_device: msg.to_device,
|
|
||||||
device_lists: msg.device_lists,
|
|
||||||
}))) {
|
|
||||||
log::error!("Failed to propagate event! {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(None) => {
|
|
||||||
log::debug!("Received no message from Matrix");
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to receive a message from Matrix! {e}");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
241
src/user.rs
241
src/user.rs
@@ -1,241 +0,0 @@
|
|||||||
use s3::error::S3Error;
|
|
||||||
use s3::request::ResponseData;
|
|
||||||
use s3::{Bucket, BucketConfiguration};
|
|
||||||
use std::str::FromStr;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
use crate::app_config::AppConfig;
|
|
||||||
use crate::constants::TOKEN_LEN;
|
|
||||||
use crate::utils::base_utils::{curr_time, format_time, rand_str};
|
|
||||||
|
|
||||||
type HttpClient = ruma::client::http_client::HyperNativeTls;
|
|
||||||
pub type RumaClient = ruma::Client<HttpClient>;
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum UserError {
|
|
||||||
#[error("failed to fetch user configuration: {0}")]
|
|
||||||
FetchUserConfig(S3Error),
|
|
||||||
#[error("missing matrix token")]
|
|
||||||
MissingMatrixToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
|
|
||||||
pub struct UserID(pub String);
|
|
||||||
|
|
||||||
impl UserID {
|
|
||||||
fn conf_path_in_bucket(&self) -> String {
|
|
||||||
format!("confs/{}.json", urlencoding::encode(&self.0))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
|
||||||
pub struct User {
|
|
||||||
pub id: UserID,
|
|
||||||
pub name: String,
|
|
||||||
pub email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
|
|
||||||
pub struct APIClientID(pub uuid::Uuid);
|
|
||||||
|
|
||||||
impl APIClientID {
|
|
||||||
pub fn generate() -> Self {
|
|
||||||
Self(uuid::Uuid::new_v4())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromStr for APIClientID {
|
|
||||||
type Err = uuid::Error;
|
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
||||||
Ok(Self(uuid::Uuid::from_str(s)?))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Single API client information
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
|
||||||
pub struct APIClient {
|
|
||||||
/// Client unique ID
|
|
||||||
pub id: APIClientID,
|
|
||||||
|
|
||||||
/// Client description
|
|
||||||
pub description: String,
|
|
||||||
|
|
||||||
/// Restricted API network for token
|
|
||||||
pub network: Option<ipnet::IpNet>,
|
|
||||||
|
|
||||||
/// Client secret
|
|
||||||
pub secret: String,
|
|
||||||
|
|
||||||
/// Client creation time
|
|
||||||
pub created: u64,
|
|
||||||
|
|
||||||
/// Client last usage time
|
|
||||||
pub used: u64,
|
|
||||||
|
|
||||||
/// Read only access
|
|
||||||
pub readonly_client: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl APIClient {
|
|
||||||
pub fn fmt_created(&self) -> String {
|
|
||||||
format_time(self.created).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn fmt_used(&self) -> String {
|
|
||||||
format_time(self.used).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn need_update_last_used(&self) -> bool {
|
|
||||||
self.used + 60 * 15 < curr_time().unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl APIClient {
|
|
||||||
/// Generate a new API client
|
|
||||||
pub fn generate(description: String, network: Option<ipnet::IpNet>) -> Self {
|
|
||||||
Self {
|
|
||||||
id: APIClientID::generate(),
|
|
||||||
description,
|
|
||||||
network,
|
|
||||||
secret: rand_str(TOKEN_LEN),
|
|
||||||
created: curr_time().unwrap(),
|
|
||||||
used: curr_time().unwrap(),
|
|
||||||
readonly_client: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize, Clone)]
|
|
||||||
pub struct UserConfig {
|
|
||||||
/// Target user ID
|
|
||||||
pub user_id: UserID,
|
|
||||||
|
|
||||||
/// Configuration creation time
|
|
||||||
pub created: u64,
|
|
||||||
|
|
||||||
/// Configuration last update time
|
|
||||||
pub updated: u64,
|
|
||||||
|
|
||||||
/// Current user matrix token
|
|
||||||
pub matrix_token: String,
|
|
||||||
|
|
||||||
/// API clients
|
|
||||||
pub clients: Vec<APIClient>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UserConfig {
|
|
||||||
/// Create S3 bucket if required
|
|
||||||
pub async fn create_bucket_if_required() -> anyhow::Result<()> {
|
|
||||||
if AppConfig::get().s3_skip_auto_create_bucket {
|
|
||||||
log::debug!("Skipping bucket existence check");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let bucket = AppConfig::get().s3_bucket()?;
|
|
||||||
|
|
||||||
match bucket.location().await {
|
|
||||||
Ok(_) => {
|
|
||||||
log::debug!("The bucket already exists.");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Err(S3Error::HttpFailWithBody(404, s)) if s.contains("<Code>NoSuchKey</Code>") => {
|
|
||||||
log::warn!("Failed to fetch bucket location, but it seems that bucket exists.");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Err(S3Error::HttpFailWithBody(404, s)) if s.contains("<Code>NoSuchBucket</Code>") => {
|
|
||||||
log::warn!("The bucket does not seem to exists, trying to create it!")
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Got unexpected error when querying bucket info: {e}");
|
|
||||||
return Err(e.into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Bucket::create_with_path_style(
|
|
||||||
&bucket.name,
|
|
||||||
bucket.region,
|
|
||||||
AppConfig::get().s3_credentials()?,
|
|
||||||
BucketConfiguration::private(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get current user configuration
|
|
||||||
pub async fn load(user_id: &UserID, allow_non_existing: bool) -> anyhow::Result<Self> {
|
|
||||||
let res: Result<ResponseData, S3Error> = AppConfig::get()
|
|
||||||
.s3_bucket()?
|
|
||||||
.get_object(user_id.conf_path_in_bucket())
|
|
||||||
.await;
|
|
||||||
|
|
||||||
match (res, allow_non_existing) {
|
|
||||||
(Ok(res), _) => Ok(serde_json::from_slice(res.as_slice())?),
|
|
||||||
(Err(S3Error::HttpFailWithBody(404, _)), true) => {
|
|
||||||
log::warn!("User configuration does not exists, generating a new one...");
|
|
||||||
Ok(Self {
|
|
||||||
user_id: user_id.clone(),
|
|
||||||
created: curr_time()?,
|
|
||||||
updated: curr_time()?,
|
|
||||||
matrix_token: "".to_string(),
|
|
||||||
clients: vec![],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
(Err(e), _) => Err(UserError::FetchUserConfig(e).into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set user configuration
|
|
||||||
pub async fn save(&mut self) -> anyhow::Result<()> {
|
|
||||||
log::info!("Saving new configuration for user {:?}", self.user_id);
|
|
||||||
|
|
||||||
self.updated = curr_time()?;
|
|
||||||
|
|
||||||
// Save updated configuration
|
|
||||||
AppConfig::get()
|
|
||||||
.s3_bucket()?
|
|
||||||
.put_object(
|
|
||||||
self.user_id.conf_path_in_bucket(),
|
|
||||||
&serde_json::to_vec(self)?,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get current user matrix token, in an obfuscated form
|
|
||||||
pub fn obfuscated_matrix_token(&self) -> String {
|
|
||||||
self.matrix_token
|
|
||||||
.chars()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(num, c)| match num {
|
|
||||||
0 | 1 => c,
|
|
||||||
_ => 'X',
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Find a client by its id
|
|
||||||
pub fn find_client_by_id(&self, id: &APIClientID) -> Option<&APIClient> {
|
|
||||||
self.clients.iter().find(|c| &c.id == id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Find a client by its id and get a mutable reference
|
|
||||||
pub fn find_client_by_id_mut(&mut self, id: &APIClientID) -> Option<&mut APIClient> {
|
|
||||||
self.clients.iter_mut().find(|c| &c.id == id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get a matrix client instance for the current user
|
|
||||||
pub async fn matrix_client(&self) -> anyhow::Result<RumaClient> {
|
|
||||||
if self.matrix_token.is_empty() {
|
|
||||||
return Err(UserError::MissingMatrixToken.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(ruma::Client::builder()
|
|
||||||
.homeserver_url(AppConfig::get().matrix_homeserver.to_string())
|
|
||||||
.access_token(Some(self.matrix_token.clone()))
|
|
||||||
.build()
|
|
||||||
.await?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user