Actions.vala 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Statum;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. namespace Example {
  5. /**
  6. * `POST /_statum/action/{guid}` — logs in: reads the submitted name, builds a
  7. * session `auth` slot from typed models (public + private), embedding a
  8. * `logout` action reference, and redirects home.
  9. */
  10. public class LoginAction : StatumAction {
  11. public override async DirectiveBuilder handle() throws GLib.Error {
  12. var name = "guest";
  13. if (request.form != null) {
  14. var submitted = request.form.get_field("name");
  15. if (submitted != null && ((!)submitted).length > 0) {
  16. name = (!)submitted;
  17. }
  18. }
  19. var is_admin = name == "admin";
  20. var pub = new AuthPublic();
  21. pub.name = name;
  22. pub.role = is_admin ? "admin" : "member";
  23. pub.logout = action_registry.author<LogoutAction>();
  24. var priv = new AuthPrivate();
  25. priv.is_admin = is_admin;
  26. return directives()
  27. .set_private_typed<AuthPublic, AuthPrivate>("auth", Scope.SESSION, pub, priv)
  28. .navigate("/");
  29. }
  30. }
  31. /**
  32. * `POST /_statum/action/{guid}` — logs out: clears the held `auth` slot and
  33. * redirects home.
  34. */
  35. public class LogoutAction : StatumAction {
  36. public override async DirectiveBuilder handle() throws GLib.Error {
  37. HeldSlot auth;
  38. if (request.held.try_get("auth", out auth)) {
  39. yield state_service.clear_slot(auth.key);
  40. return directives().clear(auth.key).navigate("/");
  41. }
  42. return directives().navigate("/");
  43. }
  44. }
  45. /**
  46. * `POST /_statum/action/{guid}` — bumps the counter by the typed private
  47. * `delta`, using the typed {@link DirectiveBuilder.update_held} so the
  48. * `bump` action reference is preserved automatically across the update.
  49. */
  50. public class BumpCounterAction : TypedStatumAction<CounterPrivate> {
  51. public override async DirectiveBuilder handle() throws GLib.Error {
  52. var delta = request_private != null ? ((!)request_private).delta : 1;
  53. return directives().update_held<CounterPublic>("counter", c => c.value += delta);
  54. }
  55. }
  56. }