sumba 2.34.4 → 2.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/docs/Sumba.html +1 -1
  2. package/docs/data/search.json +1 -1
  3. package/docs/global.html +1 -1
  4. package/docs/index.html +1 -1
  5. package/docs/index.js.html +1564 -233
  6. package/docs/lib_constant.js.html +98 -0
  7. package/docs/lib_token-schema.js.html +47 -0
  8. package/extend/bajo/hook.js +27 -192
  9. package/extend/bajo/intl/en-US.json +12 -12
  10. package/extend/bajo/intl/id.json +13 -13
  11. package/extend/dobo/model.js +27 -1
  12. package/extend/waibuDb/schema/model-guard.js +2 -2
  13. package/extend/waibuMpa/extend/waibuAdmin/route/action-guard/@action.js +11 -0
  14. package/extend/waibuMpa/extend/waibuAdmin/route/{model-guard → query-guard}/@action.js +2 -2
  15. package/extend/waibuMpa/extend/waibuAdmin/route/team/@action.js +1 -1
  16. package/extend/waibuMpa/extend/waibuAdmin/route/team-setting/@action.js +1 -1
  17. package/extend/waibuMpa/extend/waibuAdmin/route/team-user/@action.js +1 -1
  18. package/extend/waibuMpa/extend/waibuAdmin/route/user/@action.js +1 -1
  19. package/extend/waibuMpa/extend/waibuAdmin/route/user-setting/@action.js +1 -1
  20. package/extend/waibuRestApi/route/user/access-token/@type/create.js +1 -1
  21. package/extend/waibuRestApi/route/user/api-key/get.js +1 -1
  22. package/extend/waibuRestApi/route/your-stuff/api-key/update.js +1 -1
  23. package/index.js +1061 -45
  24. package/lib/constant.js +95 -0
  25. package/package.json +9 -3
  26. package/wiki/CHANGES.md +6 -0
  27. package/lib/create-new-site.js +0 -106
  28. package/lib/get-site.js +0 -70
  29. package/lib/get-user.js +0 -89
  30. package/lib/remove-site.js +0 -39
  31. package/lib/token-schema.js +0 -29
@@ -1,35 +1,51 @@
1
1
  <!DOCTYPE html><html lang="en" style="font-size:16px"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Source: index.js</title><!--[if lt IE 9]>
2
2
  <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
3
- <![endif]--><script src="scripts/third-party/hljs.js" defer="defer"></script><script src="scripts/third-party/hljs-line-num.js" defer="defer"></script><script src="scripts/third-party/popper.js" defer="defer"></script><script src="scripts/third-party/tippy.js" defer="defer"></script><script src="scripts/third-party/tocbot.min.js"></script><script>var baseURL="/",locationPathname="";baseURL=(locationPathname=document.location.pathname).substr(0,locationPathname.lastIndexOf("/")+1)</script><link rel="stylesheet" href="styles/clean-jsdoc-theme.min.css"><svg aria-hidden="true" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display:none"><defs><symbol id="copy-icon" viewbox="0 0 488.3 488.3"><g><path d="M314.25,85.4h-227c-21.3,0-38.6,17.3-38.6,38.6v325.7c0,21.3,17.3,38.6,38.6,38.6h227c21.3,0,38.6-17.3,38.6-38.6V124 C352.75,102.7,335.45,85.4,314.25,85.4z M325.75,449.6c0,6.4-5.2,11.6-11.6,11.6h-227c-6.4,0-11.6-5.2-11.6-11.6V124 c0-6.4,5.2-11.6,11.6-11.6h227c6.4,0,11.6,5.2,11.6,11.6V449.6z"/><path d="M401.05,0h-227c-21.3,0-38.6,17.3-38.6,38.6c0,7.5,6,13.5,13.5,13.5s13.5-6,13.5-13.5c0-6.4,5.2-11.6,11.6-11.6h227 c6.4,0,11.6,5.2,11.6,11.6v325.7c0,6.4-5.2,11.6-11.6,11.6c-7.5,0-13.5,6-13.5,13.5s6,13.5,13.5,13.5c21.3,0,38.6-17.3,38.6-38.6 V38.6C439.65,17.3,422.35,0,401.05,0z"/></g></symbol><symbol id="search-icon" viewBox="0 0 512 512"><g><g><path d="M225.474,0C101.151,0,0,101.151,0,225.474c0,124.33,101.151,225.474,225.474,225.474 c124.33,0,225.474-101.144,225.474-225.474C450.948,101.151,349.804,0,225.474,0z M225.474,409.323 c-101.373,0-183.848-82.475-183.848-183.848S124.101,41.626,225.474,41.626s183.848,82.475,183.848,183.848 S326.847,409.323,225.474,409.323z"/></g></g><g><g><path d="M505.902,476.472L386.574,357.144c-8.131-8.131-21.299-8.131-29.43,0c-8.131,8.124-8.131,21.306,0,29.43l119.328,119.328 c4.065,4.065,9.387,6.098,14.715,6.098c5.321,0,10.649-2.033,14.715-6.098C514.033,497.778,514.033,484.596,505.902,476.472z"/></g></g></symbol><symbol id="font-size-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11.246 15H4.754l-2 5H.6L7 4h2l6.4 16h-2.154l-2-5zm-.8-2L8 6.885 5.554 13h4.892zM21 12.535V12h2v8h-2v-.535a4 4 0 1 1 0-6.93zM19 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/></symbol><symbol id="add-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></symbol><symbol id="minus-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M5 11h14v2H5z"/></symbol><symbol id="dark-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M10 7a7 7 0 0 0 12 4.9v.1c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2h.1A6.979 6.979 0 0 0 10 7zm-6 5a8 8 0 0 0 15.062 3.762A9 9 0 0 1 8.238 4.938 7.999 7.999 0 0 0 4 12z"/></symbol><symbol id="light-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12zm0-2a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM11 1h2v3h-2V1zm0 19h2v3h-2v-3zM3.515 4.929l1.414-1.414L7.05 5.636 5.636 7.05 3.515 4.93zM16.95 18.364l1.414-1.414 2.121 2.121-1.414 1.414-2.121-2.121zm2.121-14.85l1.414 1.415-2.121 2.121-1.414-1.414 2.121-2.121zM5.636 16.95l1.414 1.414-2.121 2.121-1.414-1.414 2.121-2.121zM23 11v2h-3v-2h3zM4 11v2H1v-2h3z"/></symbol><symbol id="reset-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M18.537 19.567A9.961 9.961 0 0 1 12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10c0 2.136-.67 4.116-1.81 5.74L17 12h3a8 8 0 1 0-2.46 5.772l.997 1.795z"/></symbol><symbol id="down-icon" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.7803 6.21967C13.0732 6.51256 13.0732 6.98744 12.7803 7.28033L8.53033 11.5303C8.23744 11.8232 7.76256 11.8232 7.46967 11.5303L3.21967 7.28033C2.92678 6.98744 2.92678 6.51256 3.21967 6.21967C3.51256 5.92678 3.98744 5.92678 4.28033 6.21967L8 9.93934L11.7197 6.21967C12.0126 5.92678 12.4874 5.92678 12.7803 6.21967Z"></path></symbol><symbol id="codepen-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M16.5 13.202L13 15.535v3.596L19.197 15 16.5 13.202zM14.697 12L12 10.202 9.303 12 12 13.798 14.697 12zM20 10.869L18.303 12 20 13.131V10.87zM19.197 9L13 4.869v3.596l3.5 2.333L19.197 9zM7.5 10.798L11 8.465V4.869L4.803 9 7.5 10.798zM4.803 15L11 19.131v-3.596l-3.5-2.333L4.803 15zM4 13.131L5.697 12 4 10.869v2.262zM2 9a1 1 0 0 1 .445-.832l9-6a1 1 0 0 1 1.11 0l9 6A1 1 0 0 1 22 9v6a1 1 0 0 1-.445.832l-9 6a1 1 0 0 1-1.11 0l-9-6A1 1 0 0 1 2 15V9z"/></symbol><symbol id="close-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z"/></symbol><symbol id="menu-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M3 4h18v2H3V4zm0 7h18v2H3v-2zm0 7h18v2H3v-2z"/></symbol></defs></svg></head><body data-theme="light"><div class="sidebar-container"><div class="sidebar" id="sidebar"><a href="/" class="sidebar-title sidebar-title-anchor">Sumba API</a><div class="sidebar-items-container"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="Sumba.html">Sumba</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div></div></div><div class="navbar-container" id="VuAckcnZhf"><nav class="navbar"><div class="navbar-left-items"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/sumba" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/sumba" target="">Github</a></div><div class="navbar-item"><a id="" href="https://sumba.bajo.app/" target="">Sumba</a></div><div class="navbar-item"><a id="" href="https://bajo.app/" target="">Bajo</a></div></div><div class="navbar-right-items"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div><nav></nav></nav></div><div class="toc-container"><div class="toc-content"><span class="bold">On this page</span><div id="eed4d2a0bfd64539bb9df78095dec881"></div></div></div><div class="body-wrapper"><div class="main-content"><div class="main-wrapper"><section id="source-page" class="source-page"><header><h1 id="title" class="has-anchor">index.js</h1></header><article><pre class="prettyprint source lang-js"><code>import path from 'path'
3
+ <![endif]--><script src="scripts/third-party/hljs.js" defer="defer"></script><script src="scripts/third-party/hljs-line-num.js" defer="defer"></script><script src="scripts/third-party/popper.js" defer="defer"></script><script src="scripts/third-party/tippy.js" defer="defer"></script><script src="scripts/third-party/tocbot.min.js"></script><script>var baseURL="/",locationPathname="";baseURL=(locationPathname=document.location.pathname).substr(0,locationPathname.lastIndexOf("/")+1)</script><link rel="stylesheet" href="styles/clean-jsdoc-theme.min.css"><svg aria-hidden="true" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display:none"><defs><symbol id="copy-icon" viewbox="0 0 488.3 488.3"><g><path d="M314.25,85.4h-227c-21.3,0-38.6,17.3-38.6,38.6v325.7c0,21.3,17.3,38.6,38.6,38.6h227c21.3,0,38.6-17.3,38.6-38.6V124 C352.75,102.7,335.45,85.4,314.25,85.4z M325.75,449.6c0,6.4-5.2,11.6-11.6,11.6h-227c-6.4,0-11.6-5.2-11.6-11.6V124 c0-6.4,5.2-11.6,11.6-11.6h227c6.4,0,11.6,5.2,11.6,11.6V449.6z"/><path d="M401.05,0h-227c-21.3,0-38.6,17.3-38.6,38.6c0,7.5,6,13.5,13.5,13.5s13.5-6,13.5-13.5c0-6.4,5.2-11.6,11.6-11.6h227 c6.4,0,11.6,5.2,11.6,11.6v325.7c0,6.4-5.2,11.6-11.6,11.6c-7.5,0-13.5,6-13.5,13.5s6,13.5,13.5,13.5c21.3,0,38.6-17.3,38.6-38.6 V38.6C439.65,17.3,422.35,0,401.05,0z"/></g></symbol><symbol id="search-icon" viewBox="0 0 512 512"><g><g><path d="M225.474,0C101.151,0,0,101.151,0,225.474c0,124.33,101.151,225.474,225.474,225.474 c124.33,0,225.474-101.144,225.474-225.474C450.948,101.151,349.804,0,225.474,0z M225.474,409.323 c-101.373,0-183.848-82.475-183.848-183.848S124.101,41.626,225.474,41.626s183.848,82.475,183.848,183.848 S326.847,409.323,225.474,409.323z"/></g></g><g><g><path d="M505.902,476.472L386.574,357.144c-8.131-8.131-21.299-8.131-29.43,0c-8.131,8.124-8.131,21.306,0,29.43l119.328,119.328 c4.065,4.065,9.387,6.098,14.715,6.098c5.321,0,10.649-2.033,14.715-6.098C514.033,497.778,514.033,484.596,505.902,476.472z"/></g></g></symbol><symbol id="font-size-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11.246 15H4.754l-2 5H.6L7 4h2l6.4 16h-2.154l-2-5zm-.8-2L8 6.885 5.554 13h4.892zM21 12.535V12h2v8h-2v-.535a4 4 0 1 1 0-6.93zM19 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/></symbol><symbol id="add-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></symbol><symbol id="minus-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M5 11h14v2H5z"/></symbol><symbol id="dark-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M10 7a7 7 0 0 0 12 4.9v.1c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2h.1A6.979 6.979 0 0 0 10 7zm-6 5a8 8 0 0 0 15.062 3.762A9 9 0 0 1 8.238 4.938 7.999 7.999 0 0 0 4 12z"/></symbol><symbol id="light-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12zm0-2a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM11 1h2v3h-2V1zm0 19h2v3h-2v-3zM3.515 4.929l1.414-1.414L7.05 5.636 5.636 7.05 3.515 4.93zM16.95 18.364l1.414-1.414 2.121 2.121-1.414 1.414-2.121-2.121zm2.121-14.85l1.414 1.415-2.121 2.121-1.414-1.414 2.121-2.121zM5.636 16.95l1.414 1.414-2.121 2.121-1.414-1.414 2.121-2.121zM23 11v2h-3v-2h3zM4 11v2H1v-2h3z"/></symbol><symbol id="reset-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M18.537 19.567A9.961 9.961 0 0 1 12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10c0 2.136-.67 4.116-1.81 5.74L17 12h3a8 8 0 1 0-2.46 5.772l.997 1.795z"/></symbol><symbol id="down-icon" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.7803 6.21967C13.0732 6.51256 13.0732 6.98744 12.7803 7.28033L8.53033 11.5303C8.23744 11.8232 7.76256 11.8232 7.46967 11.5303L3.21967 7.28033C2.92678 6.98744 2.92678 6.51256 3.21967 6.21967C3.51256 5.92678 3.98744 5.92678 4.28033 6.21967L8 9.93934L11.7197 6.21967C12.0126 5.92678 12.4874 5.92678 12.7803 6.21967Z"></path></symbol><symbol id="codepen-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M16.5 13.202L13 15.535v3.596L19.197 15 16.5 13.202zM14.697 12L12 10.202 9.303 12 12 13.798 14.697 12zM20 10.869L18.303 12 20 13.131V10.87zM19.197 9L13 4.869v3.596l3.5 2.333L19.197 9zM7.5 10.798L11 8.465V4.869L4.803 9 7.5 10.798zM4.803 15L11 19.131v-3.596l-3.5-2.333L4.803 15zM4 13.131L5.697 12 4 10.869v2.262zM2 9a1 1 0 0 1 .445-.832l9-6a1 1 0 0 1 1.11 0l9 6A1 1 0 0 1 22 9v6a1 1 0 0 1-.445.832l-9 6a1 1 0 0 1-1.11 0l-9-6A1 1 0 0 1 2 15V9z"/></symbol><symbol id="close-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z"/></symbol><symbol id="menu-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M3 4h18v2H3V4zm0 7h18v2H3v-2zm0 7h18v2H3v-2z"/></symbol></defs></svg></head><body data-theme="light"><div class="sidebar-container"><div class="sidebar" id="sidebar"><a href="/" class="sidebar-title sidebar-title-anchor">Sumba API</a><div class="sidebar-items-container"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="Sumba.html">Sumba</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#TConfig">TConfig</a></div><div class="sidebar-section-children"><a href="global.html#TTokenBody">TTokenBody</a></div><div class="sidebar-section-children"><a href="global.html#TTokenData">TTokenData</a></div><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div></div></div><div class="navbar-container" id="VuAckcnZhf"><nav class="navbar"><div class="navbar-left-items"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/sumba" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/sumba" target="">Github</a></div><div class="navbar-item"><a id="" href="https://sumba.bajo.app/" target="">Sumba</a></div><div class="navbar-item"><a id="" href="https://bajo.app/" target="">Bajo</a></div></div><div class="navbar-right-items"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div><nav></nav></nav></div><div class="toc-container"><div class="toc-content"><span class="bold">On this page</span><div id="eed4d2a0bfd64539bb9df78095dec881"></div></div></div><div class="body-wrapper"><div class="main-content"><div class="main-wrapper"><section id="source-page" class="source-page"><header><h1 id="title" class="has-anchor">index.js</h1></header><article><pre class="prettyprint source lang-js"><code>import path from 'path'
4
+ import { joiPasswordExtendCore } from 'joi-password'
5
+
6
+ const defMultiSite = {
7
+ enabled: false,
8
+ catchAll: 'default'
9
+ }
4
10
 
