UsersExample.vala 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. using Astralis;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. using InvercargillSql;
  5. using InvercargillSql.Migrations;
  6. using InvercargillSqlInversion;
  7. using Inversion;
  8. using Spry;
  9. using Spry.Authentication;
  10. using Spry.Authorisation;
  11. /**
  12. * UsersExample.vala - Complete example demonstrating the Spry Authentication system
  13. *
  14. * This example demonstrates:
  15. * 1. Application Migration - Extends UserTableMigration with a specific version
  16. * 2. Service Setup - Using Inversion's inject<T>() pattern
  17. * 3. User Registration - Creating a new user with username/email/password
  18. * 4. User Authentication - Login flow with AuthorisationToken
  19. * 5. Permission Management - Setting and checking permissions
  20. * 6. Protected Content - Pages that require authentication
  21. * 7. Login Form - Using the built-in LoginFormComponent
  22. * 8. User Management - Using UserManagementComponent (for users with permission)
  23. * 9. Authorisation Context - Using AuthorisationContext for permission checking
  24. *
  25. * Route structure:
  26. * / -> HomePage (public landing page)
  27. * /register -> RegisterPage (create new account)
  28. * /login -> LoginPage (uses LoginFormComponent)
  29. * /logout -> LogoutEndpoint (clears cookie and redirects)
  30. * /dashboard -> DashboardPage (protected - requires authentication)
  31. * /admin/users -> UserAdminPage (protected - requires "user-management" permission, uses UserManagementComponent)
  32. */
  33. // =============================================================================
  34. // APPLICATION PERMISSIONS - Define permissions available in this application
  35. // =============================================================================
  36. /**
  37. * Creates a Vector of permissions for the UsersExample application.
  38. *
  39. * These permissions are passed to the authentication components so they can
  40. * display appropriate checkboxes. The components themselves do NOT hardcode
  41. * any permissions - they must be provided by the application.
  42. *
  43. * Returns a Vector<string> which is required for proper property binding
  44. * in the authentication components.
  45. */
  46. public Vector<string> get_application_permissions() {
  47. var permissions = new Vector<string>();
  48. permissions.add("user-management");
  49. permissions.add("user.create");
  50. permissions.add("user.read");
  51. permissions.add("user.update");
  52. permissions.add("user.delete");
  53. permissions.add("admin");
  54. return permissions;
  55. }
  56. // =============================================================================
  57. // STYLESHEETS - CSS content served as FastResources
  58. // =============================================================================
  59. private const string MAIN_CSS = """
  60. /* Base Reset & Layout */
  61. * { box-sizing: border-box; margin: 0; padding: 0; }
  62. html, body {
  63. height: 100%;
  64. }
  65. body {
  66. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  67. line-height: 1.6;
  68. background: #f5f7fa;
  69. display: flex;
  70. flex-direction: column;
  71. min-height: 100vh;
  72. }
  73. /* Header */
  74. header {
  75. background: #2c3e50;
  76. color: white;
  77. padding: 1rem 2rem;
  78. display: flex;
  79. justify-content: space-between;
  80. align-items: center;
  81. flex-shrink: 0;
  82. }
  83. header nav a {
  84. color: white;
  85. margin-right: 1.5rem;
  86. text-decoration: none;
  87. font-weight: 500;
  88. transition: opacity 0.2s;
  89. }
  90. header nav a:hover { opacity: 0.8; }
  91. header nav a:last-child { margin-right: 0; }
  92. header .user-info {
  93. font-size: 0.9rem;
  94. }
  95. header .user-info a {
  96. margin-left: 1rem;
  97. color: #3498db;
  98. }
  99. /* Main Content */
  100. main.container {
  101. flex: 1;
  102. max-width: 800px;
  103. width: 100%;
  104. margin: 0 auto;
  105. padding: 2rem 1rem;
  106. }
  107. /* Cards */
  108. .card {
  109. background: white;
  110. border-radius: 12px;
  111. padding: 2rem;
  112. margin-bottom: 1.5rem;
  113. box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  114. }
  115. /* Typography */
  116. h1 { color: #2c3e50; margin-bottom: 1rem; }
  117. h2 { color: #34495e; margin-bottom: 0.75rem; margin-top: 1.5rem; }
  118. p { color: #555; margin-bottom: 1rem; }
  119. ul { margin-left: 1.5rem; margin-bottom: 1rem; }
  120. li { margin-bottom: 0.5rem; color: #555; }
  121. /* Links */
  122. a { color: #3498db; text-decoration: none; transition: color 0.2s; }
  123. a:hover { color: #2980b9; text-decoration: underline; }
  124. /* Forms */
  125. .form-group {
  126. margin-bottom: 1.25rem;
  127. }
  128. .form-group label {
  129. display: block;
  130. margin-bottom: 0.5rem;
  131. font-weight: 500;
  132. color: #34495e;
  133. }
  134. .form-group input {
  135. width: 100%;
  136. padding: 0.75rem;
  137. border: 2px solid #e0e0e0;
  138. border-radius: 6px;
  139. font-size: 1rem;
  140. transition: border-color 0.2s;
  141. }
  142. .form-group input:focus {
  143. outline: none;
  144. border-color: #3498db;
  145. }
  146. .form-group-checkbox {
  147. display: flex;
  148. align-items: center;
  149. gap: 0.5rem;
  150. }
  151. .form-group-checkbox input {
  152. width: auto;
  153. }
  154. .form-group-checkbox label {
  155. margin: 0;
  156. font-weight: normal;
  157. }
  158. /* Buttons */
  159. button, .btn {
  160. background: #3498db;
  161. color: white;
  162. border: none;
  163. padding: 0.75rem 1.5rem;
  164. border-radius: 6px;
  165. cursor: pointer;
  166. font-size: 1rem;
  167. font-weight: 500;
  168. transition: all 0.2s;
  169. text-decoration: none;
  170. display: inline-block;
  171. }
  172. button:hover, .btn:hover {
  173. background: #2980b9;
  174. text-decoration: none;
  175. }
  176. .btn-secondary {
  177. background: #6c757d;
  178. }
  179. .btn-secondary:hover {
  180. background: #545b62;
  181. }
  182. /* Alerts */
  183. .alert {
  184. padding: 1rem;
  185. border-radius: 6px;
  186. margin-bottom: 1rem;
  187. }
  188. .alert-success {
  189. background: #d4edda;
  190. color: #155724;
  191. border: 1px solid #c3e6cb;
  192. }
  193. .alert-error {
  194. background: #f8d7da;
  195. color: #721c24;
  196. border: 1px solid #f5c6cb;
  197. }
  198. .error-message {
  199. color: #dc3545;
  200. font-size: 0.9rem;
  201. margin-top: 0.5rem;
  202. }
  203. /* Login Form */
  204. .spry-login-form {
  205. max-width: 400px;
  206. }
  207. .login-btn {
  208. width: 100%;
  209. margin-top: 1rem;
  210. }
  211. /* Footer */
  212. footer {
  213. background: #2c3e50;
  214. color: rgba(255,255,255,0.7);
  215. padding: 1.5rem;
  216. text-align: center;
  217. flex-shrink: 0;
  218. }
  219. /* Dashboard */
  220. .welcome-section {
  221. margin-bottom: 2rem;
  222. }
  223. .permission-list {
  224. display: flex;
  225. flex-wrap: wrap;
  226. gap: 0.5rem;
  227. margin-top: 0.5rem;
  228. }
  229. .permission-badge {
  230. background: #e9ecef;
  231. color: #495057;
  232. padding: 0.25rem 0.75rem;
  233. border-radius: 20px;
  234. font-size: 0.85rem;
  235. }
  236. .permission-badge.admin {
  237. background: #ffc107;
  238. color: #856404;
  239. }
  240. """;
  241. // =============================================================================
  242. // PAGE TEMPLATE - Provides consistent layout for all pages
  243. // =============================================================================
  244. /**
  245. * MainLayoutTemplate - Base template for all pages
  246. *
  247. * Provides:
  248. * - HTML document structure
  249. * - Common <head> elements (scripts, styles)
  250. * - Site-wide header with navigation (changes based on auth state)
  251. * - Site-wide footer
  252. *
  253. * Uses AuthorisationContext to check authentication status.
  254. */
  255. public class MainLayoutTemplate : PageTemplate {
  256. private AuthorisationContext _auth_context = inject<AuthorisationContext>();
  257. public override string markup { get {
  258. return """
  259. <!DOCTYPE html>
  260. <html lang="en">
  261. <head>
  262. <meta charset="UTF-8">
  263. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  264. <title>Spry Authentication Example</title>
  265. <link rel="stylesheet" href="/styles/main.css">
  266. <script spry-res="htmx.js"></script>
  267. </head>
  268. <body>
  269. <header>
  270. <nav>
  271. <a href="/">Home</a>
  272. <a href="/dashboard">Dashboard</a>
  273. <a href="/admin/users">User Admin</a>
  274. </nav>
  275. <div class="user-info" sid="user-info">
  276. <!-- Will be populated based on auth state -->
  277. </div>
  278. </header>
  279. <main class="container">
  280. <spry-content />
  281. </main>
  282. <footer>
  283. <p>Built with Spry Framework - Authentication Example</p>
  284. </footer>
  285. </body>
  286. </html>
  287. """;
  288. }}
  289. public override async void prepare() throws Error {
  290. // Check authentication using AuthorisationContext
  291. if (!_auth_context.is_anonymous() && _auth_context.token != null) {
  292. var token = _auth_context.token;
  293. this["user-info"].inner_html = @"Logged in as $(token.username) | <a href=\"/logout\">Logout</a>";
  294. } else {
  295. this["user-info"].inner_html = "<a href=\"/login\">Login</a> | <a href=\"/register\">Register</a>";
  296. }
  297. }
  298. }
  299. // =============================================================================
  300. // PAGE COMPONENTS - Public pages
  301. // =============================================================================
  302. /**
  303. * HomePage - Public landing page
  304. *
  305. * This page is accessible to everyone, authenticated or not.
  306. * It provides an overview of the Authentication system features.
  307. */
  308. public class HomePage : PageComponent {
  309. private AuthorisationContext _auth_context = inject<AuthorisationContext>();
  310. public const string ROUTE = "/";
  311. public override string markup { get {
  312. return """
  313. <div class="card">
  314. <h1>Welcome to the Spry Authentication Example</h1>
  315. <p>This example demonstrates the complete Spry Authentication system including:</p>
  316. <h2>Features</h2>
  317. <ul>
  318. <li><strong>User Registration</strong> - Create new accounts with username/email/password</li>
  319. <li><strong>Authentication</strong> - Login with AuthorisationToken management</li>
  320. <li><strong>Permissions</strong> - Granular permission system with wildcard support</li>
  321. <li><strong>Protected Pages</strong> - Pages that require authentication</li>
  322. <li><strong>User Management</strong> - Admin interface for managing users</li>
  323. <li><strong>Authorisation Context</strong> - Request-scoped permission checking</li>
  324. </ul>
  325. <h2>Try It Out</h2>
  326. <p sid="status-message"></p>
  327. <ul>
  328. <li><a href="/register">Register</a> - Create a new account</li>
  329. <li><a href="/login">Login</a> - Sign in to your account</li>
  330. <li><a href="/dashboard">Dashboard</a> - Protected page (requires login)</li>
  331. <li><a href="/admin/users">User Admin</a> - Admin page (requires permission)</li>
  332. </ul>
  333. </div>
  334. """;
  335. }}
  336. public override async void prepare() throws Error {
  337. // Check if user is authenticated using AuthorisationContext
  338. if (!_auth_context.is_anonymous() && _auth_context.token != null) {
  339. var token = _auth_context.token;
  340. this["status-message"].text_content = @"You are logged in as <strong>$(token.username)</strong>.";
  341. } else {
  342. this["status-message"].text_content = "You are not logged in. Register or login to access protected pages.";
  343. }
  344. }
  345. }
  346. /**
  347. * RegisterPage - User registration page
  348. *
  349. * Allows new users to create an account with username, email, and password.
  350. * Demonstrates direct use of UserService.register_user().
  351. */
  352. public class RegisterPage : PageComponent {
  353. private UserService _user_service = inject<UserService>();
  354. private HttpContext _http_context = inject<HttpContext>();
  355. public string? error_message { get; private set; default = null; }
  356. public string? success_message { get; private set; default = null; }
  357. public string preserved_username { get; private set; default = ""; }
  358. public string preserved_email { get; private set; default = ""; }
  359. public const string ROUTE = "/register";
  360. public override string markup { get {
  361. return """
  362. <div class="card" sid="register-card" hx-swap="outerHTML">
  363. <h1>Create Account</h1>
  364. <div spry-if="this.success_message != null" class="alert alert-success" sid="success-alert">
  365. <span content-expr="this.success_message"></span>
  366. </div>
  367. <form sid="register-form" spry-action=":Register" spry-target="register-card">
  368. <div class="form-group">
  369. <label for="username">Username</label>
  370. <input type="text" name="username" sid="username-input" required
  371. autocomplete="username" placeholder="Choose a username"/>
  372. </div>
  373. <div class="form-group">
  374. <label for="email">Email</label>
  375. <input type="email" name="email" sid="email-input" required
  376. autocomplete="email" placeholder="Enter your email"/>
  377. </div>
  378. <div class="form-group">
  379. <label for="forename">First Name</label>
  380. <input type="text" name="forename" sid="forename-input" required
  381. autocomplete="given-name" placeholder="Enter your first name"/>
  382. </div>
  383. <div class="form-group">
  384. <label for="surname">Last Name</label>
  385. <input type="text" name="surname" sid="surname-input" required
  386. autocomplete="family-name" placeholder="Enter your last name"/>
  387. </div>
  388. <div class="form-group">
  389. <label for="date-of-birth">Date of Birth</label>
  390. <input type="date" name="date_of_birth" sid="dob-input" required
  391. autocomplete="bday" placeholder="YYYY-MM-DD"/>
  392. </div>
  393. <div class="form-group">
  394. <label for="password">Password</label>
  395. <input type="password" name="password" sid="password-input" required
  396. autocomplete="new-password" placeholder="Choose a password"/>
  397. </div>
  398. <div class="form-group">
  399. <label for="confirm-password">Confirm Password</label>
  400. <input type="password" name="confirm_password" sid="confirm-password-input" required
  401. autocomplete="new-password" placeholder="Confirm your password"/>
  402. </div>
  403. <div spry-if="this.error_message != null" class="error-message" sid="error-container">
  404. <span content-expr="this.error_message"></span>
  405. </div>
  406. <button type="submit">Create Account</button>
  407. </form>
  408. <p style="margin-top: 1.5rem;">
  409. Already have an account? <a href="/login">Login here</a>
  410. </p>
  411. </div>
  412. """;
  413. }}
  414. public override async void prepare() throws Error {
  415. // Preserve form values after failed submission
  416. if (preserved_username.length > 0) {
  417. this["username-input"].set_attribute("value", preserved_username);
  418. }
  419. if (preserved_email.length > 0) {
  420. this["email-input"].set_attribute("value", preserved_email);
  421. }
  422. }
  423. public async override void handle_action(string action) throws Error {
  424. if (action == "Register") {
  425. yield handle_register_async();
  426. }
  427. }
  428. private async void handle_register_async() throws Error {
  429. var query = _http_context.request.query_params;
  430. // Get form values
  431. var username = (query.get_any_or_default("username") ?? "").strip();
  432. var email = (query.get_any_or_default("email") ?? "").strip();
  433. var forename = (query.get_any_or_default("forename") ?? "").strip();
  434. var surname = (query.get_any_or_default("surname") ?? "").strip();
  435. var dob_string = query.get_any_or_default("date_of_birth") ?? "";
  436. var password = query.get_any_or_default("password") ?? "";
  437. var confirm_password = query.get_any_or_default("confirm_password") ?? "";
  438. // Preserve values for re-display
  439. preserved_username = username;
  440. preserved_email = email;
  441. // Validate inputs
  442. if (username.length < 3) {
  443. error_message = "Username must be at least 3 characters";
  444. return;
  445. }
  446. if (!email.contains("@") || !email.contains(".")) {
  447. error_message = "Please enter a valid email address";
  448. return;
  449. }
  450. if (forename.length == 0) {
  451. error_message = "Please enter your first name";
  452. return;
  453. }
  454. if (surname.length == 0) {
  455. error_message = "Please enter your last name";
  456. return;
  457. }
  458. // Parse date of birth
  459. DateTime? date_of_birth = null;
  460. if (dob_string.length > 0) {
  461. try {
  462. date_of_birth = new DateTime.from_iso8601(dob_string, new TimeZone.utc());
  463. } catch (Error e) {
  464. error_message = "Please enter a valid date of birth (YYYY-MM-DD)";
  465. return;
  466. }
  467. } else {
  468. error_message = "Please enter your date of birth";
  469. return;
  470. }
  471. if (password.length < 6) {
  472. error_message = "Password must be at least 6 characters";
  473. return;
  474. }
  475. if (password != confirm_password) {
  476. error_message = "Passwords do not match";
  477. return;
  478. }
  479. // Attempt to create user using the new register_user method
  480. try {
  481. var user = yield _user_service.register_user(
  482. username,
  483. email,
  484. forename,
  485. surname,
  486. date_of_birth,
  487. password,
  488. true // enabled
  489. );
  490. // Grant basic permissions to new users
  491. yield _user_service.set_user_permission(user.id, "user.read");
  492. success_message = @"Account created successfully! You can now <a href=\"/login\">login</a>.";
  493. error_message = null;
  494. // Clear preserved values on success
  495. preserved_username = "";
  496. preserved_email = "";
  497. } catch (Error e) {
  498. // Handle duplicate username/email errors
  499. if (e.message.contains("UNIQUE constraint failed") || e.message.contains("duplicate")) {
  500. if (e.message.contains("username")) {
  501. error_message = "Username already exists. Please choose another.";
  502. } else if (e.message.contains("email")) {
  503. error_message = "Email already registered. Please use another or login.";
  504. } else {
  505. error_message = "A user with this information already exists.";
  506. }
  507. } else {
  508. error_message = "Registration failed: %s".printf(e.message);
  509. }
  510. }
  511. }
  512. }
  513. // =============================================================================
  514. // PAGE COMPONENTS - Authentication pages
  515. // =============================================================================
  516. /**
  517. * LoginPage - Login page using the built-in LoginFormComponent
  518. *
  519. * This page demonstrates how to use the LoginFormComponent for authentication.
  520. * The component handles:
  521. * - Form display and validation
  522. * - Authentication via UserService.authenticate_user()
  523. * - Cookie management via AuthorisationService
  524. * - Redirect after successful login
  525. */
  526. public class LoginPage : PageComponent {
  527. private ComponentFactory _factory = inject<ComponentFactory>();
  528. public const string ROUTE = "/login";
  529. public override string markup { get {
  530. return """
  531. <div class="card">
  532. <h1>Login</h1>
  533. <spry-component name="SpryAuthenticationLoginComponent" />
  534. <p style="margin-top: 1.5rem;">
  535. Don't have an account? <a href="/register">Register here</a>
  536. </p>
  537. </div>
  538. """;
  539. }}
  540. }
  541. /**
  542. * LogoutEndpoint - Handles logout by clearing the authorisation cookie
  543. *
  544. * This demonstrates:
  545. * - Simply clearing the authorisation cookie
  546. * - Returning a redirect response
  547. *
  548. * Note: In the refined authentication system, there's no server-side session
  549. * to delete - authentication is stateless using signed tokens.
  550. */
  551. public class LogoutEndpoint : Object, Endpoint {
  552. public async HttpResult handle_request(HttpContext http_context, RouteContext route_context) throws Error {
  553. // Create redirect result with Location header
  554. var result = new HttpStringResult("Redirecting to home page...", 302);
  555. result.set_header("Location", "/");
  556. // Clear the authorisation cookie by setting it to empty with an expired date
  557. result.headers.add("Set-Cookie", "_spry-authorisation=; Secure; Max-Age=0");
  558. return result;
  559. }
  560. }
  561. // =============================================================================
  562. // PAGE COMPONENTS - Protected pages
  563. // =============================================================================
  564. /**
  565. * DashboardPage - Protected dashboard page
  566. *
  567. * This page demonstrates:
  568. * - Checking authentication using AuthorisationContext
  569. * - Redirecting unauthenticated users to login
  570. * - Accessing the current user's information from AuthorisationToken
  571. * - Checking permissions using AuthorisationContext
  572. * - Displaying user-specific content
  573. */
  574. public class DashboardPage : PageComponent {
  575. private AuthorisationContext _auth_context = inject<AuthorisationContext>();
  576. public const string ROUTE = "/dashboard";
  577. public override string markup { get {
  578. return """
  579. <div class="card">
  580. <!-- Not authenticated message -->
  581. <div spry-if="this.is_anonymous" class="alert alert-error">
  582. <h2>Authentication Required</h2>
  583. <p>You must be logged in to view this page.</p>
  584. <p style="margin-top: 1rem;">
  585. <a href="/login" class="btn">Login</a>
  586. <a href="/register" class="btn btn-secondary" style="margin-left: 0.5rem;">Register</a>
  587. </p>
  588. </div>
  589. <!-- Authenticated content -->
  590. <div spry-if="!this.is_anonymous">
  591. <div class="welcome-section">
  592. <h1 sid="welcome-heading">Dashboard</h1>
  593. <p>Welcome to your dashboard! This page demonstrates protected content.</p>
  594. </div>
  595. <h2>Your Profile</h2>
  596. <ul>
  597. <li><strong>Username:</strong> <span sid="username"></span></li>
  598. <li><strong>Email:</strong> <span sid="email"></span></li>
  599. <li><strong>User ID:</strong> <span sid="user-id"></span></li>
  600. <li><strong>Account Created:</strong> <span sid="created-at"></span></li>
  601. </ul>
  602. <h2>Your Permissions</h2>
  603. <div class="permission-list" sid="permission-list">
  604. <!-- Permissions will be listed here -->
  605. </div>
  606. <div spry-if="this.is_admin" class="alert alert-success" style="margin-top: 1.5rem;">
  607. <strong>Admin Access:</strong> You have admin privileges.
  608. <a href="/admin/users" style="color: #155724;">Go to User Management</a>
  609. </div>
  610. <p style="margin-top: 1.5rem;">
  611. <a href="/" class="btn btn-secondary">Back to Home</a>
  612. </p>
  613. </div>
  614. </div>
  615. """;
  616. }}
  617. // Track if user is authenticated (for template binding)
  618. public bool is_anonymous { get; private set; default = true; }
  619. // Track if user has admin permission
  620. public bool is_admin { get; private set; default = false; }
  621. public override async void prepare() throws Error {
  622. // Check authentication using AuthorisationContext
  623. if (_auth_context.is_anonymous()) {
  624. // Not authenticated - show message and link to login
  625. is_anonymous = true;
  626. return;
  627. }
  628. is_anonymous = false;
  629. var token = _auth_context.token;
  630. if (token == null) {
  631. is_anonymous = true;
  632. return;
  633. }
  634. // Check permissions using AuthorisationContext
  635. is_admin = _auth_context.has_permission("admin");
  636. // Populate user info from the token
  637. this["welcome-heading"].text_content = @"Welcome, $(token.username)!";
  638. this["username"].text_content = token.username;
  639. this["user-id"].text_content = token.user_identifier.to_string();
  640. // Get additional user data from the token's data properties
  641. var user_data = token.data;
  642. string? email_val = null;
  643. DateTime? created_val = null;
  644. // Try to get email and created from properties
  645. try {
  646. var email_element = user_data.get("email");
  647. email_val = email_element.as_string_or_null();
  648. } catch (Error e) {
  649. // Email not available
  650. }
  651. try {
  652. var created_element = user_data.get("created");
  653. created_val = created_element.as<DateTime>();
  654. } catch (Error e) {
  655. // Created not available
  656. }
  657. this["email"].text_content = email_val ?? "N/A";
  658. this["created-at"].text_content = created_val != null ?
  659. ((DateTime)created_val).format("%Y-%m-%d %H:%M:%S UTC") : "N/A";
  660. // Populate permissions from the token
  661. var perm_text = "";
  662. var user_permissions = token.permissions;
  663. int perm_count = 0;
  664. foreach (var perm in user_permissions) {
  665. var badge_class = perm == "admin" ? "permission-badge admin" : "permission-badge";
  666. perm_text += @"<span class=\"$badge_class\">$perm</span> ";
  667. perm_count++;
  668. }
  669. if (perm_count == 0) {
  670. perm_text = "<span class=\"permission-badge\">No permissions assigned</span>";
  671. }
  672. this["permission-list"].inner_html = perm_text;
  673. }
  674. }
  675. // =============================================================================
  676. // PAGE COMPONENTS - Admin pages
  677. // =============================================================================
  678. /**
  679. * UserAdminPage - Admin page for user management
  680. *
  681. * This page demonstrates how to use UserManagementComponent within your own
  682. * page layout. Unlike the old UserManagementPage (which was a PageComponent
  683. * that generated a full HTML document), UserManagementComponent is a regular
  684. * Component that can be placed anywhere.
  685. *
  686. * Applications now have full control over:
  687. * - The page layout and navigation
  688. * - CSS styling via their own stylesheets
  689. * - Where the user management component appears
  690. */
  691. public class UserAdminPage : PageComponent {
  692. private ComponentFactory _factory = inject<ComponentFactory>();
  693. private UserManagementComponent _user_management;
  694. public const string ROUTE = "/admin/users";
  695. public override string markup { get {
  696. return """
  697. <div class="card">
  698. <h1>User Administration</h1>
  699. <p>Manage user accounts, permissions, and access control.</p>
  700. <spry-outlet sid="user-management-outlet"/>
  701. </div>
  702. """;
  703. }}
  704. public override async void prepare() throws Error {
  705. // Create the user management component
  706. _user_management = _factory.create<UserManagementComponent>();
  707. // Pass the application-defined permissions to the component
  708. // This allows the component to display appropriate checkboxes
  709. // _user_management.available_permissions = get_application_permissions();
  710. // Add it to our outlet
  711. _user_management.authorisation_permission = "admin";
  712. add_outlet_child("user-management-outlet", _user_management);
  713. // Share globals with the component (required for action handling)
  714. add_globals_from(_user_management);
  715. }
  716. }
  717. // =============================================================================
  718. // SEED DATA - Creates initial admin user
  719. // =============================================================================
  720. /**
  721. * SeedData - Creates initial users for testing
  722. *
  723. * This demonstrates how to:
  724. * - Check if users exist before creating
  725. * - Create users programmatically using register_user()
  726. * - Grant permissions to users using set_user_permission()
  727. */
  728. public class SeedData : Object {
  729. public static async void ensure_admin_exists(UserService user_service) throws Error {
  730. // Try to get list of users and check if admin exists
  731. var users = yield user_service.list_users(0, 100);
  732. bool admin_exists = false;
  733. bool testuser_exists = false;
  734. int64? admin_id = null;
  735. int64? testuser_id = null;
  736. foreach (var user in users) {
  737. if (user.username == "admin") {
  738. admin_exists = true;
  739. admin_id = user.id;
  740. }
  741. if (user.username == "testuser") {
  742. testuser_exists = true;
  743. testuser_id = user.id;
  744. }
  745. }
  746. if (admin_exists) {
  747. print("Admin user already exists\n");
  748. } else {
  749. print("Creating admin user...\n");
  750. // Create admin user using register_user
  751. var admin_user = yield user_service.register_user(
  752. "admin",
  753. "admin@example.com",
  754. "Admin",
  755. "User",
  756. new DateTime.utc(1990, 1, 1, 0, 0, 0.0),
  757. "admin123",
  758. true
  759. );
  760. admin_id = admin_user.id;
  761. // Grant admin permissions
  762. yield user_service.set_user_permission(admin_id, "admin");
  763. yield user_service.set_user_permission(admin_id, "user-management");
  764. yield user_service.set_user_permission(admin_id, "user.create");
  765. yield user_service.set_user_permission(admin_id, "user.read");
  766. yield user_service.set_user_permission(admin_id, "user.update");
  767. yield user_service.set_user_permission(admin_id, "user.delete");
  768. print("Admin user created with username 'admin' and password 'admin123'\n");
  769. }
  770. if (!testuser_exists) {
  771. print("Creating test user...\n");
  772. var test_user = yield user_service.register_user(
  773. "testuser",
  774. "test@example.com",
  775. "Test",
  776. "User",
  777. new DateTime.utc(1995, 6, 15, 0, 0, 0.0),
  778. "test123",
  779. true
  780. );
  781. testuser_id = test_user.id;
  782. yield user_service.set_user_permission(testuser_id, "user.read");
  783. print("Test user created with username 'testuser' and password 'test123'\n");
  784. } else {
  785. print("Test user already exists\n");
  786. }
  787. }
  788. }
  789. // =============================================================================
  790. // APPLICATION SETUP
  791. // =============================================================================
  792. // =============================================================================
  793. // ASYNC MAIN LOOP - Required for async initialization
  794. // =============================================================================
  795. private MainLoop main_loop;
  796. public static int main(string[] args) {
  797. int port = args.length > 1 ? int.parse(args[1]) : 8080;
  798. print("═══════════════════════════════════════════════════════════════\n");
  799. print(" Spry Authentication Example - Complete Demo\n");
  800. print("═══════════════════════════════════════════════════════════════\n");
  801. print(" Port: %d\n", port);
  802. print("═══════════════════════════════════════════════════════════════\n");
  803. print(" Public Endpoints:\n");
  804. print(" / - Home page (public)\n");
  805. print(" /register - Create new account\n");
  806. print(" /login - Login page\n");
  807. print("═══════════════════════════════════════════════════════════════\n");
  808. print(" Protected Endpoints (requires login):\n");
  809. print(" /dashboard - User dashboard\n");
  810. print(" /logout - Logout and clear cookie\n");
  811. print("═══════════════════════════════════════════════════════════════\n");
  812. print(" Admin Endpoints (requires 'user-management' permission):\n");
  813. print(" /admin/users - User management page\n");
  814. print("═══════════════════════════════════════════════════════════════\n");
  815. print(" Default Users:\n");
  816. print(" admin / admin123 - Has all permissions\n");
  817. print(" testuser / test123 - Regular user\n");
  818. print("═══════════════════════════════════════════════════════════════\n");
  819. print("\nPress Ctrl+C to stop the server\n\n");
  820. main_loop = new MainLoop();
  821. try {
  822. start_application.begin(port, (obj, res) => {
  823. try {
  824. start_application.end(res);
  825. } catch (Error e) {
  826. printerr("Application error: %s\n", e.message);
  827. main_loop.quit();
  828. }
  829. });
  830. main_loop.run();
  831. return 0;
  832. } catch (Error e) {
  833. printerr("Error: %s\n", e.message);
  834. return 1;
  835. }
  836. }
  837. /**
  838. * Start the web application.
  839. */
  840. private async void start_application(int port) throws Error {
  841. var application = new WebApplication(port);
  842. // Enable compression
  843. application.use_compression();
  844. // Add Spry module for component actions
  845. application.add_module<SpryModule>();
  846. // Configure the database using InvercargillSqlInversion
  847. var db_config = application.container.configure_with<DatabaseConfigurator>();
  848. db_config.register_connection(@"sqlite://./db.sqlite");
  849. db_config.migrate_on_startup();
  850. // Add authentication module to register entity mappings
  851. application.add_module<AuthenticationModule>();
  852. // Register Authentication system services
  853. application.add_scoped<UserService>();
  854. // Register Authorisation system services
  855. application.add_scoped<AuthorisationService>();
  856. // Add the authorisation pipeline component to read tokens from requests
  857. // This component creates a scoped AuthorisationContext per request
  858. application.add_scoped<AuthorisationPipelineComponent>()
  859. .as<Astralis.PipelineComponent>();
  860. // Register template with route prefix
  861. // MainLayoutTemplate applies to ALL routes (empty prefix)
  862. var spry_cfg = application.configure_with<SpryConfigurator>();
  863. spry_cfg.add_template<MainLayoutTemplate>("");
  864. // Register page components as endpoints
  865. application.add_transient<HomePage>();
  866. application.add_endpoint<HomePage>(new EndpointRoute(HomePage.ROUTE));
  867. application.add_transient<RegisterPage>();
  868. application.add_endpoint<RegisterPage>(new EndpointRoute(RegisterPage.ROUTE));
  869. application.add_transient<LoginPage>();
  870. application.add_endpoint<LoginPage>(new EndpointRoute(LoginPage.ROUTE));
  871. application.add_transient<DashboardPage>();
  872. application.add_endpoint<DashboardPage>(new EndpointRoute(DashboardPage.ROUTE));
  873. // Register logout endpoint
  874. application.add_endpoint<LogoutEndpoint>(new EndpointRoute("/logout"));
  875. // Register UserAdminPage (admin page wrapping UserManagementComponent)
  876. application.add_transient<UserAdminPage>();
  877. application.add_endpoint<UserAdminPage>(new EndpointRoute(UserAdminPage.ROUTE));
  878. // Register LoginFormComponent (used by LoginPage)
  879. application.add_transient<LoginComponent>();
  880. // Register new user management components
  881. application.add_transient<UserManagementComponent>();
  882. application.add_transient<UserComponent>();
  883. application.add_transient<UserEditComponent>();
  884. // Register CSS as FastResource
  885. application.add_startup_endpoint<FastResource>(new EndpointRoute("/styles/main.css"), () => {
  886. try {
  887. return new FastResource.from_string(MAIN_CSS)
  888. .with_content_type("text/css; charset=utf-8")
  889. .with_default_compressors();
  890. } catch (Error e) {
  891. error("Failed to create main CSS resource: %s", e.message);
  892. }
  893. });
  894. print("Starting web server on port %d...\n\n", port);
  895. // Seed initial data after migrations have run (migrations execute during application.run())
  896. // Use Idle.add() to ensure this runs after the main loop starts
  897. GLib.Idle.add(() => {
  898. seed_initial_data.begin(application.container);
  899. return false; // Don't repeat
  900. });
  901. application.run();
  902. }
  903. /**
  904. * Seed initial data (admin and test users).
  905. */
  906. private async void seed_initial_data(Container container) {
  907. try {
  908. var scope = container.create_scope();
  909. var user_service = scope.resolve<UserService>();
  910. yield SeedData.ensure_admin_exists(user_service);
  911. } catch (Error e) {
  912. printerr("Warning: Failed to seed initial data: %s\n", e.message);
  913. }
  914. }