support interaction between module and apps for updating templates before rendering
[squeep-authentication-module] / lib / template / helpers.js
diff --git a/lib/template/helpers.js b/lib/template/helpers.js
new file mode 100644 (file)
index 0000000..67162f8
--- /dev/null
@@ -0,0 +1,46 @@
+'use strict';
+
+/**
+ * Populates nevLinks with (currently hardcoded) session-related links.
+ * @param {Number} pagePathLevel relative to base
+ * @param {Object} ctx
+ * @param {String=} ctx.url redirect on logout
+ * @param {Object=} ctx.session
+ * @param {String=} ctx.session.authenticatedIdentifier
+ * @param {String=} ctx.session.authenticatedProfile
+ * @param {Object} options
+ * @param {Object[]=} options.navLinks created if not present
+ * @param {String=} options.pageIdentifier
+ */
+function sessionNavLinks(pagePathLevel, ctx, options) {
+  if (!options.navLinks) {
+    options.navLinks = [];
+  }
+  const rootPath = '../'.repeat(pagePathLevel);
+  const redirectQuery = ctx?.url ? `?r=${encodeURIComponent(ctx.url)}` : rootPath;
+  const adminPath = rootPath + 'admin/';
+
+  const user = ctx?.session?.authenticatedProfile || ctx?.session?.authenticatedIdentifier;
+  if (user) {
+    if (options.pageIdentifier !== 'account') {
+      options.navLinks.push({
+        text: 'Account',
+        href: `${adminPath}settings`,
+      });
+    }
+    options.navLinks.push({
+      text: `Logout (${user})`,
+      href: `${adminPath}logout${redirectQuery}`,
+    });
+  } else {
+    options.navLinks.push({
+      text: 'Login',
+      href: `${adminPath}login${redirectQuery}`,
+    });
+  }
+}
+
+
+module.exports = {
+  sessionNavLinks,
+};