Compare commits
36 Commits
cd363cd971
...
migrate-to
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ba5372468 | |||
| 1438e2de0e | |||
| 1eaec9d319 | |||
| 37fad9ff55 | |||
| 3dab9f41d2 | |||
| a44327ddb0 | |||
| f9fb99cdb5 | |||
| 3de26c0fff | |||
| 79b5a767f3 | |||
| fdcd565431 | |||
| d9c96e85f7 | |||
| 9ed711777c | |||
| 20a42f3c55 | |||
| d05747e60e | |||
| 1cdd3d9e60 | |||
| bc815a5cf1 | |||
| 830f47b61f | |||
| 602edaae79 | |||
| f7e1d1539f | |||
| 2f74c3b1a6 | |||
| d2791f821f | |||
| 4a7eb57cf3 | |||
| 29e32c56cc | |||
| bde815b123 | |||
| c428e51df0 | |||
| 1967b29b9f | |||
| ed8ee5dc58 | |||
| 1c9ce3cc32 | |||
| f4e9fcf40f | |||
| f522d0e700 | |||
| 45213e74cb | |||
| 627647bf47 | |||
| 392b9fd5d6 | |||
| 1c47cbe0d8 | |||
| becfea8e82 | |||
| f6c9d7f4d6 |
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
|
||||
35
Cargo.toml
35
Cargo.toml
@@ -1,35 +0,0 @@
|
||||
[package]
|
||||
name = "matrix_gateway"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.28"
|
||||
env_logger = "0.11.8"
|
||||
clap = { version = "4.5.48", features = ["derive", "env"] }
|
||||
lazy_static = "1.5.0"
|
||||
anyhow = "1.0.100"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.143"
|
||||
rust-s3 = { version = "0.37.0", features = ["tokio"] }
|
||||
actix-web = "4.11.0"
|
||||
actix-session = { version = "0.11.0", features = ["redis-session"] }
|
||||
light-openid = "1.0.4"
|
||||
thiserror = "2.0.16"
|
||||
rand = "0.9.2"
|
||||
rust-embed = "8.7.2"
|
||||
mime_guess = "2.0.5"
|
||||
askama = "0.14.0"
|
||||
urlencoding = "2.1.3"
|
||||
uuid = { version = "1.18.1", 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.12", default-features = false, features = ["pure-rust"] }
|
||||
actix-remote-ip = "0.1.0"
|
||||
bytes = "1.10.1"
|
||||
sha2 = "0.11.0-rc.2"
|
||||
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"] }
|
||||
actix-ws = "0.3.0"
|
||||
tokio = { version = "1.47.1", features = ["rt", "time", "macros", "rt-multi-thread"] }
|
||||
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)
|
||||
|
||||
31
README.md
31
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**:
|
||||
|
||||
- Supports only a limited subset of Matrix API
|
||||
- Does not support E2E encryption
|
||||
- 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
|
||||
```bash
|
||||
@@ -17,21 +16,43 @@ docker run --rm -it docker.io/pierre42100/matrix_gateway --help
|
||||
```
|
||||
|
||||
## Setup dev environment
|
||||
|
||||
### Dependencies
|
||||
```
|
||||
mkdir -p storage/postgres storage/synapse storage/minio
|
||||
sudo apt install -y libsqlite3-dev
|
||||
|
||||
cd matrixgw_backend
|
||||
mkdir -p storage/maspostgres storage/synapse
|
||||
docker compose up
|
||||
```
|
||||
|
||||
To create default account, in another terminal, run the following command:
|
||||
|
||||
```bash
|
||||
docker compose --profile create-accounts up -d
|
||||
```
|
||||
|
||||
URLs:
|
||||
* Element: http://localhost:8080/
|
||||
* Synapse: http://localhost:8448/
|
||||
* Matrix Authentication Service: http://localhost:8778/
|
||||
* OpenID configuration: http://127.0.0.1:9001/dex/.well-known/openid-configuration
|
||||
* Minio console: http://localhost:9002/
|
||||
|
||||
Auto-created Matrix accounts:
|
||||
|
||||
* `admin1` : `admin1`
|
||||
* `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,2 +0,0 @@
|
||||
register_new_matrix_user -a --user admin1 --password admin1 --config /config/homeserver.yaml;
|
||||
register_new_matrix_user --no-admin --user user1 --password user1 --config /config/homeserver.yaml;
|
||||
1
.gitignore → matrixgw_backend/.gitignore
vendored
1
.gitignore → matrixgw_backend/.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
storage
|
||||
app_storage
|
||||
.idea
|
||||
target
|
||||
3704
Cargo.lock → matrixgw_backend/Cargo.lock
generated
3704
Cargo.lock → matrixgw_backend/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
34
matrixgw_backend/Cargo.toml
Normal file
34
matrixgw_backend/Cargo.toml
Normal file
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "matrixgw_backend"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
env_logger = "0.11.8"
|
||||
log = "0.4.28"
|
||||
clap = { version = "4.5.51", features = ["derive", "env"] }
|
||||
lazy_static = "1.5.0"
|
||||
anyhow = "1.0.100"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
tokio = { version = "1.48.0", features = ["full"] }
|
||||
actix-web = "4.11.0"
|
||||
actix-session = { version = "0.11.0", features = ["redis-session"] }
|
||||
actix-remote-ip = "0.1.0"
|
||||
actix-cors = "0.7.1"
|
||||
light-openid = "1.0.4"
|
||||
bytes = "1.10.1"
|
||||
sha2 = "0.10.9"
|
||||
urlencoding = "2.1.3"
|
||||
base16ct = { version = "0.3.0", features = ["alloc"] }
|
||||
futures-util = "0.3.31"
|
||||
jwt-simple = { version = "0.12.13", default-features = false, features = ["pure-rust"] }
|
||||
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"
|
||||
matrix-sdk = "0.14.0"
|
||||
url = "2.5.7"
|
||||
ractor = "0.15.9"
|
||||
serde_json = "1.0.145"
|
||||
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.
|
||||
@@ -1,15 +1,48 @@
|
||||
services:
|
||||
mas:
|
||||
image: ghcr.io/element-hq/matrix-authentication-service:main
|
||||
user: "1000"
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- masdb
|
||||
volumes:
|
||||
- ./docker/mas:/config:ro
|
||||
command: server -c /config/config.yaml
|
||||
ports:
|
||||
- "8778:8778/tcp"
|
||||
|
||||
mas_create_admin1:
|
||||
image: ghcr.io/element-hq/matrix-authentication-service:main
|
||||
user: "1000"
|
||||
restart: no
|
||||
profiles: ["create-accounts"]
|
||||
depends_on:
|
||||
- mas
|
||||
volumes:
|
||||
- ./docker/mas:/config:ro
|
||||
command: |
|
||||
manage register-user -c /config/config.yaml -y --ignore-password-complexity
|
||||
-p admin1 -e admin1@admin1.local --admin -d "Admin One" admin1
|
||||
|
||||
mas_create_user1:
|
||||
image: ghcr.io/element-hq/matrix-authentication-service:main
|
||||
user: "1000"
|
||||
restart: no
|
||||
profiles: ["create-accounts"]
|
||||
depends_on:
|
||||
- mas
|
||||
volumes:
|
||||
- ./docker/mas:/config:ro
|
||||
command: |
|
||||
manage register-user -c /config/config.yaml -y --ignore-password-complexity
|
||||
-p user1 -e user1@user1.local -d "User One" user1
|
||||
|
||||
synapse:
|
||||
image: docker.io/matrixdotorg/synapse:latest
|
||||
user: "1000"
|
||||
# Since synapse does not retry to connect to the database, restart upon
|
||||
# failure
|
||||
restart: unless-stopped
|
||||
entrypoint: /bin/bash
|
||||
command: >
|
||||
-c "nohup bash -c 'sleep 10; /config/delayed_accounts_creation.sh' \&
|
||||
./start.py"
|
||||
|
||||
# See the readme for a full documentation of the environment settings
|
||||
# NOTE: You must edit homeserver.yaml to use postgres, it defaults to sqlite
|
||||
environment:
|
||||
@@ -22,61 +55,48 @@ services:
|
||||
# - ./files:/data
|
||||
# - /path/to/ssd:/data/uploads
|
||||
# - /path/to/large_hdd:/data/media
|
||||
depends_on:
|
||||
- db
|
||||
# In order to expose Synapse, remove one of the following, you might for
|
||||
# instance expose the TLS port directly:
|
||||
ports:
|
||||
- 8448:8448/tcp
|
||||
- "8448:8448/tcp"
|
||||
|
||||
db:
|
||||
image: docker.io/postgres:17-alpine
|
||||
masdb:
|
||||
image: docker.io/postgres:18-alpine
|
||||
user: "1000"
|
||||
environment:
|
||||
- POSTGRES_USER=synapse
|
||||
- POSTGRES_DB=masdb
|
||||
- POSTGRES_USER=masdb
|
||||
- POSTGRES_PASSWORD=changeme
|
||||
# ensure the database gets created correctly
|
||||
# https://element-hq.github.io/synapse/latest/postgres.html#set-up-database
|
||||
- POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C
|
||||
- PGDATA=/data
|
||||
volumes:
|
||||
# You may store the database tables in a local folder..
|
||||
- ./storage/postgres:/var/lib/postgresql/data
|
||||
- ./storage/maspostgres:/data
|
||||
# .. or store them on some high performance storage for better results
|
||||
# - /path/to/ssd/storage:/var/lib/postgresql/data
|
||||
|
||||
element:
|
||||
image: docker.io/vectorim/element-web
|
||||
ports:
|
||||
- 8080:80/tcp
|
||||
- "8080:80/tcp"
|
||||
volumes:
|
||||
- ./docker/element/config.json:/app/config.json:ro
|
||||
|
||||
oidc:
|
||||
image: dexidp/dex
|
||||
ports:
|
||||
- 9001:9001
|
||||
- "9001:9001"
|
||||
volumes:
|
||||
- ./docker/dex:/conf:ro
|
||||
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
|
||||
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
|
||||
|
||||
redis:
|
||||
image: redis:alpine
|
||||
command: redis-server --requirepass ${REDIS_PASS:-secretredis}
|
||||
ports:
|
||||
- 6379:6379
|
||||
- "6379:6379"
|
||||
volumes:
|
||||
- ./storage/redis-data:/data
|
||||
- ./storage/redis-conf:/usr/local/etc/redis/redis.conf
|
||||
@@ -22,5 +22,5 @@ staticClients:
|
||||
- id: foo
|
||||
secret: bar
|
||||
redirectURIs:
|
||||
- http://localhost:8000/oidc_cb
|
||||
- http://localhost:5173/oidc_cb
|
||||
name: Project
|
||||
113
matrixgw_backend/docker/mas/config.yaml
Normal file
113
matrixgw_backend/docker/mas/config.yaml
Normal file
@@ -0,0 +1,113 @@
|
||||
http:
|
||||
listeners:
|
||||
- name: web
|
||||
resources:
|
||||
- name: discovery
|
||||
- name: human
|
||||
- name: oauth
|
||||
- name: compat
|
||||
- name: graphql
|
||||
- name: assets
|
||||
binds:
|
||||
- address: '[::]:8778'
|
||||
proxy_protocol: false
|
||||
- name: internal
|
||||
resources:
|
||||
- name: health
|
||||
binds:
|
||||
- host: localhost
|
||||
port: 8081
|
||||
proxy_protocol: false
|
||||
trusted_proxies:
|
||||
- 192.168.0.0/16
|
||||
- 172.16.0.0/12
|
||||
- 10.0.0.0/10
|
||||
- 127.0.0.1/8
|
||||
- fd00::/8
|
||||
- ::1/128
|
||||
public_base: http://localhost:8778/
|
||||
issuer: http://localhost:8778/
|
||||
database:
|
||||
uri: postgresql://masdb:changeme@masdb/masdb
|
||||
max_connections: 10
|
||||
min_connections: 0
|
||||
connect_timeout: 30
|
||||
idle_timeout: 600
|
||||
max_lifetime: 1800
|
||||
email:
|
||||
from: '"Authentication Service" <root@localhost>'
|
||||
reply_to: '"Authentication Service" <root@localhost>'
|
||||
transport: blackhole
|
||||
secrets:
|
||||
encryption: 12de9ad7bc2bacfa2ab9b1e3f7f1b3feb802195c8ebe66a8293cdb27f00be471
|
||||
keys:
|
||||
- kid: Bj2PICQ7mf
|
||||
key: |
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEogIBAAKCAQEAsCYCrrCJA7IuGbTYzP5yZN74QszbzudBUCX6MyN/+36HO2r6
|
||||
xL8x1PRJ+Klx9Y90J9pWuo+cIuEmFLqO+Yfblo9fSQgZVvkWAFpO6Xh8J4z9qg49
|
||||
M8xm0Ct8EnRDZDCEOBnwoDaAB9RTbpJGa1RPVCiamfi+xU+j47Zl4Er5jvLm81O7
|
||||
DSlH9eK8Eih8AxuKTkAbKE1zyXquImE26Mj2dmMRfjDrWV/I8oqE3WFViAKR12Av
|
||||
zw6TUyduiz8nK9pONCF3NIcQvBdHntBz1HlDXv6i0fRvlGIhjNL5LBgo6XQ3rNM1
|
||||
bW2KYOw/iFP0YbfD4/xRjkBPvK2coQ8aRzK2VwIDAQABAoH/G4XU5Xav8ePlUB7x
|
||||
wRYAycINCGL59Vos2lkUvujNFn6uopoUlKlLH/sLk87l/3hqrc9vvbayrsB/Mr3z
|
||||
mQmhReUg/khFrVE+Hs/9hH1O6N8ew3N2HKHTbrNcr4V7AiySfDGRZ3ccihyi7KPu
|
||||
XNbPjlbJ0UUMicfn06ysPl94nt0So0UAmXg+c7sDDqyzh3cY8emedYZ5FCljo/jA
|
||||
F8k40rs7CywLJYMJB9O1vtomgt1xkDRO4F8UrZrriMIcYn0iFKe7i4AH8D6nkgNu
|
||||
/v9Z43Leu8yRKrUvbpH3NaX8DlUSFWAXKpwUWr4sAQgWcLkVgjAXG1v9jCE97qW2
|
||||
f0nBAoGBAOaKrnY5rWeZ74dERnPhSCsYiqRMneQAh7eJR+Er+xu1yF/bxwkhq2tK
|
||||
/txheTK448DqhQRtr095t/v7TMZcPl3bSmybT1CQg/wiMJsgDMZqlC9tofvcq6uz
|
||||
xP8vxMFHd0YSMSP693dkny4MzNY6LuoVWDLT+HxKPJyzGs1alruzAoGBAMOZp5J2
|
||||
3ODcHQlcsGBtj1yVpQ4UXMvrSZF2ygiGK9bagL/f1iAtwACVOh5rgmbiOLSVgmR2
|
||||
n4nupTgSAXMYkjmAmDyEh0PDaRl4WWvYEKp8GMvTPVPvjc6N0dT+y8Mf9bu+LcEt
|
||||
+uZqPOZNbO5Vi+UgGeM9zZpxq/K7dpJmM/jNAoGBALsYHRGxKTsEwFEkZZCxaWIg
|
||||
HpPL4e8hRwL6FC13BeitFBpHQDX27yi5yi+Lo1I4ngz3xk+bvERhYaDLhrkML0j4
|
||||
KGQPfsTBI3vBO3UJA5Ua9XuwG19M7L0BvYPjfmfk2bUyGlM63w4zyMMUfD/3JA+w
|
||||
ls1ZHTWxAZOh/sRdGirlAoGAX16B1+XgmDp6ZeAtlzaUGd5U1eKTxFF6U1SJ+VIB
|
||||
+gYblHI84v+riB06cy6ULDnM0C+9neJAs24KXKZa0pV+Zk8O6yLrGN0kV2jYoL5+
|
||||
kcFkDa13T3+TssxvLNz22LKyi9GUWYZjuQi/nMLPg/1t8k+Oj7/Iia822WkRzRvL
|
||||
51kCgYEAwrN5Us8LR+fThm3C0vhvwv2wap6ccw0qq5+FTN+igAZAmmvKKvhow2Vi
|
||||
LnPKBkc7QvxvQSNoXkdUo4qs3zOQ7DGvJLqSG9pwxFW5X1+78pNEm5OWe8AlT1uZ
|
||||
Jz8Z1/Ae7fr/fFaucW9LkWjcuoPwPLiZ3b7ZQ6phs8qzoL+FpBI=
|
||||
-----END RSA PRIVATE KEY-----
|
||||
- kid: HcRvLHat12
|
||||
key: |
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIOCCFSnkfz1ksln6kus8enQstBTu0q62IGJVzuX0WiXPoAoGCCqGSM49
|
||||
AwEHoUQDQgAEVWPLbvSdxquLAjU3zJLcCWdaxr6QK1tPVbV1IS+87QUMv/zKiCMa
|
||||
fNpwgBXwU7dF0gY507R2yY9pcdTmRtnRug==
|
||||
-----END EC PRIVATE KEY-----
|
||||
- kid: YjMITk5VSn
|
||||
key: |
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIGkAgEBBDCoPSjaN7qqnPz+vdzHeIy8RZCCtFOqLTkvylM1gz6xOGaVsS63VJw9
|
||||
Td9BtpolZ0egBwYFK4EEACKhZANiAAT8tH88HYBHNiQTSqZzlxElSuSDC0+Xn0O9
|
||||
ukj0xTTVBp8rUM9lCJQAlB8PjS2XK/n0YvYdzysQb3AYqszJa45/rOGvSar30YNE
|
||||
gwpJvu36xNIKZT+nHalNwg069FdjNBc=
|
||||
-----END EC PRIVATE KEY-----
|
||||
- kid: NvFzzeMRU3
|
||||
key: |
|
||||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHQCAQEEILJEmFPDGFZoBVBQf1P6h4YfasYsFiu8a6FrFxiJvKXPoAcGBSuBBAAK
|
||||
oUQDQgAE4NY5H3+D8r9GNOhrpbUn2dvLZIzi4A+SiwfqvtvPEmZkW+KDbd2tzKmx
|
||||
maydZBn52QWedVY65snGAEoh9mV1TQ==
|
||||
-----END EC PRIVATE KEY-----
|
||||
passwords:
|
||||
enabled: true
|
||||
schemes:
|
||||
- version: 1
|
||||
algorithm: argon2id
|
||||
minimum_complexity: 0
|
||||
account:
|
||||
password_registration_enabled: true
|
||||
password_registration_email_required: false
|
||||
matrix:
|
||||
kind: synapse
|
||||
homeserver: localhost
|
||||
secret: IhKoLn6jWf1qRRZWvqgaKuIdwD6H0Mvx
|
||||
endpoint: http://synapse:8448/
|
||||
|
||||
policy:
|
||||
data:
|
||||
client_registration:
|
||||
allow_insecure_uris: true
|
||||
@@ -33,3 +33,9 @@ signing_key_path: "/config/localhost.signing.key"
|
||||
trusted_key_servers:
|
||||
- server_name: "matrix.org"
|
||||
# vim:ft=yaml
|
||||
matrix_authentication_service:
|
||||
enabled: true
|
||||
endpoint: http://mas:8778/
|
||||
secret: "IhKoLn6jWf1qRRZWvqgaKuIdwD6H0Mvx"
|
||||
# Alternatively, using a file:
|
||||
#secret_file: /path/to/secret.txt
|
||||
@@ -1,8 +1,9 @@
|
||||
use clap::Parser;
|
||||
use jwt_simple::algorithms::HS256Key;
|
||||
use jwt_simple::prelude::{Clock, Duration, JWTClaims, MACLike};
|
||||
use matrix_gateway::extractors::client_auth::TokenClaims;
|
||||
use matrix_gateway::utils::base_utils::rand_str;
|
||||
use matrixgw_backend::constants;
|
||||
use matrixgw_backend::extractors::auth_extractor::TokenClaims;
|
||||
use matrixgw_backend::utils::rand_utils::rand_string;
|
||||
use std::ops::Add;
|
||||
use std::os::unix::prelude::CommandExt;
|
||||
use std::process::Command;
|
||||
@@ -59,7 +60,7 @@ fn main() {
|
||||
subject: None,
|
||||
audiences: None,
|
||||
jwt_id: None,
|
||||
nonce: Some(rand_str(10)),
|
||||
nonce: Some(rand_string(10)),
|
||||
custom: TokenClaims {
|
||||
method: args.method.to_string(),
|
||||
uri: args.uri,
|
||||
@@ -78,7 +79,7 @@ fn main() {
|
||||
|
||||
let _ = Command::new("curl")
|
||||
.args(["-X", &args.method])
|
||||
.args(["-H", &format!("x-client-auth: {jwt}")])
|
||||
.args(["-H", &format!("{}: {jwt}", constants::API_AUTH_HEADER)])
|
||||
.args(args.run)
|
||||
.arg(full_url)
|
||||
.exec();
|
||||
248
matrixgw_backend/src/app_config.rs
Normal file
248
matrixgw_backend/src/app_config.rs
Normal file
@@ -0,0 +1,248 @@
|
||||
use crate::users::{APITokenID, UserEmail};
|
||||
use crate::utils::crypt_utils::sha256str;
|
||||
use clap::Parser;
|
||||
use matrix_sdk::authentication::oauth::registration::{
|
||||
ApplicationType, ClientMetadata, Localized, OAuthGrantType,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use url::Url;
|
||||
|
||||
/// Matrix gateway backend API
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
pub struct AppConfig {
|
||||
/// Listen address
|
||||
#[clap(short, long, env, default_value = "0.0.0.0:8000")]
|
||||
pub listen_address: String,
|
||||
|
||||
/// Website origin
|
||||
#[clap(short, long, env, default_value = "http://localhost:5173")]
|
||||
pub website_origin: String,
|
||||
|
||||
/// Proxy IP, might end with a star "*"
|
||||
#[clap(short, long, env)]
|
||||
pub proxy_ip: Option<String>,
|
||||
|
||||
/// 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 = "")]
|
||||
secret: String,
|
||||
|
||||
/// Matrix homeserver origin
|
||||
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
|
||||
pub matrix_homeserver: String,
|
||||
|
||||
/// Redis connection hostname
|
||||
#[clap(long, env, default_value = "localhost")]
|
||||
redis_hostname: String,
|
||||
|
||||
/// Redis connection port
|
||||
#[clap(long, env, default_value_t = 6379)]
|
||||
redis_port: u16,
|
||||
|
||||
/// Redis database number
|
||||
#[clap(long, env, default_value_t = 0)]
|
||||
redis_db_number: i64,
|
||||
|
||||
/// Redis username
|
||||
#[clap(long, env)]
|
||||
redis_username: Option<String>,
|
||||
|
||||
/// Redis password
|
||||
#[clap(long, env, default_value = "secretredis")]
|
||||
redis_password: String,
|
||||
|
||||
/// URL where the OpenID configuration can be found
|
||||
#[arg(
|
||||
long,
|
||||
env,
|
||||
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
|
||||
)]
|
||||
pub oidc_configuration_url: String,
|
||||
|
||||
/// OpenID provider name
|
||||
#[arg(long, env, default_value = "3rd party provider")]
|
||||
pub oidc_provider_name: String,
|
||||
|
||||
/// OpenID client ID
|
||||
#[arg(long, env, default_value = "foo")]
|
||||
pub oidc_client_id: String,
|
||||
|
||||
/// OpenID client secret
|
||||
#[arg(long, env, default_value = "bar")]
|
||||
pub oidc_client_secret: String,
|
||||
|
||||
/// OpenID login redirect URL
|
||||
#[arg(long, env, default_value = "APP_ORIGIN/oidc_cb")]
|
||||
oidc_redirect_url: String,
|
||||
|
||||
/// Matrix oauth redirect URL
|
||||
#[arg(long, env, default_value = "APP_ORIGIN/matrix_auth_cb")]
|
||||
matrix_oauth_redirect_url: String,
|
||||
|
||||
/// Application storage path
|
||||
#[arg(long, env, default_value = "app_storage")]
|
||||
storage_path: String,
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref ARGS: AppConfig = {
|
||||
AppConfig::parse()
|
||||
};
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
/// Get parsed command line arguments
|
||||
pub fn get() -> &'static AppConfig {
|
||||
&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
|
||||
pub fn secret(&self) -> &str {
|
||||
let mut secret = self.secret.as_str();
|
||||
|
||||
if cfg!(debug_assertions) && secret.is_empty() {
|
||||
secret = "DEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEY";
|
||||
}
|
||||
|
||||
if secret.is_empty() {
|
||||
panic!("SECRET is undefined or too short (min 64 chars)!")
|
||||
}
|
||||
|
||||
secret
|
||||
}
|
||||
|
||||
/// Check if auth is disabled
|
||||
pub fn is_auth_disabled(&self) -> bool {
|
||||
self.unsecure_auto_login_email().is_some()
|
||||
}
|
||||
|
||||
/// Get Redis connection configuration
|
||||
pub fn redis_connection_string(&self) -> String {
|
||||
format!(
|
||||
"redis://{}:{}@{}:{}/{}",
|
||||
self.redis_username.as_deref().unwrap_or(""),
|
||||
self.redis_password,
|
||||
self.redis_hostname,
|
||||
self.redis_port,
|
||||
self.redis_db_number
|
||||
)
|
||||
}
|
||||
|
||||
/// Get OpenID providers configuration
|
||||
pub fn openid_provider(&self) -> OIDCProvider<'_> {
|
||||
OIDCProvider {
|
||||
client_id: self.oidc_client_id.as_str(),
|
||||
client_secret: self.oidc_client_secret.as_str(),
|
||||
configuration_url: self.oidc_configuration_url.as_str(),
|
||||
name: self.oidc_provider_name.as_str(),
|
||||
redirect_url: self
|
||||
.oidc_redirect_url
|
||||
.replace("APP_ORIGIN", &self.website_origin),
|
||||
}
|
||||
}
|
||||
|
||||
/// Matrix OAuth redirect URL
|
||||
pub fn matrix_oauth_redirect_url(&self) -> String {
|
||||
self.matrix_oauth_redirect_url
|
||||
.replace("APP_ORIGIN", &self.website_origin)
|
||||
}
|
||||
|
||||
/// Get Matrix client metadata information
|
||||
pub fn matrix_client_metadata(&self) -> ClientMetadata {
|
||||
let client_uri = Localized::new(
|
||||
Url::parse(&self.website_origin).expect("Invalid website origin!"),
|
||||
[],
|
||||
);
|
||||
ClientMetadata {
|
||||
application_type: ApplicationType::Native,
|
||||
grant_types: vec![OAuthGrantType::AuthorizationCode {
|
||||
redirect_uris: vec![
|
||||
Url::parse(&self.matrix_oauth_redirect_url())
|
||||
.expect("Failed to parse matrix auth redirect URI!"),
|
||||
],
|
||||
}],
|
||||
client_name: Some(Localized::new("MatrixGW".to_string(), [])),
|
||||
logo_uri: Some(Localized::new(
|
||||
Url::parse(&format!("{}/favicon.png", self.website_origin))
|
||||
.expect("Invalid website origin!"),
|
||||
[],
|
||||
)),
|
||||
policy_uri: Some(client_uri.clone()),
|
||||
tos_uri: Some(client_uri.clone()),
|
||||
client_uri,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get storage path
|
||||
pub fn storage_path(&self) -> &Path {
|
||||
Path::new(self.storage_path.as_str())
|
||||
}
|
||||
|
||||
/// User storage directory
|
||||
pub fn user_directory(&self, mail: &UserEmail) -> PathBuf {
|
||||
self.storage_path().join("users").join(sha256str(&mail.0))
|
||||
}
|
||||
|
||||
/// User metadata file
|
||||
pub fn user_metadata_file_path(&self, mail: &UserEmail) -> PathBuf {
|
||||
self.user_directory(mail).join("metadata.json")
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
|
||||
/// Get user Matrix database path
|
||||
pub fn user_matrix_db_path(&self, mail: &UserEmail) -> PathBuf {
|
||||
self.user_directory(mail).join("matrix-db")
|
||||
}
|
||||
|
||||
/// Get user Matrix database passphrase path
|
||||
pub fn user_matrix_passphrase_path(&self, mail: &UserEmail) -> PathBuf {
|
||||
self.user_directory(mail).join("matrix-db-passphrase")
|
||||
}
|
||||
|
||||
/// Get user Matrix session file path
|
||||
pub fn user_matrix_session_file_path(&self, mail: &UserEmail) -> PathBuf {
|
||||
self.user_directory(mail).join("matrix-session.json")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct OIDCProvider<'a> {
|
||||
pub name: &'a str,
|
||||
pub client_id: &'a str,
|
||||
pub client_secret: &'a str,
|
||||
pub configuration_url: &'a str,
|
||||
pub redirect_url: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::app_config::AppConfig;
|
||||
|
||||
#[test]
|
||||
fn verify_cli() {
|
||||
use clap::CommandFactory;
|
||||
AppConfig::command().debug_assert()
|
||||
}
|
||||
}
|
||||
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";
|
||||
}
|
||||
132
matrixgw_backend/src/controllers/auth_controller.rs
Normal file
132
matrixgw_backend/src/controllers/auth_controller.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::controllers::{HttpFailure, HttpResult};
|
||||
use crate::extractors::auth_extractor::{AuthExtractor, AuthenticatedMethod};
|
||||
use crate::extractors::matrix_client_extractor::MatrixClientExtractor;
|
||||
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(client: MatrixClientExtractor) -> HttpResult {
|
||||
Ok(HttpResponse::Ok().json(client.to_extended_user_info().await?))
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
30
matrixgw_backend/src/controllers/matrix_link_controller.rs
Normal file
30
matrixgw_backend/src/controllers/matrix_link_controller.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use crate::controllers::HttpResult;
|
||||
use crate::extractors::matrix_client_extractor::MatrixClientExtractor;
|
||||
use crate::matrix_connection::matrix_client::FinishMatrixAuth;
|
||||
use actix_web::HttpResponse;
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct StartAuthResponse {
|
||||
url: String,
|
||||
}
|
||||
|
||||
/// Start user authentication on Matrix server
|
||||
pub async fn start_auth(client: MatrixClientExtractor) -> HttpResult {
|
||||
let url = client.client.initiate_login().await?.to_string();
|
||||
Ok(HttpResponse::Ok().json(StartAuthResponse { url }))
|
||||
}
|
||||
|
||||
/// Finish user authentication on Matrix server
|
||||
pub async fn finish_auth(client: MatrixClientExtractor) -> HttpResult {
|
||||
match client
|
||||
.client
|
||||
.finish_login(client.auth.decode_json_body::<FinishMatrixAuth>()?)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(HttpResponse::Accepted().finish()),
|
||||
Err(e) => {
|
||||
log::error!("Failed to finish Matrix authentication: {e}");
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use std::error::Error;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub mod api;
|
||||
pub mod web_ui;
|
||||
pub mod auth_controller;
|
||||
pub mod matrix_link_controller;
|
||||
pub mod server_controller;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum HttpFailure {
|
||||
@@ -12,24 +12,10 @@ pub enum HttpFailure {
|
||||
Forbidden,
|
||||
#[error("this resource was not found")]
|
||||
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}")]
|
||||
OpenID(Box<dyn Error>),
|
||||
#[error("an error occurred while fetching user configuration: {0}")]
|
||||
FetchUserConfig(anyhow::Error),
|
||||
#[error("an unspecified internal error occurred: {0}")]
|
||||
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 {
|
||||
@@ -42,7 +28,9 @@ impl ResponseError for HttpFailure {
|
||||
}
|
||||
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
HttpResponse::build(self.status_code()).body(self.to_string())
|
||||
HttpResponse::build(self.status_code())
|
||||
.content_type("text/plain")
|
||||
.body(self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
317
matrixgw_backend/src/extractors/auth_extractor.rs
Normal file
317
matrixgw_backend/src/extractors/auth_extractor.rs
Normal file
@@ -0,0 +1,317 @@
|
||||
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 jwt_simple::reexports::serde_json;
|
||||
use serde::de::DeserializeOwned;
|
||||
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>>,
|
||||
}
|
||||
|
||||
impl AuthExtractor {
|
||||
pub fn decode_json_body<E: DeserializeOwned + Send>(&self) -> anyhow::Result<E> {
|
||||
let payload = self
|
||||
.payload
|
||||
.as_ref()
|
||||
.context("Failed to decode request as json: missing payload!")?;
|
||||
serde_json::from_slice(payload).context("Failed to decode request json!")
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
48
matrixgw_backend/src/extractors/matrix_client_extractor.rs
Normal file
48
matrixgw_backend/src/extractors/matrix_client_extractor.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use crate::extractors::auth_extractor::AuthExtractor;
|
||||
use crate::matrix_connection::matrix_client::MatrixClient;
|
||||
use crate::matrix_connection::matrix_manager::MatrixManagerMsg;
|
||||
use crate::users::ExtendedUserInfo;
|
||||
use actix_web::dev::Payload;
|
||||
use actix_web::{FromRequest, HttpRequest, web};
|
||||
use ractor::ActorRef;
|
||||
|
||||
pub struct MatrixClientExtractor {
|
||||
pub auth: AuthExtractor,
|
||||
pub client: MatrixClient,
|
||||
}
|
||||
|
||||
impl MatrixClientExtractor {
|
||||
pub async fn to_extended_user_info(&self) -> anyhow::Result<ExtendedUserInfo> {
|
||||
Ok(ExtendedUserInfo {
|
||||
user: self.auth.user.clone(),
|
||||
matrix_user_id: self.client.client.user_id().map(|id| id.to_string()),
|
||||
matrix_device_id: self.client.client.device_id().map(|id| id.to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for MatrixClientExtractor {
|
||||
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 mut payload = payload.take();
|
||||
Box::pin(async move {
|
||||
let auth = AuthExtractor::from_request(&req, &mut payload).await?;
|
||||
|
||||
let matrix_manager_actor =
|
||||
web::Data::<ActorRef<MatrixManagerMsg>>::from_request(&req, &mut Payload::None)
|
||||
.await?;
|
||||
let client = ractor::call!(
|
||||
matrix_manager_actor,
|
||||
MatrixManagerMsg::GetClient,
|
||||
auth.user.email.clone()
|
||||
)
|
||||
.expect("Failed to query manager actor!")
|
||||
.expect("Failed to get client!");
|
||||
|
||||
Ok(Self { auth, client })
|
||||
})
|
||||
}
|
||||
}
|
||||
3
matrixgw_backend/src/extractors/mod.rs
Normal file
3
matrixgw_backend/src/extractors/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod auth_extractor;
|
||||
pub mod matrix_client_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),
|
||||
)
|
||||
}
|
||||
}
|
||||
7
matrixgw_backend/src/lib.rs
Normal file
7
matrixgw_backend/src/lib.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
pub mod app_config;
|
||||
pub mod constants;
|
||||
pub mod controllers;
|
||||
pub mod extractors;
|
||||
pub mod matrix_connection;
|
||||
pub mod users;
|
||||
pub mod utils;
|
||||
112
matrixgw_backend/src/main.rs
Normal file
112
matrixgw_backend/src/main.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
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, matrix_link_controller, server_controller};
|
||||
use matrixgw_backend::matrix_connection::matrix_manager::MatrixManagerActor;
|
||||
use matrixgw_backend::users::User;
|
||||
use ractor::Actor;
|
||||
|
||||
#[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());
|
||||
|
||||
log::info!("Connect to Redis session store...");
|
||||
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!");
|
||||
}
|
||||
|
||||
// Create matrix clients manager actor
|
||||
let (manager_actor, manager_actor_handle) = Actor::spawn(
|
||||
Some("matrix-clients-manager".to_string()),
|
||||
MatrixManagerActor,
|
||||
(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to start Matrix manager actor!");
|
||||
|
||||
log::info!(
|
||||
"Starting to listen on {} for {}",
|
||||
AppConfig::get().listen_address,
|
||||
AppConfig::get().website_origin
|
||||
);
|
||||
|
||||
let manager_actor_clone = manager_actor.clone();
|
||||
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(["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(manager_actor_clone.clone()))
|
||||
.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),
|
||||
)
|
||||
// Matrix link controller
|
||||
.route(
|
||||
"/api/matrix_link/start_auth",
|
||||
web::post().to(matrix_link_controller::start_auth),
|
||||
)
|
||||
.route(
|
||||
"/api/matrix_link/finish_auth",
|
||||
web::post().to(matrix_link_controller::finish_auth),
|
||||
)
|
||||
})
|
||||
.workers(4)
|
||||
.bind(&AppConfig::get().listen_address)?
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
// Terminate manager actor
|
||||
manager_actor.stop(None);
|
||||
manager_actor_handle.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
257
matrixgw_backend/src/matrix_connection/matrix_client.rs
Normal file
257
matrixgw_backend/src/matrix_connection/matrix_client.rs
Normal file
@@ -0,0 +1,257 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::users::UserEmail;
|
||||
use crate::utils::rand_utils::rand_string;
|
||||
use anyhow::Context;
|
||||
use matrix_sdk::authentication::oauth::error::OAuthDiscoveryError;
|
||||
use matrix_sdk::authentication::oauth::{
|
||||
ClientId, OAuthError, OAuthSession, UrlOrQuery, UserSession,
|
||||
};
|
||||
use matrix_sdk::ruma::serde::Raw;
|
||||
use matrix_sdk::{Client, ClientBuildError};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
/// The full session to persist.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
struct StoredSession {
|
||||
/// The OAuth 2.0 user session.
|
||||
user_session: UserSession,
|
||||
|
||||
/// The OAuth 2.0 client ID.
|
||||
client_id: ClientId,
|
||||
}
|
||||
|
||||
/// Matrix Gateway session errors
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
enum MatrixClientError {
|
||||
#[error("Failed to destroy previous client data! {0}")]
|
||||
DestroyPreviousData(Box<MatrixClientError>),
|
||||
#[error("Failed to create Matrix database storage directory! {0}")]
|
||||
CreateMatrixDbDir(std::io::Error),
|
||||
#[error("Failed to create database passphrase! {0}")]
|
||||
CreateDbPassphrase(std::io::Error),
|
||||
#[error("Failed to read database passphrase! {0}")]
|
||||
ReadDbPassphrase(std::io::Error),
|
||||
#[error("Failed to build Matrix client! {0}")]
|
||||
BuildMatrixClient(ClientBuildError),
|
||||
#[error("Failed to clear Matrix session file! {0}")]
|
||||
ClearMatrixSessionFile(std::io::Error),
|
||||
#[error("Failed to clear Matrix database storage directory! {0}")]
|
||||
ClearMatrixDbDir(std::io::Error),
|
||||
#[error("Failed to remove database passphrase! {0}")]
|
||||
ClearDbPassphrase(std::io::Error),
|
||||
#[error("Failed to fetch server metadata! {0}")]
|
||||
FetchServerMetadata(OAuthDiscoveryError),
|
||||
#[error("Failed to load stored session! {0}")]
|
||||
LoadStoredSession(std::io::Error),
|
||||
#[error("Failed to decode stored session! {0}")]
|
||||
DecodeStoredSession(serde_json::Error),
|
||||
#[error("Failed to restore stored session! {0}")]
|
||||
RestoreSession(matrix_sdk::Error),
|
||||
#[error("Failed to parse auth redirect URL! {0}")]
|
||||
ParseAuthRedirectURL(url::ParseError),
|
||||
#[error("Failed to build auth request! {0}")]
|
||||
BuildAuthRequest(OAuthError),
|
||||
#[error("Failed to finalize authentication! {0}")]
|
||||
FinishLogin(matrix_sdk::Error),
|
||||
#[error("Failed to write session file! {0}")]
|
||||
WriteSessionFile(std::io::Error),
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct FinishMatrixAuth {
|
||||
code: String,
|
||||
state: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MatrixClient {
|
||||
pub email: UserEmail,
|
||||
pub client: Client,
|
||||
}
|
||||
|
||||
impl MatrixClient {
|
||||
/// Start to build Matrix client to initiate user authentication
|
||||
pub async fn build_client(email: &UserEmail) -> anyhow::Result<Self> {
|
||||
// Check if we are restoring a previous state
|
||||
let session_file_path = AppConfig::get().user_matrix_session_file_path(email);
|
||||
let is_restoring = session_file_path.is_file();
|
||||
if !is_restoring {
|
||||
Self::destroy_data(email).map_err(MatrixClientError::DestroyPreviousData)?;
|
||||
}
|
||||
|
||||
// Determine Matrix database path
|
||||
let db_path = AppConfig::get().user_matrix_db_path(email);
|
||||
std::fs::create_dir_all(&db_path).map_err(MatrixClientError::CreateMatrixDbDir)?;
|
||||
|
||||
// Generate or load passphrase
|
||||
let passphrase_path = AppConfig::get().user_matrix_passphrase_path(email);
|
||||
if !passphrase_path.exists() {
|
||||
std::fs::write(&passphrase_path, rand_string(32))
|
||||
.map_err(MatrixClientError::CreateDbPassphrase)?;
|
||||
}
|
||||
let passphrase = std::fs::read_to_string(passphrase_path)
|
||||
.map_err(MatrixClientError::ReadDbPassphrase)?;
|
||||
|
||||
let client = Client::builder()
|
||||
.server_name_or_homeserver_url(&AppConfig::get().matrix_homeserver)
|
||||
// Automatically refresh tokens if needed
|
||||
.handle_refresh_tokens()
|
||||
.sqlite_store(&db_path, Some(&passphrase))
|
||||
.build()
|
||||
.await
|
||||
.map_err(MatrixClientError::BuildMatrixClient)?;
|
||||
|
||||
// Check metadata
|
||||
let oauth = client.oauth();
|
||||
let server_metadata = oauth
|
||||
.server_metadata()
|
||||
.await
|
||||
.map_err(MatrixClientError::FetchServerMetadata)?;
|
||||
log::info!("OAuth2 server issuer: {:?}", server_metadata.issuer);
|
||||
|
||||
if is_restoring {
|
||||
let session: StoredSession = serde_json::from_str(
|
||||
std::fs::read_to_string(session_file_path)
|
||||
.map_err(MatrixClientError::LoadStoredSession)?
|
||||
.as_str(),
|
||||
)
|
||||
.map_err(MatrixClientError::DecodeStoredSession)?;
|
||||
|
||||
// Restore data
|
||||
client
|
||||
.restore_session(OAuthSession {
|
||||
client_id: session.client_id,
|
||||
user: session.user_session,
|
||||
})
|
||||
.await
|
||||
.map_err(MatrixClientError::RestoreSession)?;
|
||||
}
|
||||
|
||||
let client = Self {
|
||||
email: email.clone(),
|
||||
client,
|
||||
};
|
||||
|
||||
// Automatically save session when token gets refreshed
|
||||
client.setup_background_session_save().await;
|
||||
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// Destroy Matrix client related data
|
||||
fn destroy_data(email: &UserEmail) -> anyhow::Result<(), Box<MatrixClientError>> {
|
||||
let session_path = AppConfig::get().user_matrix_session_file_path(email);
|
||||
if session_path.is_file() {
|
||||
std::fs::remove_file(&session_path)
|
||||
.map_err(MatrixClientError::ClearMatrixSessionFile)?;
|
||||
}
|
||||
|
||||
let db_path = AppConfig::get().user_matrix_db_path(email);
|
||||
if db_path.is_dir() {
|
||||
std::fs::remove_dir_all(&db_path).map_err(MatrixClientError::ClearMatrixDbDir)?;
|
||||
}
|
||||
|
||||
let passphrase_path = AppConfig::get().user_matrix_passphrase_path(email);
|
||||
if passphrase_path.is_file() {
|
||||
std::fs::remove_file(passphrase_path).map_err(MatrixClientError::ClearDbPassphrase)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initiate OAuth authentication
|
||||
pub async fn initiate_login(&self) -> anyhow::Result<Url> {
|
||||
let oauth = self.client.oauth();
|
||||
|
||||
let metadata = AppConfig::get().matrix_client_metadata();
|
||||
let client_metadata = Raw::new(&metadata).expect("Couldn't serialize client metadata");
|
||||
|
||||
let auth = oauth
|
||||
.login(
|
||||
Url::parse(&AppConfig::get().matrix_oauth_redirect_url())
|
||||
.map_err(MatrixClientError::ParseAuthRedirectURL)?,
|
||||
None,
|
||||
Some(client_metadata.into()),
|
||||
None,
|
||||
)
|
||||
.build()
|
||||
.await
|
||||
.map_err(MatrixClientError::BuildAuthRequest)?;
|
||||
|
||||
Ok(auth.url)
|
||||
}
|
||||
|
||||
/// Finish OAuth authentication
|
||||
pub async fn finish_login(&self, info: FinishMatrixAuth) -> anyhow::Result<()> {
|
||||
let oauth = self.client.oauth();
|
||||
oauth
|
||||
.finish_login(UrlOrQuery::Query(format!(
|
||||
"state={}&code={}",
|
||||
info.state, info.code
|
||||
)))
|
||||
.await
|
||||
.map_err(MatrixClientError::FinishLogin)?;
|
||||
|
||||
log::info!(
|
||||
"User successfully authenticated as {}!",
|
||||
self.client.user_id().unwrap()
|
||||
);
|
||||
|
||||
// Persist session tokens
|
||||
self.save_stored_session().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Automatically persist session onto disk
|
||||
pub async fn setup_background_session_save(&self) {
|
||||
let this = self.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(update) = this.client.subscribe_to_session_changes().recv().await {
|
||||
match update {
|
||||
matrix_sdk::SessionChange::UnknownToken { soft_logout } => {
|
||||
log::warn!("Received an unknown token error; soft logout? {soft_logout:?}");
|
||||
}
|
||||
matrix_sdk::SessionChange::TokensRefreshed => {
|
||||
// The tokens have been refreshed, persist them to disk.
|
||||
if let Err(err) = this.save_stored_session().await {
|
||||
log::error!("Unable to store a session in the background: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Update the session stored on the filesystem.
|
||||
async fn save_stored_session(&self) -> anyhow::Result<()> {
|
||||
log::debug!("Save the stored session for {:?}...", self.email);
|
||||
|
||||
let user_session: UserSession = self
|
||||
.client
|
||||
.oauth()
|
||||
.user_session()
|
||||
.context("A logged in client must have a session")?;
|
||||
|
||||
let stored_session = StoredSession {
|
||||
user_session,
|
||||
client_id: self
|
||||
.client
|
||||
.oauth()
|
||||
.client_id()
|
||||
.context("Client ID should be set at this point!")?
|
||||
.clone(),
|
||||
};
|
||||
|
||||
let serialized_session = serde_json::to_string(&stored_session)?;
|
||||
std::fs::write(
|
||||
AppConfig::get().user_matrix_session_file_path(&self.email),
|
||||
serialized_session,
|
||||
)
|
||||
.map_err(MatrixClientError::WriteSessionFile)?;
|
||||
|
||||
log::debug!("Updating the stored session: done!");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
62
matrixgw_backend/src/matrix_connection/matrix_manager.rs
Normal file
62
matrixgw_backend/src/matrix_connection/matrix_manager.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use crate::matrix_connection::matrix_client::MatrixClient;
|
||||
use crate::users::UserEmail;
|
||||
use ractor::{Actor, ActorProcessingErr, ActorRef, RpcReplyPort};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct MatrixManagerState {
|
||||
pub clients: HashMap<UserEmail, MatrixClient>,
|
||||
}
|
||||
|
||||
pub enum MatrixManagerMsg {
|
||||
GetClient(UserEmail, RpcReplyPort<anyhow::Result<MatrixClient>>),
|
||||
}
|
||||
|
||||
pub struct MatrixManagerActor;
|
||||
|
||||
impl Actor for MatrixManagerActor {
|
||||
type Msg = MatrixManagerMsg;
|
||||
type State = MatrixManagerState;
|
||||
type Arguments = ();
|
||||
|
||||
async fn pre_start(
|
||||
&self,
|
||||
_myself: ActorRef<Self::Msg>,
|
||||
_args: Self::Arguments,
|
||||
) -> Result<Self::State, ActorProcessingErr> {
|
||||
Ok(MatrixManagerState {
|
||||
clients: HashMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle(
|
||||
&self,
|
||||
_myself: ActorRef<Self::Msg>,
|
||||
message: Self::Msg,
|
||||
state: &mut Self::State,
|
||||
) -> Result<(), ActorProcessingErr> {
|
||||
match message {
|
||||
// Get client information
|
||||
MatrixManagerMsg::GetClient(email, port) => {
|
||||
let res = port.send(match state.clients.get(&email) {
|
||||
None => {
|
||||
// Generate client if required
|
||||
log::info!("Building new client for {:?}", &email);
|
||||
match MatrixClient::build_client(&email).await {
|
||||
Ok(c) => {
|
||||
state.clients.insert(email.clone(), c.clone());
|
||||
Ok(c)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
Some(c) => Ok(c.clone()),
|
||||
});
|
||||
|
||||
if let Err(e) = res {
|
||||
log::warn!("Failed to send client information: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
2
matrixgw_backend/src/matrix_connection/mod.rs
Normal file
2
matrixgw_backend/src/matrix_connection/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod matrix_client;
|
||||
pub mod matrix_manager;
|
||||
176
matrixgw_backend/src/users.rs
Normal file
176
matrixgw_backend/src/users.rs
Normal file
@@ -0,0 +1,176 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, Debug, Clone)]
|
||||
pub struct ExtendedUserInfo {
|
||||
#[serde(flatten)]
|
||||
pub user: User,
|
||||
pub matrix_user_id: Option<String>,
|
||||
pub matrix_device_id: Option<String>,
|
||||
}
|
||||
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 |
65
matrixgw_frontend/src/App.tsx
Normal file
65
matrixgw_frontend/src/App.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
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 { MatrixLinkRoute } from "./routes/MatrixLinkRoute";
|
||||
import { NotFoundRoute } from "./routes/NotFoundRoute";
|
||||
import { BaseLoginPage } from "./widgets/auth/BaseLoginPage";
|
||||
import BaseAuthenticatedPage from "./widgets/dashboard/BaseAuthenticatedPage";
|
||||
import { MatrixAuthCallback } from "./routes/MatrixAuthCallback";
|
||||
|
||||
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="matrix_link" element={<MatrixLinkRoute />} />
|
||||
<Route path="matrix_auth_cb" element={<MatrixAuthCallback />} />
|
||||
<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,
|
||||
};
|
||||
}
|
||||
}
|
||||
89
matrixgw_frontend/src/api/AuthApi.ts
Normal file
89
matrixgw_frontend/src/api/AuthApi.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { APIClient } from "./ApiClient";
|
||||
|
||||
export interface UserInfo {
|
||||
id: number;
|
||||
time_create: number;
|
||||
time_update: number;
|
||||
name: string;
|
||||
email: string;
|
||||
matrix_user_id?: string;
|
||||
matrix_device_id?: 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 user information
|
||||
*/
|
||||
static async GetUserInfo(): Promise<UserInfo> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
26
matrixgw_frontend/src/api/MatrixLinkApi.ts
Normal file
26
matrixgw_frontend/src/api/MatrixLinkApi.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { APIClient } from "./ApiClient";
|
||||
|
||||
export class MatrixLinkApi {
|
||||
/**
|
||||
* Start Matrix Account login
|
||||
*/
|
||||
static async StartAuth(): Promise<{ url: string }> {
|
||||
return (
|
||||
await APIClient.exec({
|
||||
uri: "/matrix_link/start_auth",
|
||||
method: "POST",
|
||||
})
|
||||
).data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finish Matrix Account login
|
||||
*/
|
||||
static async FinishAuth(code: string, state: string): Promise<void> {
|
||||
await APIClient.exec({
|
||||
uri: "/matrix_link/finish_auth",
|
||||
method: "POST",
|
||||
jsonData: { code, state },
|
||||
});
|
||||
}
|
||||
}
|
||||
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>
|
||||
);
|
||||
10
matrixgw_frontend/src/routes/HomeRoute.tsx
Normal file
10
matrixgw_frontend/src/routes/HomeRoute.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";
|
||||
import { NotLinkedAccountMessage } from "../widgets/NotLinkedAccountMessage";
|
||||
|
||||
export function HomeRoute(): React.ReactElement {
|
||||
const user = useUserInfo();
|
||||
|
||||
if (!user.info.matrix_user_id) return <NotLinkedAccountMessage />;
|
||||
|
||||
return <p>Todo home route</p>;
|
||||
}
|
||||
81
matrixgw_frontend/src/routes/MatrixAuthCallback.tsx
Normal file
81
matrixgw_frontend/src/routes/MatrixAuthCallback.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
import { Alert, Box, Button, CircularProgress } from "@mui/material";
|
||||
import React from "react";
|
||||
import { useNavigate, useSearchParams } from "react-router";
|
||||
import { MatrixLinkApi } from "../api/MatrixLinkApi";
|
||||
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";
|
||||
import { RouterLink } from "../widgets/RouterLink";
|
||||
import { useSnackbar } from "../hooks/contexts_provider/SnackbarProvider";
|
||||
|
||||
export function MatrixAuthCallback(): React.ReactElement {
|
||||
const navigate = useNavigate();
|
||||
const snackbar = useSnackbar();
|
||||
|
||||
const info = useUserInfo();
|
||||
|
||||
const [error, setError] = React.useState<null | string>(null);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const code = searchParams.get("code");
|
||||
const state = searchParams.get("state");
|
||||
|
||||
const count = React.useRef("");
|
||||
|
||||
React.useEffect(() => {
|
||||
const load = async () => {
|
||||
try {
|
||||
if (count.current === code) {
|
||||
return;
|
||||
}
|
||||
count.current = code!;
|
||||
|
||||
await MatrixLinkApi.FinishAuth(code!, state!);
|
||||
|
||||
snackbar("Successfully linked to Matrix account!");
|
||||
navigate("/matrix_link");
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setError(String(e));
|
||||
} finally {
|
||||
info.reloadUserInfo();
|
||||
}
|
||||
};
|
||||
|
||||
load();
|
||||
}, [code, state]);
|
||||
|
||||
if (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" }}
|
||||
>
|
||||
Failed to finalize Matrix authentication!
|
||||
<br />
|
||||
<br />
|
||||
{error}
|
||||
</Alert>
|
||||
|
||||
<Button>
|
||||
<RouterLink to="/matrix_link">Go back</RouterLink>
|
||||
</Button>
|
||||
</Box>
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={{ textAlign: "center" }}>
|
||||
<CircularProgress />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
106
matrixgw_frontend/src/routes/MatrixLinkRoute.tsx
Normal file
106
matrixgw_frontend/src/routes/MatrixLinkRoute.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import LinkIcon from "@mui/icons-material/Link";
|
||||
import LinkOffIcon from "@mui/icons-material/LinkOff";
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardActions,
|
||||
CardContent,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { MatrixLinkApi } from "../api/MatrixLinkApi";
|
||||
import { useAlert } from "../hooks/contexts_provider/AlertDialogProvider";
|
||||
import { useLoadingMessage } from "../hooks/contexts_provider/LoadingMessageProvider";
|
||||
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";
|
||||
import { MatrixGWRouteContainer } from "../widgets/MatrixGWRouteContainer";
|
||||
|
||||
export function MatrixLinkRoute(): React.ReactElement {
|
||||
const user = useUserInfo();
|
||||
return (
|
||||
<MatrixGWRouteContainer label={"Matrix account link"}>
|
||||
{user.info.matrix_user_id === null ? <ConnectCard /> : <ConnectedCard />}
|
||||
</MatrixGWRouteContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectCard(): React.ReactElement {
|
||||
const alert = useAlert();
|
||||
const loadingMessage = useLoadingMessage();
|
||||
|
||||
const startMatrixConnection = async () => {
|
||||
try {
|
||||
loadingMessage.show("Initiating Matrix link...");
|
||||
|
||||
const res = await MatrixLinkApi.StartAuth();
|
||||
|
||||
window.location.href = res.url;
|
||||
} catch (e) {
|
||||
console.error(`Failed to connect to Matrix account! ${e}`);
|
||||
alert(`Failed to connect to Matrix account! ${e}`);
|
||||
} finally {
|
||||
loadingMessage.hide();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h5" component="div" gutterBottom>
|
||||
<i>Disconnected from your Matrix account</i>
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" gutterBottom>
|
||||
You need to connect MatrixGW to your Matrix account to let it access
|
||||
your messages.
|
||||
</Typography>
|
||||
</CardContent>
|
||||
<CardActions>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
startIcon={<LinkIcon />}
|
||||
onClick={startMatrixConnection}
|
||||
>
|
||||
Connect now
|
||||
</Button>
|
||||
</CardActions>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedCard(): React.ReactElement {
|
||||
const user = useUserInfo();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent>
|
||||
<Typography variant="h5" component="div" gutterBottom>
|
||||
<i>Connected to your Matrix account</i>
|
||||
</Typography>
|
||||
|
||||
<Typography variant="body1" gutterBottom>
|
||||
<p>
|
||||
MatrixGW is currently connected to your account with the following
|
||||
information:
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
User id: <i>{user.info.matrix_user_id}</i>
|
||||
</li>
|
||||
<li>
|
||||
Device id: <i>{user.info.matrix_device_id}</i>
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
If you encounter issues with your Matrix account you can try to
|
||||
disconnect and connect back again.
|
||||
</p>
|
||||
</Typography>
|
||||
</CardContent>
|
||||
<CardActions>
|
||||
<Button size="small" variant="outlined" startIcon={<LinkOffIcon />}>
|
||||
Disconnect
|
||||
</Button>
|
||||
</CardActions>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
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();
|
||||
}
|
||||
37
matrixgw_frontend/src/widgets/MatrixGWRouteContainer.tsx
Normal file
37
matrixgw_frontend/src/widgets/MatrixGWRouteContainer.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { Typography } from "@mui/material";
|
||||
import React, { type PropsWithChildren } from "react";
|
||||
|
||||
export function MatrixGWRouteContainer(
|
||||
p: {
|
||||
label: string | React.ReactElement;
|
||||
actions?: React.ReactElement;
|
||||
} & PropsWithChildren
|
||||
): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
margin: "50px",
|
||||
flexGrow: 1,
|
||||
flexShrink: 0,
|
||||
flexBasis: 0,
|
||||
minWidth: 0,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "20px",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4">{p.label}</Typography>
|
||||
{p.actions ?? <></>}
|
||||
</div>
|
||||
|
||||
{p.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
14
matrixgw_frontend/src/widgets/NotLinkedAccountMessage.tsx
Normal file
14
matrixgw_frontend/src/widgets/NotLinkedAccountMessage.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
export function NotLinkedAccountMessage(): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
Your Matrix account is not linked yet!
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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,141 @@
|
||||
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, useNavigate } from "react-router";
|
||||
import DashboardHeader from "./DashboardHeader";
|
||||
import DashboardSidebar from "./DashboardSidebar";
|
||||
import { AuthApi, type UserInfo } from "../../api/AuthApi";
|
||||
import { AsyncWidget } from "../AsyncWidget";
|
||||
import { Button } from "@mui/material";
|
||||
import { useAuth } from "../../App";
|
||||
|
||||
interface UserInfoContext {
|
||||
info: UserInfo;
|
||||
reloadUserInfo: () => void;
|
||||
signOut: () => void;
|
||||
}
|
||||
|
||||
const UserInfoContextK = React.createContext<UserInfoContext | null>(null);
|
||||
|
||||
export default function BaseAuthenticatedPage(): React.ReactElement {
|
||||
const theme = useTheme();
|
||||
|
||||
const [userInfo, setuserInfo] = React.useState<null | UserInfo>(null);
|
||||
const loadUserInfo = async () => {
|
||||
setuserInfo(await AuthApi.GetUserInfo());
|
||||
};
|
||||
|
||||
const auth = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const signOut = () => {
|
||||
AuthApi.SignOut();
|
||||
navigate("/");
|
||||
auth.setSignedIn(false);
|
||||
};
|
||||
|
||||
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 (
|
||||
<AsyncWidget
|
||||
loadKey="1"
|
||||
load={loadUserInfo}
|
||||
errMsg="Failed to load user information!"
|
||||
errAdditionalElement={() => (
|
||||
<>
|
||||
<Button onClick={signOut}>Sign out</Button>
|
||||
</>
|
||||
)}
|
||||
build={() => (
|
||||
<UserInfoContextK
|
||||
value={{
|
||||
info: userInfo!,
|
||||
reloadUserInfo: loadUserInfo,
|
||||
signOut,
|
||||
}}
|
||||
>
|
||||
<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",
|
||||
}}
|
||||
>
|
||||
<Outlet />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</UserInfoContextK>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function useUserInfo(): UserInfoContext {
|
||||
return React.use(UserInfoContextK)!;
|
||||
}
|
||||
156
matrixgw_frontend/src/widgets/dashboard/DashboardHeader.tsx
Normal file
156
matrixgw_frontend/src/widgets/dashboard/DashboardHeader.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
import { mdiMessageTextFast } from "@mdi/js";
|
||||
import Icon from "@mdi/react";
|
||||
import LogoutIcon from "@mui/icons-material/Logout";
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import MenuOpenIcon from "@mui/icons-material/MenuOpen";
|
||||
import { Avatar } from "@mui/material";
|
||||
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 { useUserInfo } from "./BaseAuthenticatedPage";
|
||||
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 user = useUserInfo();
|
||||
|
||||
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,
|
||||
display: { xs: "none", sm: "block" },
|
||||
}}
|
||||
>
|
||||
MatrixGW
|
||||
</Typography>
|
||||
</Stack>
|
||||
</RouterLink>
|
||||
</Stack>
|
||||
|
||||
{/* User avatar */}
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
p: 2,
|
||||
gap: 1,
|
||||
alignItems: "center",
|
||||
borderTop: "1px solid",
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
<Avatar
|
||||
sizes="small"
|
||||
alt={user.info.name}
|
||||
sx={{ width: 36, height: 36 }}
|
||||
/>
|
||||
<Box sx={{ mr: "auto", display: { xs: "none", md: "block" } }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ fontWeight: 500, lineHeight: "16px" }}
|
||||
>
|
||||
{user.info.name}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: "text.secondary" }}>
|
||||
{user.info.email}
|
||||
</Typography>
|
||||
</Box>
|
||||
<ThemeSwitcher />
|
||||
<Tooltip title="Sign out">
|
||||
<IconButton size="small" onClick={user.signOut}>
|
||||
<LogoutIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</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="/matrix_link"
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
57
matrixgw_frontend/src/widgets/dashboard/ThemeSwitcher.tsx
Normal file
57
matrixgw_frontend/src/widgets/dashboard/ThemeSwitcher.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
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}
|
||||
>
|
||||
<LightModeIcon
|
||||
sx={{
|
||||
display: "inline",
|
||||
[theme.getColorSchemeSelector("dark")]: {
|
||||
display: "none",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<DarkModeIcon
|
||||
sx={{
|
||||
display: "none",
|
||||
[theme.getColorSchemeSelector("dark")]: {
|
||||
display: "inline",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</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,187 +0,0 @@
|
||||
use clap::Parser;
|
||||
use s3::creds::Credentials;
|
||||
use s3::{Bucket, Region};
|
||||
|
||||
/// Matrix gateway backend API
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
pub struct AppConfig {
|
||||
/// Listen address
|
||||
#[clap(short, long, env, default_value = "0.0.0.0:8000")]
|
||||
pub listen_address: String,
|
||||
|
||||
/// Website origin
|
||||
#[clap(short, long, env, default_value = "http://localhost:8000")]
|
||||
pub website_origin: String,
|
||||
|
||||
/// Proxy IP, might end with a star "*"
|
||||
#[clap(short, long, env)]
|
||||
pub proxy_ip: Option<String>,
|
||||
|
||||
/// Secret key, used to sign some resources. Must be randomly generated
|
||||
#[clap(short = 'S', long, env, default_value = "")]
|
||||
secret: String,
|
||||
|
||||
/// Matrix API origin
|
||||
#[clap(short, long, env, default_value = "http://127.0.0.1:8448")]
|
||||
pub matrix_homeserver: String,
|
||||
|
||||
/// Redis connection hostname
|
||||
#[clap(long, env, default_value = "localhost")]
|
||||
redis_hostname: String,
|
||||
|
||||
/// Redis connection port
|
||||
#[clap(long, env, default_value_t = 6379)]
|
||||
redis_port: u16,
|
||||
|
||||
/// Redis database number
|
||||
#[clap(long, env, default_value_t = 0)]
|
||||
redis_db_number: i64,
|
||||
|
||||
/// Redis username
|
||||
#[clap(long, env)]
|
||||
redis_username: Option<String>,
|
||||
|
||||
/// Redis password
|
||||
#[clap(long, env, default_value = "secretredis")]
|
||||
redis_password: String,
|
||||
|
||||
/// URL where the OpenID configuration can be found
|
||||
#[arg(
|
||||
long,
|
||||
env,
|
||||
default_value = "http://localhost:9001/dex/.well-known/openid-configuration"
|
||||
)]
|
||||
pub oidc_configuration_url: String,
|
||||
|
||||
/// OpenID client ID
|
||||
#[arg(long, env, default_value = "foo")]
|
||||
pub oidc_client_id: String,
|
||||
|
||||
/// OpenID client secret
|
||||
#[arg(long, env, default_value = "bar")]
|
||||
pub oidc_client_secret: String,
|
||||
|
||||
/// OpenID login redirect URL
|
||||
#[arg(long, env, default_value = "APP_ORIGIN/oidc_cb")]
|
||||
oidc_redirect_url: String,
|
||||
|
||||
/// S3 Bucket name
|
||||
#[arg(long, env, default_value = "matrix-gw")]
|
||||
s3_bucket_name: 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! {
|
||||
static ref ARGS: AppConfig = {
|
||||
AppConfig::parse()
|
||||
};
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
/// Get parsed command line arguments
|
||||
pub fn get() -> &'static AppConfig {
|
||||
&ARGS
|
||||
}
|
||||
|
||||
/// Get app secret
|
||||
pub fn secret(&self) -> &str {
|
||||
let mut secret = self.secret.as_str();
|
||||
|
||||
if cfg!(debug_assertions) && secret.is_empty() {
|
||||
secret = "DEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEYDEBUGKEY";
|
||||
}
|
||||
|
||||
if secret.is_empty() {
|
||||
panic!("SECRET is undefined or too short (min 64 chars)!")
|
||||
}
|
||||
|
||||
secret
|
||||
}
|
||||
|
||||
/// Get Redis connection configuration
|
||||
pub fn redis_connection_string(&self) -> String {
|
||||
format!(
|
||||
"redis://{}:{}@{}:{}/{}",
|
||||
self.redis_username.as_deref().unwrap_or(""),
|
||||
self.redis_password,
|
||||
self.redis_hostname,
|
||||
self.redis_port,
|
||||
self.redis_db_number
|
||||
)
|
||||
}
|
||||
|
||||
/// Get OpenID providers configuration
|
||||
pub fn openid_provider(&self) -> OIDCProvider<'_> {
|
||||
OIDCProvider {
|
||||
client_id: self.oidc_client_id.as_str(),
|
||||
client_secret: self.oidc_client_secret.as_str(),
|
||||
configuration_url: self.oidc_configuration_url.as_str(),
|
||||
redirect_url: self
|
||||
.oidc_redirect_url
|
||||
.replace("APP_ORIGIN", &self.website_origin),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get s3 bucket credentials
|
||||
pub fn s3_credentials(&self) -> anyhow::Result<Credentials> {
|
||||
Ok(Credentials::new(
|
||||
Some(&self.s3_access_key),
|
||||
Some(&self.s3_secret_key),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Get S3 bucket
|
||||
pub fn s3_bucket(&self) -> anyhow::Result<Box<Bucket>> {
|
||||
Ok(Bucket::new(
|
||||
&self.s3_bucket_name,
|
||||
Region::Custom {
|
||||
region: self.s3_region.to_string(),
|
||||
endpoint: self.s3_endpoint.to_string(),
|
||||
},
|
||||
self.s3_credentials()?,
|
||||
)?
|
||||
.with_path_style())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct OIDCProvider<'a> {
|
||||
pub client_id: &'a str,
|
||||
pub client_secret: &'a str,
|
||||
pub configuration_url: &'a str,
|
||||
pub redirect_url: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::app_config::AppConfig;
|
||||
|
||||
#[test]
|
||||
fn verify_cli() {
|
||||
use clap::CommandFactory;
|
||||
AppConfig::command().debug_assert()
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user