Skip to content

Commit

Permalink
Wire user auth state into JS runtime.
Browse files Browse the repository at this point in the history
  • Loading branch information
ignatz committed Nov 14, 2024
1 parent 0755444 commit 21b59dc
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 7 deletions.
10 changes: 9 additions & 1 deletion client/testfixture/trailbase.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ export type HeaderMapType = {
export type PathParamsType = {
[key: string]: string;
};
export type UserType = {
id: string;
email: string;
csrf: string;
};
export type RequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: Uint8Array;
};
export type ResponseType = {
Expand Down Expand Up @@ -88,6 +94,7 @@ export type StringRequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: string;
};
export type StringResponseType = {
Expand All @@ -106,6 +113,7 @@ export type JsonRequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: object | string;
};
export interface JsonResponseType {
Expand All @@ -115,7 +123,7 @@ export interface JsonResponseType {
}
export declare function jsonHandler(f: (req: JsonRequestType) => MaybeResponse<JsonRequestType | object>): CallbackType;
export declare function addRoute(method: string, route: string, callback: CallbackType): void;
export declare function dispatch(method: string, route: string, uri: string, pathParams: [string, string][], headers: [string, string][], body: Uint8Array): Promise<ResponseType>;
export declare function dispatch(method: string, route: string, uri: string, pathParams: [string, string][], headers: [string, string][], user: UserType | undefined, body: Uint8Array): Promise<ResponseType>;
export declare function query(queryStr: string, params: unknown[]): Promise<unknown[][]>;
export declare function execute(queryStr: string, params: unknown[]): Promise<number>;
export type ParsedPath = {
Expand Down
8 changes: 6 additions & 2 deletions client/testfixture/trailbase.js
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ export function stringHandler(f) {
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});
if (resp === undefined) {
Expand Down Expand Up @@ -411,6 +412,7 @@ export function htmlHandler(f) {
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});
if (resp === undefined) {
Expand Down Expand Up @@ -449,6 +451,7 @@ export function jsonHandler(f) {
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});
if (resp === undefined) {
Expand Down Expand Up @@ -487,7 +490,7 @@ export function addRoute(method, route, callback) {
callbacks.set(`${method}:${route}`, callback);
console.debug("JS: Added route:", method, route);
}
export async function dispatch(method, route, uri, pathParams, headers, body) {
export async function dispatch(method, route, uri, pathParams, headers, user, body) {
const key = `${method}:${route}`;
const cb = callbacks.get(key);
if (!cb) {
Expand All @@ -497,9 +500,11 @@ export async function dispatch(method, route, uri, pathParams, headers, body) {
uri,
params: Object.fromEntries(pathParams),
headers: Object.fromEntries(headers),
user: user,
body,
})) ?? { status: StatusCodes.OK });
}
globalThis.__dispatch = dispatch;
export async function query(queryStr, params) {
return await rustyscript.async_functions.query(queryStr, params);
}
Expand Down Expand Up @@ -658,4 +663,3 @@ export function encodeFallback(string) {
// because the original array still exists.
return target.slice ? target.slice(0, at) : target.subarray(0, at);
}
globalThis.__dispatch = dispatch;
20 changes: 18 additions & 2 deletions trailbase-core/js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@ declare var globalThis: any;

export type HeaderMapType = { [key: string]: string };
export type PathParamsType = { [key: string]: string };
export type UserType = {
/// Base64 encoded UUIDv7 user id.
id: string;
/// The user's email address.
email: string;
/// The user's CSRF token.
csrf: string;
};
export type RequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: Uint8Array;
};
export type ResponseType = {
Expand Down Expand Up @@ -397,6 +406,7 @@ export type StringRequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: string;
};
export type StringResponseType = {
Expand All @@ -415,6 +425,7 @@ export function stringHandler(
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});

Expand Down Expand Up @@ -463,6 +474,7 @@ export function htmlHandler(
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});

Expand Down Expand Up @@ -500,6 +512,7 @@ export type JsonRequestType = {
uri: string;
params: PathParamsType;
headers: HeaderMapType;
user?: UserType;
body?: object | string;
};
export interface JsonResponseType {
Expand All @@ -518,6 +531,7 @@ export function jsonHandler(
uri: req.uri,
params: req.params,
headers: req.headers,
user: req.user,
body: body && decodeFallback(body),
});

Expand Down Expand Up @@ -571,6 +585,7 @@ export async function dispatch(
uri: string,
pathParams: [string, string][],
headers: [string, string][],
user: UserType | undefined,
body: Uint8Array,
): Promise<ResponseType> {
const key = `${method}:${route}`;
Expand All @@ -584,11 +599,14 @@ export async function dispatch(
uri,
params: Object.fromEntries(pathParams),
headers: Object.fromEntries(headers),
user: user,
body,
})) ?? { status: StatusCodes.OK }
);
}

globalThis.__dispatch = dispatch;

export async function query(
queryStr: string,
params: unknown[],
Expand Down Expand Up @@ -771,5 +789,3 @@ export function encodeFallback(string: string): Uint8Array {
// because the original array still exists.
return target.slice ? target.slice(0, at) : target.subarray(0, at);
}

globalThis.__dispatch = dispatch;
20 changes: 18 additions & 2 deletions trailbase-core/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ use axum::Router;
use libsql::Connection;
use parking_lot::Mutex;
use rustyscript::{init_platform, json_args, Module, Runtime};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use serde_json::from_value;
use std::collections::HashSet;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use thiserror::Error;

use crate::assets::cow_to_string;
use crate::auth::user::User;
use crate::js::import_provider::JsRuntimeAssets;
use crate::records::sql_to_json::rows_to_json_arrays;
use crate::{AppState, DataDir};
Expand Down Expand Up @@ -357,7 +358,7 @@ fn add_route_to_router(
let method_uppercase = method.to_uppercase();

let route_path = route.clone();
let handler = move |params: RawPathParams, req: Request| async move {
let handler = move |params: RawPathParams, user: Option<User>, req: Request| async move {
let (parts, body) = req.into_parts();

let Ok(body_bytes) = axum::body::to_bytes(body, usize::MAX).await else {
Expand All @@ -383,6 +384,20 @@ fn add_route_to_router(
})
.collect();

#[derive(Serialize)]
struct JsUser {
// Base64 encoded user id.
id: String,
email: String,
csrf: String,
}

let js_user: Option<JsUser> = user.map(|u| JsUser {
id: u.id,
email: u.email,
csrf: u.csrf_token,
});

#[derive(Deserialize)]
struct JsResponse {
headers: Option<Vec<(String, String)>>,
Expand All @@ -404,6 +419,7 @@ fn add_route_to_router(
uri.to_string(),
path_params,
headers,
js_user,
body_bytes
),
)
Expand Down

0 comments on commit 21b59dc

Please sign in to comment.