Compare commits

..

No commits in common. "68aa13e216519df144f580fc19a6e86b775d6a85" and "e64086b7cff8609287f2c3cede5d6ee4d3105409" have entirely different histories.

12 changed files with 153 additions and 331 deletions

View File

@ -2,9 +2,32 @@
recorder-playground = "run -p recorder --example playground -- --environment development" recorder-playground = "run -p recorder --example playground -- --environment development"
[build] [build]
rustflags = [ rustflags = ["-Zthreads=8", "--cfg", "feature=\"testcontainers\""]
"-Zthreads=8",
"--cfg", [target.x86_64-unknown-linux-gnu]
"feature=\"testcontainers\"", linker = "clang"
"-Zshare-generics=y", rustflags = ["-Zthreads=8", "-Clink-arg=-fuse-ld=lld", "-Zshare-generics=y"]
]
[target.x86_64-pc-windows-msvc]
linker = "rust-lld.exe"
rustflags = ["-Zthreads=8", "-Zshare-generics=n"]
# NOTE: you must install [Mach-O LLD Port](https://lld.llvm.org/MachO/index.html) on mac. you can easily do this by installing llvm which includes lld with the "brew" package manager:
# `brew install llvm`
#[target.x86_64-apple-darwin]
#rustflags = [
# "-Zthreads=8",
# "-C",
# "link-arg=-fuse-ld=/usr/local/opt/llvm/bin/ld64.lld",
# "-Zshare-generics=y",
#]
# NOTE: you must install [Mach-O LLD Port](https://lld.llvm.org/MachO/index.html) on mac. you can easily do this by installing llvm which includes lld with the "brew" package manager:
# `brew install llvm`
#[target.aarch64-apple-darwin]
#rustflags = [
# "-Zthreads=8",
# "-C",
# "link-arg=-fuse-ld=/opt/homebrew/opt/llvm/bin/ld64.lld",
# "-Zshare-generics=y",
#]

15
.vscode/settings.json vendored
View File

@ -28,18 +28,5 @@
"emmet.showExpandedAbbreviation": "never", "emmet.showExpandedAbbreviation": "never",
"prettier.enable": false, "prettier.enable": false,
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"rust-analyzer.cargo.features": [ "rust-analyzer.cargo.features": ["testcontainers"]
"testcontainers"
],
"sqltools.connections": [
{
"previewLimit": 50,
"server": "localhost",
"port": 5432,
"driver": "PostgreSQL",
"name": "konobangu-dev",
"database": "konobangu",
"username": "konobangu"
}
]
} }

3
Cargo.lock generated
View File