5
11
  /**
6
- * Plugin factory
12
+ * Plugin factory.
13
+ *
14
+ * **Never** call this function directly!!! It's only-meant to be called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
7
15
  *
8
16
  * @param {string} pkgName - NPM package name
9
- * @returns {class}
17
+ * @returns {Sumba} Sumba class
10
18
  */
11
19
  async function factory (pkgName) {
12
20
  const me = this
21
+ const { getModel } = this.app.dobo
22
+ const { cloneDeep, isEmpty } = this.app.lib._
13
23
 
14
24
  /**
15
- * Sumba class
25
+ * Sumba class definition.
16
26
  *
17
27
  * @class
18
28
  */
19
29
  class Sumba extends this.app.baseClass.Base {
20
- static alias = 'sumba'
21
- static dependencies = ['bajo-extra', 'bajo-common-db', 'bajo-config', 'bajo-markdown']
22
-
30
+ /**
31
+ * Constructor
32
+ */
23
33
  constructor () {
24
34
  super(pkgName, me.app)
35
+ /**
36
+ * @type {TConfig}
37
+ */
25
38
  this.config = {
26
- multiSite: false,
39
+ multiSite: cloneDeep(defMultiSite),
40
+ xSiteAdmins: [], // format: "&lt;siteAlias>:&lt;username>"
27
41
  waibu: {
28
42
  title: 'site',
29
43
  prefix: 'site'
30
44
  },
45
+ dobo: {
46
+ model: {}
47
+ },
31
48
  waibuMpa: {
32
- home: 'sumba:/your-stuff/profile',
33
49
  icon: 'globe',
34
50
  redirect: {
35
51
  '/': 'sumba:/your-stuff/profile',
@@ -40,8 +56,17 @@ async function factory (pkgName) {
40
56
  '/help': 'sumba:/help/contact-form',
41
57
  '/help/trouble-tickets': 'sumba:/help/trouble-tickets/list'
42
58
  },
59
+ redirectSubRoute: {
60
+ waibuAdmin: {
61
+ '/': 'waibuAdmin:/site/site',
62
+ '/x': 'waibuAdmin:/site/x/site/list',
63
+ '/x/*': 'waibuAdmin:/site/x/{2}/list',
64
+ '/*': 'waibuAdmin:/site/{1}/list'
65
+ }
66
+ },
43
67
  menuHandler: [{
44
68
  title: 'account',
69
+ icon: 'person',
45
70
  level: 9998,
46
71
  children: [
47
72
  // anonymous only
@@ -59,6 +84,7 @@ async function factory (pkgName) {
59
84
  ]
60
85
  }, {
61
86
  title: 'help',
87
+ icon: 'signInfo',
62
88
  level: 9999,
63
89
  children: [
64
90
  { title: 'contactForm', href: 'sumba:/help/contact-form' },
@@ -80,16 +106,17 @@ async function factory (pkgName) {
80
106
  apiKey: {
81
107
  type: 'Bearer',
82
108
  qsKey: 'apiKey',
83
- headerKey: 'X-Sumba-ApiKey'
109
+ headerKey: 'X-Auth-ApiKey',
110
+ algo: 'sha256' // changing this require each and every user to reset their apiKey
84
111
  },
85
112
  basic: {
86
113
  },
87
114
  jwt: {
88
115
  type: 'Bearer',
89
116
  qsKey: 'token',
90
- headerKey: 'X-Sumba-Token',
117
+ headerKey: 'X-Auth-Jwt',
91
118
  secret: '668de9cf57316c7dbf52f7ff7611c299',
92
- expiresIn: 604800000
119
+ expiresInDur: '7d'
93
120
  }
94
121
  },
95
122
  waibuRestApi: {
@@ -104,8 +131,8 @@ async function factory (pkgName) {
104
131
  methods: ['basic', 'apiKey', 'jwt'],
105
132
  basic: {
106
133
  useUtf8: true,
107
- realm: 'Protected Area',
108
- warningMessage: 'Please authenticate yourself, thank you!'
134
+ realm: true,
135
+ warningMessage: 'pleaseAuthenticate'
109
136
  },
110
137
  silentOnError: false
111
138
  }
@@ -118,30 +145,168 @@ async function factory (pkgName) {
118
145
  },
119
146
  siteSetting: {
120
147
  forgotPasswordExpDur: '5m',
148
+ timeZone: 'UTC',
121
149
  userPassword: {
122
- minUppercase: 1,
123
- minLowercase: 1,
150
+ minUpperCase: 1,
151
+ minLowerCase: 1,
124
152
  minSpecialChar: 1,
125
153
  minNumeric: 1,
126
154
  noWhitespace: false,
127
- latinOnlyChars: false
155
+ latinOnlyChars: false,
156
+ pattern: {
157
+ lowerCase: 'abcdefghijklmnopqrstuvwxyz',
158
+ upperCase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
159
+ specialChar: '!@#$%*',
160
+ numeric: '0123456789'
161
+ }
128
162
  }
163
+ },
164
+ cacheTtl: {
165
+ getSiteDur: '1m',
166
+ getUserByIdDur: '1m',
167
+ getUserByTokenDur: '1m'
129
168
  }
130
169
  }
170
+ this.secureGuards = []
171
+ this.actionGuards = []
172
+ this.queryGuards = []
173
+ this.attribGuards = []
174
+ this.secureGuards = []
175
+ this.anonymousGuards = []
176
+
131
177
  this.unsafeUserFields = ['password']
132
178
  }
133
179
 
180
+ /**
181
+ * Plugin initialization method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
182
+ *
183
+ * @async
184
+ * @method
185
+ */
134
186
  init = async () => {
135
- const { getPluginDataDir } = this.app.bajo
136
- this.downloadDir = `${getPluginDataDir(this.ns)}/download`
187
+ this.downloadDir = `${this.app.getPluginDataDir(this.ns)}/download`
137
188
  this.app.lib.fs.ensureDirSync(this.downloadDir)
138
- for (const type of ['secure', 'anonymous', 'team']) {
139
- this[`${type}Routes`] = this[`${type}Routes`] ?? []
140
- this[`${type}NegRoutes`] = this[`${type}NegRoutes`] ?? []
189
+ if (this.config.multiSite === true) {
190
+ this.config.multiSite = cloneDeep(defMultiSite)
191
+ this.config.multiSite.enabled = true
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Plugin start method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin start.
197
+ *
198
+ * @async
199
+ * @method
200
+ */
201
+ start = async () => {
202
+ await this.populateRouteGuards()
203
+ if (!this.config.multiSite.enabled) {
204
+ this.config.xSiteAdmins = []
205
+ return
206
+ }
207
+ if (this.config.xSiteAdmins.length === 0) {
208
+ const site = await getModel('SumbaSite').findOneRecord({ query: { alias: 'default' } }, { noMagic: true })
209
+ const user = await getModel('SumbaUser').findOneRecord({ query: { username: 'admin', siteId: site.id + '' } }, { noMagic: true })
210
+ this.config.xSiteAdmins.push(`${site.alias}:${user.username}`)
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Populate route guards at start
216
+ *
217
+ * @async
218
+ * @method
219
+ * @param {array} [sites] - List of sites to populate route guards for. If not provided, it will fetch all active sites.
220
+ */
221
+ populateRouteGuards = async (sites) => {
222
+ const { isString, get, difference } = this.app.lib._
223
+ const { pascalCase } = this.app.lib.aneka
224
+ const { eachPlugins, readConfig, breakNsPath } = this.app.bajo
225
+ const { getModel } = this.app.dobo
226
+
227
+ const allNs = this.app.getAllNs()
228
+ if (!sites) sites = await getModel('SumbaSite').findAllRecord({ query: { status: 'ACTIVE' } }, { noMagic: true, dataOnly: true, fields: ['id', 'hostname'] })
229
+
230
+ const sanitize = (item, ns) => {
231
+ if (isString(item)) item = { path: item }
232
+ let [prefix, ...args] = item.path.split(':')
233
+ const neg = prefix[0] === '!'
234
+ if (neg) prefix = prefix.slice(1)
235
+ if (isEmpty(args)) {
236
+ args = prefix
237
+ prefix = null
238
+ } else args = args.join(':')
239
+ if (isEmpty(prefix)) prefix = ns
240
+ else {
241
+ const [_ns, subNs] = prefix.split('.')
242
+ if (subNs) prefix = `${ns}.${subNs}`
243
+ else if (!allNs.includes(_ns)) prefix = `${ns}.${_ns}`
244
+ else prefix = _ns
245
+ }
246
+ item.path = `${neg ? '!' : ''}${prefix}:${args}`
247
+ item._immutable = item._immutable ?? ['path']
248
+ if (neg) {
249
+ item.allTeams = true
250
+ item.teamIds = []
251
+ item._immutable = ['path', 'teamIds', 'allTeams']
252
+ }
253
+ return item
254
+ }
255
+
256
+ const filterFn = item => {
257
+ let [ns] = (item.path.split(':')[0] ?? '').split('.')
258
+ if (ns[0] === '!') ns = ns.slice(1)
259
+ return allNs.includes(ns)
260
+ }
261
+
262
+ for (const type of ['secure', 'anonymous']) {
263
+ const routes = []
264
+ // get it from &lt;pluginDir>/extend/sumba/route/*
265
+ await eachPlugins(async function ({ file }) {
266
+ const { ns } = this
267
+ const items = (await readConfig(file)).map(item => sanitize(item, ns)).filter(filterFn)
268
+ routes.push(...items)
269
+ }, { glob: `route/${type}.*`, prefix: this.ns })
270
+ // get it from config
271
+ const items = get(this, `config.route.${type}`, []).map(item => {
272
+ if (isString(item)) item = { path: item }
273
+ const neg = item.path[0] === '!'
274
+ if (neg) item.path.slice(1)
275
+ const { fullNs } = breakNsPath(item.path)
276
+ if (neg) item.path = '!' + item.path
277
+ return sanitize(item, fullNs)
278
+ }).filter(filterFn)
279
+ routes.push(...items)
280
+ const paths = routes.map(item => item.path)
281
+ const model = getModel(pascalCase(`Sumba ${type} Guard`))
282
+ for (const site of sites) {
283
+ const query = { path: { $in: paths }, siteId: site.id + '' }
284
+ const recs = await model.findAllRecord({ query }, { noMagic: true, dataOnly: true, fields: ['path', 'status'] })
285
+ const spaths = difference(paths, recs.map(rec => rec.path))
286
+ for (const path of spaths) {
287
+ const body = cloneDeep(routes.find(r => r.path === path))
288
+ body.status = 'ACTIVE'
289
+ body.siteId = site.id + ''
290
+ await model.sanitizeFixture({ body, lookupValue: body })
291
+ try {
292
+ await model.createRecord(body, { noMagic: true, noReturn: true })
293
+ } catch (err) {}
294
+ }
295
+ }
141
296
  }
142
297
  }
143
298
 
144
- _getSetting = async (type, source) => {
299
+ /**
300
+ * Get authentication setting based on type and source
301
+ *
302
+ * @async
303
+ * @method
304
+ * @private
305
+ * @param {string} type - The type of authentication setting to retrieve.
306
+ * @param {string} source - The source of the authentication setting.
307
+ * @returns {object} - The authentication setting object.
308
+ */
309
+ _getAuthSetting = async (type, source) => {
145
310
  const { defaultsDeep } = this.app.lib.aneka
146
311
  const { get } = this.app.lib._
147
312
 
@@ -150,10 +315,21 @@ async function factory (pkgName) {
150
315
  return setting
151
316
  }
152
317
 
153
- _getToken = async (type, req, source) => {
318
+ /**
319
+ * Get authentication token based on type, request, and source
320
+ *
321
+ * @async
322
+ * @method
323
+ * @private
324
+ * @param {string} type - The type of authentication setting.
325
+ * @param {object} req - The request object.
326
+ * @param {string} source - The source of the authentication setting.
327
+ * @returns {string|boolean} - The token if found, otherwise false.
328
+ */
329
+ _getAuthToken = async (type, req, source) => {
154
330
  const { isEmpty } = this.app.lib._
155
331
 
156
- const setting = await this._getSetting(type, source)
332
+ const setting = await this._getAuthSetting(type, source)
157
333
  let token = req.headers[setting.headerKey.toLowerCase()]
158
334
  if (!['basic'].includes(type) &amp;&amp; isEmpty(token)) token = req.query[setting.qsKey]
159
335
  if (isEmpty(token)) {
@@ -164,161 +340,200 @@ async function factory (pkgName) {
164
340
  return token
165
341
  }
166
342
 
343
+ /**
344
+ * Build admin menu based on locals and request
345
+ *
346
+ * @async
347
+ * @method
348
+ * @param {object} locals - The locals object.
349
+ * @param {object} req - The request object.
350
+ * @returns {array} - The admin menu items.
351
+ */
167
352
  adminMenu = async (locals, req) => {
168
353
  if (!this.app.waibuAdmin) return
169
354
  const { getPluginPrefix } = this.app.waibu
355
+ const { findIndex } = this.app.lib._
170
356
  const prefix = getPluginPrefix(this.ns)
171
- return [{
172
- title: 'supportSystem',
357
+ const params = { action: 'list' }
358
+ const items = [{
359
+ title: 'manageSite',
173
360
  children: [
174
- { title: 'contactForm', href: `waibuAdmin:/${prefix}/contact-form/list` },
175
- { title: 'contactFormCat', href: `waibuAdmin:/${prefix}/contact-form-cat/list` },
176
- { title: 'ticket', href: `waibuAdmin:/${prefix}/ticket/list` },
177
- { title: 'ticketCat', href: `waibuAdmin:/${prefix}/ticket-cat/list` }
361
+ { title: 'siteProfile', href: `waibuAdmin:/${prefix}/site` },
362
+ { title: 'siteSetting', href: `waibuAdmin:/${prefix}/site-setting/:action`, params }
178
363
  ]
179
364
  }, {
180
- title: 'management',
365
+ title: 'manageUser',
181
366
  children: [
182
- { title: 'manageSite', href: `waibuAdmin:/${prefix}/site` },
183
- { title: 'manageUser', href: `waibuAdmin:/${prefix}/user/list` },
184
- { title: 'manageTeam', href: `waibuAdmin:/${prefix}/team/list` },
185
- { title: 'manageTeamUser', href: `waibuAdmin:/${prefix}/team-user/list` },
186
- { title: 'manageDownload', href: `waibuAdmin:/${prefix}/download/list` },
367
+ { title: 'userProfile', href: `waibuAdmin:/${prefix}/user/:action`, params },
368
+ { title: 'userSetting', href: `waibuAdmin:/${prefix}/user-setting/:action`, params },
187
369
  { title: 'resetUserPassword', href: `waibuAdmin:/${prefix}/reset-user-password` }
188
370
  ]
371
+ }, {
372
+ title: 'manageTeam',
373
+ children: [
374
+ { title: 'teamProfile', href: `waibuAdmin:/${prefix}/team/:action`, params },
375
+ { title: 'teamUser', href: `waibuAdmin:/${prefix}/team-user/:action`, params },
376
+ { title: 'teamSetting', href: `waibuAdmin:/${prefix}/team-setting/:action`, params }
377
+ ]
378
+ }, {
379
+ title: 'permission',
380
+ children: [
381
+ { title: 'secureGuard', href: `waibuAdmin:/${prefix}/secure-guard/:action`, params },
382
+ { title: 'anonymousGuard', href: `waibuAdmin:/${prefix}/anonymous-guard/:action`, params },
383
+ { title: 'queryGuard', href: `waibuAdmin:/${prefix}/query-guard/:action`, params },
384
+ { title: 'actionGuard', href: `waibuAdmin:/${prefix}/action-guard/:action`, params },
385
+ { title: 'attribGuard', href: `waibuAdmin:/${prefix}/attrib-guard/:action`, params }
386
+ ]
387
+ }, {
388
+ title: 'supportSystem',
389
+ children: [
390
+ { title: 'contactForm', href: `waibuAdmin:/${prefix}/contact-form/:action`, params },
391
+ { title: 'contactFormCat', href: `waibuAdmin:/${prefix}/contact-form-cat/:action`, params },
392
+ { title: 'ticket', href: `waibuAdmin:/${prefix}/ticket/:action`, params },
393
+ { title: 'ticketCat', href: `waibuAdmin:/${prefix}/ticket-cat/:action`, params }
394
+ ]
189
395
  }, {
190
396
  title: 'misc',
191
397
  children: [
192
- { title: 'userSession', href: `waibuAdmin:/${prefix}/session/list` }
398
+ { title: 'manageDownload', href: `waibuAdmin:/${prefix}/download/:action`, params }
193
399
  ]
194
400
  }]
195
- }
196
-
197
- getUser = async (rec, safe = true) => {
198
- const { omit, isPlainObject } = this.app.lib._
199
- let user
200
- if (isPlainObject(rec)) user = rec
201
- else {
202
- const mdl = this.app.dobo.getModel('SumbaUser')
203
- user = await mdl.getRecord(rec, { noHook: true, throwNotFound: false })
401
+ const sessionMenu = { title: 'userSession', href: `waibuAdmin:/${prefix}/x/session/:action`, params }
402
+ const cacheMenu = { title: 'cacheStorage', href: `waibuAdmin:/${prefix}/x/cache/:action`, params }
403
+ if (this.config.multiSite.enabled) {
404
+ items.unshift({
405
+ title: 'xSite',
406
+ children: [
407
+ { title: 'allSites', href: `waibuAdmin:/${prefix}/x/site/:action`, params },
408
+ { title: 'siteSetting', href: `waibuAdmin:/${prefix}/x/site-setting/:action`, params },
409
+ sessionMenu
410
+ ]
411
+ })
412
+ } else {
413
+ const idx = findIndex(items, i => i.title === 'misc')
414
+ if (idx > -1) items[idx].children.push(sessionMenu)
204
415
  }
205
- if (!user) return null
206
- return safe ? omit(user, this.unsafeUserFields) : user
207
- }
208
-
209
- mergeTeam = async (user, site) => {
210
- if (!user) return
211
- const { map, pick } = this.app.lib._
212
- user.teams = []
213
- const query = { userId: user.id, siteId: site.id }
214
- let mdl = this.app.dobo.getModel('SumbaTeamUser')
215
- const userTeam = await mdl.findAllRecord({ query })
216
- if (userTeam.length === 0) return
217
- delete query.userId
218
- query.id = { $in: map(userTeam, 'id') }
219
- query.status = 'ENABLED'
220
- mdl = this.app.dobo.getModel('SumbaTeam')
221
- const team = await mdl.findAllRecord({ query })
222
- if (team.length > 0) user.teams.push(...map(team, t => pick(t, ['id', 'alias'])))
223
- }
224
-
225
- getUserFromUsernamePassword = async (username = '', password = '', req) => {
226
- const { importPkg } = this.app.bajo
227
- const model = this.app.dobo.getModel('SumbaUser')
228
- await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
229
- const bcrypt = await importPkg('bajoExtra:bcrypt')
230
-
231
- const query = { username, provider: 'local' }
232
- const rows = await model.findRecord({ query }, { req, forceNoHidden: true, noHook: true })
233
- if (rows.length === 0) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
234
- const rec = rows[0]
235
- if (rec.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
236
- const verified = await bcrypt.compare(password, rec.password)
237
- if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
238
- return rec
416
+ if (this.app.bajoCache) {
417
+ const idx = findIndex(items, i => i.title === this.config.multiSite.enabled ? 'xSite' : 'misc')
418
+ if (idx > -1)items[idx].children.push(cacheMenu)
419
+ }
420
+ return items
239
421
  }
240
422
 
423
+ /**
424
+ * Create JWT from user record
425
+ *
426
+ * @async
427
+ * @method
428
+ * @param {object} rec - The user record object.
429
+ * @returns {object} - The JWT token and its expiration date.
430
+ */
241
431
  createJwtFromUserRecord = async (rec) => {
242
432
  const { importPkg } = this.app.bajo
243
433
  const { dayjs } = this.app.lib
244
- const { hash } = this.app.bajoExtra
245
434
  const { get, pick } = this.app.lib._
246
435
 
247
436
  const fastJwt = await importPkg('bajoExtra:fast-jwt')
248
437
  const { createSigner } = fastJwt
249
438
 
250
- const opts = pick(this.config.auth.common.jwt, ['expiresIn'])
439
+ const opts = pick(this.config.auth.common.jwt, ['expiresInDur'])
251
440
  opts.key = get(this.config, 'auth.common.jwt.secret')
252
441
  const sign = createSigner(opts)
253
- const apiKey = await hash(rec.password)
442
+ const apiKey = await this.hash(rec.token)
254
443
  const payload = { uid: rec.id, apiKey }
255
444
  const token = await sign(payload)
256
- const expiresAt = dayjs().add(opts.expiresIn).toDate()
445
+ const expiresAt = dayjs().add(opts.expiresInDur).toDate()
257
446
  return { token, expiresAt }
258
447
  }
259
448
 
449
+ /**
450
+ * Verify user session
451
+ *
452
+ * @async
453
+ * @method
454
+ * @param {object} req - The request object.
455
+ * @param {object} reply - The reply object.
456
+ * @param {string} source - The source of the authentication setting.
457
+ * @param {object} payload - The payload object.
458
+ * @returns {boolean} - True if the session is valid, otherwise false.
459
+ */
260
460
  verifySession = async (req, reply, source, payload) => {
261
- const { getUser } = this
262
461
  const { routePath } = this.app.waibu
462
+ const { query, params } = req
263
463
 
264
464
  if (!req.session) return false
265
465
  if (req.session.userId) {
266
- req.user = await getUser(req.session.userId)
466
+ req.user = await this.getUserById(req.session.userId, req)
267
467
  return true
268
468
  }
269
- const redir = routePath(this.config.redirect.signin, req)
469
+ const redir = routePath(this.config.redirect.signin, { query, params })
270
470
  req.session.ref = req.url
271
- throw this.error('_redirect', { redirect: redir })
471
+ throw this.error('_redirect', { path: redir })
272
472
  }
273
473
 
474
+ /**
475
+ * Verify API key
476
+ *
477
+ * @async
478
+ * @method
479
+ * @param {object} req - The request object.
480
+ * @param {object} reply - The reply object.
481
+ * @param {string} source - The source of the authentication setting.
482
+ * @param {object} payload - The payload object.
483
+ * @returns {boolean} - True if the API key is valid, otherwise false.
484
+ */
274
485
  verifyApiKey = async (req, reply, source, payload) => {
275
- const { merge } = this.app.lib._
276
- const { isMd5, hash } = this.app.bajoExtra
277
- const { getUser } = this
278
-
279
- let token = await this._getToken('apiKey', req, source)
280
- if (!isMd5(token)) return false
281
- token = await hash(token)
282
- const query = { token }
283
- const rows = await this.app.dobo.getModel('SumbaUser').findRecord({ query }, { req, noHook: true })
284
- if (rows.length === 0) throw this.error('invalidKey', merge({ statusCode: 401 }, payload))
285
- if (rows[0].status !== 'ACTIVE') throw this.error('userInactive', merge({ details: [{ field: 'status', error: 'inactive' }], statusCode: 401 }, payload))
286
- req.user = await getUser(rows[0])
486
+ const { merge, camelCase } = this.app.lib._
487
+ const checker = this.app.bajoExtra[camelCase(`is ${this.config.auth.common.apiKey.algo}`)]
488
+
489
+ let token = await this._getAuthToken('apiKey', req, source)
490
+ if (!checker(token)) return false
491
+ token = await this.hash(token)
492
+ const user = await this.getUserByToken(token, req)
493
+ if (!user) throw this.error('invalidKey', merge({ statusCode: 401 }, payload))
494
+ if (user.status !== 'ACTIVE') throw this.error('userInactive', merge({ details: [{ field: 'status', error: 'inactive' }], statusCode: 401 }, payload))
495
+ req.user = user
287
496
  return true
288
497
  }
289
498
 
499
+ /**
500
+ * Verify basic authentication
501
+ *
502
+ * @async
503
+ * @method
504
+ * @param {object} req - The request object.
505
+ * @param {object} reply - The reply object.
506
+ * @param {string} source - The source of the authentication setting.
507
+ * @param {object} payload - The payload object.
508
+ * @returns {boolean|string} - True if the basic authentication is valid, otherwise false or an error message.
509
+ */
290
510
  verifyBasic = async (req, reply, source, payload) => {
291
- const { getUserFromUsernamePassword } = this
292
- const { getUser } = this
293
511
  const { isEmpty, merge } = this.app.lib._
294
512
 
295
513
  const setHeader = async (setting, reply) => {
296
- const { isString } = this.app.lib._
297
-
298
514
  let header = setting.type
299
515
  const exts = []
300
- if (isString(setting.realm)) exts.push(`realm="${setting.realm}"`)
516
+ if (setting.realm) exts.push(`realm="${req.t('protectedArea')}"`)
301
517
  if (setting.useUtf8) exts.push('charset="UTF-8"')
302
518
  if (exts.length > 0) header += ` ${exts.join(', ')}`
303
519
  reply.header('WWW-Authenticate', header)
304
520
  reply.code(401)
305
521
  }
306
522
 
307
- const setting = await this._getSetting('basic', source)
523
+ const setting = await this._getAuthSetting('basic', source)
308
524
  let authInfo
309
525
  const parts = (req.headers.authorization ?? '').split(' ')
310
526
  if (parts[0] === setting.type) authInfo = parts[1]
311
527
  if (isEmpty(authInfo)) {
312
528
  if (setting.realm) {
313
529
  await setHeader(setting, reply)
314
- throw this.error(setting.warningMessage)
530
+ throw this.error(req.t('pleaseAuthenticate'), { statusCode: 403 })
315
531
  } else return false
316
532
  }
317
533
  const decoded = Buffer.from(authInfo, 'base64').toString()
318
534
  const [username, password] = decoded.split(':')
319
535
  try {
320
- const user = await getUserFromUsernamePassword(username, password, req)
321
- req.user = await getUser(user)
536
+ req.user = await this.getUserByUsernamePassword(username, password, req)
322
537
  } catch (err) {
323
538
  if (err.statusCode === 401 &amp;&amp; setting.realm) {
324
539
  await setHeader(setting, reply)
@@ -329,15 +544,25 @@ async function factory (pkgName) {
329
544
  return true
330
545
  }
331
546
 
547
+ /**
548
+ * Verify JWT authentication
549
+ *
550
+ * @async
551
+ * @method
552
+ * @param {object} req - The request object.
553
+ * @param {object} reply - The reply object.
554
+ * @param {string} source - The source of the authentication setting.
555
+ * @param {object} payload - The payload object.
556
+ * @returns {boolean} - True if the JWT authentication is valid, otherwise false.
557
+ */
332
558
  verifyJwt = async (req, reply, source, payload) => {
333
559
  const { importPkg } = this.app.bajo
334
- const { getUser } = this
335
560
  const { isEmpty, merge } = this.app.lib._
336
561
 
337
562
  const fastJwt = await importPkg('bajoExtra:fast-jwt')
338
563
  const { createVerifier } = fastJwt
339
- const setting = await this._getSetting('jwt', source)
340
- const token = await this._getToken('jwt', req, source)
564
+ const setting = await this._getAuthSetting('jwt', source)
565
+ const token = await this._getAuthToken('jwt', req, source)
341
566
  if (isEmpty(token)) return false
342
567
  const verifier = createVerifier({
343
568
  key: setting.secret,
@@ -346,10 +571,10 @@ async function factory (pkgName) {
346
571
  const decoded = await verifier(token)
347
572
  const id = decoded.payload.uid
348
573
  try {
349
- const rec = await this.app.dobo.getModel('SumbaUser').getRecord(id, { req, noHook: true })
350
- if (!rec) throw this.error('invalidToken', { statusCode: 401 })
351
- if (rec.status !== 'ACTIVE') throw this.error('userInactive', { details: [{ field: 'status', error: 'inactive' }], statusCode: 401 })
352
- req.user = await getUser(rec)
574
+ const user = await this.getUserById(id, req)
575
+ if (!user) throw this.error('invalidToken', { statusCode: 401 })
576
+ if (user.status !== 'ACTIVE') throw this.error('userInactive', { details: [{ field: 'status', error: 'inactive' }], statusCode: 401 })
577
+ req.user = user
353
578
  } catch (err) {
354
579
  merge(err, payload)
355
580
  throw err
@@ -357,111 +582,33 @@ async function factory (pkgName) {
357
582
  return true
358
583
  }
359
584
 
360
- checkPathsByTeam = ({ paths = [], method = 'GET', teams = [], guards = [] }) => {
361
- const { includes } = this.app.lib.aneka
585
+ /**
586
+ * Check route guard
587
+ *
588
+ * @method
589
+ * @param {Array} guards - The array of guard objects.
590
+ * @param {Array} paths - The array of paths to check.
591
+ * @returns {string|undefined} - The matched path or undefined if no match is found.
592
+ */
593
+ checkRouteGuard = (guards, paths) => {
362
594
  const { outmatch } = this.app.lib
363
-
364
- for (const item of guards) {
365
- const matchPath = outmatch(item.path)
366
- for (const path of paths) {
367
- if (matchPath(path)) {
368
- const matchMethods = outmatch(item.methods, { separator: false })
369
- if (matchMethods(method)) {
370
- if (item.teams.length === 0) return item
371
- if (includes(teams, item.teams)) return item
372
- }
373
- }
374
- }
375
- }
376
- }
377
-
378
- checkPathsByRoute = ({ paths = [], method = 'GET', guards = [] }) => {
379
- const { outmatch } = this.app.lib
380
-
381
- for (const item of guards) {
382
- const matchPath = outmatch(item.path)
383
- for (const path of paths) {
384
- if (matchPath(path)) {
385
- const matchMethods = outmatch(item.methods, { separator: false })
386
- if (matchMethods(method)) return item
387
- }
388
- }
389
- }
390
- }
391
-
392
- checkPathsByGuard = ({ guards, paths }) => {
393
- const { outmatch } = this.app.lib
394
- const matcher = outmatch(guards)
395
- let guarded
396
- for (const path of paths) {
397
- if (!guarded) guarded = matcher(path)
398
- }
399
- return guarded
400
- }
401
-
402
- getSite = async (hostname, useId) => {
403
- const { omit } = this.app.lib._
404
- const omitted = ['status']
405
-
406
- const mergeSetting = async (site) => {
407
- const { defaultsDeep } = this.app.lib.aneka
408
- const { parseObject } = this.app.lib
409
- const { trim, get, filter } = this.app.lib._
410
- const defSetting = {}
411
- const nsSetting = {}
412
- const names = this.app.getAllNs()
413
- const query = {
414
- ns: { $in: names },
415
- siteId: site.id
416
- }
417
- const all = await this.app.dobo.getModel('SumbaSiteSetting').findRecord({ query, limit: -1 })
418
- for (const ns of names) {
419
- nsSetting[ns] = {}
420
- defSetting[ns] = get(this, `app.${ns}.config.siteSetting`, {})
421
- const items = filter(all, { ns })
422
- for (const item of items) {
423
- let value = trim([item.value] ?? '')
424
- if (['[', '{'].includes(value[0])) value = JSON.parse(value)
425
- else if (Number(value)) value = Number(value)
426
- else if (['true', 'false'].includes(value)) value = value === 'true'
427
- nsSetting[ns][item.key] = value
428
- }
429
- }
430
- site.setting = parseObject(defaultsDeep({}, nsSetting, defSetting))
431
- // additional fields
432
- const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noHook: true })
433
- site.countryName = (country ?? {}).name ?? site.country
434
- }
435
-
436
- let site = {}
437
-
438
- if (!this.config.multiSite) {
439
- const resp = await this.app.dobo.getModel('SumbaSite').findRecord({ query: { alias: 'default' } }, { noHook: true })
440
- site = omit(resp[0], omitted)
441
- await mergeSetting(site)
442
- return site
443
- }
444
- let query
445
- if (useId) query = { id: hostname }
446
- else {
447
- query = {
448
- $or: [
449
- { hostname },
450
- { alias: hostname }
451
- ]
452
- }
453
- }
454
- const filter = { query, limit: 1 }
455
- const rows = await this.app.dobo.getModel('SumbaSite').findRecord(filter, { noHook: true })
456
- if (rows.length === 0) throw this.error('unknownSite')
457
- const row = omit(rows[0], omitted)
458
- if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
459
- site = row
460
- await mergeSetting(site)
461
- return site
595
+ const all = guards.map(item => item.path)
596
+ const isMatch = outmatch(all)
597
+ return paths.find(isMatch)
462
598
  }
463
599
 
464
- signout = async ({ req, reply, reason }) => {
600
+ /**
601
+ * Sign out user and redirect to the specified URL
602
+ *
603
+ * @async
604
+ * @method
605
+ * @param {object} options - The options object.
606
+ * @param {object} options.req - The request object.
607
+ * @param {object} options.reply - The reply object.
608
+ * @param {string} [options.reason] - The reason for signing out.
609
+ */
610
+ signout = async (options = {}) => {
611
+ const { req, reply, reason } = options
465
612
  const { runHook } = this.app.bajo
466
613
  const { getSessionId } = this.app.waibuMpa
467
614
  const sid = await getSessionId(req.headers.cookie)
@@ -474,7 +621,18 @@ async function factory (pkgName) {
474
621
  return reply.redirectTo(url, { query, params })
475
622
  }
476
623
 
477
- signin = async ({ user, req, reply }) => {
624
+ /**
625
+ * Sign in user and redirect to the specified URL
626
+ *
627
+ * @async
628
+ * @method
629
+ * @param {object} options - The options object.
630
+ * @param {object} options.req - The request object.
631
+ * @param {object} options.reply - The reply object.
632
+ * @param {object} options.user - The user object.
633
+ */
634
+ signin = async (options = {}) => {
635
+ const { req, reply, user } = options
478
636
  const { getSessionId } = this.app.waibuMpa
479
637
  const { runHook } = this.app.bajo
480
638
  const { isEmpty, omit } = this.app.lib._
@@ -491,21 +649,28 @@ async function factory (pkgName) {
491
649
  return reply.redirectTo(url, { query, params })
492
650
  }
493
651
 
494
- generatePassword = (req) => {
652
+ /**
653
+ * Generate a random password based on the configuration settings
654
+ *
655
+ * @method
656
+ * @param {object} req - The request object.
657
+ * @returns {string} - The generated password.
658
+ */
659
+ generatePassword = (req = {}) => {
660
+ const { get } = this.app.lib._
495
661
  const { generateId } = this.app.lib.aneka
496
- const cfg = req ? req.site.setting.sumba.userPassword : this.config.siteSetting.userPassword
662
+ const cfg = get(req, 'site.setting.sumba.userPassword', this.config.siteSetting.userPassword)
497
663
  let passwd = generateId()
498
- if (cfg.minLowercase) passwd += generateId({ pattern: 'abcdefghijklmnopqrstuvwxyz', length: cfg.minLowercase })
499
- if (cfg.minUppercase) passwd += generateId({ pattern: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', length: cfg.minUppercase })
500
- if (cfg.minSpecialChar) passwd += generateId({ pattern: '!@#$%*', length: cfg.minSpecialChar })
501
- if (cfg.minNumeric) passwd += generateId({ pattern: '0123456789', length: cfg.minNumeric })
664
+ if (cfg.minLowerCase > 0) passwd += generateId({ pattern: cfg.pattern.lowerCase, length: cfg.minLowercase })
665
+ if (cfg.minUpperCase > 0) passwd += generateId({ pattern: cfg.pattern.upperCase, length: cfg.minUppercase })
666
+ if (cfg.minSpecialChar > 0) passwd += generateId({ pattern: cfg.pattern.specialChar, length: cfg.minSpecialChar })
667
+ if (cfg.minNumeric > 0) passwd += generateId({ pattern: cfg.pattern.numeric, length: cfg.minNumeric })
502
668
  return passwd
503
669
  }
504
670
 
505
671
  pushDownload = async ({ description, worker, data, source, req, file, type }) => {
506
- const { getPlugin } = this.app.bajo
507
- const { createRecord } = getPlugin('waibuDb')
508
- const { push } = getPlugin('bajoQueue')
672
+ const { createRecord } = this.app.getPlugin('waibuDb')
673
+ const { push } = this.app.getPlugin('bajoQueue')
509
674
  description = description ?? file
510
675
  const jobQueue = {
511
676
  worker,
@@ -523,11 +688,1177 @@ async function factory (pkgName) {
523
688
  await push(jobQueue)
524
689
  }
525
690
 
691
+ /**
692
+ * Get API key from user ID by hashing the user's salt
693
+ *
694
+ * @async
695
+ * @method
696
+ * @param {string|number} id - The user ID.
697
+ * @returns {Promise&lt;string>} - A promise that resolves to the API key.
698
+ */
526
699
  getApiKeyFromUserId = async id => {
527
- const { hash } = this.app.bajoExtra
528
700
  const options = { forceNoHidden: true, noHook: true, noCache: true, attachment: true, mimeType: true }
529
- const resp = await this.app.dobo.getModel('SumbaUser').getRecord(id, options)
530
- return await hash(resp.salt)
701
+ const resp = await getModel('SumbaUser').getRecord(id, options)
702
+ return await this.hash(resp.salt)
703
+ }
704
+
705
+ /**
706
+ * Get a list of countries with their values and names
707
+ *
708
+ * @async
709
+ * @method
710
+ * @returns {Promise&lt;Array&lt;{ value: string|number, text: string }>>} - A promise that resolves to an array of country values and names.
711
+ */
712
+ getCountriesValues = async () => {
713
+ const { getModel } = this.app.dobo
714
+ const model = getModel('CdbCountry')
715
+ const items = await model.findAllRecord({}, { noMagic: true, dataOnly: true })
716
+ return items.map(item => ({ value: item.id, text: item.name }))
717
+ }
718
+
719
+ /**
720
+ * Method to send mail through Masohi Messaging System. It is a thin wrapper
721
+ * for {@link https://github.com/ardhi/masohi-mail|masohi-mail} send method.
722
+ *
723
+ * If both masohiMail and waibu are not loaded, nothing is delivered.
724
+ *
725
+ * @method
726
+ * @async
727
+ * @param {(string|Array)} tpl - Mail's template to use. If a string is given, the same template will be used for html &amp; plaintext versions. Otherwise, the first template will be used for html mail, and the second one is for it's plaintext version
728
+ * @param {Object} [params={}] - {@link https://github.com/ardhi/masohi-mail|masohi-mail}'s params object.
729
+ */
730
+ sendMail = async (tpl, { payload = {}, conn, source, options = {} } = {}) => {
731
+ if (!this.app.masohiMail || !this.app.waibu) return
732
+ conn = conn ?? 'masohiMail:default'
733
+ const { importModule } = this.app.bajo
734
+ const { get, isString } = this.app.lib._
735
+ const { generateId } = this.app.lib.aneka
736
+ const { render } = this.app.bajoTemplate
737
+ const buildLocals = await importModule('waibu:/lib/build-locals.js')
738
+
739
+ if (isString(tpl)) tpl = [tpl]
740
+ options.partial = false
741
+ const locals = await buildLocals.call(this, { params: payload.data, opts: options })
742
+ payload.from = payload.from ?? get(options, 'req.site.email', payload.from)
743
+ const opts = {
744
+ lang: get(options, 'req.lang'),
745
+ groupId: get(options, 'req.id', generateId())
746
+ }
747
+ payload.html = await render(tpl[0], locals, opts)
748
+ if (tpl[1]) payload.text = await render(tpl[1], locals, opts)
749
+ await this.app.masohiMail.send({ payload, source: source ?? this.ns, conn })
750
+ }
751
+
752
+ /**
753
+ * Reset token by generating a new salt and hashing it twice to create a new token.
754
+ *
755
+ * @async
756
+ * @method
757
+ * @param {string} [text] - Optional text to use as the salt. If not provided, a new salt will be generated.
758
+ * @returns {Promise&lt;{ salt: string, token: string }>} - A promise that resolves to an object containing the salt and token.
759
+ */
760
+ resetToken = async (text) => {
761
+ const { generateId } = this.app.lib.aneka
762
+ const salt = text ?? generateId()
763
+ const token = await this.hash(await this.hash(salt))
764
+ return { salt, token }
765
+ }
766
+
767
+ /**
768
+ * Generate a password validation rule based on the configuration settings.
769
+ *
770
+ * @async
771
+ * @method
772
+ * @param {object} req - The request object.
773
+ * @returns {object} - The Joi password validation rule.
774
+ */
775
+ passwordRule = async (req = {}) => {
776
+ const { get } = this.app.lib._
777
+ const { importPkg } = this.app.bajo
778
+ const joi = await importPkg('dobo:joi')
779
+ const joiPassword = joi.extend(joiPasswordExtendCore)
780
+ let password = joiPassword
781
+ .string()
782
+ .min(8)
783
+ .max(100)
784
+ .required()
785
+ const cfg = get(req, 'site.setting.sumba.userPassword', this.config.siteSetting.userPassword)
786
+ if (cfg.minUppeCase) password = password.minOfUppercase(cfg.minUpperCase)
787
+ if (cfg.minLowercase) password = password.minOfLowercase(cfg.minLowerCase)
788
+ if (cfg.minSpecialChar) password = password.minOfSpecialCharacters(cfg.minSpecialChar)
789
+ if (cfg.minNumeric) password = password.minOfNumeric(cfg.minNumeric)
790
+ if (cfg.noWhitespace) password = password.noWhiteSpaces()
791
+ if (cfg.latinOnlyChars) password = password.onlyLatinCharacters()
792
+ return password
793
+ }
794
+
795
+ /**
796
+ * Hash the given item using the specified algorithm from the configuration.
797
+ *
798
+ * @async
799
+ * @method
800
+ * @param {*} item - The item to be hashed.
801
+ * @returns {Promise&lt;string>} - A promise that resolves to the hashed value.
802
+ */
803
+ hash = async (item) => {
804
+ const { hash } = this.app.bajoExtra
805
+ return await hash(item, this.config.auth.common.apiKey.algo)
806
+ }
807
+
808
+ /**
809
+ * Fetch guards of the specified type from the database.
810
+ *
811
+ * @async
812
+ * @method
813
+ * @private
814
+ * @param {string} type - The type of guards to fetch.
815
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of guards.
816
+ */
817
+ _fetchGuards = async (type) => {
818
+ const { getModel } = this.app.dobo
819
+ const options = { noMagic: true, noCache: true, noDriverHook: true, dataOnly: true }
820
+ const filter = { query: { status: 'ACTIVE' } }
821
+ const results = await getModel(`Sumba${type}Guard`).findAllRecord(filter, options)
822
+ return results.map(result => {
823
+ result.teamIds = result.teamIds.map(item => item + '')
824
+ return result
825
+ })
826
+ }
827
+
828
+ /**
829
+ * Process and order the guards based on their path and weight.
830
+ *
831
+ * @method
832
+ * @private
833
+ * @param {Array} inputs - The array of guard inputs.
834
+ * @returns {Array} - The processed and ordered array of guards.
835
+ */
836
+ _getGuards = (inputs = []) => {
837
+ const { routePath } = this.app.waibu
838
+ const { orderBy } = this.app.lib._
839
+ const normal = orderBy(inputs.filter(input => {
840
+ try {
841
+ input.path = routePath(input.path)
842
+ } catch (err) {
843
+ return false
844
+ }
845
+ return input.path[0] !== '!'
846
+ }), ['weight', 'path'], ['desc', 'asc'])
847
+ const inverse = orderBy(inputs.filter(input => {
848
+ try {
849
+ input.path = routePath(input.path)
850
+ } catch (err) {
851
+ return false
852
+ }
853
+ return input.path[0] === '!'
854
+ }), ['weight', 'path'], ['desc', 'asc'])
855
+ return [...normal, ...inverse]
856
+ }
857
+
858
+ /**
859
+ * Get anonymous guards, optionally reloading them from the database.
860
+ *
861
+ * @async
862
+ * @method
863
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
864
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of anonymous guards.
865
+ */
866
+ getAnonymousGuards = async (reread) => {
867
+ if (!reread) return this.anonymousGuards
868
+ const guards = await this._fetchGuards('Anonymous')
869
+ this.anonymousGuards = this._getGuards(guards)
870
+ return this.anonymousGuards
871
+ }
872
+
873
+ /**
874
+ * Get secure guards, optionally reloading them from the database.
875
+ *
876
+ * @async
877
+ * @method
878
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
879
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of secure guards.
880
+ */
881
+ getSecureGuards = async (reread) => {
882
+ if (!reread) return this.secureGuards
883
+ const guards = await this._fetchGuards('Secure')
884
+ this.secureGuards = this._getGuards(guards)
885
+ return this.secureGuards
886
+ }
887
+
888
+ /**
889
+ * Get query guards, optionally reloading them from the database.
890
+ *
891
+ * @async
892
+ * @method
893
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
894
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of query guards.
895
+ */
896
+ getQueryGuards = async (reread) => {
897
+ if (!reread) return this.queryGuards
898
+
899
+ this.queryGuards = await this._fetchGuards('Query')
900
+ return this.queryGuards
901
+ }
902
+
903
+ /**
904
+ * Get action guards, optionally reloading them from the database.
905
+ *
906
+ * @async
907
+ * @method
908
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
909
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of action guards.
910
+ */
911
+ getActionGuards = async (reread) => {
912
+ if (!reread) return this.actionGuards
913
+
914
+ this.actionGuards = await this._fetchGuards('Action')
915
+ return this.actionGuards
916
+ }
917
+
918
+ /**
919
+ * Get attribute guards, optionally reloading them from the database.
920
+ *
921
+ * @async
922
+ * @method
923
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
924
+ * @returns {Promise&lt;Array>} - A promise that resolves to an array of attribute guards.
925
+ */
926
+ getAttribGuards = async (reread) => {
927
+ if (!reread) return this.attribGuards
928
+
929
+ this.attribGuards = await this._fetchGuards('Attrib')
930
+ return this.attribGuards
931
+ }
932
+
933
+ /**
934
+ * Get all loaded model names, optionally returning them as value-text pairs.
935
+ *
936
+ * @method
937
+ * @param {boolean} [asValue] - Whether to return the model names as value-text pairs.
938
+ * @returns {Array} - An array of model names or value-text pairs.
939
+ */
940
+ getModelNames = (asValue) => {
941
+ const values = this.app.dobo.models.map(item => item.name).sort()
942
+ return asValue ? values.map(item => ({ value: item, text: item })) : values
943
+ }
944
+
945
+ /**
946
+ * Gather all paths to check for a request.
947
+ *
948
+ * @method
949
+ * @param {Object} req - The request object.
950
+ * @returns {Array} - An array of paths to check.
951
+ */
952
+ pathsToCheck = (req) => {
953
+ const { isSet } = this.app.lib.aneka
954
+ const { uniq, without } = this.app.lib._
955
+ const items = [req.routeOptions.url, req.url].filter(url => isSet(url)).map(url => url.split('?')[0].split('#')[0])
956
+ return uniq(without(items, undefined, null))
957
+ }
958
+
959
+ /**
960
+ * Check and set the iconset for a request.
961
+ *
962
+ * @async
963
+ * @method
964
+ * @param {Object} req - The request object.
965
+ * @param {Object} reply - The reply object.
966
+ * @returns {Promise&lt;void>} - A promise that resolves when the iconset is checked and set.
967
+ */
968
+ checkIconset = async (req, reply) => {
969
+ const { get, isString } = this.app.lib._
970
+ const mpa = this.app.waibuMpa
971
+
972
+ if (!req.site) return
973
+ const siteIconset = get(req, 'site.setting.waibuMpa.iconset')
974
+ req.iconset = siteIconset ?? get(mpa, 'config.iconset.set', 'default')
975
+ const hiconset = req.headers['x-iconset']
976
+ if (isString(hiconset) &amp;&amp; mpa.getIconset(hiconset)) req.iconset = hiconset
977
+ req.iconset = req.iconset ?? 'default'
978
+ }
979
+
980
+ /**
981
+ * Check and set the theme for a request.
982
+ *
983
+ * @async
984
+ * @method
985
+ * @param {Object} req - The request object.
986
+ * @param {Object} reply - The reply object.
987
+ * @returns {Promise&lt;void>} - A promise that resolves when the theme is checked and set.
988
+ */
989
+ checkTheme = async (req, reply) => {
990
+ const { get, isString } = this.app.lib._
991
+ const mpa = this.app.waibuMpa
992
+
993
+ if (!req.site) return
994
+ const siteTheme = get(req, 'site.setting.waibuMpa.theme')
995
+ req.theme = siteTheme ?? get(mpa, 'config.theme.set', 'default')
996
+ const htheme = req.headers['x-theme']
997
+ if (isString(htheme) &amp;&amp; mpa.getTheme(htheme)) req.theme = htheme
998
+ req.theme = req.theme ?? 'default'
999
+ }
1000
+
1001
+ /**
1002
+ * Check and set the team for a request.
1003
+ *
1004
+ * @async
1005
+ * @method
1006
+ * @param {Object} req - The request object.
1007
+ * @param {Object} reply - The reply object.
1008
+ * @returns {Promise&lt;void>} - A promise that resolves when the team is checked and set.
1009
+ */
1010
+ checkTeam = async (req, reply) => {
1011
+ const { includes } = this.app.lib.aneka
1012
+ const { outmatch } = this.app.lib
1013
+
1014
+ if (req.user.isAdmin) return
1015
+ if (req.routeOptions.config.xSite &amp;&amp; req.user.isXSiteAdmin) return
1016
+
1017
+ const teamIds = req.user.teams.map(item => item.id + '')
1018
+ // if (req.user.teams.map(item => item.alias).length === 0) throw this.error('accessDenied', { statusCode: 403 })
1019
+
1020
+ const paths = this.pathsToCheck(req)
1021
+ const results = (await this.getSecureGuards()).filter(item => {
1022
+ if (item.siteId !== req.site.id + '' || item.path[0] === '!') return false
1023
+ return paths.some(outmatch([item.path]))
1024
+ })
1025
+ for (const result of results) {
1026
+ if (result.allTeams) continue
1027
+ if (!includes(teamIds, result.teamIds)) throw this.error('accessDenied', { statusCode: 403 })
1028
+ }
1029
+ // passed
1030
+ }
1031
+
1032
+ /**
1033
+ * Check and set the user for a request.
1034
+ *
1035
+ * @async
1036
+ * @method
1037
+ * @param {Object} req - The request object.
1038
+ * @param {Object} reply - The reply object.
1039
+ * @param {Object} source - The source object.
1040
+ * @returns {Promise&lt;boolean|void>} - A promise that resolves to a boolean indicating the result of the check or void.
1041
+ */
1042
+ checkUser = async (req, reply, source) => {
1043
+ const { merge, isEmpty, camelCase, get } = this.app.lib._
1044
+ const { routePath } = this.app.waibu
1045
+ const userId = get(req, 'session.userId')
1046
+ const setUser = async () => {
1047
+ if (!userId) return
1048
+ try {
1049
+ const user = await this.getUserById(userId, req)
1050
+ if (user) req.user = user
1051
+ else req.session.userId = null
1052
+ } catch (err) {
1053
+ console.log(err)
1054
+ req.session.userId = null
1055
+ }
1056
+ }
1057
+
1058
+ if (req.session) req.session.siteId = req.site.id
1059
+
1060
+ const webApp = get(req, 'routeOptions.config.webApp', 'waibu')
1061
+ if (!req.routeOptions.url) {
1062
+ if (!req.session) return
1063
+ await setUser()
1064
+ return
1065
+ }
1066
+
1067
+ const paths = this.pathsToCheck(req)
1068
+ let guards = (await this.getAnonymousGuards()).filter(item => item.siteId === req.site.id + '')
1069
+ const anonymous = this.checkRouteGuard(guards, paths)
1070
+ if (anonymous) {
1071
+ if (!userId) return false
1072
+ req.session.ref = req.url
1073
+ return reply.redirectTo(routePath(this.config.redirect.signout))
1074
+ }
1075
+ guards = (await this.getSecureGuards()).filter(item => item.siteId === req.site.id + '')
1076
+ const secure = this.checkRouteGuard(guards, paths)
1077
+ if (!secure) {
1078
+ if (userId) await setUser()
1079
+ return false // regular, unguarded path. Not secure &amp; not anonymous path
1080
+ }
1081
+ if (userId) {
1082
+ await setUser()
1083
+ return secure
1084
+ }
1085
+ const silentOnError = this.config.auth[webApp].silentOnError ?? this.config.auth.common.silentOnError
1086
+ const payload = silentOnError ? { noContent: true } : undefined
1087
+ const authMethods = this.config.auth[webApp].methods ?? []
1088
+ if (isEmpty(authMethods)) throw this.error('noAuthMethod', merge({ statusCode: 500 }, payload))
1089
+ let success
1090
+ for (const m of authMethods) {
1091
+ const handler = this[camelCase(`verify ${m}`)]
1092
+ if (!handler) throw this.error('invalidAuthMethod%s', m, merge({ statusCode: 500 }, payload))
1093
+ const check = await handler(req, reply, source, payload)
1094
+ if (check) {
1095
+ success = check
1096
+ break
1097
+ }
1098
+ }
1099
+ if (!success) throw this.error('accessDeniedNoAuth', merge({ statusCode: 403 }, payload))
1100
+ return secure
1101
+ }
1102
+
1103
+ /**
1104
+ * Check and set the Cross-site settings for a request.
1105
+ *
1106
+ * @async
1107
+ * @method
1108
+ * @param {Object} req - The request object.
1109
+ * @param {Object} reply - The reply object.
1110
+ * @returns {Promise&lt;void>} - A promise that resolves when the XSite is checked and set.
1111
+ */
1112
+ checkXSite = async (req, reply) => {
1113
+ const { get } = this.app.lib._
1114
+ if (!this.config.multiSite.enabled) return
1115
+ const config = get(req, 'routeOptions.config')
1116
+ if (!get(config, 'xSite') || ['/dashboard'].includes(config.pathSrc)) return
1117
+ if (!get(req, 'user.isXSiteAdmin')) throw this.error('accessDenied', { statusCode: 403 })
1118
+ }
1119
+
1120
+ /**
1121
+ * Check the route for a request.
1122
+ *
1123
+ * @async
1124
+ * @method
1125
+ * @param {Object} req - The request object.
1126
+ * @returns {Promise&lt;void>} - A promise that resolves when the route is checked.
1127
+ */
1128
+ checkRoute = async (req) => {
1129
+ const { routePath } = this.app.waibu
1130
+ const { outmatch } = this.app.lib
1131
+ const routes = req.getSetting('waibu:route.disabled', []).map(item => routePath(item, false))
1132
+ if (routes.length === 0) return
1133
+ const isMatch = outmatch(routes)
1134
+ const paths = this.pathsToCheck(req)
1135
+ if (paths.find(isMatch)) throw this.error('_notFound')
1136
+ }
1137
+
1138
+ /**
1139
+ * Parse namespace settings for a request.
1140
+ *
1141
+ * @method
1142
+ * @param {string} ns - The namespace.
1143
+ * @param {Object} setting - The setting object.
1144
+ * @param {Array} items - The items to parse.
1145
+ */
1146
+ parseNsSettings = (ns, setting, items) => {
1147
+ const { trim, set, isPlainObject, isArray, isEmpty, find } = this.app.lib._
1148
+ const { parseObject, dayjs } = this.app.lib
1149
+
1150
+ for (const item of items) {
1151
+ if (item.ns === '_var' || ns === '_var') continue
1152
+ let value = trim([item.value] ?? '')
1153
+ if (value[0] === '#' &amp;&amp; value[value.length - 1] === '#') {
1154
+ const val = value.slice(1, -1)
1155
+ const newValue = find(items, { ns: '_var', key: val })
1156
+ if (newValue) value = newValue.value
1157
+ }
1158
+ if (['[', '{'].includes(value[0]) &amp;&amp; [']', '}'].includes(value[value.length - 1])) {
1159
+ try {
1160
+ value = parseObject(JSON.parse(value))
1161
+ } catch (err) {}
1162
+ } else if (Number(value)) value = Number(value)
1163
+ else if (['true', 'false'].includes(value)) value = value === 'true'
1164
+ else {
1165
+ const dt = dayjs(value)
1166
+ if (dt.isValid()) value = dt.toDate()
1167
+ }
1168
+ if ((isPlainObject(value) || isArray(value)) &amp;&amp; isEmpty(value)) continue
1169
+ set(setting, `${ns}.${item.key}`, value)
1170
+ }
1171
+ }
1172
+
1173
+ /**
1174
+ * Get all fixtures for the specified alias, replacing any occurrences of '{alias}' in the fixture data with the provided alias.
1175
+ *
1176
+ * @async
1177
+ * @method
1178
+ * @param {string} [alias] - The alias for the fixtures.
1179
+ * @returns {Promise&lt;object>} - A promise that resolves to the fixtures data.
1180
+ */
1181
+ getAllFixtures = async (alias) => {
1182
+ const { readConfig } = this.app.bajo
1183
+ const { isEmpty, omit, kebabCase, isString } = this.app.lib._
1184
+ const { getModel } = this.app.dobo
1185
+ const { fastGlob } = this.app.lib
1186
+ const data = {}
1187
+
1188
+ function replaceAlias (alias, items) {
1189
+ for (const item of items) {
1190
+ for (const key in item) {
1191
+ const val = item[key]
1192
+ if (isString(val)) item[key] = val.replaceAll('{alias}', alias)
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ const formats = this.app.configHandlers.map(item => item.ext.slice(1))
1198
+ const overrideBase = `${this.app.getPluginDataDir('sumba')}/create-new-site-fixtures/${alias}`
1199
+ const models = this.app.dobo.models.filter(m => {
1200
+ const prop = m.properties.find(p => p.name === 'siteId')
1201
+ return !!prop
1202
+ }).map(m => m.name)
1203
+ models.unshift('SumbaSite')
1204
+ const files = (await fastGlob(`${overrideBase}/*.{${formats.join(',')}}`)).map(file => {
1205
+ const ext = path.extname(file)
1206
+ return file.slice(0, file.length - ext.length)
1207
+ })
1208
+ for (const m of models) {
1209
+ const model = getModel(m)
1210
+ const file = `${overrideBase}/${kebabCase(m)}`
1211
+ let fixtures = (await model.loadFixtures({ collectItems: true, noLookup: true })) ?? []
1212
+ if (files.includes(file)) {
1213
+ const items = await readConfig(file, { defValue: [] })
1214
+ if (!isEmpty(items)) fixtures = items
1215
+ }
1216
+ if (!Array.isArray(fixtures)) fixtures = [fixtures]
1217
+ if (fixtures.length === 0) continue
1218
+ replaceAlias(alias, fixtures)
1219
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1220
+ const omitted = ['_attachments', 'siteId']
1221
+ for (const item of ['createdAt', 'updatedAt', 'immutable']) {
1222
+ const props = model.properties.filter(prop => prop.feature === ('dobo:' + item)).map(prop => prop.name)
1223
+ if (props.length > 0) omitted.push(...props)
1224
+ }
1225
+ for (const idx in fixtures) {
1226
+ fixtures[idx] = omit(fixtures[idx], omitted)
1227
+ }
1228
+ data[m] = m === 'SumbaSite' ? fixtures[0] : fixtures
1229
+ }
1230
+ return data
1231
+ }
1232
+
1233
+ /**
1234
+ * Create references for the specified site using the provided data, options, and verbosity settings.
1235
+ *
1236
+ * @async
1237
+ * @method
1238
+ * @param {object} site - The site object for which to create references.
1239
+ * @param {object} data - The data object containing fixtures for the site.
1240
+ * @param {object} options - Options to pass to the createRecord method.
1241
+ * @param {boolean} verbose - Whether to log verbose output.
1242
+ */
1243
+ createRefs = async (site, data, options, verbose) => {
1244
+ const { isString } = this.app.lib._
1245
+ const { getModel } = this.app.dobo
1246
+ for (const m in data) {
1247
+ if (m === 'SumbaSite') continue
1248
+ const mdl = getModel(m)
1249
+ const fixtures = data[m]
1250
+ for (const f of fixtures) {
1251
+ f.siteId = site.id + ''
1252
+ const lv = { siteId: f.siteId }
1253
+ for (const key in f) {
1254
+ const val = f[key]
1255
+ if (isString(val) &amp;&amp; val.slice(0, 2) === '?:') f[key] = await mdl._simpleLookup(val.slice(2), lv, options)
1256
+ }
1257
+ await mdl.createRecord(f, { ...options, noFlash: true })
1258
+ }
1259
+ if (verbose) this.print.succeed('writingModel%s%s', mdl.name, fixtures.length)
1260
+ }
1261
+ if (verbose) this.print.succeed('populateRouteGuard')
1262
+ await this.populateRouteGuards([site])
1263
+ }
1264
+
1265
+ /**
1266
+ * Create a new site with the specified alias and optional hostname, using fixtures for initial data.
1267
+ *
1268
+ * @async
1269
+ * @method
1270
+ * @param {string} alias - The alias for the new site.
1271
+ * @param {string} [hostname] - The hostname for the new site.
1272
+ * @param {boolean} [verbose=false] - Whether to log verbose output.
1273
+ */
1274
+ createNewSite = async (alias, hostname, verbose) => {
1275
+ const { isEmpty } = this.app.lib._
1276
+ const { getModel } = this.app.dobo
1277
+
1278
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1279
+ let spin
1280
+ if (verbose) spin = this.print.spinner().start('processing...')
1281
+ const query = { $or: [{ alias }] }
1282
+ if (!isEmpty(hostname)) query.$or.push({ hostname })
1283
+ const model = getModel('SumbaSite')
1284
+ const site = await model.findOneRecord({ query })
1285
+ if (!isEmpty(site)) {
1286
+ if (verbose) spin.stop()
1287
+ throw this.error('aliasOrHostnameExists%s%s', alias, hostname ?? '')
1288
+ }
1289
+ // lets go
1290
+ const fixtures = await this.getAllFixtures(alias)
1291
+ if (verbose) spin.stop()
1292
+ fixtures.SumbaSite.alias = alias
1293
+ if (!isEmpty(hostname)) fixtures.SumbaSite.hostname = hostname
1294
+ await model.transaction(async (trx) => {
1295
+ const newSite = await model.createRecord(fixtures.SumbaSite, { trx, noHook: true })
1296
+ if (verbose) this.print.succeed('writingModel%s%s', model.name, 1)
1297
+ const options = { trx }
1298
+ await this.createRefs(newSite, fixtures, options, verbose)
1299
+ })
1300
+ if (verbose) this.print.info('done')
1301
+ }
1302
+
1303
+ /**
1304
+ * Remove references for the specified site using the provided options and verbosity settings.
1305
+ *
1306
+ * @async
1307
+ * @method
1308
+ * @param {object} site - The site object for which to remove references.
1309
+ * @param {object} options - Options to pass to the removeRecord method.
1310
+ * @param {boolean} verbose - Whether to log verbose output.
1311
+ */
1312
+ removeRefs = async (site, options, verbose) => {
1313
+ const { orderBy } = this.app.lib._
1314
+ const { getModel } = this.app.dobo
1315
+ const models = orderBy(this.app.dobo.models, ['buildLevel'], ['desc']).filter(m => {
1316
+ const prop = m.properties.find(p => p.name === 'siteId')
1317
+ return !!prop
1318
+ }).map(m => m.name)
1319
+ for (const m of models) {
1320
+ const mdl = getModel(m)
1321
+ const rows = await mdl.findAllRecord({ query: { siteId: site.id + '' } }, { ...options, dataOnly: true })
1322
+ const ids = rows.map(item => item.id)
1323
+ // TODO: backup
1324
+ if (ids.length === 0) continue
1325
+ for (const id of ids) {
1326
+ await mdl.removeRecord(id, { noReturn: true, ...options, noFlash: true })
1327
+ }
1328
+ if (verbose) this.print.succeed('removedFrom%s%s', mdl.name, ids.length)
1329
+ }
1330
+ }
1331
+
1332
+ /**
1333
+ * Remove a site with the specified alias, along with its references, using the provided verbosity settings.
1334
+ *
1335
+ * @async
1336
+ * @method
1337
+ * @param {string} alias - The alias of the site to remove.
1338
+ * @param {boolean} [verbose=false] - Whether to log verbose output.
1339
+ */
1340
+ removeSite = async (alias, verbose) => {
1341
+ const { isEmpty } = this.app.lib._
1342
+ const { getModel } = this.app.dobo
1343
+
1344
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1345
+ const model = getModel('SumbaSite')
1346
+ const query = { alias }
1347
+ const site = await model.findOneRecord({ query })
1348
+ if (isEmpty(site)) throw this.error('aliasNotFound%s', alias)
1349
+ await model.transaction(async (trx) => {
1350
+ const options = { trx, noHook: true }
1351
+ await this.removeRefs(site, options, verbose)
1352
+ await model.removeRecord(site.id, { noReturn: true, trx, noHook: true })
1353
+ if (verbose) this.print.succeed('removedFrom%s%s', model.name, 1)
1354
+ })
1355
+ if (verbose) this.print.info('done')
1356
+ }
1357
+
1358
+ /**
1359
+ * Get site information based on the provided input, which can be either a hostname or an ID. If multi-site is enabled, it will fetch the site based on the hostname or ID; otherwise, it will return the default site.
1360
+ *
1361
+ * @async
1362
+ * @method
1363
+ * @param {string|number} input - The input value, which can be either a hostname or an ID.
1364
+ * @param {boolean} [byId=false] - Whether to fetch the site by ID.
1365
+ * @returns {object} The site information.
1366
+ */
1367
+ getSite = async (input, byId = false) => {
1368
+ const { omit } = this.app.lib._
1369
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1370
+ const omitted = ['status']
1371
+
1372
+ let site = {}
1373
+ const mergeSetting = async (site) => {
1374
+ const { defaultsDeep, isSet } = this.app.lib.aneka
1375
+ const { get, filter } = this.app.lib._
1376
+ const defSetting = {}
1377
+ const nsSetting = {}
1378
+ const names = this.app.getAllNs()
1379
+ const query = {
1380
+ ns: { $in: names },
1381
+ siteId: site.id + ''
1382
+ }
1383
+ const all = await this.app.dobo.getModel('SumbaSiteSetting').findAllRecord({ query })
1384
+ for (const ns of names) {
1385
+ const item = get(this, `app.${ns}.config.siteSetting`)
1386
+ if (isSet(item)) defSetting[ns] = item
1387
+ const items = filter(all, { ns })
1388
+ this.parseNsSettings(ns, nsSetting, items)
1389
+ }
1390
+ site.setting = defaultsDeep({}, nsSetting, defSetting)
1391
+ // additional fields
1392
+ const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noMagic: true })
1393
+ site.countryName = (country ?? {}).name ?? site.country
1394
+ }
1395
+
1396
+ if (!this.config.multiSite.enabled) {
1397
+ const filter = { query: { alias: 'default' } }
1398
+ const key = 'dobo|SumbaSite|getSite|default'
1399
+ if (getCache) {
1400
+ site = await getCache({ key })
1401
+ if (site) return site
1402
+ }
1403
+ const resp = await this.app.dobo.getModel('SumbaSite').findOneRecord(filter, { noHook: true })
1404
+ site = omit(resp, omitted)
1405
+ await mergeSetting(site)
1406
+ if (setCache) {
1407
+ await setCache({ key, value: site, ttl: this.config.cacheTtl.getSiteDur })
1408
+ }
1409
+ return site
1410
+ }
1411
+ let query
1412
+ if (byId) query = { id: input }
1413
+ else query = { hostname: input }
1414
+ const key = `dobo|SumbaSite|getSite|multiSite|${input}`
1415
+ if (getCache) {
1416
+ site = await getCache({ key })
1417
+ if (site) return JSON.parse(site)
1418
+ }
1419
+ let row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
1420
+ if (!row) {
1421
+ if (this.config.multiSite.catchAll) {
1422
+ query = { alias: this.config.multiSite.catchAll === true ? 'default' : this.config.multiSite.catchAll }
1423
+ row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
1424
+ }
1425
+ if (!row) throw this.error('unknownSite')
1426
+ }
1427
+ if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
1428
+ site = omit(row, omitted)
1429
+ await mergeSetting(site)
1430
+ if (setCache) {
1431
+ await setCache({ key, value: JSON.stringify(site), ttl: this.config.cacheTtl.getSiteDur })
1432
+ }
1433
+ return site
1434
+ }
1435
+
1436
+ /**
1437
+ * Merge team information into the user object.
1438
+ *
1439
+ * @async
1440
+ * @method
1441
+ * @param {object} user - The user object to merge team information into.
1442
+ * @param {object} req - The request object.
1443
+ */
1444
+ mergeTeam = async (user, req) => {
1445
+ const { map, pick } = this.app.lib._
1446
+ const { getModel } = this.app.dobo
1447
+ user.teams = []
1448
+ const query = { userId: user.id + '', siteId: user.siteId, status: 'ACTIVE' }
1449
+ let mdl = getModel('SumbaTeamUser')
1450
+ const userTeam = await mdl.findAllRecord({ query })
1451
+ if (userTeam.length === 0) return
1452
+ delete query.userId
1453
+ const idProp = mdl.getProperty('id')
1454
+ const $in = userTeam.map(item => ['integer', 'smallint'].includes(idProp.type) ? parseInt(item.teamId) : item.teamId)
1455
+ query.id = { $in }
1456
+ mdl = getModel('SumbaTeam')
1457
+ const teams = await mdl.findAllRecord({ query })
1458
+ if (teams.length > 0) {
1459
+ delete query.id
1460
+ delete query.status
1461
+ query.teamId = { $in: teams.map(t => t.id + '') }
1462
+ mdl = getModel('SumbaTeamSetting')
1463
+ const items = await mdl.findAllRecord({ query })
1464
+ for (const team of teams) {
1465
+ const names = map(items, 'ns')
1466
+ const item = pick(team, ['id', 'alias'])
1467
+ item.setting = {}
1468
+ for (const ns of names) {
1469
+ this.parseNsSettings(ns, item.setting, items.filter(s => s.teamId === (team.id + '')))
1470
+ }
1471
+ user.teams.push(item)
1472
+ }
1473
+ }
1474
+ user.isXSiteAdmin = this.config.xSiteAdmins.includes(`${req.site.alias}:${user.username}`)
1475
+ user.isAdmin = user.teams.some(t => t.alias === 'administrator')
1476
+ for (const field of this.unsafeUserFields) {
1477
+ delete user[field]
1478
+ }
1479
+ }
1480
+
1481
+ /**
1482
+ * Get a user by their ID.
1483
+ *
1484
+ * @async
1485
+ * @method
1486
+ * @param {string|number} id - The ID of the user to retrieve.
1487
+ * @param {object} req - The request object.
1488
+ * @returns {object|null} The user object if found, otherwise null.
1489
+ */
1490
+ getUserById = async (id, req) => {
1491
+ const { getModel } = this.app.dobo
1492
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1493
+ const key = `dobo|SumbaUser|getUserById|${id}`
1494
+ let user
1495
+ if (getCache) {
1496
+ user = await getCache({ key })
1497
+ if (user) return JSON.parse(user)
1498
+ }
1499
+ user = await getModel('SumbaUser').getRecord(id, { noHook: true, noDriverHook: true, throwNotFound: false, req })
1500
+ if (!user) return
1501
+ await this.mergeTeam(user, req)
1502
+ if (setCache) {
1503
+ await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByIdDur })
1504
+ }
1505
+ return user
1506
+ }
1507
+
1508
+ /**
1509
+ * Get a user by their token.
1510
+ *
1511
+ * @async
1512
+ * @method
1513
+ * @param {string} token - The token of the user to retrieve.
1514
+ * @param {object} req - The request object.
1515
+ * @returns {object|null} The user object if found, otherwise null.
1516
+ */
1517
+ getUserByToken = async (token, req) => {
1518
+ const { getModel } = this.app.dobo
1519
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1520
+ const key = `dobo|SumbaUser|getUserByToken|${token}`
1521
+ let user
1522
+ if (getCache) {
1523
+ user = await getCache({ key })
1524
+ if (user) return JSON.parse(user)
1525
+ }
1526
+ user = await getModel('SumbaUser').findOneRecord({ query: { token } }, { noHook: true, noDriverHook: true, throwNotFound: false, req })
1527
+ if (!user) return
1528
+ await this.mergeTeam(user, req)
1529
+ if (setCache) {
1530
+ await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByTokenDur })
1531
+ }
1532
+ return user
1533
+ }
1534
+
1535
+ getUserByUsernamePassword = async (username = '', password = '', req) => {
1536
+ const { getModel } = this.app.dobo
1537
+ const { importPkg } = this.app.bajo
1538
+ const model = getModel('SumbaUser')
1539
+ await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
1540
+ const bcrypt = await importPkg('bajoExtra:bcrypt')
1541
+
1542
+ const query = { username, provider: 'local', siteId: req.site.id + '' }
1543
+ const user = await model.findOneRecord({ query }, { req, forceNoHidden: true, noHook: true, noDriverHook: true })
1544
+ if (!user) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
1545
+ if (user.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
1546
+ const verified = await bcrypt.compare(password, user.password)
1547
+ if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
1548
+ await this.mergeTeam(user, req)
1549
+ return user
1550
+ }
1551
+
1552
+ /**
1553
+ * Clear the cache for a specific site.
1554
+ *
1555
+ * @async
1556
+ * @method
1557
+ * @param {string|number} id - The ID of the site.
1558
+ * @param {object} result - The result object containing site data.
1559
+ */
1560
+ clearCacheSite = async (id, result) => {
1561
+ if (!this.app.bajoCache) return
1562
+ const { clear } = this.app.bajoCache ?? {}
1563
+ const { get } = this.app.lib._
1564
+ await clear({ key: 'dobo|SumbaSite|getSite|default' })
1565
+ await clear({ key: `dobo|SumbaSite|getSite|multiSite|${id}` })
1566
+ await clear({ key: `dobo|SumbaSite|getSite|multiSite|${get(result, 'data.hostname', get(result, 'oldData.hostname'))}` })
1567
+ }
1568
+
1569
+ /**
1570
+ * Clear the cache for a specific user.
1571
+ *
1572
+ * @async
1573
+ * @method
1574
+ * @param {string|number} id - The ID of the user.
1575
+ * @param {object} result - The result object containing user data.
1576
+ */
1577
+ clearCacheUser = async (id, result) => {
1578
+ if (!this.app.bajoCache) return
1579
+ const { clear } = this.app.bajoCache ?? {}
1580
+ const { get } = this.app.lib._
1581
+ const token = get(result, 'data.token', get(result, 'oldData.token', ''))
1582
+ await clear({ key: `dobo|SumbaUser|getUserById|${id}` })
1583
+ await clear({ key: `dobo|SumbaUser|getUserByToken|${token}` })
1584
+ }
1585
+
1586
+ /**
1587
+ * Filter model data based on settings.
1588
+ *
1589
+ * @method
1590
+ * @param {object} opts - The options object.
1591
+ * @param {object} opts.model - The model object.
1592
+ * @param {string} opts.field - The field to filter.
1593
+ * @param {object} [opts.options={}] - Additional options.
1594
+ * @returns {object} The filtered results and operation values.
1595
+ */
1596
+ filterModelFromSetting = (opts = {}) => {
1597
+ const { model, field, options = {} } = opts
1598
+ const { isEmpty, isArray, set } = this.app.lib._
1599
+ const { isSet } = this.app.lib.aneka
1600
+ const { req } = options
1601
+ const opValue = req.getSetting(`sumba:queryGuard.${field}`, {})
1602
+ const results = []
1603
+ const prop = model.getProperty(field)
1604
+ for (const op of ['in', 'nin', 'inOrEmpty']) {
1605
+ if (isEmpty(opValue[op]) || !isArray(opValue[op])) continue
1606
+ if (op === 'inOrEmpty') {
1607
+ const val = set({}, field, set({}, '$in', opValue[op]))
1608
+ const nl = set({}, field, { $eq: null })
1609
+ const item = { $or: [val, nl] }
1610
+ let v
1611
+ if (['string', 'text'].includes(prop.type)) v = ''
1612
+ else if (['integer', 'smallint', 'float', 'double'].includes(prop.type)) v = 0
1613
+ if (isSet(v)) {
1614
+ const bl = set({}, field, { $eq: v })
1615
+ item.$or.push(bl)
1616
+ }
1617
+ results.push(item)
1618
+ } else results.push(set({}, field, set({}, '$' + op, opValue[op])))
1619
+ }
1620
+ return { results, opValue }
1621
+ }
1622
+
1623
+ /**
1624
+ * Apply query guards to the provided query.
1625
+ *
1626
+ * @async
1627
+ * @method
1628
+ * @param {object} [opts={}] - The options object.
1629
+ * @param {object} opts.model - The model object.
1630
+ * @param {object} [opts.q={}] - The query object.
1631
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1632
+ * @param {object} [opts.options={}] - Additional options.
1633
+ */
1634
+ runQueryGuard = async (opts = {}) => {
1635
+ const { model, q = {}, teamIds = [], options = {} } = opts
1636
+ const { set, orderBy, isEmpty, isArray } = this.app.lib._
1637
+ const { includes } = this.app.lib.aneka
1638
+ const { sanitizeByType } = this.app.dobo
1639
+ const { req } = options
1640
+ const results = []
1641
+
1642
+ const guards = await this.getQueryGuards()
1643
+ const fields = model.getNonVirtualProperties().map(prop => prop.name)
1644
+ const filterFn = item => {
1645
+ const bySiteId = item.siteId === req.site.id + ''
1646
+ const byModel = item.models.includes(model.name)
1647
+ const byFields = fields.includes(item.field)
1648
+ return bySiteId &amp;&amp; byModel &amp;&amp; byFields
1649
+ }
1650
+
1651
+ const rules = orderBy(guards.filter(filterFn), ['field'])
1652
+ for (const field of fields) {
1653
+ if (!model.getNonVirtualProperties(true).includes(field)) continue // or, should it throws exception instead?
1654
+ const inSetting = this.filterModelFromSetting({ model, field, options })
1655
+ if (inSetting.results.length > 0) inSetting.results.push(...inSetting.results)
1656
+ const prop = model.getProperty(field)
1657
+ const items = rules.filter(item => item.field === field)
1658
+ for (const item of items) {
1659
+ let values = item.value.map(val => {
1660
+ return sanitizeByType(val, prop.type, { strict: true, inputFormat: 'string', model: model.name })
1661
+ })
1662
+ const op = item.condition.toLowerCase()
1663
+ if (['in', 'nin'].includes(op) &amp;&amp; !isEmpty(inSetting.opValue[op]) &amp;&amp; isArray(inSetting.opValue[op])) values = values.filter(val => inSetting.opValue[op].includes(val))
1664
+ if (isEmpty(values)) continue
1665
+ let value
1666
+ if (['in', 'nin'].includes(op)) value = set({}, '$' + op, values)
1667
+ else if (op === 'between') value = { $gte: values[0], $lte: values[1] }
1668
+ else value = set({}, '$' + op, values[0])
1669
+ const teamOk = item.allTeams ? true : (item.teamIds.length === 0 ? false : includes(item.teamIds, teamIds))
1670
+ if (!teamOk) throw this.error('_abortAction')
1671
+ results.push(set({}, field, value))
1672
+ }
1673
+ }
1674
+ q.$and.push(...results)
1675
+ }
1676
+
1677
+ /**
1678
+ * Apply attribute guards to the provided model.
1679
+ *
1680
+ * @async
1681
+ * @method
1682
+ * @param {object} [opts={}] - The options object.
1683
+ * @param {object} opts.model - The model object.
1684
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1685
+ * @param {object} [opts.options={}] - Additional options.
1686
+ */
1687
+ runAttribGuard = async (opts = {}) => {
1688
+ const { model, teamIds = [], options = {} } = opts
1689
+ const { uniq } = this.app.lib._
1690
+ const { includes } = this.app.lib.aneka
1691
+ const { req } = options
1692
+ const results = []
1693
+
1694
+ const guards = await this.getAttribGuards()
1695
+ const filterFn = item => {
1696
+ const bySiteId = item.siteId === req.site.id + ''
1697
+ const byModel = item.models.includes(model.name)
1698
+ const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
1699
+ return bySiteId &amp;&amp; byModel &amp;&amp; byTeamId
1700
+ }
1701
+ guards.filter(filterFn).forEach(item => results.push(...item.hiddenFields))
1702
+ options.hidden = options.hidden ?? []
1703
+ options.hidden.push(...results)
1704
+ options.hidden = uniq(options.hidden)
1705
+ }
1706
+
1707
+ /**
1708
+ * Get the team IDs and aliases for the user in the request.
1709
+ *
1710
+ * @method
1711
+ * @param {object} req - The request object.
1712
+ * @returns {object} An object containing the team IDs and aliases.
1713
+ */
1714
+ getTeamIdsAndAliases = (req) => {
1715
+ const { get } = this.app.lib._
1716
+ const teams = get(req, 'user.teams', [])
1717
+ const teamIds = teams.map(team => team.id + '')
1718
+ const aliases = teams.map(team => team.alias)
1719
+ return { teamIds, aliases }
1720
+ }
1721
+
1722
+ /**
1723
+ * Rebuild the filter for the provided model.
1724
+ *
1725
+ * @async
1726
+ * @method
1727
+ * @param {object} model - The model object.
1728
+ * @param {object} [filter={}] - The filter object.
1729
+ * @param {object} [options={}] - Additional options.
1730
+ * @returns {Promise&lt;object>} The rebuilt filter.
1731
+ */
1732
+ rebuildFilter = async (model, filter = {}, options = {}) => {
1733
+ const { isEmpty, get, keys } = this.app.lib._
1734
+ const { req } = options
1735
+ const allowEmpty = !get(this, `app.${model.ns}.config.sumba.noEmptyQuery`, []).includes(model.name)
1736
+ const hasSiteId = model.hasProperty('siteId')
1737
+ const hasUserId = model.hasProperty('userId')
1738
+ const hasTeamId = model.hasProperty('teamId')
1739
+ const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
1740
+ const q = { $and: [] }
1741
+
1742
+ filter.query = filter.query ?? {}
1743
+ if (!isEmpty(filter.query)) {
1744
+ if (filter.query.$and) q.$and.push(...filter.query.$and)
1745
+ else q.$and.push(filter.query)
1746
+ }
1747
+ if (req.routeOptions.config.xSite) {
1748
+ filter.query = q
1749
+ return
1750
+ }
1751
+ if (hasSiteId) q.$and.push({ siteId: req.site.id + '' })
1752
+ if (aliases.includes('administrator')) {
1753
+ if (get(req, 'site.alias') === 'default') {
1754
+ filter.query = q
1755
+ return
1756
+ }
1757
+ const fields = keys(req.getSetting('sumba:queryGuard', {}))
1758
+ const results = []
1759
+ for (const field of fields) {
1760
+ if (!model.hasProperty(field)) continue
1761
+ const inSetting = this.filterModelFromSetting({ model, field, options })
1762
+ if (inSetting.results.length > 0) results.push(...inSetting.results)
1763
+ }
1764
+ if (results.length > 0) q.$and.push(...results)
1765
+ filter.query = q
1766
+ return
1767
+ }
1768
+ if (isEmpty(req.user)) {
1769
+ if (q.$and.length === 0 &amp;&amp; !allowEmpty) throw this.error('_emptyColumnQuery')
1770
+ filter.query = q
1771
+ return
1772
+ }
1773
+
1774
+ const condUserId = {
1775
+ $or: [
1776
+ { userId: req.user.id + '' },
1777
+ { userId: { $eq: null } }
1778
+ ]
1779
+ }
1780
+
1781
+ const condTeamId = {
1782
+ $or: [
1783
+ { teamId: { $in: teamIds } },
1784
+ { teamId: { $eq: null } }
1785
+ ]
1786
+ }
1787
+
1788
+ if (hasTeamId) {
1789
+ if (hasUserId) q.$and.push({ $or: [condTeamId, condUserId] })
1790
+ else q.$and.push(condTeamId)
1791
+ } else if (hasUserId) q.$and.push(condUserId)
1792
+
1793
+ await this.runQueryGuard({ model, q, teamIds, options, allowEmpty })
1794
+ await this.runAttribGuard({ model, teamIds, options })
1795
+ if (q.$and.length === 0 &amp;&amp; !allowEmpty) throw this.error('_emptyColumnQuery')
1796
+ filter.query = q
1797
+ }
1798
+
1799
+ /**
1800
+ * Apply query hook to the provided model.
1801
+ *
1802
+ * @async
1803
+ * @method
1804
+ * @param {object} model - The model object.
1805
+ * @param {string|number} id - The ID of the model.
1806
+ * @param {object} options - Additional options.
1807
+ * @returns {object} The result of the model hook.
1808
+ */
1809
+ applyQueryHook = async (model, id, options = {}) => {
1810
+ const { isEmpty } = this.app.lib._
1811
+ const { req = {} } = options
1812
+ if (options.noAutoFilter || isEmpty(req) || isEmpty(req.site)) return
1813
+
1814
+ const filter = {}
1815
+ await this.rebuildFilter(model, filter, options)
1816
+ if (filter.query.$and) filter.query.$and.push({ id })
1817
+ else filter.query.id = id
1818
+ const row = await model.findOneRecord(filter, { count: false })
1819
+ if (!row) throw this.app.dobo.error('recordNotFound%s%s', id, this.name, { statusCode: 404 })
1820
+ }
1821
+
1822
+ /**
1823
+ * Apply action hook to the provided model.
1824
+ *
1825
+ * @async
1826
+ * @method
1827
+ * @param {object} [opts={}] - The options object.
1828
+ * @param {object} opts.model - The model object.
1829
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1830
+ * @param {object} [opts.options={}] - Additional options.
1831
+ */
1832
+ applyActionHook = async (opts = {}) => {
1833
+ const { model, options = {} } = opts
1834
+ const { includes } = this.app.lib.aneka
1835
+ const { req } = options
1836
+ const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
1837
+ if (aliases.includes('administrator')) return
1838
+
1839
+ const actions = {
1840
+ READ: ['findOneRecord', 'findRecord', 'countRecord', 'getRecord'],
1841
+ EXPORT: ['findAllRecord'],
1842
+ CREATE: ['createRecord', 'bulkCreateRecord'],
1843
+ UPDATE: ['updateRecord', 'upsertRecord'],
1844
+ DELETE: ['removeRecord']
1845
+ }
1846
+
1847
+ const guards = await this.getActionGuards()
1848
+ const filterFn = item => {
1849
+ const bySiteId = item.siteId === req.site.id + ''
1850
+ const byModel = item.models.includes(model.name)
1851
+ const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
1852
+ return bySiteId &amp;&amp; byModel &amp;&amp; byTeamId
1853
+ }
1854
+ let abort = false
1855
+ for (const item of guards.filter(filterFn)) {
1856
+ if (item.value.includes('*')) continue
1857
+ for (const action in actions) {
1858
+ if (actions[action].includes(options.action) &amp;&amp; !item.value.includes(action)) abort = true
1859
+ }
1860
+ }
1861
+ if (abort) throw this.error('accessDenied', { statusCode: 403 })
531
1862
  }
532
1863
  }
533
1864
 
@@ -535,4 +1866,4 @@ async function factory (pkgName) {
535
1866
  }
536
1867
 
537
1868
  export default factory
538
- </code></pre></article></section></div></div></div><div class="search-container" id="PkfLWpAbet" style="display:none"><div class="wrapper" id="iCxFxjkHbP"><button class="icon-button search-close-button" id="VjLlGakifb" aria-label="close search"><svg><use xlink:href="#close-icon"></use></svg></button><div class="search-box-c"><svg><use xlink:href="#search-icon"></use></svg> <input type="text" id="vpcKVYIppa" class="search-input" placeholder="Search..." autofocus></div><div class="search-result-c" id="fWwVHRuDuN"><span class="search-result-c-text">Type anything to view search result</span></div></div></div><div class="mobile-menu-icon-container"><button class="icon-button" id="mobile-menu" data-isopen="false" aria-label="menu"><svg><use xlink:href="#menu-icon"></use></svg></button></div><div id="mobile-sidebar" class="mobile-sidebar-container"><div class="mobile-sidebar-wrapper"><a href="/" class="sidebar-title sidebar-title-anchor">Sumba API</a><div class="mobile-nav-links"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/sumba" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/sumba" target="">Github</a></div><div class="navbar-item"><a id="" href="https://sumba.bajo.app/" target="">Sumba</a></div><div class="navbar-item"><a id="" href="https://bajo.app/" target="">Bajo</a></div></div><div class="mobile-sidebar-items-c"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="Sumba.html">Sumba</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div><div class="mobile-navbar-actions"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div></div></div><script type="text/javascript" src="scripts/core.min.js"></script><script src="scripts/search.min.js" defer="defer"></script><script src="scripts/third-party/fuse.js" defer="defer"></script><script type="text/javascript">var tocbotInstance=tocbot.init({tocSelector:"#eed4d2a0bfd64539bb9df78095dec881",contentSelector:".main-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0,scrollContainer:".main-content",headingsOffset:130,onClick:bringLinkToView})</script></body></html>
1869
+ </code></pre></article></section></div></div></div><div class="search-container" id="PkfLWpAbet" style="display:none"><div class="wrapper" id="iCxFxjkHbP"><button class="icon-button search-close-button" id="VjLlGakifb" aria-label="close search"><svg><use xlink:href="#close-icon"></use></svg></button><div class="search-box-c"><svg><use xlink:href="#search-icon"></use></svg> <input type="text" id="vpcKVYIppa" class="search-input" placeholder="Search..." autofocus></div><div class="search-result-c" id="fWwVHRuDuN"><span class="search-result-c-text">Type anything to view search result</span></div></div></div><div class="mobile-menu-icon-container"><button class="icon-button" id="mobile-menu" data-isopen="false" aria-label="menu"><svg><use xlink:href="#menu-icon"></use></svg></button></div><div id="mobile-sidebar" class="mobile-sidebar-container"><div class="mobile-sidebar-wrapper"><a href="/" class="sidebar-title sidebar-title-anchor">Sumba API</a><div class="mobile-nav-links"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/sumba" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/sumba" target="">Github</a></div><div class="navbar-item"><a id="" href="https://sumba.bajo.app/" target="">Sumba</a></div><div class="navbar-item"><a id="" href="https://bajo.app/" target="">Bajo</a></div></div><div class="mobile-sidebar-items-c"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="Sumba.html">Sumba</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#TConfig">TConfig</a></div><div class="sidebar-section-children"><a href="global.html#TTokenBody">TTokenBody</a></div><div class="sidebar-section-children"><a href="global.html#TTokenData">TTokenData</a></div><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div><div class="mobile-navbar-actions"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div></div></div><script type="text/javascript" src="scripts/core.min.js"></script><script src="scripts/search.min.js" defer="defer"></script><script src="scripts/third-party/fuse.js" defer="defer"></script><script type="text/javascript">var tocbotInstance=tocbot.init({tocSelector:"#eed4d2a0bfd64539bb9df78095dec881",contentSelector:".main-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0,scrollContainer:".main-content",headingsOffset:130,onClick:bringLinkToView})</script></body></html>