| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935 |
- using Astralis;
- using Invercargill;
- using Invercargill.DataStructures;
- using Inversion;
- using Implexus;
- using Implexus.Core;
- using Implexus.Engine;
- using Implexus.Migrations;
- using Spry;
- using Spry.Users;
- using Spry.Users.Components;
- /**
- * UsersExample.vala - Complete example demonstrating the Spry Users system
- *
- * This example demonstrates:
- * 1. Application Migration - Extends UsersMigration with a specific version
- * 2. Service Setup - Using Inversion's inject<T>() pattern
- * 3. User Registration - Creating a new user with username/email/password
- * 4. User Authentication - Login flow with session creation
- * 5. Permission Management - Setting and checking permissions
- * 6. Protected Content - Pages that require authentication
- * 7. Login Form - Using the built-in LoginFormComponent
- * 8. User Management - Using UserManagementPage (for users with permission)
- *
- * Route structure:
- * / -> HomePage (public landing page)
- * /register -> RegisterPage (create new account)
- * /login -> LoginPage (uses LoginFormComponent)
- * /logout -> LogoutEndpoint (clears session and redirects)
- * /dashboard -> DashboardPage (protected - requires authentication)
- * /admin/users -> UserManagementPage (protected - requires "user-management" permission)
- */
- // =============================================================================
- // MIGRATION - Sets up the Users system storage structure
- // =============================================================================
- /**
- * MyAppUsersMigration - Application-specific migration for the Users system
- *
- * This creates:
- * - /spry/users/users - Container for user documents
- * - /spry/users/sessions - Container for session documents
- * - /spry/users/users/by_username - Catalogue for username lookups
- * - /spry/users/users/by_email - Catalogue for email lookups
- *
- * The version string must be unique within your application's migration system.
- */
- public class MyAppUsersMigration : UsersMigration {
- public override string version { owned get { return "2026031501"; } }
- }
- // =============================================================================
- // STYLESHEETS - CSS content served as FastResources
- // =============================================================================
- private const string MAIN_CSS = """
- /* Base Reset & Layout */
- * { box-sizing: border-box; margin: 0; padding: 0; }
- html, body {
- height: 100%;
- }
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- line-height: 1.6;
- background: #f5f7fa;
- display: flex;
- flex-direction: column;
- min-height: 100vh;
- }
- /* Header */
- header {
- background: #2c3e50;
- color: white;
- padding: 1rem 2rem;
- display: flex;
- justify-content: space-between;
- align-items: center;
- flex-shrink: 0;
- }
- header nav a {
- color: white;
- margin-right: 1.5rem;
- text-decoration: none;
- font-weight: 500;
- transition: opacity 0.2s;
- }
- header nav a:hover { opacity: 0.8; }
- header nav a:last-child { margin-right: 0; }
- header .user-info {
- font-size: 0.9rem;
- }
- header .user-info a {
- margin-left: 1rem;
- color: #3498db;
- }
- /* Main Content */
- main.container {
- flex: 1;
- max-width: 800px;
- width: 100%;
- margin: 0 auto;
- padding: 2rem 1rem;
- }
- /* Cards */
- .card {
- background: white;
- border-radius: 12px;
- padding: 2rem;
- margin-bottom: 1.5rem;
- box-shadow: 0 2px 8px rgba(0,0,0,0.08);
- }
- /* Typography */
- h1 { color: #2c3e50; margin-bottom: 1rem; }
- h2 { color: #34495e; margin-bottom: 0.75rem; margin-top: 1.5rem; }
- p { color: #555; margin-bottom: 1rem; }
- ul { margin-left: 1.5rem; margin-bottom: 1rem; }
- li { margin-bottom: 0.5rem; color: #555; }
- /* Links */
- a { color: #3498db; text-decoration: none; transition: color 0.2s; }
- a:hover { color: #2980b9; text-decoration: underline; }
- /* Forms */
- .form-group {
- margin-bottom: 1.25rem;
- }
- .form-group label {
- display: block;
- margin-bottom: 0.5rem;
- font-weight: 500;
- color: #34495e;
- }
- .form-group input {
- width: 100%;
- padding: 0.75rem;
- border: 2px solid #e0e0e0;
- border-radius: 6px;
- font-size: 1rem;
- transition: border-color 0.2s;
- }
- .form-group input:focus {
- outline: none;
- border-color: #3498db;
- }
- .form-group-checkbox {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- }
- .form-group-checkbox input {
- width: auto;
- }
- .form-group-checkbox label {
- margin: 0;
- font-weight: normal;
- }
- /* Buttons */
- button, .btn {
- background: #3498db;
- color: white;
- border: none;
- padding: 0.75rem 1.5rem;
- border-radius: 6px;
- cursor: pointer;
- font-size: 1rem;
- font-weight: 500;
- transition: all 0.2s;
- text-decoration: none;
- display: inline-block;
- }
- button:hover, .btn:hover {
- background: #2980b9;
- text-decoration: none;
- }
- .btn-secondary {
- background: #6c757d;
- }
- .btn-secondary:hover {
- background: #545b62;
- }
- /* Alerts */
- .alert {
- padding: 1rem;
- border-radius: 6px;
- margin-bottom: 1rem;
- }
- .alert-success {
- background: #d4edda;
- color: #155724;
- border: 1px solid #c3e6cb;
- }
- .alert-error {
- background: #f8d7da;
- color: #721c24;
- border: 1px solid #f5c6cb;
- }
- .error-message {
- color: #dc3545;
- font-size: 0.9rem;
- margin-top: 0.5rem;
- }
- /* Login Form */
- .spry-login-form {
- max-width: 400px;
- }
- .login-btn {
- width: 100%;
- margin-top: 1rem;
- }
- /* Footer */
- footer {
- background: #2c3e50;
- color: rgba(255,255,255,0.7);
- padding: 1.5rem;
- text-align: center;
- flex-shrink: 0;
- }
- /* Dashboard */
- .welcome-section {
- margin-bottom: 2rem;
- }
- .permission-list {
- display: flex;
- flex-wrap: wrap;
- gap: 0.5rem;
- margin-top: 0.5rem;
- }
- .permission-badge {
- background: #e9ecef;
- color: #495057;
- padding: 0.25rem 0.75rem;
- border-radius: 20px;
- font-size: 0.85rem;
- }
- .permission-badge.admin {
- background: #ffc107;
- color: #856404;
- }
- """;
- // =============================================================================
- // PAGE TEMPLATE - Provides consistent layout for all pages
- // =============================================================================
- /**
- * MainLayoutTemplate - Base template for all pages
- *
- * Provides:
- * - HTML document structure
- * - Common <head> elements (scripts, styles)
- * - Site-wide header with navigation (changes based on auth state)
- * - Site-wide footer
- */
- public class MainLayoutTemplate : PageTemplate {
-
- private SessionService _session_service = inject<SessionService>();
- private UserService _user_service = inject<UserService>();
- private HttpContext _http_context = inject<HttpContext>();
-
- public User? current_user { get; private set; }
-
- public override string markup { get {
- return """
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Spry Users Example</title>
- <link rel="stylesheet" href="/styles/main.css">
- <script spry-res="htmx.js"></script>
- </head>
- <body>
- <header>
- <nav>
- <a href="/">Home</a>
- <a href="/dashboard">Dashboard</a>
- <a href="/admin/users">User Admin</a>
- </nav>
- <div class="user-info" sid="user-info">
- <!-- Will be populated based on auth state -->
- </div>
- </header>
- <main class="container">
- <spry-template-outlet />
- </main>
- <footer>
- <p>Built with Spry Framework - Users Example</p>
- </footer>
- </body>
- </html>
- """;
- }}
-
- public override async void prepare() throws Error {
- // Try to authenticate the request
- var auth_result = yield _session_service.authenticate_request_async(_http_context, _user_service);
-
- if (auth_result.is_authenticated && auth_result.user != null) {
- current_user = auth_result.user;
- this["user-info"].inner_html = @"Logged in as $(auth_result.user.username) | <a href=\"/logout\">Logout</a>";
- } else {
- this["user-info"].inner_html = "<a href=\"/login\">Login</a> | <a href=\"/register\">Register</a>";
- }
- }
- }
- // =============================================================================
- // PAGE COMPONENTS - Public pages
- // =============================================================================
- /**
- * HomePage - Public landing page
- *
- * This page is accessible to everyone, authenticated or not.
- * It provides an overview of the Users system features.
- */
- public class HomePage : PageComponent {
-
- private SessionService _session_service = inject<SessionService>();
- private UserService _user_service = inject<UserService>();
- private HttpContext _http_context = inject<HttpContext>();
-
- public User? current_user { get; private set; }
-
- public const string ROUTE = "/";
-
- public override string markup { get {
- return """
- <div class="card">
- <h1>Welcome to the Spry Users Example</h1>
- <p>This example demonstrates the complete Spry Users system including:</p>
-
- <h2>Features</h2>
- <ul>
- <li><strong>User Registration</strong> - Create new accounts with username/email/password</li>
- <li><strong>Authentication</strong> - Login with session management</li>
- <li><strong>Permissions</strong> - Granular permission system with wildcard support</li>
- <li><strong>Protected Pages</strong> - Pages that require authentication</li>
- <li><strong>User Management</strong> - Admin interface for managing users</li>
- </ul>
-
- <h2>Try It Out</h2>
- <p sid="status-message"></p>
-
- <ul>
- <li><a href="/register">Register</a> - Create a new account</li>
- <li><a href="/login">Login</a> - Sign in to your account</li>
- <li><a href="/dashboard">Dashboard</a> - Protected page (requires login)</li>
- <li><a href="/admin/users">User Admin</a> - Admin page (requires permission)</li>
- </ul>
- </div>
- """;
- }}
-
- public override async void prepare() throws Error {
- // Check if user is authenticated
- var auth_result = yield _session_service.authenticate_request_async(_http_context, _user_service);
-
- if (auth_result.is_authenticated && auth_result.user != null) {
- current_user = auth_result.user;
- this["status-message"].text_content = @"You are logged in as <strong>$(auth_result.user.username)</strong>.";
- } else {
- this["status-message"].text_content = "You are not logged in. Register or login to access protected pages.";
- }
- }
- }
- /**
- * RegisterPage - User registration page
- *
- * Allows new users to create an account with username, email, and password.
- * Demonstrates direct use of UserService.create_user_async().
- */
- public class RegisterPage : PageComponent {
-
- private UserService _user_service = inject<UserService>();
- private PermissionService _permission_service = inject<PermissionService>();
- private HttpContext _http_context = inject<HttpContext>();
-
- public string? error_message { get; private set; default = null; }
- public string? success_message { get; private set; default = null; }
- public string preserved_username { get; private set; default = ""; }
- public string preserved_email { get; private set; default = ""; }
-
- public const string ROUTE = "/register";
-
- public override string markup { get {
- return """
- <div class="card" sid="register-card" hx-swap="outerHTML">
- <h1>Create Account</h1>
-
- <div spry-if="this.success_message != null" class="alert alert-success" sid="success-alert">
- <span content-expr="this.success_message"></span>
- </div>
-
- <form sid="register-form" spry-action=":Register" spry-target="register-card">
- <div class="form-group">
- <label for="username">Username</label>
- <input type="text" name="username" sid="username-input" required
- autocomplete="username" placeholder="Choose a username"/>
- </div>
-
- <div class="form-group">
- <label for="email">Email</label>
- <input type="email" name="email" sid="email-input" required
- autocomplete="email" placeholder="Enter your email"/>
- </div>
-
- <div class="form-group">
- <label for="password">Password</label>
- <input type="password" name="password" sid="password-input" required
- autocomplete="new-password" placeholder="Choose a password"/>
- </div>
-
- <div class="form-group">
- <label for="confirm-password">Confirm Password</label>
- <input type="password" name="confirm_password" sid="confirm-password-input" required
- autocomplete="new-password" placeholder="Confirm your password"/>
- </div>
-
- <div spry-if="this.error_message != null" class="error-message" sid="error-container">
- <span content-expr="this.error_message"></span>
- </div>
-
- <button type="submit">Create Account</button>
- </form>
-
- <p style="margin-top: 1.5rem;">
- Already have an account? <a href="/login">Login here</a>
- </p>
- </div>
- """;
- }}
-
- public override async void prepare() throws Error {
- // Preserve form values after failed submission
- if (preserved_username.length > 0) {
- this["username-input"].set_attribute("value", preserved_username);
- }
- if (preserved_email.length > 0) {
- this["email-input"].set_attribute("value", preserved_email);
- }
- }
-
- public async override void handle_action(string action) throws Error {
- if (action == "Register") {
- yield handle_register_async();
- }
- }
-
- private async void handle_register_async() throws Error {
- var query = _http_context.request.query_params;
-
- // Get form values
- var username = (query.get_any_or_default("username") ?? "").strip();
- var email = (query.get_any_or_default("email") ?? "").strip();
- var password = query.get_any_or_default("password") ?? "";
- var confirm_password = query.get_any_or_default("confirm_password") ?? "";
-
- // Preserve values for re-display
- preserved_username = username;
- preserved_email = email;
-
- // Validate inputs
- if (username.length < 3) {
- error_message = "Username must be at least 3 characters";
- return;
- }
-
- if (!email.contains("@") || !email.contains(".")) {
- error_message = "Please enter a valid email address";
- return;
- }
-
- if (password.length < 6) {
- error_message = "Password must be at least 6 characters";
- return;
- }
-
- if (password != confirm_password) {
- error_message = "Passwords do not match";
- return;
- }
-
- // Attempt to create user
- try {
- var user = yield _user_service.create_user_async(username, email, password);
-
- // Grant basic permissions to new users
- yield _permission_service.set_permission_async(user, PermissionService.USER_READ);
-
- success_message = @"Account created successfully! You can now <a href=\"/login\">login</a>.";
- error_message = null;
-
- // Clear preserved values on success
- preserved_username = "";
- preserved_email = "";
-
- } catch (UserError.DUPLICATE_USERNAME e) {
- error_message = "Username already exists. Please choose another.";
- } catch (UserError.DUPLICATE_EMAIL e) {
- error_message = "Email already registered. Please use another or login.";
- } catch (Error e) {
- error_message = "Registration failed: %s".printf(e.message);
- }
- }
- }
- // =============================================================================
- // PAGE COMPONENTS - Authentication pages
- // =============================================================================
- /**
- * LoginPage - Login page using the built-in LoginFormComponent
- *
- * This page demonstrates how to use the LoginFormComponent for authentication.
- * The component handles:
- * - Form display and validation
- * - Authentication via UserService
- * - Session creation via SessionService
- * - Cookie management
- * - Redirect after successful login
- */
- public class LoginPage : PageComponent {
-
- private ComponentFactory _factory = inject<ComponentFactory>();
- private LoginFormComponent _login_form;
-
- public const string ROUTE = "/login";
-
- public override string markup { get {
- return """
- <div class="card">
- <h1>Login</h1>
- <spry-outlet sid="login-form-outlet"/>
- <p style="margin-top: 1.5rem;">
- Don't have an account? <a href="/register">Register here</a>
- </p>
- </div>
- """;
- }}
-
- public override async void prepare() throws Error {
- // Create and configure the login form component
- _login_form = _factory.create<LoginFormComponent>();
- _login_form.redirect_url = "/dashboard"; // Redirect here after successful login
-
- // Add the form to our outlet
- add_outlet_child("login-form-outlet", _login_form);
-
- // Share globals with the login form (required for action handling)
- add_globals_from(_login_form);
- }
- }
- /**
- * LogoutEndpoint - Handles logout by clearing the session
- *
- * This demonstrates:
- * - Getting the current session from the cookie
- * - Deleting the session from storage
- * - Clearing the session cookie
- * - Returning a redirect response
- */
- public class LogoutEndpoint : Object, Endpoint {
-
- private SessionService _session_service = inject<SessionService>();
- private UserService _user_service = inject<UserService>();
-
- public async HttpResult handle_request(HttpContext http_context, RouteContext route_context) throws Error {
- // Try to get the current session
- var auth_result = yield _session_service.authenticate_request_async(http_context, _user_service);
-
- if (auth_result.is_authenticated && auth_result.session != null) {
- // Delete the session from storage
- yield _session_service.delete_session_async(auth_result.session.id);
- }
-
- // Create redirect result with Location header
- // Note: We use 302 (FOUND) redirect - StatusCode enum may not have FOUND, so we use the numeric value
- var result = new HttpStringResult("Redirecting to home page...", 302);
- result.set_header("Location", "/");
-
- // Clear the session cookie
- _session_service.clear_session_cookie(result);
-
- return result;
- }
- }
- // =============================================================================
- // PAGE COMPONENTS - Protected pages
- // =============================================================================
- /**
- * DashboardPage - Protected dashboard page
- *
- * This page demonstrates:
- * - Checking authentication in prepare()
- * - Redirecting unauthenticated users to login
- * - Accessing the current user's information
- * - Checking permissions
- * - Displaying user-specific content
- */
- public class DashboardPage : PageComponent {
-
- private SessionService _session_service = inject<SessionService>();
- private UserService _user_service = inject<UserService>();
- private PermissionService _permission_service = inject<PermissionService>();
- private HttpContext _http_context = inject<HttpContext>();
-
- public User? current_user { get; private set; }
- public bool is_admin { get; private set; default = false; }
- public Vector<string> permissions { get; private set; }
-
- public const string ROUTE = "/dashboard";
-
- public override string markup { get {
- return """
- <div class="card">
- <!-- Not authenticated message -->
- <div spry-if="!this.is_authenticated" class="alert alert-error">
- <h2>Authentication Required</h2>
- <p>You must be logged in to view this page.</p>
- <p style="margin-top: 1rem;">
- <a href="/login" class="btn">Login</a>
- <a href="/register" class="btn btn-secondary" style="margin-left: 0.5rem;">Register</a>
- </p>
- </div>
-
- <!-- Authenticated content -->
- <div spry-if="this.is_authenticated">
- <div class="welcome-section">
- <h1 sid="welcome-heading">Dashboard</h1>
- <p>Welcome to your dashboard! This page demonstrates protected content.</p>
- </div>
-
- <h2>Your Profile</h2>
- <ul>
- <li><strong>Username:</strong> <span sid="username"></span></li>
- <li><strong>Email:</strong> <span sid="email"></span></li>
- <li><strong>User ID:</strong> <span sid="user-id"></span></li>
- <li><strong>Account Created:</strong> <span sid="created-at"></span></li>
- </ul>
-
- <h2>Your Permissions</h2>
- <div class="permission-list" sid="permission-list">
- <!-- Permissions will be listed here -->
- </div>
-
- <div spry-if="this.is_admin" class="alert alert-success" style="margin-top: 1.5rem;">
- <strong>Admin Access:</strong> You have admin privileges.
- <a href="/admin/users" style="color: #155724;">Go to User Management</a>
- </div>
-
- <p style="margin-top: 1.5rem;">
- <a href="/" class="btn btn-secondary">Back to Home</a>
- </p>
- </div>
- </div>
- """;
- }}
-
- // Track if user is authenticated (for template binding)
- public bool is_authenticated { get; private set; default = false; }
-
- public override async void prepare() throws Error {
- // Authenticate the request
- var auth_result = yield _session_service.authenticate_request_async(_http_context, _user_service);
-
- if (!auth_result.is_authenticated || auth_result.user == null) {
- // Not authenticated - show message and link to login
- // Note: PageComponent doesn't have redirect(), so we show a message instead
- is_authenticated = false;
- return;
- }
-
- is_authenticated = true;
-
- current_user = auth_result.user;
- permissions = _permission_service.get_permissions(current_user);
- is_admin = _permission_service.has_permission(current_user, PermissionService.ADMIN);
-
- // Populate user info
- this["welcome-heading"].text_content = @"Welcome, $(current_user.username)!";
- this["username"].text_content = current_user.username;
- this["email"].text_content = current_user.email;
- this["user-id"].text_content = current_user.id;
- this["created-at"].text_content = current_user.created_at.format("%Y-%m-%d %H:%M:%S UTC");
-
- // Populate permissions
- var perm_text = "";
- foreach (var perm in permissions) {
- var badge_class = perm == PermissionService.ADMIN ? "permission-badge admin" : "permission-badge";
- perm_text += @"<span class=\"$badge_class\">$perm</span> ";
- }
- if (permissions.length == 0) {
- perm_text = "<span class=\"permission-badge\">No permissions assigned</span>";
- }
- this["permission-list"].inner_html = perm_text;
- }
- }
- // =============================================================================
- // SEED DATA - Creates initial admin user
- // =============================================================================
- /**
- * SeedData - Creates initial users for testing
- *
- * This demonstrates how to:
- * - Check if users exist before creating
- * - Create users programmatically
- * - Grant permissions to users
- */
- public class SeedData : Object {
-
- public static async void ensure_admin_exists(UserService user_service, PermissionService permission_service) throws Error {
- // Check if admin user exists
- var admin_user = yield user_service.get_user_by_username_async("admin");
-
- if (admin_user != null) {
- print("Admin user already exists\n");
- return;
- }
-
- print("Creating admin user...\n");
-
- // Create admin user
- admin_user = yield user_service.create_user_async("admin", "admin@example.com", "admin123");
-
- // Grant admin permissions
- yield permission_service.set_permission_async(admin_user, PermissionService.ADMIN);
- yield permission_service.set_permission_async(admin_user, PermissionService.USER_MANAGEMENT);
- yield permission_service.set_permission_async(admin_user, PermissionService.USER_CREATE);
- yield permission_service.set_permission_async(admin_user, PermissionService.USER_READ);
- yield permission_service.set_permission_async(admin_user, PermissionService.USER_UPDATE);
- yield permission_service.set_permission_async(admin_user, PermissionService.USER_DELETE);
-
- print("Admin user created with username 'admin' and password 'admin123'\n");
-
- // Create a regular test user
- var test_user = yield user_service.get_user_by_username_async("testuser");
- if (test_user == null) {
- print("Creating test user...\n");
- test_user = yield user_service.create_user_async("testuser", "test@example.com", "test123");
- yield permission_service.set_permission_async(test_user, PermissionService.USER_READ);
- print("Test user created with username 'testuser' and password 'test123'\n");
- }
- }
- }
- // =============================================================================
- // APPLICATION SETUP
- // =============================================================================
- // =============================================================================
- // ASYNC MAIN LOOP - Required for async initialization
- // =============================================================================
- private MainLoop main_loop;
- private Implexus.Core.Engine global_engine;
- public static int main(string[] args) {
- int port = args.length > 1 ? int.parse(args[1]) : 8080;
-
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Spry Users Example - Complete Demo\n");
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Port: %d\n", port);
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Public Endpoints:\n");
- print(" / - Home page (public)\n");
- print(" /register - Create new account\n");
- print(" /login - Login page\n");
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Protected Endpoints (requires login):\n");
- print(" /dashboard - User dashboard\n");
- print(" /logout - Logout and clear session\n");
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Admin Endpoints (requires 'user-management' permission):\n");
- print(" /admin/users - User management page\n");
- print("═══════════════════════════════════════════════════════════════\n");
- print(" Default Users:\n");
- print(" admin / admin123 - Has all permissions\n");
- print(" testuser / test123 - Regular user\n");
- print("═══════════════════════════════════════════════════════════════\n");
- print("\nPress Ctrl+C to stop the server\n\n");
-
- main_loop = new MainLoop();
-
- try {
- // 1. Create the embedded engine FIRST
- print("Creating database engine...\n");
- global_engine = EngineFactory.create_embedded();
-
- // 2. Run migrations to set up containers and catalogues
- print("Running migrations...\n");
- run_migrations.begin((obj, res) => {
- try {
- run_migrations.end(res);
-
- // 3. Now start the application
- start_application.begin(port, (obj, res) => {
- try {
- start_application.end(res);
- } catch (Error e) {
- printerr("Application error: %s\n", e.message);
- main_loop.quit();
- }
- });
- } catch (Error e) {
- printerr("Migration error: %s\n", e.message);
- main_loop.quit();
- }
- });
-
- main_loop.run();
- return 0;
-
- } catch (Error e) {
- printerr("Error: %s\n", e.message);
- return 1;
- }
- }
- /**
- * Run database migrations to set up the Users system structure.
- */
- private async void run_migrations() throws Error {
- var migration = new MyAppUsersMigration();
- yield migration.up_async(global_engine);
- print("Migrations completed successfully.\n");
- }
- /**
- * Start the web application after migrations are complete.
- */
- private async void start_application(int port) throws Error {
- var application = new WebApplication(port);
-
- // Register the Engine in the container FIRST before any services
- // This is critical - services use inject<Engine>() and need it to be available
- application.add_singleton<Implexus.Core.Engine>(() => global_engine);
-
- // Enable compression
- application.use_compression();
-
- // Add Spry module for component actions
- application.add_module<SpryModule>();
-
- // Register Users system services
- // These use inject<Engine>() internally, so Engine must be registered first
- application.add_singleton<UserService>();
- application.add_singleton<SessionService>();
- application.add_singleton<PermissionService>();
-
- // Seed initial data (admin user, test user)
- application.add_singleton<CryptographyProvider>();
- seed_initial_data.begin(application.container);
-
- // Register template with route prefix
- // MainLayoutTemplate applies to ALL routes (empty prefix)
- var spry_cfg = application.configure_with<SpryConfigurator>();
- spry_cfg.add_template<MainLayoutTemplate>("");
-
- // Register page components as endpoints
- application.add_transient<HomePage>();
- application.add_endpoint<HomePage>(new EndpointRoute(HomePage.ROUTE));
-
- application.add_transient<RegisterPage>();
- application.add_endpoint<RegisterPage>(new EndpointRoute(RegisterPage.ROUTE));
-
- application.add_transient<LoginPage>();
- application.add_endpoint<LoginPage>(new EndpointRoute(LoginPage.ROUTE));
-
- application.add_transient<DashboardPage>();
- application.add_endpoint<DashboardPage>(new EndpointRoute(DashboardPage.ROUTE));
-
- // Register logout endpoint
- application.add_endpoint<LogoutEndpoint>(new EndpointRoute("/logout"));
-
- // Register UserManagementPage (admin page)
- application.add_transient<UserManagementPage>();
- application.add_endpoint<UserManagementPage>(new EndpointRoute("/admin/users"));
-
- // Register LoginFormComponent (used by LoginPage)
- application.add_transient<LoginFormComponent>();
-
- // Register child components used by UserManagementPage
- application.add_transient<UserListComponent>();
- application.add_transient<UserListItemComponent>();
- application.add_transient<UserFormComponent>();
- application.add_transient<PermissionEditorComponent>();
-
- // Register CSS as FastResource
- application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/main.css"), () => {
- try {
- return new FastResource.from_string(MAIN_CSS)
- .with_content_type("text/css; charset=utf-8")
- .with_default_compressors();
- } catch (Error e) {
- error("Failed to create main CSS resource: %s", e.message);
- }
- });
-
- print("Starting web server on port %d...\n\n", port);
- application.run();
- }
- /**
- * Seed initial data (admin and test users).
- */
- private async void seed_initial_data(Container container) {
- try {
- var scope = container.create_scope();
- var user_service = scope.resolve<UserService>();
- var permission_service = scope.resolve<PermissionService>();
- yield SeedData.ensure_admin_exists(user_service, permission_service);
- } catch (Error e) {
- printerr("Warning: Failed to seed initial data: %s\n", e.message);
- }
- }
|