category.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * GET users listing.
  3. */
  4. import express = require('express');
  5. const router = express.Router();
  6. import Security from '../src/Security';
  7. import { ILDAPManager } from '../src/ldapInterface';
  8. import LDAPEntry from '../src/LDAPEntry';
  9. import ConfigManager, { LDAPAttribute, LDAPCategory } from '../src/ConfigLoader';
  10. function GetCurrentCategory(req: express.Request, defaultResult: LDAPCategory): LDAPCategory|null {
  11. if (!req.query["category"])
  12. return null;
  13. let query = Array.isArray(req.query["category"]) ? req.query["category"][0] : req.query["category"];
  14. return LinkToCategory(query.toString()) || defaultResult;
  15. }
  16. function LinkToCategory(query: string): LDAPCategory | null {
  17. return ConfigManager.GetInstance().GetCategoryByName(query);
  18. }
  19. function CategoryToLink(category: LDAPCategory): string {
  20. return category.GetName();
  21. }
  22. function DnToLink(dn: string): string {
  23. return dn.replace(new RegExp("=", "g"), "-").replace(new RegExp("[^a-zA-Z\-]", "g"), "_");
  24. }
  25. router.get('/', (req: express.Request, res: express.Response) => {
  26. if (!Security.requireLoggedUser(req, res))
  27. return;
  28. req.ldapManager.GetInstance().then((ldap: ILDAPManager): void => {
  29. ldap.GetTree().then(root => {
  30. let categories = ConfigManager.GetInstance().GetCategories();
  31. let category = GetCurrentCategory(req, categories[0]);
  32. if (category == null) {
  33. res.render("index", {
  34. tree: root.GetChildren()[0],
  35. rootSrc: "?category=" + CategoryToLink(categories[0])
  36. });
  37. } else {
  38. let session = Security.GetSession(req);
  39. ldap.ListEntries(category).then(items => {
  40. res.render("category", {
  41. csrf: session ? session.GetCSRFToken() : "",
  42. categoryName: category?.GetName(),
  43. allCategories: categories.map((i) => { return { name: i.GetName(), lnk: "?category=" + CategoryToLink(i) } }),
  44. items: items,
  45. attributes: category?.GetAttributes(),
  46. DnToLnk: DnToLink,
  47. GetAttributeLink: function (attr: LDAPAttribute, entityDn: string) {
  48. if (attr.type.startsWith("entry")) {
  49. let link = attr.type.split("#", 2)[1];
  50. if (link)
  51. return "?category=" + link + "#" + DnToLink(entityDn);
  52. }
  53. return null;
  54. },
  55. GetAttributeValue: function (user: LDAPEntry, attribute: LDAPAttribute) {
  56. return user.GetAttributeByName(attribute.name);
  57. }
  58. });
  59. });
  60. }
  61. });
  62. });
  63. });
  64. export default router;