@ -5632,7 +5632,8 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]] [[package]]
name = "seaography" name = "seaography"
version = "1.1.4" version = "1.1.4"
source = "git+https://github.com/lonelyhentxi/seaography.git?rev=0c4cc5c#0c4cc5ccd43730338802f98401120d5faeccd096" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f5e0455935e4f31eb64ce606d9963715efd4c1856edb129619126f6b5372fcf"
dependencies = [ dependencies = [
"async-graphql", "async-graphql",
"fnv", "fnv",

View File

@ -50,4 +50,3 @@ recorder = { path = "./apps/recorder" }
[patch.crates-io] [patch.crates-io]
jwt-authorizer = { git = "https://github.com/blablacio/jwt-authorizer.git", rev = "e956774" } jwt-authorizer = { git = "https://github.com/blablacio/jwt-authorizer.git", rev = "e956774" }
seaography = { git = "https://github.com/lonelyhentxi/seaography.git", rev = "0c4cc5c" }

View File

@ -1,8 +1,8 @@
AUTH_TYPE = "oidc" # or oidc AUTH_TYPE = "basic" # or oidc
BASIC_USER = "konobangu" BASIC_USER = "konobangu"
BASIC_PASSWORD = "konobangu" BASIC_PASSWORD = "konobangu"
OIDC_ISSUER="https://auth.logto.io/oidc" # OIDC_ISSUER="https://auth.logto.io/oidc"
OIDC_AUDIENCE = "https://konobangu.com/api" # OIDC_API_AUDIENCE = "https://konobangu.com/api"
OIDC_CLIENT_ID = "client_id" # OIDC_CLIENT_ID = "client_id"
OIDC_CLIENT_SECRET = "client_secret" # optional # OIDC_CLIENT_SECRET = "client_secret" # optional
OIDC_EXTRA_SCOPES = "read:konobangu write:konobangu" # OIDC_EXTRA_SCOPES = "read:konobangu write:konobangu"

View File

@ -4,8 +4,11 @@ use async_graphql::dynamic::{ResolverContext, ValueAccessor};
use sea_orm::EntityTrait; use sea_orm::EntityTrait;
use seaography::{BuilderContext, FnGuard, GuardAction}; use seaography::{BuilderContext, FnGuard, GuardAction};
use super::util::{get_column_key, get_entity_key}; use super::util::get_entity_key;
use crate::auth::{AuthError, AuthUserInfo}; use crate::{
auth::{AuthError, AuthUserInfo},
graphql::util::get_column_key,
};
fn guard_data_object_accessor_with_subscriber_id( fn guard_data_object_accessor_with_subscriber_id(
value: ValueAccessor<'_>, value: ValueAccessor<'_>,
@ -47,20 +50,27 @@ fn guard_data_object_accessor_with_optional_subscriber_id(
} }
} }
pub fn guard_entity_with_subscriber_id<T>(_context: &BuilderContext, _column: &T::Column) -> FnGuard fn guard_filter_object_accessor_with_subscriber_id(
where value: ValueAccessor<'_>,
T: EntityTrait, column_name: &str,
<T as EntityTrait>::Model: Sync, subscriber_id: i32,
{ ) -> async_graphql::Result<()> {
Box::new(move |context: &ResolverContext| -> GuardAction { let obj = value.object()?;
match context.ctx.data::<AuthUserInfo>() { let subscriber_id_filter_input_value = obj.try_get(column_name)?;
Ok(_) => GuardAction::Allow,
Err(err) => GuardAction::Block(Some(err.message)), let subscriber_id_filter_input_obj = subscriber_id_filter_input_value.object()?;
}
}) let subscriber_id_value = subscriber_id_filter_input_obj.try_get("eq")?;
let id = subscriber_id_value.i64()?;
if id == subscriber_id as i64 {
Ok(())
} else {
Err(async_graphql::Error::new("subscriber not match"))
}
} }
pub fn guard_field_with_subscriber_id<T>(context: &BuilderContext, column: &T::Column) -> FnGuard pub fn guard_entity_with_subscriber_id<T>(context: &BuilderContext, column: &T::Column) -> FnGuard
where where
T: EntityTrait, T: EntityTrait,
<T as EntityTrait>::Model: Sync, <T as EntityTrait>::Model: Sync,
@ -85,13 +95,23 @@ where
)); ));
let entity_create_batch_mutation_data_field_name = let entity_create_batch_mutation_data_field_name =
Arc::new(context.entity_create_batch_mutation.data_field.clone()); Arc::new(context.entity_create_batch_mutation.data_field.clone());
let entity_delete_mutation_field_name = Arc::new(format!(
"{}{}",
entity_name,
context.entity_delete_mutation.mutation_suffix.clone()
));
let entity_delete_mutation_filter_field_name =
Arc::new(context.entity_delete_mutation.filter_field.clone());
let entity_update_mutation_field_name = Arc::new(format!( let entity_update_mutation_field_name = Arc::new(format!(
"{}{}", "{}{}",
entity_name, context.entity_update_mutation.mutation_suffix entity_name, context.entity_update_mutation.mutation_suffix
)); ));
let entity_update_mutation_filter_field_name =
Arc::new(context.entity_update_mutation.filter_field.clone());
let entity_update_mutation_data_field_name = let entity_update_mutation_data_field_name =
Arc::new(context.entity_update_mutation.data_field.clone()); Arc::new(context.entity_update_mutation.data_field.clone());
let entity_query_field_name = Arc::new(entity_name);
let entity_query_filter_field_name = Arc::new(context.entity_query_field.filters.clone());
Box::new(move |context: &ResolverContext| -> GuardAction { Box::new(move |context: &ResolverContext| -> GuardAction {
match context.ctx.data::<AuthUserInfo>() { match context.ctx.data::<AuthUserInfo>() {
Ok(user_info) => { Ok(user_info) => {
@ -137,26 +157,80 @@ where
&column_name, &column_name,
) )
}), }),
field if field == entity_update_mutation_field_name.as_str() => { field if field == entity_delete_mutation_field_name.as_str() => context
match context.args.get(&entity_update_mutation_data_field_name) { .args
Some(data_value) => { .try_get(&entity_delete_mutation_filter_field_name)
guard_data_object_accessor_with_optional_subscriber_id( .and_then(|filter_value| {
data_value, guard_filter_object_accessor_with_subscriber_id(
&column_name, filter_value,
subscriber_id, &column_name,
) subscriber_id,
.map_err(|inner_error| { )
AuthError::from_graphql_subscribe_id_guard( })
inner_error, .map_err(|inner_error| {
context, AuthError::from_graphql_subscribe_id_guard(
&entity_update_mutation_data_field_name, inner_error,
context,
&entity_delete_mutation_filter_field_name,
&column_name,
)
}),
field if field == entity_update_mutation_field_name.as_str() => context
.args
.try_get(&entity_update_mutation_filter_field_name)
.and_then(|filter_value| {
guard_filter_object_accessor_with_subscriber_id(
filter_value,
&column_name,
subscriber_id,
)
})
.map_err(|inner_error| {
AuthError::from_graphql_subscribe_id_guard(
inner_error,
context,
&entity_update_mutation_filter_field_name,
&column_name,
)
})
.and_then(|_| {
match context.args.get(&entity_update_mutation_data_field_name) {
Some(data_value) => {
guard_data_object_accessor_with_optional_subscriber_id(
data_value,
&column_name, &column_name,
subscriber_id,
) )
}) .map_err(|inner_error| {
AuthError::from_graphql_subscribe_id_guard(
inner_error,
context,
&entity_update_mutation_data_field_name,
&column_name,
)
})
}
None => Ok(()),
} }
None => Ok(()), }),
} field if field == entity_query_field_name.as_str() => context
} .args
.try_get(&entity_query_filter_field_name)
.and_then(|filter_value| {
guard_filter_object_accessor_with_subscriber_id(
filter_value,
&column_name,
subscriber_id,
)
})
.map_err(|inner_error| {
AuthError::from_graphql_subscribe_id_guard(
inner_error,
context,
&entity_query_filter_field_name,
&column_name,
)
}),
field => Err(AuthError::from_graphql_subscribe_id_guard( field => Err(AuthError::from_graphql_subscribe_id_guard(
async_graphql::Error::new("unsupport graphql field"), async_graphql::Error::new("unsupport graphql field"),
context, context,

View File

@ -4,7 +4,6 @@ pub mod guard;
pub mod schema_root; pub mod schema_root;
pub mod service; pub mod service;
pub mod subscriptions; pub mod subscriptions;
pub mod transformer;
pub mod util; pub mod util;
pub use config::GraphQLConfig; pub use config::GraphQLConfig;

View File

@ -3,16 +3,13 @@ use once_cell::sync::OnceCell;
use sea_orm::{DatabaseConnection, EntityTrait, Iterable}; use sea_orm::{DatabaseConnection, EntityTrait, Iterable};
use seaography::{Builder, BuilderContext, FilterType, FilterTypesMapHelper}; use seaography::{Builder, BuilderContext, FilterType, FilterTypesMapHelper};
use super::transformer::filter_condition_transformer; use super::{
use crate::graphql::{ filter::{SUBSCRIBER_ID_FILTER_INFO, subscriber_id_condition_function},
filter::{
SUBSCRIBER_ID_FILTER_INFO, init_custom_filter_info, subscriber_id_condition_function,
},
guard::{guard_entity_with_subscriber_id, guard_field_with_subscriber_id},
util::{get_entity_column_key, get_entity_key}, util::{get_entity_column_key, get_entity_key},
}; };
use crate::graphql::{filter::init_custom_filter_info, guard::guard_entity_with_subscriber_id};
pub static CONTEXT: OnceCell<BuilderContext> = OnceCell::new(); static CONTEXT: OnceCell<BuilderContext> = OnceCell::new();
fn restrict_filter_input_for_entity<T>( fn restrict_filter_input_for_entity<T>(
context: &mut BuilderContext, context: &mut BuilderContext,
@ -34,13 +31,9 @@ where
let entity_key = get_entity_key::<T>(context); let entity_key = get_entity_key::<T>(context);
let entity_column_key = get_entity_column_key::<T>(context, column); let entity_column_key = get_entity_column_key::<T>(context, column);
context.guards.entity_guards.insert( context.guards.entity_guards.insert(
entity_key.clone(), entity_key,
guard_entity_with_subscriber_id::<T>(context, column), guard_entity_with_subscriber_id::<T>(context, column),
); );
context.guards.field_guards.insert(
entity_column_key.clone(),
guard_field_with_subscriber_id::<T>(context, column),
);
context.filter_types.overwrites.insert( context.filter_types.overwrites.insert(
entity_column_key.clone(), entity_column_key.clone(),
Some(FilterType::Custom( Some(FilterType::Custom(
@ -51,10 +44,6 @@ where
entity_column_key, entity_column_key,
subscriber_id_condition_function::<T>(context, column), subscriber_id_condition_function::<T>(context, column),
); );
context.transformers.filter_conditions_transformers.insert(
entity_key,
filter_condition_transformer::<T>(context, column),
);
} }
pub fn schema( pub fn schema(
@ -164,6 +153,7 @@ pub fn schema(
}; };
schema schema
.data(database) .data(database)
// .extension(GraphqlAuthExtension)
.finish() .finish()
.inspect_err(|e| tracing::error!(e = ?e)) .inspect_err(|e| tracing::error!(e = ?e))
} }

View File

@ -1,27 +0,0 @@
use async_graphql::dynamic::ResolverContext;
use sea_orm::{ColumnTrait, Condition, EntityTrait};
use seaography::{BuilderContext, FnFilterConditionsTransformer};
use crate::auth::AuthUserInfo;
pub fn filter_condition_transformer<T>(
_context: &BuilderContext,
column: &T::Column,
) -> FnFilterConditionsTransformer
where
T: EntityTrait,
<T as EntityTrait>::Model: Sync,
{
let column = *column;
Box::new(
move |context: &ResolverContext, condition: Condition| -> Condition {
match context.ctx.data::<AuthUserInfo>() {
Ok(user_info) => {
let subscriber_id = user_info.subscriber_auth.subscriber_id;
condition.add(column.eq(subscriber_id))
}
Err(err) => unreachable!("auth user info must be guarded: {:?}", err),
}
},
)
}

View File

@ -5,7 +5,7 @@ AUTH_TYPE = "basic" # or oidc
BASIC_USER = "konobangu" BASIC_USER = "konobangu"
BASIC_PASSWORD = "konobangu" BASIC_PASSWORD = "konobangu"
# OIDC_ISSUER="https://auth.logto.io/oidc" # OIDC_ISSUER="https://auth.logto.io/oidc"
# OIDC_AUDIENCE = "https://konobangu.com/api" # OIDC_API_AUDIENCE = "https://konobangu.com/api"
# OIDC_CLIENT_ID = "client_id" # OIDC_CLIENT_ID = "client_id"
# OIDC_CLIENT_SECRET = "client_secret" # optional # OIDC_CLIENT_SECRET = "client_secret" # optional
# OIDC_EXTRA_SCOPES = "read:konobangu write:konobangu" # OIDC_EXTRA_SCOPES = "read:konobangu write:konobangu"

View File

@ -42,7 +42,7 @@ export interface OidcAuthContext {
type: typeof AuthMethodEnum.OIDC; type: typeof AuthMethodEnum.OIDC;
oidcSecurityService: OidcSecurityService; oidcSecurityService: OidcSecurityService;
isAuthenticated$: Observable<boolean>; isAuthenticated$: Observable<boolean>;
userData$: Observable<{}>; userData$: Observable<any>;
checkAuthResultEvent$: Observable<CheckAuthResultEventType>; checkAuthResultEvent$: Observable<CheckAuthResultEventType>;
} }

View File

@ -1,37 +1,5 @@
import { useAuth } from '@/auth/hooks';
import { Button } from '@/components/ui/button';
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import type { RouteStateDataOption } from '@/traits/router'; import type { RouteStateDataOption } from '@/traits/router';
import { createFileRoute } from '@tanstack/react-router'; import { createFileRoute } from '@tanstack/react-router';
import { useNavigate } from '@tanstack/react-router';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
export const Route = createFileRoute('/_app/subscriptions/create')({ export const Route = createFileRoute('/_app/subscriptions/create')({
component: SubscriptionCreateRouteComponent, component: SubscriptionCreateRouteComponent,
@ -40,198 +8,6 @@ export const Route = createFileRoute('/_app/subscriptions/create')({
} satisfies RouteStateDataOption, } satisfies RouteStateDataOption,
}); });
type SubscriptionFormValues = {
displayName: string;
sourceUrl: string;
category: string;
enabled: boolean;
};
function SubscriptionCreateRouteComponent() { function SubscriptionCreateRouteComponent() {
const { userData } = useAuth(); return <div>Hello "/subscriptions/create"!</div>;
console.log(JSON.stringify(userData, null, 2));
const [isSubmitting, setIsSubmitting] = useState(false);
const navigate = useNavigate();
const form = useForm<SubscriptionFormValues>({
defaultValues: {
displayName: '',
sourceUrl: '',
category: 'Mikan',
enabled: true,
},
});
const onSubmit = async (data: SubscriptionFormValues) => {
try {
setIsSubmitting(true);
const requestData = {
query: `
mutation CreateSubscription($input: SubscriptionsInsertInput!) {
subscriptionsCreateOne(data: $input) {
id
displayName
sourceUrl
enabled
category
}
}
`,
variables: {
input: {
category: data.category,
displayName: data.displayName,
sourceUrl: data.sourceUrl,
enabled: data.enabled,
},
},
};
const response = await fetch('/api/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData),
});
const responseData = await response.json();
if (responseData.errors) {
throw new Error(
responseData.errors[0]?.message || 'Failed to create subscription'
);
}
toast.success('Subscription created successfully');
navigate({ to: '/subscriptions/manage' });
} catch (error) {
console.error('Failed to create subscription:', error);
toast.error(
`Subscription creation failed: ${
error instanceof Error ? error.message : 'Unknown error'
}`
);
} finally {
setIsSubmitting(false);
}
};
return (
<Card>
<CardHeader>
<CardTitle>Create Anime Subscription</CardTitle>
<CardDescription>Add a new anime subscription source</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="category"
render={({ field }) => (
<FormItem>
<FormLabel>Source Type</FormLabel>
<Select
disabled
value={field.value}
onValueChange={field.onChange}
defaultValue="Mikan"
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select source type" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="Mikan">Mikan</SelectItem>
</SelectContent>
</Select>
<FormDescription>
Currently only Mikan source is supported
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="displayName"
render={({ field }) => (
<FormItem>
<FormLabel>Display Name</FormLabel>
<FormControl>
<Input
placeholder="Enter subscription display name"
{...field}
/>
</FormControl>
<FormDescription>
Set an easily recognizable name for this subscription
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="sourceUrl"
render={({ field }) => (
<FormItem>
<FormLabel>Source URL</FormLabel>
<FormControl>
<Input
placeholder="Enter subscription source URL"
{...field}
/>
</FormControl>
<FormDescription>
Copy the RSS subscription link from the source website, e.g.
https://mikanani.me/RSS/Bangumi?bangumiId=3141&subgroupid=370
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="enabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Enable Subscription
</FormLabel>
<FormDescription>
Enable this subscription immediately after creation
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</form>
</Form>
</CardContent>
<CardFooter className="flex justify-between">
<Button
variant="outline"
onClick={() => navigate({ to: '/subscriptions/manage' })}
>
Cancel
</Button>
<Button
type="submit"
onClick={form.handleSubmit(onSubmit)}
disabled={isSubmitting}
>
{isSubmitting ? 'Creating...' : 'Create Subscription'}
</Button>
</CardFooter>
</Card>
);
} }