Skip to content

Latest commit

 

History

History
184 lines (133 loc) · 5.76 KB

File metadata and controls

184 lines (133 loc) · 5.76 KB

Using Custom Entities with SeaORM Pro Actix Integration

This guide explains how to use the SeaORM Pro admin interface with your own Sea-ORM entities instead of the built-in ones.

Overview

The Actix Web integration feature supports two modes:

  1. Default Mode: Uses sea-orm-pro's built-in entities (Django-style user models)
  2. Custom Mode: Uses your own Sea-ORM entities with a custom GraphQL schema

Default Mode (Built-in Entities)

use sea_orm_pro_backend::actix_integration::{SeaOrmProActixConfigurator, SeaOrmProActixOptions};

let config = SeaOrmProActixConfigurator::new(
    SeaOrmProActixOptions::new(db.clone(), secret_key)
        .with_admin_base_path("/admin")
)?;

// Mount on your Actix server...

Custom Mode (Your Own Entities)

Step 1: Define Your Entities

Use sea-orm-cli to generate entities from your database:

sea-orm-cli generate entity -u sqlite://your_database.db -o src/entities

Step 2: Build GraphQL Schema from Your Entities

Create a function to build your GraphQL schema using seaography:

// In your main application code (not in sea-orm-pro)
use sea_orm::DatabaseConnection;
use seaography::{Builder, BuilderContext, LifecycleHooks, MultiLifecycleHooks};
use async_graphql::dynamic::Schema;

/// Build GraphQL schema from your custom entities
pub fn build_custom_admin_schema(
    db: DatabaseConnection,
    depth: Option<usize>,
    complexity: Option<usize>,
) -> Result<Schema, async_graphql::dynamic::SchemaError> {
    // Create builder context
    let context = BuilderContext {
        hooks: LifecycleHooks::new(MultiLifecycleHooks::default()),
        ..Default::default()
    };

    let builder = Builder::new(&context, db.clone());
    
    // Register your entities
    let builder = register_custom_entities(builder);
    
    builder
        .set_depth_limit(depth)
        .set_complexity_limit(complexity)
        .schema_builder()
        .data(db)
        .finish()
}

/// Register all your custom entities with the schema builder
fn register_custom_entities(builder: Builder) -> Builder {
    // Add entity registration for each of your entities
    // For example:
    // builder.register_entity::<MyEntity>()
    //     .register_entity::<AnotherEntity>()
    
    // See seaography documentation for entity registration details
    builder
}

Step 3: Mount with Custom Schema

use sea_orm_pro_backend::actix_integration::{SeaOrmProActixConfigurator, SeaOrmProActixOptions};

// Build your custom schema
let custom_schema = build_custom_admin_schema(db.clone(), Some(100), Some(1000))?;

// Use it with SeaORM Pro
let config = SeaOrmProActixConfigurator::new(
    SeaOrmProActixOptions::new(db.clone(), secret_key)
        .with_custom_schema(custom_schema)
        .with_admin_base_path("/admin")
)?;

// Mount on your Actix server...

User Authentication

SeaORM Pro's admin interface expects a users_user table with:

  • email (VARCHAR, unique primary id)
  • password (VARCHAR, bcrypt hash)
  • username (VARCHAR, optional)
  • is_email_verified (BOOLEAN, optional)

If you don't have this table with this exact schema, you'll need to:

  1. Create the table in your database before using the admin interface
  2. Seed it with an initial admin user
  3. Update authentication code if your user model differs significantly

Example: Seeding Admin User

# Generate bcrypt hash for password "admin123"
python3 -c "import bcrypt; print(bcrypt.hashpw(b'admin123', bcrypt.gensalt())).decode())"

# Insert into database
sqlite3 your_database.db "
INSERT INTO users_user (email, password, username, is_email_verified) 
VALUES ('admin@example.com', '\$2b\$12\$...', 'admin', true)
"

Accessing the Admin Interface

Once mounted, you can access:

  • GraphQL Playground: http://localhost:8080/admin/graphql
  • Login: POST /admin/auth/login with {"email": "...", "password": "..."}
  • Current User: GET /admin/user/current (requires auth)
  • Config: GET /admin/config (public)

Example: Login and Query

# 1. Login to get JWT token
TOKEN=$(curl -s -X POST http://localhost:8080/admin/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@example.com","password":"admin123"}' \
  | jq -r '.token')

# 2. Use token for authenticated requests
curl -s http://localhost:8080/admin/user/current \
  -H "Authorization: Bearer $TOKEN" | jq

# 3. Query GraphQL with auth
curl -s -X POST http://localhost:8080/admin/graphql \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __typename }"}'

Limitations & Notes

  1. User Table Required: The admin interface always assumes a users_user table exists with email/password fields for authentication

  2. Custom Entities: You can expose any Sea-ORM entities through the GraphQL schema, but the auth layer is hardcoded to use users_user

  3. GraphQL Limits: Default depth limit is 100, complexity limit is 1000. Adjust with .with_graphql_limits()

  4. JWT Secret: Must be non-empty. Should be >= 32 characters for production

Troubleshooting

"Schema build error"

  • Ensure all entities are properly registered with the seaography builder
  • Check entity definitions have proper derives and attributes

"Unauthorized" on protected routes

  • Verify Authorization: Bearer <token> header is present and token is valid
  • Check JWT secret matches between login and protected endpoint

"Database error" on login

  • Ensure users_user table exists and has correct schema
  • Verify database connection is working

See Also