category.ts 2.9 KB

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