Actions.vala 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Statum;
  2. using Invercargill;
  3. using Invercargill.DataStructures;
  4. namespace Example {
  5. /**
  6. * `POST /login` — creates a session-scoped `auth` slot from the submitted
  7. * name and redirects the client home. The `is_admin` flag is kept in the
  8. * slot's (encrypted, server-only) private data.
  9. */
  10. public class LoginAction : StatumAction {
  11. public override async Lot<Model.DirectiveDto> 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 auth_public = new PropertyDictionary();
  21. auth_public.set_native<string>("name", name);
  22. auth_public.set_native<string>("role", is_admin ? "admin" : "member");
  23. var auth_private = new PropertyDictionary();
  24. auth_private.set_native<bool>("is_admin", is_admin);
  25. var state = new State() {
  26. type_name = "auth",
  27. public_data = auth_public,
  28. private_data = auth_private
  29. };
  30. var slot = state_service.new_slot(Scope.SESSION, state);
  31. var frame = state_service.sign_slot(slot.id);
  32. var directives = new Series<Model.DirectiveDto>();
  33. directives.add(new Model.SetDirectiveDto.with_frame((!)frame));
  34. directives.add(new Model.NavigateDirectiveDto.with_uri("/"));
  35. return directives;
  36. }
  37. }
  38. /**
  39. * `POST /logout` — clears the held `auth` slot and redirects home.
  40. */
  41. public class LogoutAction : StatumAction {
  42. public override async Lot<Model.DirectiveDto> handle() throws GLib.Error {
  43. var directives = new Series<Model.DirectiveDto>();
  44. HeldSlot auth;
  45. if (request.held.try_get("auth", out auth)) {
  46. yield state_service.clear_slot(auth.key);
  47. directives.add(new Model.ClearDirectiveDto.with_key(auth.key));
  48. }
  49. directives.add(new Model.NavigateDirectiveDto.with_uri("/"));
  50. return directives;
  51. }
  52. }
  53. }