sumba 2.34.4 → 2.36.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.
- package/docs/Sumba.html +1 -1
- package/docs/data/search.json +1 -1
- package/docs/global.html +1 -1
- package/docs/index.html +1 -1
- package/docs/index.js.html +1544 -331
- package/docs/lib_config.js.html +201 -0
- package/docs/lib_constant.js.html +47 -0
- package/docs/lib_token-schema.js.html +47 -0
- package/extend/bajo/hook.js +27 -192
- package/extend/bajo/intl/en-US.json +14 -13
- package/extend/bajo/intl/id.json +15 -14
- package/extend/dobo/model.js +27 -1
- package/extend/waibuDb/schema/model-guard.js +2 -2
- package/extend/waibuMpa/extend/waibuAdmin/route/action-guard/@action.js +11 -0
- package/extend/waibuMpa/extend/waibuAdmin/route/{model-guard → query-guard}/@action.js +2 -2
- package/extend/waibuMpa/extend/waibuAdmin/route/team/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/team-setting/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/team-user/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/user/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/user-setting/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/x/site-setting/@action.js +1 -1
- package/extend/waibuRestApi/route/user/access-token/@type/create.js +1 -1
- package/extend/waibuRestApi/route/user/api-key/get.js +1 -1
- package/extend/waibuRestApi/route/your-stuff/api-key/update.js +1 -1
- package/index.js +1077 -192
- package/lib/config.js +198 -0
- package/lib/constant.js +44 -0
- package/package.json +9 -3
- package/wiki/CHANGES.md +12 -0
- package/lib/create-new-site.js +0 -106
- package/lib/get-site.js +0 -70
- package/lib/get-user.js +0 -89
- package/lib/remove-site.js +0 -39
- package/lib/token-schema.js +0 -29
package/docs/index.js.html
CHANGED
|
@@ -1,159 +1,199 @@
|
|
|
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 configFactory, { defMultiSite } from './lib/config.js'
|
|
5
|
+
import { joiPasswordExtendCore } from 'joi-password'
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
|
-
* Plugin factory
|
|
8
|
+
* Plugin factory.
|
|
9
|
+
*
|
|
10
|
+
* **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
11
|
*
|
|
8
12
|
* @param {string} pkgName - NPM package name
|
|
9
|
-
* @returns {class
|
|
13
|
+
* @returns {Sumba} Sumba class
|
|
10
14
|
*/
|
|
11
15
|
async function factory (pkgName) {
|
|
12
16
|
const me = this
|
|
17
|
+
const { getModel } = this.app.dobo
|
|
18
|
+
const { cloneDeep, isEmpty } = this.app.lib._
|
|
19
|
+
const config = await configFactory.call(this)
|
|
13
20
|
|
|
14
21
|
/**
|
|
15
|
-
* Sumba class
|
|
22
|
+
* Sumba class definition.
|
|
16
23
|
*
|
|
17
24
|
* @class
|
|
18
25
|
*/
|
|
19
26
|
class Sumba extends this.app.baseClass.Base {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Constructor
|
|
29
|
+
*/
|
|
23
30
|
constructor () {
|
|
24
31
|
super(pkgName, me.app)
|
|
25
|
-
this.config =
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
icon: 'globe',
|
|
34
|
-
redirect: {
|
|
35
|
-
'/': 'sumba:/your-stuff/profile',
|
|
36
|
-
'/your-stuff': 'sumba:/your-stuff/profile',
|
|
37
|
-
'/info': 'sumba:/info/about-us',
|
|
38
|
-
'/user': 'sumba:/your-stuff/profile',
|
|
39
|
-
'/db/export': 'sumba:/db/export/list',
|
|
40
|
-
'/help': 'sumba:/help/contact-form',
|
|
41
|
-
'/help/trouble-tickets': 'sumba:/help/trouble-tickets/list'
|
|
42
|
-
},
|
|
43
|
-
menuHandler: [{
|
|
44
|
-
title: 'account',
|
|
45
|
-
level: 9998,
|
|
46
|
-
children: [
|
|
47
|
-
// anonymous only
|
|
48
|
-
{ title: 'signin', href: 'sumba:/signin', visible: 'anon' },
|
|
49
|
-
{ title: 'forgotPassword', href: 'sumba:/user/forgot-password', visible: 'anon' },
|
|
50
|
-
{ title: 'newUserSignup', href: 'sumba:/user/signup', visible: 'anon' },
|
|
51
|
-
{ title: '-', visible: 'anon' },
|
|
52
|
-
{ title: 'activation', href: 'sumba:/user/activation', visible: 'anon' },
|
|
53
|
-
// authenticated only
|
|
54
|
-
{ title: 'yourProfile', href: 'sumba:/your-stuff/profile', visible: 'auth' },
|
|
55
|
-
{ title: 'changePassword', href: 'sumba:/your-stuff/change-password', visible: 'auth' },
|
|
56
|
-
{ title: 'downloadList', href: 'sumba:/your-stuff/download/list', visible: 'auth' },
|
|
57
|
-
{ title: '-', visible: 'auth' },
|
|
58
|
-
{ title: 'signout', href: 'sumba:/signout', visible: 'auth' }
|
|
59
|
-
]
|
|
60
|
-
}, {
|
|
61
|
-
title: 'help',
|
|
62
|
-
level: 9999,
|
|
63
|
-
children: [
|
|
64
|
-
{ title: 'contactForm', href: 'sumba:/help/contact-form' },
|
|
65
|
-
{ title: 'troubleTickets', href: 'sumba:/help/trouble-tickets', visible: 'auth' },
|
|
66
|
-
{ title: '-' },
|
|
67
|
-
{ title: 'cookiePolicy', href: 'sumba:/info/cookie-policy' },
|
|
68
|
-
{ title: 'privacy', href: 'sumba:/info/privacy' },
|
|
69
|
-
{ title: 'termsConditions', href: 'sumba:/info/terms-conditions' }
|
|
70
|
-
]
|
|
71
|
-
}]
|
|
72
|
-
},
|
|
73
|
-
waibuAdmin: {
|
|
74
|
-
menuHandler: 'sumba:adminMenu',
|
|
75
|
-
menuCollapsible: true,
|
|
76
|
-
modelDisabled: 'all'
|
|
77
|
-
},
|
|
78
|
-
auth: {
|
|
79
|
-
common: {
|
|
80
|
-
apiKey: {
|
|
81
|
-
type: 'Bearer',
|
|
82
|
-
qsKey: 'apiKey',
|
|
83
|
-
headerKey: 'X-Sumba-ApiKey'
|
|
84
|
-
},
|
|
85
|
-
basic: {
|
|
86
|
-
},
|
|
87
|
-
jwt: {
|
|
88
|
-
type: 'Bearer',
|
|
89
|
-
qsKey: 'token',
|
|
90
|
-
headerKey: 'X-Sumba-Token',
|
|
91
|
-
secret: '668de9cf57316c7dbf52f7ff7611c299',
|
|
92
|
-
expiresIn: 604800000
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
waibuRestApi: {
|
|
96
|
-
methods: ['basic', 'apiKey', 'jwt'],
|
|
97
|
-
silentOnError: false
|
|
98
|
-
},
|
|
99
|
-
waibuMpa: {
|
|
100
|
-
methods: ['session'],
|
|
101
|
-
silentOnError: false
|
|
102
|
-
},
|
|
103
|
-
waibuStatic: {
|
|
104
|
-
methods: ['basic', 'apiKey', 'jwt'],
|
|
105
|
-
basic: {
|
|
106
|
-
useUtf8: true,
|
|
107
|
-
realm: 'Protected Area',
|
|
108
|
-
warningMessage: 'Please authenticate yourself, thank you!'
|
|
109
|
-
},
|
|
110
|
-
silentOnError: false
|
|
111
|
-
}
|
|
112
|
-
},
|
|
113
|
-
redirect: {
|
|
114
|
-
signin: 'sumba:/signin',
|
|
115
|
-
afterSignin: '/',
|
|
116
|
-
signout: 'sumba:/signout',
|
|
117
|
-
afterSignout: '/'
|
|
118
|
-
},
|
|
119
|
-
siteSetting: {
|
|
120
|
-
forgotPasswordExpDur: '5m',
|
|
121
|
-
userPassword: {
|
|
122
|
-
minUppercase: 1,
|
|
123
|
-
minLowercase: 1,
|
|
124
|
-
minSpecialChar: 1,
|
|
125
|
-
minNumeric: 1,
|
|
126
|
-
noWhitespace: false,
|
|
127
|
-
latinOnlyChars: false
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
32
|
+
this.config = config
|
|
33
|
+
this.secureGuards = []
|
|
34
|
+
this.actionGuards = []
|
|
35
|
+
this.queryGuards = []
|
|
36
|
+
this.attribGuards = []
|
|
37
|
+
this.secureGuards = []
|
|
38
|
+
this.anonymousGuards = []
|
|
39
|
+
|
|
131
40
|
this.unsafeUserFields = ['password']
|
|
132
41
|
}
|
|
133
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Plugin initialization method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
|
|
45
|
+
*
|
|
46
|
+
* @async
|
|
47
|
+
* @method
|
|
48
|
+
*/
|
|
134
49
|
init = async () => {
|
|
135
|
-
|
|
136
|
-
this.downloadDir = `${getPluginDataDir(this.ns)}/download`
|
|
50
|
+
this.downloadDir = `${this.app.getPluginDataDir(this.ns)}/download`
|
|
137
51
|
this.app.lib.fs.ensureDirSync(this.downloadDir)
|
|
138
|
-
|
|
139
|
-
this
|
|
140
|
-
this
|
|
52
|
+
if (this.config.multiSite === true) {
|
|
53
|
+
this.config.multiSite = cloneDeep(defMultiSite)
|
|
54
|
+
this.config.multiSite.enabled = true
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Plugin start method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin start.
|
|
60
|
+
*
|
|
61
|
+
* @async
|
|
62
|
+
* @method
|
|
63
|
+
*/
|
|
64
|
+
start = async () => {
|
|
65
|
+
await this.populateRouteGuards()
|
|
66
|
+
if (!this.config.multiSite.enabled) {
|
|
67
|
+
this.config.xSiteAdmins = []
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
if (this.config.xSiteAdmins.length === 0) {
|
|
71
|
+
const site = await getModel('SumbaSite').findOneRecord({ query: { alias: 'default' } }, { noMagic: true })
|
|
72
|
+
const user = await getModel('SumbaUser').findOneRecord({ query: { username: 'admin', siteId: site.id + '' } }, { noMagic: true })
|
|
73
|
+
this.config.xSiteAdmins.push(`${site.alias}:${user.username}`)
|
|
141
74
|
}
|
|
142
75
|
}
|
|
143
76
|
|
|
144
|
-
|
|
77
|
+
/**
|
|
78
|
+
* Populate route guards at start
|
|
79
|
+
*
|
|
80
|
+
* @async
|
|
81
|
+
* @method
|
|
82
|
+
* @param {array} [sites] - List of sites to populate route guards for. If not provided, it will fetch all active sites.
|
|
83
|
+
*/
|
|
84
|
+
populateRouteGuards = async (sites) => {
|
|
85
|
+
const { isString, get, difference } = this.app.lib._
|
|
86
|
+
const { pascalCase } = this.app.lib.aneka
|
|
87
|
+
const { eachPlugins, readConfig, breakNsPath } = this.app.bajo
|
|
88
|
+
const { getModel } = this.app.dobo
|
|
89
|
+
|
|
90
|
+
const allNs = this.app.getAllNs()
|
|
91
|
+
if (!sites) sites = await getModel('SumbaSite').findAllRecord({ query: { status: 'ACTIVE' } }, { noMagic: true, dataOnly: true, fields: ['id', 'hostname'] })
|
|
92
|
+
|
|
93
|
+
const sanitize = (item, ns) => {
|
|
94
|
+
if (isString(item)) item = { path: item }
|
|
95
|
+
let [prefix, ...args] = item.path.split(':')
|
|
96
|
+
const neg = prefix[0] === '!'
|
|
97
|
+
if (neg) prefix = prefix.slice(1)
|
|
98
|
+
if (isEmpty(args)) {
|
|
99
|
+
args = prefix
|
|
100
|
+
prefix = null
|
|
101
|
+
} else args = args.join(':')
|
|
102
|
+
if (isEmpty(prefix)) prefix = ns
|
|
103
|
+
else {
|
|
104
|
+
const [_ns, subNs] = prefix.split('.')
|
|
105
|
+
if (subNs) prefix = `${ns}.${subNs}`
|
|
106
|
+
else if (!allNs.includes(_ns)) prefix = `${ns}.${_ns}`
|
|
107
|
+
else prefix = _ns
|
|
108
|
+
}
|
|
109
|
+
item.path = `${neg ? '!' : ''}${prefix}:${args}`
|
|
110
|
+
item._immutable = item._immutable ?? ['path']
|
|
111
|
+
if (neg) {
|
|
112
|
+
item.allTeams = true
|
|
113
|
+
item.teamIds = []
|
|
114
|
+
item._immutable = ['path', 'teamIds', 'allTeams']
|
|
115
|
+
}
|
|
116
|
+
return item
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const filterFn = item => {
|
|
120
|
+
let [ns] = (item.path.split(':')[0] ?? '').split('.')
|
|
121
|
+
if (ns[0] === '!') ns = ns.slice(1)
|
|
122
|
+
return allNs.includes(ns)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
for (const type of ['secure', 'anonymous']) {
|
|
126
|
+
const routes = []
|
|
127
|
+
// get it from <pluginDir>/extend/sumba/route/*
|
|
128
|
+
await eachPlugins(async function ({ file }) {
|
|
129
|
+
const { ns } = this
|
|
130
|
+
const items = (await readConfig(file)).map(item => sanitize(item, ns)).filter(filterFn)
|
|
131
|
+
routes.push(...items)
|
|
132
|
+
}, { glob: `route/${type}.*`, prefix: this.ns })
|
|
133
|
+
// get it from config
|
|
134
|
+
const items = get(this, `config.route.${type}`, []).map(item => {
|
|
135
|
+
if (isString(item)) item = { path: item }
|
|
136
|
+
const neg = item.path[0] === '!'
|
|
137
|
+
if (neg) item.path.slice(1)
|
|
138
|
+
const { fullNs } = breakNsPath(item.path)
|
|
139
|
+
if (neg) item.path = '!' + item.path
|
|
140
|
+
return sanitize(item, fullNs)
|
|
141
|
+
}).filter(filterFn)
|
|
142
|
+
routes.push(...items)
|
|
143
|
+
const paths = routes.map(item => item.path)
|
|
144
|
+
const model = getModel(pascalCase(`Sumba ${type} Guard`))
|
|
145
|
+
for (const site of sites) {
|
|
146
|
+
const query = { path: { $in: paths }, siteId: site.id + '' }
|
|
147
|
+
const recs = await model.findAllRecord({ query }, { noMagic: true, dataOnly: true, fields: ['path', 'status'] })
|
|
148
|
+
const spaths = difference(paths, recs.map(rec => rec.path))
|
|
149
|
+
for (const path of spaths) {
|
|
150
|
+
const body = cloneDeep(routes.find(r => r.path === path))
|
|
151
|
+
body.status = 'ACTIVE'
|
|
152
|
+
body.siteId = site.id + ''
|
|
153
|
+
await model.sanitizeFixture({ body, lookupValue: body })
|
|
154
|
+
try {
|
|
155
|
+
await model.createRecord(body, { noMagic: true, noReturn: true })
|
|
156
|
+
} catch (err) {}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Get authentication setting based on type and source
|
|
164
|
+
*
|
|
165
|
+
* @method
|
|
166
|
+
* @private
|
|
167
|
+
* @param {string} type - The type of authentication setting to retrieve. If not provided, it will use parent setting.
|
|
168
|
+
* @param {string} [source] - The source of the authentication setting. If not provided, it will use the default setting.
|
|
169
|
+
* @returns {object} - The authentication setting object.
|
|
170
|
+
*/
|
|
171
|
+
_getAuthSetting = (type, source) => {
|
|
145
172
|
const { defaultsDeep } = this.app.lib.aneka
|
|
146
173
|
const { get } = this.app.lib._
|
|
147
174
|
|
|
148
|
-
|
|
175
|
+
let setting
|
|
176
|
+
const withType = type ? `.${type}` : ''
|
|
177
|
+
if (source) setting = defaultsDeep(get(this.config, `${source}.auth${withType}`, {}), get(this.config, `auth${withType}`, {}))
|
|
178
|
+
else setting = get(this.config, `auth${withType}`, {})
|
|
149
179
|
if (type === 'basic') setting.type = 'Basic'
|
|
150
180
|
return setting
|
|
151
181
|
}
|
|
152
182
|
|
|
153
|
-
|
|
183
|
+
/**
|
|
184
|
+
* Get authentication token based on type, request, and source
|
|
185
|
+
*
|
|
186
|
+
* @method
|
|
187
|
+
* @private
|
|
188
|
+
* @param {string} type - The type of authentication setting.
|
|
189
|
+
* @param {object} req - The request object.
|
|
190
|
+
* @param {string} [source] - The source of the authentication setting. If not provided, it will use the default setting.
|
|
191
|
+
* @returns {string|boolean} - The token if found, otherwise false.
|
|
192
|
+
*/
|
|
193
|
+
_getAuthToken = (type, req, source) => {
|
|
154
194
|
const { isEmpty } = this.app.lib._
|
|
155
195
|
|
|
156
|
-
const setting =
|
|
196
|
+
const setting = this._getAuthSetting(type, source)
|
|
157
197
|
let token = req.headers[setting.headerKey.toLowerCase()]
|
|
158
198
|
if (!['basic'].includes(type) && isEmpty(token)) token = req.query[setting.qsKey]
|
|
159
199
|
if (isEmpty(token)) {
|
|
@@ -164,161 +204,202 @@ async function factory (pkgName) {
|
|
|
164
204
|
return token
|
|
165
205
|
}
|
|
166
206
|
|
|
207
|
+
/**
|
|
208
|
+
* Build admin menu based on locals and request.
|
|
209
|
+
*
|
|
210
|
+
* - If multi-site is enabled, it will include the cross-site menu with options to manage all sites and site settings.
|
|
211
|
+
* - If caching is enabled, it will include the cache storage menu in the appropriate section.
|
|
212
|
+
* - Session management menu is also included in the appropriate section.
|
|
213
|
+
*
|
|
214
|
+
* @async
|
|
215
|
+
* @method
|
|
216
|
+
* @param {object} locals - The locals object.
|
|
217
|
+
* @param {object} req - The request object.
|
|
218
|
+
* @returns {array} - The admin menu items.
|
|
219
|
+
*/
|
|
167
220
|
adminMenu = async (locals, req) => {
|
|
168
221
|
if (!this.app.waibuAdmin) return
|
|
169
222
|
const { getPluginPrefix } = this.app.waibu
|
|
223
|
+
const { findIndex } = this.app.lib._
|
|
170
224
|
const prefix = getPluginPrefix(this.ns)
|
|
171
|
-
|
|
172
|
-
|
|
225
|
+
const params = { action: 'list' }
|
|
226
|
+
const items = [{
|
|
227
|
+
title: 'manageSite',
|
|
173
228
|
children: [
|
|
174
|
-
{ title: '
|
|
175
|
-
{ title: '
|
|
176
|
-
{ title: 'ticket', href: `waibuAdmin:/${prefix}/ticket/list` },
|
|
177
|
-
{ title: 'ticketCat', href: `waibuAdmin:/${prefix}/ticket-cat/list` }
|
|
229
|
+
{ title: 'siteProfile', href: `waibuAdmin:/${prefix}/site` },
|
|
230
|
+
{ title: 'manageSiteSetting', href: `waibuAdmin:/${prefix}/site-setting/:action`, params }
|
|
178
231
|
]
|
|
179
232
|
}, {
|
|
180
|
-
title: '
|
|
233
|
+
title: 'manageUserTeam',
|
|
181
234
|
children: [
|
|
182
|
-
{ title: '
|
|
183
|
-
{ title: '
|
|
184
|
-
{ title: 'manageTeam', href: `waibuAdmin:/${prefix}/team
|
|
185
|
-
{ title: 'manageTeamUser', href: `waibuAdmin:/${prefix}/team-user
|
|
186
|
-
{ title: '
|
|
235
|
+
{ title: 'manageUser', href: `waibuAdmin:/${prefix}/user/:action`, params },
|
|
236
|
+
{ title: 'manageUserSetting', href: `waibuAdmin:/${prefix}/user-setting/:action`, params },
|
|
237
|
+
{ title: 'manageTeam', href: `waibuAdmin:/${prefix}/team/:action`, params },
|
|
238
|
+
{ title: 'manageTeamUser', href: `waibuAdmin:/${prefix}/team-user/:action`, params },
|
|
239
|
+
{ title: 'manageTeamSetting', href: `waibuAdmin:/${prefix}/team-setting/:action`, params },
|
|
187
240
|
{ title: 'resetUserPassword', href: `waibuAdmin:/${prefix}/reset-user-password` }
|
|
188
241
|
]
|
|
242
|
+
}, {
|
|
243
|
+
title: 'permissionGuard',
|
|
244
|
+
children: [
|
|
245
|
+
{ title: 'secureGuard', href: `waibuAdmin:/${prefix}/secure-guard/:action`, params },
|
|
246
|
+
{ title: 'anonymousGuard', href: `waibuAdmin:/${prefix}/anonymous-guard/:action`, params },
|
|
247
|
+
{ title: 'actionGuard', href: `waibuAdmin:/${prefix}/action-guard/:action`, params },
|
|
248
|
+
{ title: 'queryGuard', href: `waibuAdmin:/${prefix}/query-guard/:action`, params },
|
|
249
|
+
{ title: 'attribGuard', href: `waibuAdmin:/${prefix}/attrib-guard/:action`, params }
|
|
250
|
+
]
|
|
251
|
+
}, {
|
|
252
|
+
title: 'supportSystem',
|
|
253
|
+
children: [
|
|
254
|
+
{ title: 'contactForm', href: `waibuAdmin:/${prefix}/contact-form/:action`, params },
|
|
255
|
+
{ title: 'contactFormCat', href: `waibuAdmin:/${prefix}/contact-form-cat/:action`, params },
|
|
256
|
+
{ title: 'ticket', href: `waibuAdmin:/${prefix}/ticket/:action`, params },
|
|
257
|
+
{ title: 'ticketCat', href: `waibuAdmin:/${prefix}/ticket-cat/:action`, params }
|
|
258
|
+
]
|
|
189
259
|
}, {
|
|
190
260
|
title: 'misc',
|
|
191
261
|
children: [
|
|
192
|
-
{ title: '
|
|
262
|
+
{ title: 'manageDownload', href: `waibuAdmin:/${prefix}/download/:action`, params }
|
|
193
263
|
]
|
|
194
264
|
}]
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
265
|
+
const sessionMenu = { title: 'userSession', href: `waibuAdmin:/${prefix}/x/session/:action`, params }
|
|
266
|
+
const cacheMenu = { title: 'cacheStorage', href: `waibuAdmin:/${prefix}/x/cache/:action`, params }
|
|
267
|
+
if (this.config.multiSite.enabled) {
|
|
268
|
+
items.unshift({
|
|
269
|
+
title: 'xSite',
|
|
270
|
+
children: [
|
|
271
|
+
{ title: 'manageAllSites', href: `waibuAdmin:/${prefix}/x/site/:action`, params },
|
|
272
|
+
{ title: 'manageAllSiteSettings', href: `waibuAdmin:/${prefix}/x/site-setting/:action`, params },
|
|
273
|
+
sessionMenu
|
|
274
|
+
]
|
|
275
|
+
})
|
|
276
|
+
} else {
|
|
277
|
+
const idx = findIndex(items, i => i.title === 'misc')
|
|
278
|
+
if (idx > -1) items[idx].children.push(sessionMenu)
|
|
204
279
|
}
|
|
205
|
-
if (
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
|
280
|
+
if (this.app.bajoCache) {
|
|
281
|
+
const idx = findIndex(items, i => i.title === this.config.multiSite.enabled ? 'xSite' : 'misc')
|
|
282
|
+
if (idx > -1)items[idx].children.push(cacheMenu)
|
|
283
|
+
}
|
|
284
|
+
return items
|
|
239
285
|
}
|
|
240
286
|
|
|
287
|
+
/**
|
|
288
|
+
* Create JWT from user record
|
|
289
|
+
*
|
|
290
|
+
* @async
|
|
291
|
+
* @method
|
|
292
|
+
* @param {object} rec - The user record object.
|
|
293
|
+
* @returns {Promise<object>} - The JWT token and its expiration date.
|
|
294
|
+
*/
|
|
241
295
|
createJwtFromUserRecord = async (rec) => {
|
|
242
296
|
const { importPkg } = this.app.bajo
|
|
243
297
|
const { dayjs } = this.app.lib
|
|
244
|
-
const { hash } = this.app.bajoExtra
|
|
245
298
|
const { get, pick } = this.app.lib._
|
|
246
299
|
|
|
247
300
|
const fastJwt = await importPkg('bajoExtra:fast-jwt')
|
|
248
301
|
const { createSigner } = fastJwt
|
|
249
302
|
|
|
250
|
-
const
|
|
251
|
-
opts
|
|
303
|
+
const setting = this._getAuthSetting('jwt')
|
|
304
|
+
const opts = pick(setting, ['expiresInDur'])
|
|
305
|
+
opts.key = get(setting, 'secret')
|
|
252
306
|
const sign = createSigner(opts)
|
|
253
|
-
const apiKey = await hash(rec.
|
|
307
|
+
const apiKey = await this.hash(rec.token)
|
|
254
308
|
const payload = { uid: rec.id, apiKey }
|
|
255
309
|
const token = await sign(payload)
|
|
256
|
-
const expiresAt = dayjs().add(opts.
|
|
310
|
+
const expiresAt = dayjs().add(opts.expiresInDur).toDate()
|
|
257
311
|
return { token, expiresAt }
|
|
258
312
|
}
|
|
259
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Verify user session
|
|
316
|
+
*
|
|
317
|
+
* @async
|
|
318
|
+
* @method
|
|
319
|
+
* @param {object} req - The request object.
|
|
320
|
+
* @param {object} reply - The reply object.
|
|
321
|
+
* @param {string} source - The source of the authentication setting.
|
|
322
|
+
* @param {object} payload - The payload object.
|
|
323
|
+
* @returns {boolean} - True if the session is valid, otherwise false.
|
|
324
|
+
*/
|
|
260
325
|
verifySession = async (req, reply, source, payload) => {
|
|
261
|
-
const { getUser } = this
|
|
262
326
|
const { routePath } = this.app.waibu
|
|
327
|
+
const { query, params } = req
|
|
263
328
|
|
|
264
329
|
if (!req.session) return false
|
|
265
330
|
if (req.session.userId) {
|
|
266
|
-
req.user = await
|
|
331
|
+
req.user = await this.getUserById(req.session.userId, req)
|
|
267
332
|
return true
|
|
268
333
|
}
|
|
269
|
-
const redir = routePath(this.config.redirect.signin,
|
|
334
|
+
const redir = routePath(this.config.redirect.signin, { query, params })
|
|
270
335
|
req.session.ref = req.url
|
|
271
|
-
throw this.error('_redirect', {
|
|
336
|
+
throw this.error('_redirect', { path: redir })
|
|
272
337
|
}
|
|
273
338
|
|
|
339
|
+
/**
|
|
340
|
+
* Verify API key
|
|
341
|
+
*
|
|
342
|
+
* @async
|
|
343
|
+
* @method
|
|
344
|
+
* @param {object} req - The request object.
|
|
345
|
+
* @param {object} reply - The reply object.
|
|
346
|
+
* @param {string} source - The source of the authentication setting.
|
|
347
|
+
* @param {object} payload - The payload object.
|
|
348
|
+
* @returns {boolean} - True if the API key is valid, otherwise false.
|
|
349
|
+
*/
|
|
274
350
|
verifyApiKey = async (req, reply, source, payload) => {
|
|
275
|
-
const { merge } = this.app.lib._
|
|
276
|
-
const
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
let token = await this.
|
|
280
|
-
if (!
|
|
281
|
-
token = await hash(token)
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
if (
|
|
285
|
-
|
|
286
|
-
req.user = await getUser(rows[0])
|
|
351
|
+
const { merge, camelCase } = this.app.lib._
|
|
352
|
+
const setting = this._getAuthSetting(null, source)
|
|
353
|
+
const checker = this.app.bajoExtra[camelCase(`is ${setting.apiKey.algo}`)]
|
|
354
|
+
|
|
355
|
+
let token = await this._getAuthToken('apiKey', req, source)
|
|
356
|
+
if (!checker(token)) return false
|
|
357
|
+
token = await this.hash(token)
|
|
358
|
+
const user = await this.getUserByToken(token, req)
|
|
359
|
+
if (!user) throw this.error('invalidKey', merge({ statusCode: 401 }, payload))
|
|
360
|
+
if (user.status !== 'ACTIVE') throw this.error('userInactive', merge({ details: [{ field: 'status', error: 'inactive' }], statusCode: 401 }, payload))
|
|
361
|
+
req.user = user
|
|
287
362
|
return true
|
|
288
363
|
}
|
|
289
364
|
|
|
365
|
+
/**
|
|
366
|
+
* Verify basic authentication
|
|
367
|
+
*
|
|
368
|
+
* @async
|
|
369
|
+
* @method
|
|
370
|
+
* @param {object} req - The request object.
|
|
371
|
+
* @param {object} reply - The reply object.
|
|
372
|
+
* @param {string} source - The source of the authentication setting.
|
|
373
|
+
* @param {object} payload - The payload object.
|
|
374
|
+
* @returns {boolean|string} - True if the basic authentication is valid, otherwise false or an error message.
|
|
375
|
+
*/
|
|
290
376
|
verifyBasic = async (req, reply, source, payload) => {
|
|
291
|
-
const { getUserFromUsernamePassword } = this
|
|
292
|
-
const { getUser } = this
|
|
293
377
|
const { isEmpty, merge } = this.app.lib._
|
|
294
378
|
|
|
295
379
|
const setHeader = async (setting, reply) => {
|
|
296
|
-
const { isString } = this.app.lib._
|
|
297
|
-
|
|
298
380
|
let header = setting.type
|
|
299
381
|
const exts = []
|
|
300
|
-
if (
|
|
382
|
+
if (setting.realm) exts.push(`realm="${req.t('protectedArea')}"`)
|
|
301
383
|
if (setting.useUtf8) exts.push('charset="UTF-8"')
|
|
302
384
|
if (exts.length > 0) header += ` ${exts.join(', ')}`
|
|
303
385
|
reply.header('WWW-Authenticate', header)
|
|
304
386
|
reply.code(401)
|
|
305
387
|
}
|
|
306
388
|
|
|
307
|
-
const setting =
|
|
389
|
+
const setting = this._getAuthSetting('basic', source)
|
|
308
390
|
let authInfo
|
|
309
391
|
const parts = (req.headers.authorization ?? '').split(' ')
|
|
310
392
|
if (parts[0] === setting.type) authInfo = parts[1]
|
|
311
393
|
if (isEmpty(authInfo)) {
|
|
312
394
|
if (setting.realm) {
|
|
313
395
|
await setHeader(setting, reply)
|
|
314
|
-
throw this.error(
|
|
396
|
+
throw this.error(req.t('pleaseAuthenticate'), { statusCode: 403 })
|
|
315
397
|
} else return false
|
|
316
398
|
}
|
|
317
399
|
const decoded = Buffer.from(authInfo, 'base64').toString()
|
|
318
400
|
const [username, password] = decoded.split(':')
|
|
319
401
|
try {
|
|
320
|
-
|
|
321
|
-
req.user = await getUser(user)
|
|
402
|
+
req.user = await this.getUserByUsernamePassword(username, password, req)
|
|
322
403
|
} catch (err) {
|
|
323
404
|
if (err.statusCode === 401 && setting.realm) {
|
|
324
405
|
await setHeader(setting, reply)
|
|
@@ -329,15 +410,25 @@ async function factory (pkgName) {
|
|
|
329
410
|
return true
|
|
330
411
|
}
|
|
331
412
|
|
|
413
|
+
/**
|
|
414
|
+
* Verify JWT authentication
|
|
415
|
+
*
|
|
416
|
+
* @async
|
|
417
|
+
* @method
|
|
418
|
+
* @param {object} req - The request object.
|
|
419
|
+
* @param {object} reply - The reply object.
|
|
420
|
+
* @param {string} source - The source of the authentication setting.
|
|
421
|
+
* @param {object} payload - The payload object.
|
|
422
|
+
* @returns {boolean} - True if the JWT authentication is valid, otherwise false.
|
|
423
|
+
*/
|
|
332
424
|
verifyJwt = async (req, reply, source, payload) => {
|
|
333
425
|
const { importPkg } = this.app.bajo
|
|
334
|
-
const { getUser } = this
|
|
335
426
|
const { isEmpty, merge } = this.app.lib._
|
|
336
427
|
|
|
337
428
|
const fastJwt = await importPkg('bajoExtra:fast-jwt')
|
|
338
429
|
const { createVerifier } = fastJwt
|
|
339
|
-
const setting =
|
|
340
|
-
const token =
|
|
430
|
+
const setting = this._getAuthSetting('jwt', source)
|
|
431
|
+
const token = this._getAuthToken('jwt', req, source)
|
|
341
432
|
if (isEmpty(token)) return false
|
|
342
433
|
const verifier = createVerifier({
|
|
343
434
|
key: setting.secret,
|
|
@@ -346,10 +437,10 @@ async function factory (pkgName) {
|
|
|
346
437
|
const decoded = await verifier(token)
|
|
347
438
|
const id = decoded.payload.uid
|
|
348
439
|
try {
|
|
349
|
-
const
|
|
350
|
-
if (!
|
|
351
|
-
if (
|
|
352
|
-
req.user =
|
|
440
|
+
const user = await this.getUserById(id, req)
|
|
441
|
+
if (!user) throw this.error('invalidToken', { statusCode: 401 })
|
|
442
|
+
if (user.status !== 'ACTIVE') throw this.error('userInactive', { details: [{ field: 'status', error: 'inactive' }], statusCode: 401 })
|
|
443
|
+
req.user = user
|
|
353
444
|
} catch (err) {
|
|
354
445
|
merge(err, payload)
|
|
355
446
|
throw err
|
|
@@ -357,111 +448,33 @@ async function factory (pkgName) {
|
|
|
357
448
|
return true
|
|
358
449
|
}
|
|
359
450
|
|
|
360
|
-
|
|
361
|
-
|
|
451
|
+
/**
|
|
452
|
+
* Check route guard
|
|
453
|
+
*
|
|
454
|
+
* @method
|
|
455
|
+
* @param {Array} guards - The array of guard objects.
|
|
456
|
+
* @param {Array} paths - The array of paths to check.
|
|
457
|
+
* @returns {string|undefined} - The matched path or undefined if no match is found.
|
|
458
|
+
*/
|
|
459
|
+
checkRouteGuard = (guards, paths) => {
|
|
362
460
|
const { outmatch } = this.app.lib
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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
|
-
}
|
|
461
|
+
const all = guards.map(item => item.path)
|
|
462
|
+
const isMatch = outmatch(all)
|
|
463
|
+
return paths.find(isMatch)
|
|
376
464
|
}
|
|
377
465
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
signout = async ({ req, reply, reason }) => {
|
|
466
|
+
/**
|
|
467
|
+
* Sign out user and redirect to the specified URL
|
|
468
|
+
*
|
|
469
|
+
* @async
|
|
470
|
+
* @method
|
|
471
|
+
* @param {object} options - The options object.
|
|
472
|
+
* @param {object} options.req - The request object.
|
|
473
|
+
* @param {object} options.reply - The reply object.
|
|
474
|
+
* @param {string} [options.reason] - The reason for signing out.
|
|
475
|
+
*/
|
|
476
|
+
signout = async (options = {}) => {
|
|
477
|
+
const { req, reply, reason } = options
|
|
465
478
|
const { runHook } = this.app.bajo
|
|
466
479
|
const { getSessionId } = this.app.waibuMpa
|
|
467
480
|
const sid = await getSessionId(req.headers.cookie)
|
|
@@ -474,7 +487,18 @@ async function factory (pkgName) {
|
|
|
474
487
|
return reply.redirectTo(url, { query, params })
|
|
475
488
|
}
|
|
476
489
|
|
|
477
|
-
|
|
490
|
+
/**
|
|
491
|
+
* Sign in user and redirect to the specified URL
|
|
492
|
+
*
|
|
493
|
+
* @async
|
|
494
|
+
* @method
|
|
495
|
+
* @param {object} options - The options object.
|
|
496
|
+
* @param {object} options.req - The request object.
|
|
497
|
+
* @param {object} options.reply - The reply object.
|
|
498
|
+
* @param {object} options.user - The user object.
|
|
499
|
+
*/
|
|
500
|
+
signin = async (options = {}) => {
|
|
501
|
+
const { req, reply, user } = options
|
|
478
502
|
const { getSessionId } = this.app.waibuMpa
|
|
479
503
|
const { runHook } = this.app.bajo
|
|
480
504
|
const { isEmpty, omit } = this.app.lib._
|
|
@@ -491,21 +515,28 @@ async function factory (pkgName) {
|
|
|
491
515
|
return reply.redirectTo(url, { query, params })
|
|
492
516
|
}
|
|
493
517
|
|
|
494
|
-
|
|
518
|
+
/**
|
|
519
|
+
* Generate a random password based on the configuration settings
|
|
520
|
+
*
|
|
521
|
+
* @method
|
|
522
|
+
* @param {object} req - The request object.
|
|
523
|
+
* @returns {string} - The generated password.
|
|
524
|
+
*/
|
|
525
|
+
generatePassword = (req = {}) => {
|
|
526
|
+
const { get } = this.app.lib._
|
|
495
527
|
const { generateId } = this.app.lib.aneka
|
|
496
|
-
const cfg = req
|
|
528
|
+
const cfg = get(req, 'site.setting.sumba.userPassword', this.config.siteSetting.userPassword)
|
|
497
529
|
let passwd = generateId()
|
|
498
|
-
if (cfg.
|
|
499
|
-
if (cfg.
|
|
500
|
-
if (cfg.minSpecialChar) passwd += generateId({ pattern:
|
|
501
|
-
if (cfg.minNumeric) passwd += generateId({ pattern:
|
|
530
|
+
if (cfg.minLowerCase > 0) passwd += generateId({ pattern: cfg.pattern.lowerCase, length: cfg.minLowercase })
|
|
531
|
+
if (cfg.minUpperCase > 0) passwd += generateId({ pattern: cfg.pattern.upperCase, length: cfg.minUppercase })
|
|
532
|
+
if (cfg.minSpecialChar > 0) passwd += generateId({ pattern: cfg.pattern.specialChar, length: cfg.minSpecialChar })
|
|
533
|
+
if (cfg.minNumeric > 0) passwd += generateId({ pattern: cfg.pattern.numeric, length: cfg.minNumeric })
|
|
502
534
|
return passwd
|
|
503
535
|
}
|
|
504
536
|
|
|
505
537
|
pushDownload = async ({ description, worker, data, source, req, file, type }) => {
|
|
506
|
-
const {
|
|
507
|
-
const {
|
|
508
|
-
const { push } = getPlugin('bajoQueue')
|
|
538
|
+
const { createRecord } = this.app.getPlugin('waibuDb')
|
|
539
|
+
const { push } = this.app.getPlugin('bajoQueue')
|
|
509
540
|
description = description ?? file
|
|
510
541
|
const jobQueue = {
|
|
511
542
|
worker,
|
|
@@ -523,11 +554,1193 @@ async function factory (pkgName) {
|
|
|
523
554
|
await push(jobQueue)
|
|
524
555
|
}
|
|
525
556
|
|
|
557
|
+
/**
|
|
558
|
+
* Get API key from user ID by hashing the user's salt
|
|
559
|
+
*
|
|
560
|
+
* @async
|
|
561
|
+
* @method
|
|
562
|
+
* @param {string|number} id - The user ID.
|
|
563
|
+
* @returns {Promise<string>} - A promise that resolves to the API key.
|
|
564
|
+
*/
|
|
526
565
|
getApiKeyFromUserId = async id => {
|
|
527
|
-
const { hash } = this.app.bajoExtra
|
|
528
566
|
const options = { forceNoHidden: true, noHook: true, noCache: true, attachment: true, mimeType: true }
|
|
529
|
-
const resp = await
|
|
530
|
-
return await hash(resp.salt)
|
|
567
|
+
const resp = await getModel('SumbaUser').getRecord(id, options)
|
|
568
|
+
return await this.hash(resp.salt)
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Get a list of countries with their values and names
|
|
573
|
+
*
|
|
574
|
+
* @async
|
|
575
|
+
* @method
|
|
576
|
+
* @returns {Promise<Array<{ value: string|number, text: string }>>} - A promise that resolves to an array of country values and names.
|
|
577
|
+
*/
|
|
578
|
+
getCountriesValues = async () => {
|
|
579
|
+
const { getModel } = this.app.dobo
|
|
580
|
+
const model = getModel('CdbCountry')
|
|
581
|
+
const items = await model.findAllRecord({}, { noMagic: true, dataOnly: true })
|
|
582
|
+
return items.map(item => ({ value: item.id, text: item.name }))
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Method to send mail through Masohi Messaging System. It is a thin wrapper
|
|
587
|
+
* for {@link https://github.com/ardhi/masohi-mail|masohi-mail} send method.
|
|
588
|
+
*
|
|
589
|
+
* If both masohiMail and waibu are not loaded, nothing is delivered.
|
|
590
|
+
*
|
|
591
|
+
* @method
|
|
592
|
+
* @async
|
|
593
|
+
* @param {(string|Array)} tpl - Mail's template to use. If a string is given, the same template will be used for html & plaintext versions. Otherwise, the first template will be used for html mail, and the second one is for it's plaintext version
|
|
594
|
+
* @param {Object} [params={}] - {@link https://github.com/ardhi/masohi-mail|masohi-mail}'s params object.
|
|
595
|
+
*/
|
|
596
|
+
sendMail = async (tpl, { payload = {}, conn, source, options = {} } = {}) => {
|
|
597
|
+
if (!this.app.masohiMail || !this.app.waibu) return
|
|
598
|
+
conn = conn ?? 'masohiMail:default'
|
|
599
|
+
const { importModule } = this.app.bajo
|
|
600
|
+
const { get, isString } = this.app.lib._
|
|
601
|
+
const { generateId } = this.app.lib.aneka
|
|
602
|
+
const { render } = this.app.bajoTemplate
|
|
603
|
+
const buildLocals = await importModule('waibu:/lib/build-locals.js')
|
|
604
|
+
|
|
605
|
+
if (isString(tpl)) tpl = [tpl]
|
|
606
|
+
options.partial = false
|
|
607
|
+
const locals = await buildLocals.call(this, { params: payload.data, opts: options })
|
|
608
|
+
payload.from = payload.from ?? get(options, 'req.site.email', payload.from)
|
|
609
|
+
const opts = {
|
|
610
|
+
lang: get(options, 'req.lang'),
|
|
611
|
+
groupId: get(options, 'req.id', generateId())
|
|
612
|
+
}
|
|
613
|
+
payload.html = await render(tpl[0], locals, opts)
|
|
614
|
+
if (tpl[1]) payload.text = await render(tpl[1], locals, opts)
|
|
615
|
+
await this.app.masohiMail.send({ payload, source: source ?? this.ns, conn })
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Reset token by generating a new salt and hashing it twice to create a new token.
|
|
620
|
+
*
|
|
621
|
+
* @async
|
|
622
|
+
* @method
|
|
623
|
+
* @param {string} [text] - Optional text to use as the salt. If not provided, a new salt will be generated.
|
|
624
|
+
* @returns {Promise<{ salt: string, token: string }>} - A promise that resolves to an object containing the salt and token.
|
|
625
|
+
*/
|
|
626
|
+
resetToken = async (text) => {
|
|
627
|
+
const { generateId } = this.app.lib.aneka
|
|
628
|
+
const salt = text ?? generateId()
|
|
629
|
+
const token = await this.hash(await this.hash(salt))
|
|
630
|
+
return { salt, token }
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Generate a password validation rule based on the configuration settings.
|
|
635
|
+
*
|
|
636
|
+
* @async
|
|
637
|
+
* @method
|
|
638
|
+
* @param {object} req - The request object.
|
|
639
|
+
* @returns {object} - The Joi password validation rule.
|
|
640
|
+
*/
|
|
641
|
+
passwordRule = async (req = {}) => {
|
|
642
|
+
const { get } = this.app.lib._
|
|
643
|
+
const { importPkg } = this.app.bajo
|
|
644
|
+
const joi = await importPkg('dobo:joi')
|
|
645
|
+
const joiPassword = joi.extend(joiPasswordExtendCore)
|
|
646
|
+
let password = joiPassword
|
|
647
|
+
.string()
|
|
648
|
+
.min(8)
|
|
649
|
+
.max(100)
|
|
650
|
+
.required()
|
|
651
|
+
const cfg = get(req, 'site.setting.sumba.userPassword', this.config.siteSetting.userPassword)
|
|
652
|
+
if (cfg.minUppeCase) password = password.minOfUppercase(cfg.minUpperCase)
|
|
653
|
+
if (cfg.minLowercase) password = password.minOfLowercase(cfg.minLowerCase)
|
|
654
|
+
if (cfg.minSpecialChar) password = password.minOfSpecialCharacters(cfg.minSpecialChar)
|
|
655
|
+
if (cfg.minNumeric) password = password.minOfNumeric(cfg.minNumeric)
|
|
656
|
+
if (cfg.noWhitespace) password = password.noWhiteSpaces()
|
|
657
|
+
if (cfg.latinOnlyChars) password = password.onlyLatinCharacters()
|
|
658
|
+
return password
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Hash the given item using the specified algorithm from the configuration.
|
|
663
|
+
*
|
|
664
|
+
* @async
|
|
665
|
+
* @method
|
|
666
|
+
* @param {*} item - The item to be hashed.
|
|
667
|
+
* @returns {Promise<string>} - A promise that resolves to the hashed value.
|
|
668
|
+
*/
|
|
669
|
+
hash = async (item) => {
|
|
670
|
+
const { hash } = this.app.bajoExtra
|
|
671
|
+
const setting = this._getAuthSetting('apiKey')
|
|
672
|
+
return await hash(item, setting.algo)
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Fetch guards of the specified type from the database.
|
|
677
|
+
*
|
|
678
|
+
* @async
|
|
679
|
+
* @method
|
|
680
|
+
* @private
|
|
681
|
+
* @param {string} type - The type of guards to fetch. Available types are 'Action', 'Attrib', 'Query', 'Secure', and 'Anonymous'.
|
|
682
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of guards.
|
|
683
|
+
*/
|
|
684
|
+
_fetchGuards = async (type) => {
|
|
685
|
+
const { getModel } = this.app.dobo
|
|
686
|
+
const options = { noMagic: true, noCache: true, noDriverHook: true, dataOnly: true }
|
|
687
|
+
const filter = { query: { status: 'ACTIVE' } }
|
|
688
|
+
const results = await getModel(`Sumba${type}Guard`).findAllRecord(filter, options)
|
|
689
|
+
return results.map(result => {
|
|
690
|
+
result.teamIds = result.teamIds.map(item => item + '')
|
|
691
|
+
return result
|
|
692
|
+
})
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Process and order the guards based on their path and weight.
|
|
697
|
+
*
|
|
698
|
+
* @method
|
|
699
|
+
* @private
|
|
700
|
+
* @param {Array} inputs - The array of guard inputs.
|
|
701
|
+
* @returns {Array} - The processed and ordered array of guards.
|
|
702
|
+
*/
|
|
703
|
+
_getGuards = (inputs = []) => {
|
|
704
|
+
const { routePath } = this.app.waibu
|
|
705
|
+
const { orderBy } = this.app.lib._
|
|
706
|
+
const normal = orderBy(inputs.filter(input => {
|
|
707
|
+
try {
|
|
708
|
+
input.path = routePath(input.path)
|
|
709
|
+
} catch (err) {
|
|
710
|
+
return false
|
|
711
|
+
}
|
|
712
|
+
return input.path[0] !== '!'
|
|
713
|
+
}), ['weight', 'path'], ['desc', 'asc'])
|
|
714
|
+
const inverse = orderBy(inputs.filter(input => {
|
|
715
|
+
try {
|
|
716
|
+
input.path = routePath(input.path)
|
|
717
|
+
} catch (err) {
|
|
718
|
+
return false
|
|
719
|
+
}
|
|
720
|
+
return input.path[0] === '!'
|
|
721
|
+
}), ['weight', 'path'], ['desc', 'asc'])
|
|
722
|
+
return [...normal, ...inverse]
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* Get anonymous guards, optionally reloading them from the database.
|
|
727
|
+
*
|
|
728
|
+
* @async
|
|
729
|
+
* @method
|
|
730
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
731
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of anonymous guards.
|
|
732
|
+
*/
|
|
733
|
+
getAnonymousGuards = async (reread) => {
|
|
734
|
+
if (!reread) return this.anonymousGuards
|
|
735
|
+
const guards = await this._fetchGuards('Anonymous')
|
|
736
|
+
this.anonymousGuards = this._getGuards(guards)
|
|
737
|
+
return this.anonymousGuards
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* Get secure guards, optionally reloading them from the database.
|
|
742
|
+
*
|
|
743
|
+
* @async
|
|
744
|
+
* @method
|
|
745
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
746
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of secure guards.
|
|
747
|
+
*/
|
|
748
|
+
getSecureGuards = async (reread) => {
|
|
749
|
+
if (!reread) return this.secureGuards
|
|
750
|
+
const guards = await this._fetchGuards('Secure')
|
|
751
|
+
this.secureGuards = this._getGuards(guards)
|
|
752
|
+
return this.secureGuards
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Get query guards, optionally reloading them from the database.
|
|
757
|
+
*
|
|
758
|
+
* @async
|
|
759
|
+
* @method
|
|
760
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
761
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of query guards.
|
|
762
|
+
*/
|
|
763
|
+
getQueryGuards = async (reread) => {
|
|
764
|
+
if (!reread) return this.queryGuards
|
|
765
|
+
|
|
766
|
+
this.queryGuards = await this._fetchGuards('Query')
|
|
767
|
+
return this.queryGuards
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Get action guards, optionally reloading them from the database.
|
|
772
|
+
*
|
|
773
|
+
* @async
|
|
774
|
+
* @method
|
|
775
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
776
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of action guards.
|
|
777
|
+
*/
|
|
778
|
+
getActionGuards = async (reread) => {
|
|
779
|
+
if (!reread) return this.actionGuards
|
|
780
|
+
|
|
781
|
+
this.actionGuards = await this._fetchGuards('Action')
|
|
782
|
+
return this.actionGuards
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* Get attribute guards, optionally reloading them from the database.
|
|
787
|
+
*
|
|
788
|
+
* @async
|
|
789
|
+
* @method
|
|
790
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
791
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of attribute guards.
|
|
792
|
+
*/
|
|
793
|
+
getAttribGuards = async (reread) => {
|
|
794
|
+
if (!reread) return this.attribGuards
|
|
795
|
+
|
|
796
|
+
this.attribGuards = await this._fetchGuards('Attrib')
|
|
797
|
+
return this.attribGuards
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Get all loaded model names, optionally returning them as value-text pairs.
|
|
802
|
+
*
|
|
803
|
+
* @method
|
|
804
|
+
* @param {boolean} [asValue] - Whether to return the model names as value-text pairs.
|
|
805
|
+
* @returns {Array} - An array of model names or value-text pairs.
|
|
806
|
+
*/
|
|
807
|
+
getModelNames = (asValue) => {
|
|
808
|
+
const values = this.app.dobo.models.map(item => item.name).sort()
|
|
809
|
+
return asValue ? values.map(item => ({ value: item, text: item })) : values
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Gather all paths to check for a request.
|
|
814
|
+
*
|
|
815
|
+
* @method
|
|
816
|
+
* @param {Object} req - The request object.
|
|
817
|
+
* @returns {Array} - An array of paths to check.
|
|
818
|
+
*/
|
|
819
|
+
pathsToCheck = (req) => {
|
|
820
|
+
const { isSet } = this.app.lib.aneka
|
|
821
|
+
const { uniq, without } = this.app.lib._
|
|
822
|
+
const items = [req.routeOptions.url, req.url].filter(url => isSet(url)).map(url => url.split('?')[0].split('#')[0])
|
|
823
|
+
return uniq(without(items, undefined, null))
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Check and set the iconset for a request.
|
|
828
|
+
*
|
|
829
|
+
* @async
|
|
830
|
+
* @method
|
|
831
|
+
* @param {Object} req - The request object.
|
|
832
|
+
* @param {Object} reply - The reply object.
|
|
833
|
+
* @returns {Promise<void>} - A promise that resolves when the iconset is checked and set.
|
|
834
|
+
*/
|
|
835
|
+
checkIconset = async (req, reply) => {
|
|
836
|
+
const { get, isString } = this.app.lib._
|
|
837
|
+
const mpa = this.app.waibuMpa
|
|
838
|
+
|
|
839
|
+
if (!req.site) return
|
|
840
|
+
const siteIconset = get(req, 'site.setting.waibuMpa.iconset')
|
|
841
|
+
req.iconset = siteIconset ?? get(mpa, 'config.iconset.set', 'default')
|
|
842
|
+
const hiconset = req.headers['x-iconset']
|
|
843
|
+
if (isString(hiconset) && mpa.getIconset(hiconset)) req.iconset = hiconset
|
|
844
|
+
req.iconset = req.iconset ?? 'default'
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Check and set the theme for a request.
|
|
849
|
+
*
|
|
850
|
+
* @async
|
|
851
|
+
* @method
|
|
852
|
+
* @param {Object} req - The request object.
|
|
853
|
+
* @param {Object} reply - The reply object.
|
|
854
|
+
* @returns {Promise<void>} - A promise that resolves when the theme is checked and set.
|
|
855
|
+
*/
|
|
856
|
+
checkTheme = async (req, reply) => {
|
|
857
|
+
const { get, isString } = this.app.lib._
|
|
858
|
+
const mpa = this.app.waibuMpa
|
|
859
|
+
|
|
860
|
+
if (!req.site) return
|
|
861
|
+
const siteTheme = get(req, 'site.setting.waibuMpa.theme')
|
|
862
|
+
req.theme = siteTheme ?? get(mpa, 'config.theme.set', 'default')
|
|
863
|
+
const htheme = req.headers['x-theme']
|
|
864
|
+
if (isString(htheme) && mpa.getTheme(htheme)) req.theme = htheme
|
|
865
|
+
req.theme = req.theme ?? 'default'
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* Check and set the team for a request.
|
|
870
|
+
*
|
|
871
|
+
* @async
|
|
872
|
+
* @method
|
|
873
|
+
* @param {Object} req - The request object.
|
|
874
|
+
* @param {Object} reply - The reply object.
|
|
875
|
+
* @returns {Promise<void>} - A promise that resolves when the team is checked and set.
|
|
876
|
+
*/
|
|
877
|
+
checkTeam = async (req, reply) => {
|
|
878
|
+
const { includes } = this.app.lib.aneka
|
|
879
|
+
const { outmatch } = this.app.lib
|
|
880
|
+
|
|
881
|
+
if (req.user.isAdmin) return
|
|
882
|
+
if (req.routeOptions.config.xSite && req.user.isXSiteAdmin) return
|
|
883
|
+
|
|
884
|
+
const teamIds = req.user.teams.map(item => item.id + '')
|
|
885
|
+
// if (req.user.teams.map(item => item.alias).length === 0) throw this.error('accessDenied', { statusCode: 403 })
|
|
886
|
+
|
|
887
|
+
const paths = this.pathsToCheck(req)
|
|
888
|
+
const results = (await this.getSecureGuards()).filter(item => {
|
|
889
|
+
if (item.siteId !== req.site.id + '' || item.path[0] === '!') return false
|
|
890
|
+
return paths.some(outmatch([item.path]))
|
|
891
|
+
})
|
|
892
|
+
for (const result of results) {
|
|
893
|
+
if (result.allTeams) continue
|
|
894
|
+
if (!includes(teamIds, result.teamIds)) throw this.error('accessDenied', { statusCode: 403 })
|
|
895
|
+
}
|
|
896
|
+
// passed
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/**
|
|
900
|
+
* Check and set the user for a request.
|
|
901
|
+
*
|
|
902
|
+
* @async
|
|
903
|
+
* @method
|
|
904
|
+
* @param {Object} req - The request object.
|
|
905
|
+
* @param {Object} reply - The reply object.
|
|
906
|
+
* @param {Object} source - The source object.
|
|
907
|
+
* @returns {Promise<boolean|void>} - A promise that resolves to a boolean indicating the result of the check or void.
|
|
908
|
+
*/
|
|
909
|
+
checkUser = async (req, reply, source) => {
|
|
910
|
+
const { merge, isEmpty, camelCase, get } = this.app.lib._
|
|
911
|
+
const { routePath } = this.app.waibu
|
|
912
|
+
const userId = get(req, 'session.userId')
|
|
913
|
+
const setUser = async () => {
|
|
914
|
+
if (!userId) return
|
|
915
|
+
try {
|
|
916
|
+
const user = await this.getUserById(userId, req)
|
|
917
|
+
if (user) req.user = user
|
|
918
|
+
else req.session.userId = null
|
|
919
|
+
} catch (err) {
|
|
920
|
+
console.log(err)
|
|
921
|
+
req.session.userId = null
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
if (req.session) req.session.siteId = req.site.id
|
|
926
|
+
|
|
927
|
+
const webApp = get(req, 'routeOptions.config.webApp', 'waibu')
|
|
928
|
+
if (!req.routeOptions.url) {
|
|
929
|
+
if (!req.session) return
|
|
930
|
+
await setUser()
|
|
931
|
+
return
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const paths = this.pathsToCheck(req)
|
|
935
|
+
let guards = (await this.getAnonymousGuards()).filter(item => item.siteId === req.site.id + '')
|
|
936
|
+
const anonymous = this.checkRouteGuard(guards, paths)
|
|
937
|
+
if (anonymous) {
|
|
938
|
+
if (!userId) return false
|
|
939
|
+
req.session.ref = req.url
|
|
940
|
+
return reply.redirectTo(routePath(this.config.redirect.signout))
|
|
941
|
+
}
|
|
942
|
+
guards = (await this.getSecureGuards()).filter(item => item.siteId === req.site.id + '')
|
|
943
|
+
const secure = this.checkRouteGuard(guards, paths)
|
|
944
|
+
if (!secure) {
|
|
945
|
+
if (userId) await setUser()
|
|
946
|
+
return false // regular, unguarded path. Not secure & not anonymous path
|
|
947
|
+
}
|
|
948
|
+
if (userId) {
|
|
949
|
+
await setUser()
|
|
950
|
+
return secure
|
|
951
|
+
}
|
|
952
|
+
const { silentOnError, methods } = this._getAuthSetting(null, webApp)
|
|
953
|
+
const payload = silentOnError ? { noContent: true } : undefined
|
|
954
|
+
if (isEmpty(methods)) throw this.error('noAuthMethod', merge({ statusCode: 500 }, payload))
|
|
955
|
+
let success
|
|
956
|
+
for (const m of methods) {
|
|
957
|
+
const handler = this[camelCase(`verify ${m}`)]
|
|
958
|
+
if (!handler) throw this.error('invalidAuthMethod%s', m, merge({ statusCode: 500 }, payload))
|
|
959
|
+
const check = await handler(req, reply, source, payload)
|
|
960
|
+
if (check) {
|
|
961
|
+
success = check
|
|
962
|
+
break
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
if (!success) throw this.error('accessDeniedNoAuth', merge({ statusCode: 403 }, payload))
|
|
966
|
+
return secure
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Check and set the Cross-site settings for a request.
|
|
971
|
+
*
|
|
972
|
+
* @async
|
|
973
|
+
* @method
|
|
974
|
+
* @param {Object} req - The request object.
|
|
975
|
+
* @param {Object} reply - The reply object.
|
|
976
|
+
* @returns {Promise<void>} - A promise that resolves when the XSite is checked and set.
|
|
977
|
+
*/
|
|
978
|
+
checkXSite = async (req, reply) => {
|
|
979
|
+
const { get } = this.app.lib._
|
|
980
|
+
if (!this.config.multiSite.enabled) return
|
|
981
|
+
const config = get(req, 'routeOptions.config')
|
|
982
|
+
if (!get(config, 'xSite') || ['/dashboard'].includes(config.pathSrc)) return
|
|
983
|
+
if (!get(req, 'user.isXSiteAdmin')) throw this.error('accessDenied', { statusCode: 403 })
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* Check the route for a request.
|
|
988
|
+
*
|
|
989
|
+
* @async
|
|
990
|
+
* @method
|
|
991
|
+
* @param {Object} req - The request object.
|
|
992
|
+
* @returns {Promise<void>} - A promise that resolves when the route is checked.
|
|
993
|
+
*/
|
|
994
|
+
checkRoute = async (req) => {
|
|
995
|
+
const { routePath } = this.app.waibu
|
|
996
|
+
const { outmatch } = this.app.lib
|
|
997
|
+
const routes = req.getSetting('waibu:route.disabled', []).map(item => routePath(item, false))
|
|
998
|
+
if (routes.length === 0) return
|
|
999
|
+
const isMatch = outmatch(routes)
|
|
1000
|
+
const paths = this.pathsToCheck(req)
|
|
1001
|
+
if (paths.find(isMatch)) throw this.error('_notFound')
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* Parse namespace settings for a request.
|
|
1006
|
+
*
|
|
1007
|
+
* @method
|
|
1008
|
+
* @param {string} ns - The namespace.
|
|
1009
|
+
* @param {Object} setting - The setting object.
|
|
1010
|
+
* @param {Array} items - The items to parse.
|
|
1011
|
+
*/
|
|
1012
|
+
parseNsSettings = (ns, setting, items) => {
|
|
1013
|
+
const { trim, set, isPlainObject, isArray, isEmpty, find } = this.app.lib._
|
|
1014
|
+
const { parseObject, dayjs } = this.app.lib
|
|
1015
|
+
|
|
1016
|
+
for (const item of items) {
|
|
1017
|
+
if (item.ns === '_var' || ns === '_var') continue
|
|
1018
|
+
let value = trim([item.value] ?? '')
|
|
1019
|
+
if (value[0] === '#' && value[value.length - 1] === '#') {
|
|
1020
|
+
const val = value.slice(1, -1)
|
|
1021
|
+
const newValue = find(items, { ns: '_var', key: val })
|
|
1022
|
+
if (newValue) value = newValue.value
|
|
1023
|
+
}
|
|
1024
|
+
if (['[', '{'].includes(value[0]) && [']', '}'].includes(value[value.length - 1])) {
|
|
1025
|
+
try {
|
|
1026
|
+
value = parseObject(JSON.parse(value))
|
|
1027
|
+
} catch (err) {}
|
|
1028
|
+
} else if (Number(value)) value = Number(value)
|
|
1029
|
+
else if (['true', 'false'].includes(value)) value = value === 'true'
|
|
1030
|
+
else {
|
|
1031
|
+
const dt = dayjs(value)
|
|
1032
|
+
if (dt.isValid()) value = dt.toDate()
|
|
1033
|
+
}
|
|
1034
|
+
if ((isPlainObject(value) || isArray(value)) && isEmpty(value)) continue
|
|
1035
|
+
set(setting, `${ns}.${item.key}`, value)
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Get all fixtures for the specified alias, replacing any occurrences of '{alias}' in the fixture data with the provided alias.
|
|
1041
|
+
*
|
|
1042
|
+
* @async
|
|
1043
|
+
* @method
|
|
1044
|
+
* @param {string} [alias] - The alias for the fixtures.
|
|
1045
|
+
* @returns {Promise<object>} - A promise that resolves to the fixtures data.
|
|
1046
|
+
*/
|
|
1047
|
+
getAllFixtures = async (alias) => {
|
|
1048
|
+
const { readConfig } = this.app.bajo
|
|
1049
|
+
const { isEmpty, omit, kebabCase, isString } = this.app.lib._
|
|
1050
|
+
const { getModel } = this.app.dobo
|
|
1051
|
+
const { fastGlob } = this.app.lib
|
|
1052
|
+
const data = {}
|
|
1053
|
+
|
|
1054
|
+
function replaceAlias (alias, items) {
|
|
1055
|
+
for (const item of items) {
|
|
1056
|
+
for (const key in item) {
|
|
1057
|
+
const val = item[key]
|
|
1058
|
+
if (isString(val)) item[key] = val.replaceAll('{alias}', alias)
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
const formats = this.app.configHandlers.map(item => item.ext.slice(1))
|
|
1064
|
+
const overrideBase = `${this.app.getPluginDataDir('sumba')}/create-new-site-fixtures/${alias}`
|
|
1065
|
+
const models = this.app.dobo.models.filter(m => {
|
|
1066
|
+
const prop = m.properties.find(p => p.name === 'siteId')
|
|
1067
|
+
return !!prop
|
|
1068
|
+
}).map(m => m.name)
|
|
1069
|
+
models.unshift('SumbaSite')
|
|
1070
|
+
const files = (await fastGlob(`${overrideBase}/*.{${formats.join(',')}}`)).map(file => {
|
|
1071
|
+
const ext = path.extname(file)
|
|
1072
|
+
return file.slice(0, file.length - ext.length)
|
|
1073
|
+
})
|
|
1074
|
+
for (const m of models) {
|
|
1075
|
+
const model = getModel(m)
|
|
1076
|
+
const file = `${overrideBase}/${kebabCase(m)}`
|
|
1077
|
+
let fixtures = (await model.loadFixtures({ collectItems: true, noLookup: true })) ?? []
|
|
1078
|
+
if (files.includes(file)) {
|
|
1079
|
+
const items = await readConfig(file, { defValue: [] })
|
|
1080
|
+
if (!isEmpty(items)) fixtures = items
|
|
1081
|
+
}
|
|
1082
|
+
if (!Array.isArray(fixtures)) fixtures = [fixtures]
|
|
1083
|
+
if (fixtures.length === 0) continue
|
|
1084
|
+
replaceAlias(alias, fixtures)
|
|
1085
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1086
|
+
const omitted = ['_attachments', 'siteId']
|
|
1087
|
+
for (const item of ['createdAt', 'updatedAt', 'immutable']) {
|
|
1088
|
+
const props = model.properties.filter(prop => prop.feature === ('dobo:' + item)).map(prop => prop.name)
|
|
1089
|
+
if (props.length > 0) omitted.push(...props)
|
|
1090
|
+
}
|
|
1091
|
+
for (const idx in fixtures) {
|
|
1092
|
+
fixtures[idx] = omit(fixtures[idx], omitted)
|
|
1093
|
+
}
|
|
1094
|
+
data[m] = m === 'SumbaSite' ? fixtures[0] : fixtures
|
|
1095
|
+
}
|
|
1096
|
+
return data
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* Create references for the specified site using the provided data, options, and verbosity settings.
|
|
1101
|
+
*
|
|
1102
|
+
* @async
|
|
1103
|
+
* @method
|
|
1104
|
+
* @param {object} site - The site object for which to create references.
|
|
1105
|
+
* @param {object} data - The data object containing fixtures for the site.
|
|
1106
|
+
* @param {object} options - Options to pass to the createRecord method.
|
|
1107
|
+
* @param {boolean} verbose - Whether to log verbose output.
|
|
1108
|
+
*/
|
|
1109
|
+
createRefs = async (site, data, options, verbose) => {
|
|
1110
|
+
const { isString } = this.app.lib._
|
|
1111
|
+
const { getModel } = this.app.dobo
|
|
1112
|
+
for (const m in data) {
|
|
1113
|
+
if (m === 'SumbaSite') continue
|
|
1114
|
+
const mdl = getModel(m)
|
|
1115
|
+
const fixtures = data[m]
|
|
1116
|
+
for (const f of fixtures) {
|
|
1117
|
+
f.siteId = site.id + ''
|
|
1118
|
+
const lv = { siteId: f.siteId }
|
|
1119
|
+
for (const key in f) {
|
|
1120
|
+
const val = f[key]
|
|
1121
|
+
if (isString(val) && val.slice(0, 2) === '?:') f[key] = await mdl._simpleLookup(val.slice(2), lv, options)
|
|
1122
|
+
}
|
|
1123
|
+
await mdl.createRecord(f, { ...options, noFlash: true })
|
|
1124
|
+
}
|
|
1125
|
+
if (verbose) this.print.succeed('writingModel%s%s', mdl.name, fixtures.length)
|
|
1126
|
+
}
|
|
1127
|
+
if (verbose) this.print.succeed('populateRouteGuard')
|
|
1128
|
+
await this.populateRouteGuards([site])
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/**
|
|
1132
|
+
* Create a new site with the specified alias and optional hostname, using fixtures for initial data.
|
|
1133
|
+
*
|
|
1134
|
+
* @async
|
|
1135
|
+
* @method
|
|
1136
|
+
* @param {string} alias - The alias for the new site.
|
|
1137
|
+
* @param {string} [hostname] - The hostname for the new site.
|
|
1138
|
+
* @param {boolean} [verbose=false] - Whether to log verbose output.
|
|
1139
|
+
*/
|
|
1140
|
+
createNewSite = async (alias, hostname, verbose) => {
|
|
1141
|
+
const { isEmpty } = this.app.lib._
|
|
1142
|
+
const { getModel } = this.app.dobo
|
|
1143
|
+
|
|
1144
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1145
|
+
let spin
|
|
1146
|
+
if (verbose) spin = this.print.spinner().start('processing...')
|
|
1147
|
+
const query = { $or: [{ alias }] }
|
|
1148
|
+
if (!isEmpty(hostname)) query.$or.push({ hostname })
|
|
1149
|
+
const model = getModel('SumbaSite')
|
|
1150
|
+
const site = await model.findOneRecord({ query })
|
|
1151
|
+
if (!isEmpty(site)) {
|
|
1152
|
+
if (verbose) spin.stop()
|
|
1153
|
+
throw this.error('aliasOrHostnameExists%s%s', alias, hostname ?? '')
|
|
1154
|
+
}
|
|
1155
|
+
// lets go
|
|
1156
|
+
const fixtures = await this.getAllFixtures(alias)
|
|
1157
|
+
if (verbose) spin.stop()
|
|
1158
|
+
fixtures.SumbaSite.alias = alias
|
|
1159
|
+
if (!isEmpty(hostname)) fixtures.SumbaSite.hostname = hostname
|
|
1160
|
+
await model.transaction(async (trx) => {
|
|
1161
|
+
const newSite = await model.createRecord(fixtures.SumbaSite, { trx, noHook: true })
|
|
1162
|
+
if (verbose) this.print.succeed('writingModel%s%s', model.name, 1)
|
|
1163
|
+
const options = { trx }
|
|
1164
|
+
await this.createRefs(newSite, fixtures, options, verbose)
|
|
1165
|
+
})
|
|
1166
|
+
if (verbose) this.print.info('done')
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
/**
|
|
1170
|
+
* Remove references for the specified site using the provided options and verbosity settings.
|
|
1171
|
+
*
|
|
1172
|
+
* @async
|
|
1173
|
+
* @method
|
|
1174
|
+
* @param {object} site - The site object for which to remove references.
|
|
1175
|
+
* @param {object} options - Options to pass to the removeRecord method.
|
|
1176
|
+
* @param {boolean} verbose - Whether to log verbose output.
|
|
1177
|
+
*/
|
|
1178
|
+
removeRefs = async (site, options, verbose) => {
|
|
1179
|
+
const { orderBy } = this.app.lib._
|
|
1180
|
+
const { getModel } = this.app.dobo
|
|
1181
|
+
const models = orderBy(this.app.dobo.models, ['buildLevel'], ['desc']).filter(m => {
|
|
1182
|
+
const prop = m.properties.find(p => p.name === 'siteId')
|
|
1183
|
+
return !!prop
|
|
1184
|
+
}).map(m => m.name)
|
|
1185
|
+
for (const m of models) {
|
|
1186
|
+
const mdl = getModel(m)
|
|
1187
|
+
const rows = await mdl.findAllRecord({ query: { siteId: site.id + '' } }, { ...options, dataOnly: true })
|
|
1188
|
+
const ids = rows.map(item => item.id)
|
|
1189
|
+
// TODO: backup
|
|
1190
|
+
if (ids.length === 0) continue
|
|
1191
|
+
for (const id of ids) {
|
|
1192
|
+
await mdl.removeRecord(id, { noReturn: true, ...options, noFlash: true })
|
|
1193
|
+
}
|
|
1194
|
+
if (verbose) this.print.succeed('removedFrom%s%s', mdl.name, ids.length)
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Remove a site with the specified alias, along with its references, using the provided verbosity settings.
|
|
1200
|
+
*
|
|
1201
|
+
* @async
|
|
1202
|
+
* @method
|
|
1203
|
+
* @param {string} alias - The alias of the site to remove.
|
|
1204
|
+
* @param {boolean} [verbose=false] - Whether to log verbose output.
|
|
1205
|
+
*/
|
|
1206
|
+
removeSite = async (alias, verbose) => {
|
|
1207
|
+
const { isEmpty } = this.app.lib._
|
|
1208
|
+
const { getModel } = this.app.dobo
|
|
1209
|
+
|
|
1210
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1211
|
+
const model = getModel('SumbaSite')
|
|
1212
|
+
const query = { alias }
|
|
1213
|
+
const site = await model.findOneRecord({ query })
|
|
1214
|
+
if (isEmpty(site)) throw this.error('aliasNotFound%s', alias)
|
|
1215
|
+
await model.transaction(async (trx) => {
|
|
1216
|
+
const options = { trx, noHook: true }
|
|
1217
|
+
await this.removeRefs(site, options, verbose)
|
|
1218
|
+
await model.removeRecord(site.id, { noReturn: true, trx, noHook: true })
|
|
1219
|
+
if (verbose) this.print.succeed('removedFrom%s%s', model.name, 1)
|
|
1220
|
+
})
|
|
1221
|
+
if (verbose) this.print.info('done')
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/**
|
|
1225
|
+
* 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.
|
|
1226
|
+
*
|
|
1227
|
+
* @async
|
|
1228
|
+
* @method
|
|
1229
|
+
* @param {string|number} input - The input value, which can be either a hostname or an ID.
|
|
1230
|
+
* @param {boolean} [byId=false] - Whether to fetch the site by ID.
|
|
1231
|
+
* @returns {object} The site information.
|
|
1232
|
+
*/
|
|
1233
|
+
getSite = async (input, byId = false) => {
|
|
1234
|
+
const { omit } = this.app.lib._
|
|
1235
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1236
|
+
const omitted = ['status']
|
|
1237
|
+
|
|
1238
|
+
let site = {}
|
|
1239
|
+
const mergeSetting = async (site) => {
|
|
1240
|
+
const { defaultsDeep, isSet } = this.app.lib.aneka
|
|
1241
|
+
const { get, filter } = this.app.lib._
|
|
1242
|
+
const defSetting = {}
|
|
1243
|
+
const nsSetting = {}
|
|
1244
|
+
const names = this.app.getAllNs()
|
|
1245
|
+
const query = {
|
|
1246
|
+
ns: { $in: names },
|
|
1247
|
+
siteId: site.id + ''
|
|
1248
|
+
}
|
|
1249
|
+
const all = await this.app.dobo.getModel('SumbaSiteSetting').findAllRecord({ query })
|
|
1250
|
+
for (const ns of names) {
|
|
1251
|
+
const item = get(this, `app.${ns}.config.siteSetting`)
|
|
1252
|
+
if (isSet(item)) defSetting[ns] = item
|
|
1253
|
+
const items = filter(all, { ns })
|
|
1254
|
+
this.parseNsSettings(ns, nsSetting, items)
|
|
1255
|
+
}
|
|
1256
|
+
site.setting = defaultsDeep({}, nsSetting, defSetting)
|
|
1257
|
+
// additional fields
|
|
1258
|
+
const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noMagic: true })
|
|
1259
|
+
site.countryName = (country ?? {}).name ?? site.country
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
if (!this.config.multiSite.enabled) {
|
|
1263
|
+
const filter = { query: { alias: 'default' } }
|
|
1264
|
+
const key = 'dobo|SumbaSite|getSite|default'
|
|
1265
|
+
if (getCache) {
|
|
1266
|
+
site = await getCache({ key })
|
|
1267
|
+
if (site) return site
|
|
1268
|
+
}
|
|
1269
|
+
const resp = await this.app.dobo.getModel('SumbaSite').findOneRecord(filter, { noHook: true })
|
|
1270
|
+
site = omit(resp, omitted)
|
|
1271
|
+
await mergeSetting(site)
|
|
1272
|
+
if (setCache) {
|
|
1273
|
+
await setCache({ key, value: site, ttl: this.config.cacheTtl.getSiteDur })
|
|
1274
|
+
}
|
|
1275
|
+
return site
|
|
1276
|
+
}
|
|
1277
|
+
let query
|
|
1278
|
+
if (byId) query = { id: input }
|
|
1279
|
+
else query = { hostname: input }
|
|
1280
|
+
const key = `dobo|SumbaSite|getSite|multiSite|${input}`
|
|
1281
|
+
if (getCache) {
|
|
1282
|
+
site = await getCache({ key })
|
|
1283
|
+
if (site) return JSON.parse(site)
|
|
1284
|
+
}
|
|
1285
|
+
let row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
|
|
1286
|
+
if (!row) {
|
|
1287
|
+
if (this.config.multiSite.catchAll) {
|
|
1288
|
+
query = { alias: this.config.multiSite.catchAll === true ? 'default' : this.config.multiSite.catchAll }
|
|
1289
|
+
row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
|
|
1290
|
+
}
|
|
1291
|
+
if (!row) throw this.error('unknownSite')
|
|
1292
|
+
}
|
|
1293
|
+
if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
|
|
1294
|
+
site = omit(row, omitted)
|
|
1295
|
+
await mergeSetting(site)
|
|
1296
|
+
if (setCache) {
|
|
1297
|
+
await setCache({ key, value: JSON.stringify(site), ttl: this.config.cacheTtl.getSiteDur })
|
|
1298
|
+
}
|
|
1299
|
+
return site
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* Merge team information into the user object.
|
|
1304
|
+
*
|
|
1305
|
+
* @async
|
|
1306
|
+
* @method
|
|
1307
|
+
* @param {object} user - The user object to merge team information into.
|
|
1308
|
+
* @param {object} req - The request object.
|
|
1309
|
+
*/
|
|
1310
|
+
mergeTeam = async (user, req) => {
|
|
1311
|
+
const { map, pick } = this.app.lib._
|
|
1312
|
+
const { getModel } = this.app.dobo
|
|
1313
|
+
user.teams = []
|
|
1314
|
+
const query = { userId: user.id + '', siteId: user.siteId, status: 'ACTIVE' }
|
|
1315
|
+
let mdl = getModel('SumbaTeamUser')
|
|
1316
|
+
const userTeam = await mdl.findAllRecord({ query })
|
|
1317
|
+
if (userTeam.length === 0) return
|
|
1318
|
+
delete query.userId
|
|
1319
|
+
const idProp = mdl.getProperty('id')
|
|
1320
|
+
const $in = userTeam.map(item => ['integer', 'smallint'].includes(idProp.type) ? parseInt(item.teamId) : item.teamId)
|
|
1321
|
+
query.id = { $in }
|
|
1322
|
+
mdl = getModel('SumbaTeam')
|
|
1323
|
+
const teams = await mdl.findAllRecord({ query })
|
|
1324
|
+
if (teams.length > 0) {
|
|
1325
|
+
delete query.id
|
|
1326
|
+
delete query.status
|
|
1327
|
+
query.teamId = { $in: teams.map(t => t.id + '') }
|
|
1328
|
+
mdl = getModel('SumbaTeamSetting')
|
|
1329
|
+
const items = await mdl.findAllRecord({ query })
|
|
1330
|
+
for (const team of teams) {
|
|
1331
|
+
const names = map(items, 'ns')
|
|
1332
|
+
const item = pick(team, ['id', 'alias'])
|
|
1333
|
+
item.setting = {}
|
|
1334
|
+
for (const ns of names) {
|
|
1335
|
+
this.parseNsSettings(ns, item.setting, items.filter(s => s.teamId === (team.id + '')))
|
|
1336
|
+
}
|
|
1337
|
+
user.teams.push(item)
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
user.isXSiteAdmin = this.config.xSiteAdmins.includes(`${req.site.alias}:${user.username}`)
|
|
1341
|
+
user.isAdmin = user.teams.some(t => t.alias === 'administrator')
|
|
1342
|
+
for (const field of this.unsafeUserFields) {
|
|
1343
|
+
delete user[field]
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
/**
|
|
1348
|
+
* Get a user by their ID.
|
|
1349
|
+
*
|
|
1350
|
+
* @async
|
|
1351
|
+
* @method
|
|
1352
|
+
* @param {string|number} id - The ID of the user to retrieve.
|
|
1353
|
+
* @param {object} req - The request object.
|
|
1354
|
+
* @returns {object|null} The user object if found, otherwise null.
|
|
1355
|
+
*/
|
|
1356
|
+
getUserById = async (id, req) => {
|
|
1357
|
+
const { getModel } = this.app.dobo
|
|
1358
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1359
|
+
const key = `dobo|SumbaUser|getUserById|${id}`
|
|
1360
|
+
let user
|
|
1361
|
+
if (getCache) {
|
|
1362
|
+
user = await getCache({ key })
|
|
1363
|
+
if (user) return JSON.parse(user)
|
|
1364
|
+
}
|
|
1365
|
+
user = await getModel('SumbaUser').getRecord(id, { noHook: true, noDriverHook: true, throwNotFound: false, req })
|
|
1366
|
+
if (!user) return
|
|
1367
|
+
await this.mergeTeam(user, req)
|
|
1368
|
+
if (setCache) {
|
|
1369
|
+
await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByIdDur })
|
|
1370
|
+
}
|
|
1371
|
+
return user
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/**
|
|
1375
|
+
* Get a user by their token.
|
|
1376
|
+
*
|
|
1377
|
+
* @async
|
|
1378
|
+
* @method
|
|
1379
|
+
* @param {string} token - The token of the user to retrieve.
|
|
1380
|
+
* @param {object} req - The request object.
|
|
1381
|
+
* @returns {object|null} The user object if found, otherwise null.
|
|
1382
|
+
*/
|
|
1383
|
+
getUserByToken = async (token, req) => {
|
|
1384
|
+
const { getModel } = this.app.dobo
|
|
1385
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1386
|
+
const key = `dobo|SumbaUser|getUserByToken|${token}`
|
|
1387
|
+
let user
|
|
1388
|
+
if (getCache) {
|
|
1389
|
+
user = await getCache({ key })
|
|
1390
|
+
if (user) return JSON.parse(user)
|
|
1391
|
+
}
|
|
1392
|
+
user = await getModel('SumbaUser').findOneRecord({ query: { token } }, { noHook: true, noDriverHook: true, throwNotFound: false, req })
|
|
1393
|
+
if (!user) return
|
|
1394
|
+
await this.mergeTeam(user, req)
|
|
1395
|
+
if (setCache) {
|
|
1396
|
+
await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByTokenDur })
|
|
1397
|
+
}
|
|
1398
|
+
return user
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
getUserByUsernamePassword = async (username = '', password = '', req) => {
|
|
1402
|
+
const { getModel } = this.app.dobo
|
|
1403
|
+
const { importPkg } = this.app.bajo
|
|
1404
|
+
const model = getModel('SumbaUser')
|
|
1405
|
+
await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
|
|
1406
|
+
const bcrypt = await importPkg('bajoExtra:bcrypt')
|
|
1407
|
+
|
|
1408
|
+
const query = { username, provider: 'local', siteId: req.site.id + '' }
|
|
1409
|
+
const user = await model.findOneRecord({ query }, { req, forceNoHidden: true, noHook: true, noDriverHook: true })
|
|
1410
|
+
if (!user) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
|
|
1411
|
+
if (user.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
|
|
1412
|
+
const verified = await bcrypt.compare(password, user.password)
|
|
1413
|
+
if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
|
|
1414
|
+
await this.mergeTeam(user, req)
|
|
1415
|
+
return user
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
/**
|
|
1419
|
+
* Clear the cache for a specific site.
|
|
1420
|
+
*
|
|
1421
|
+
* @async
|
|
1422
|
+
* @method
|
|
1423
|
+
* @param {string|number} id - The ID of the site.
|
|
1424
|
+
* @param {object} result - The result object containing site data.
|
|
1425
|
+
*/
|
|
1426
|
+
clearCacheSite = async (id, result) => {
|
|
1427
|
+
if (!this.app.bajoCache) return
|
|
1428
|
+
const { clear } = this.app.bajoCache ?? {}
|
|
1429
|
+
const { get } = this.app.lib._
|
|
1430
|
+
await clear({ key: 'dobo|SumbaSite|getSite|default' })
|
|
1431
|
+
await clear({ key: `dobo|SumbaSite|getSite|multiSite|${id}` })
|
|
1432
|
+
await clear({ key: `dobo|SumbaSite|getSite|multiSite|${get(result, 'data.hostname', get(result, 'oldData.hostname'))}` })
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
/**
|
|
1436
|
+
* Clear the cache for a specific user.
|
|
1437
|
+
*
|
|
1438
|
+
* @async
|
|
1439
|
+
* @method
|
|
1440
|
+
* @param {string|number} id - The ID of the user.
|
|
1441
|
+
* @param {object} result - The result object containing user data.
|
|
1442
|
+
*/
|
|
1443
|
+
clearCacheUser = async (id, result) => {
|
|
1444
|
+
if (!this.app.bajoCache) return
|
|
1445
|
+
const { clear } = this.app.bajoCache ?? {}
|
|
1446
|
+
const { get } = this.app.lib._
|
|
1447
|
+
const token = get(result, 'data.token', get(result, 'oldData.token', ''))
|
|
1448
|
+
await clear({ key: `dobo|SumbaUser|getUserById|${id}` })
|
|
1449
|
+
await clear({ key: `dobo|SumbaUser|getUserByToken|${token}` })
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/**
|
|
1453
|
+
* Filter model data based on settings.
|
|
1454
|
+
*
|
|
1455
|
+
* @method
|
|
1456
|
+
* @param {object} opts - The options object.
|
|
1457
|
+
* @param {object} opts.model - The model object.
|
|
1458
|
+
* @param {string} opts.field - The field to filter.
|
|
1459
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1460
|
+
* @returns {object} The filtered results and operation values.
|
|
1461
|
+
*/
|
|
1462
|
+
filterModelFromSetting = (opts = {}) => {
|
|
1463
|
+
const { model, field, options = {} } = opts
|
|
1464
|
+
const { isEmpty, isArray, set } = this.app.lib._
|
|
1465
|
+
const { isSet } = this.app.lib.aneka
|
|
1466
|
+
const { req } = options
|
|
1467
|
+
const opValue = req.getSetting(`sumba:queryGuard.${field}`, {})
|
|
1468
|
+
const results = []
|
|
1469
|
+
const prop = model.getProperty(field)
|
|
1470
|
+
for (const op of ['in', 'nin', 'inOrEmpty']) {
|
|
1471
|
+
if (isEmpty(opValue[op]) || !isArray(opValue[op])) continue
|
|
1472
|
+
if (op === 'inOrEmpty') {
|
|
1473
|
+
const val = set({}, field, set({}, '$in', opValue[op]))
|
|
1474
|
+
const nl = set({}, field, { $eq: null })
|
|
1475
|
+
const item = { $or: [val, nl] }
|
|
1476
|
+
let v
|
|
1477
|
+
if (['string', 'text'].includes(prop.type)) v = ''
|
|
1478
|
+
else if (['integer', 'smallint', 'float', 'double'].includes(prop.type)) v = 0
|
|
1479
|
+
if (isSet(v)) {
|
|
1480
|
+
const bl = set({}, field, { $eq: v })
|
|
1481
|
+
item.$or.push(bl)
|
|
1482
|
+
}
|
|
1483
|
+
results.push(item)
|
|
1484
|
+
} else results.push(set({}, field, set({}, '$' + op, opValue[op])))
|
|
1485
|
+
}
|
|
1486
|
+
return { results, opValue }
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* Apply query guards to the provided query.
|
|
1491
|
+
*
|
|
1492
|
+
* @async
|
|
1493
|
+
* @method
|
|
1494
|
+
* @param {object} [opts={}] - The options object.
|
|
1495
|
+
* @param {object} opts.model - The model object.
|
|
1496
|
+
* @param {object} [opts.q={}] - The query object.
|
|
1497
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1498
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1499
|
+
*/
|
|
1500
|
+
runQueryGuard = async (opts = {}) => {
|
|
1501
|
+
const { model, q = {}, teamIds = [], options = {} } = opts
|
|
1502
|
+
const { set, orderBy, isEmpty, isArray } = this.app.lib._
|
|
1503
|
+
const { includes } = this.app.lib.aneka
|
|
1504
|
+
const { sanitizeByType } = this.app.dobo
|
|
1505
|
+
const { req } = options
|
|
1506
|
+
const results = []
|
|
1507
|
+
|
|
1508
|
+
const guards = await this.getQueryGuards()
|
|
1509
|
+
const fields = model.getNonVirtualProperties().map(prop => prop.name)
|
|
1510
|
+
const filterFn = item => {
|
|
1511
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1512
|
+
const byModel = item.models.includes(model.name)
|
|
1513
|
+
const byFields = fields.includes(item.field)
|
|
1514
|
+
return bySiteId && byModel && byFields
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
const rules = orderBy(guards.filter(filterFn), ['field'])
|
|
1518
|
+
for (const field of fields) {
|
|
1519
|
+
if (!model.getNonVirtualProperties(true).includes(field)) continue // or, should it throws exception instead?
|
|
1520
|
+
const inSetting = this.filterModelFromSetting({ model, field, options })
|
|
1521
|
+
const prop = model.getProperty(field)
|
|
1522
|
+
const items = rules.filter(item => item.field === field)
|
|
1523
|
+
for (const item of items) {
|
|
1524
|
+
let values = item.value.map(val => {
|
|
1525
|
+
return sanitizeByType(val, prop.type, { strict: true, inputFormat: 'string', model: model.name })
|
|
1526
|
+
})
|
|
1527
|
+
const op = item.condition.toLowerCase()
|
|
1528
|
+
if (['in', 'nin'].includes(op) && !isEmpty(inSetting.opValue[op]) && isArray(inSetting.opValue[op])) values = values.filter(val => inSetting.opValue[op].includes(val))
|
|
1529
|
+
if (isEmpty(values)) continue
|
|
1530
|
+
let value
|
|
1531
|
+
if (['in', 'nin'].includes(op)) value = set({}, '$' + op, values)
|
|
1532
|
+
else if (op === 'between') value = { $gte: values[0], $lte: values[1] }
|
|
1533
|
+
else value = set({}, '$' + op, values[0])
|
|
1534
|
+
const teamOk = item.allTeams ? true : (item.teamIds.length === 0 ? false : includes(item.teamIds, teamIds))
|
|
1535
|
+
if (!teamOk) throw this.error('_abortAction')
|
|
1536
|
+
results.push(set({}, field, value))
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
q.$and.push(...results)
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* Apply attribute guards to the provided model.
|
|
1544
|
+
*
|
|
1545
|
+
* @async
|
|
1546
|
+
* @method
|
|
1547
|
+
* @param {object} [opts={}] - The options object.
|
|
1548
|
+
* @param {object} opts.model - The model object.
|
|
1549
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1550
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1551
|
+
*/
|
|
1552
|
+
runAttribGuard = async (opts = {}) => {
|
|
1553
|
+
const { model, teamIds = [], options = {} } = opts
|
|
1554
|
+
const { uniq } = this.app.lib._
|
|
1555
|
+
const { includes } = this.app.lib.aneka
|
|
1556
|
+
const { req } = options
|
|
1557
|
+
const results = []
|
|
1558
|
+
|
|
1559
|
+
const guards = await this.getAttribGuards()
|
|
1560
|
+
const filterFn = item => {
|
|
1561
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1562
|
+
const byModel = item.models.includes(model.name)
|
|
1563
|
+
const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
|
|
1564
|
+
return bySiteId && byModel && byTeamId
|
|
1565
|
+
}
|
|
1566
|
+
guards.filter(filterFn).forEach(item => results.push(...item.hiddenFields))
|
|
1567
|
+
options.hidden = options.hidden ?? []
|
|
1568
|
+
options.hidden.push(...results)
|
|
1569
|
+
options.hidden = uniq(options.hidden)
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* Get the team IDs and aliases for the user in the request.
|
|
1574
|
+
*
|
|
1575
|
+
* @method
|
|
1576
|
+
* @param {object} req - The request object.
|
|
1577
|
+
* @returns {object} An object containing the team IDs and aliases.
|
|
1578
|
+
*/
|
|
1579
|
+
getTeamIdsAndAliases = (req) => {
|
|
1580
|
+
const { get } = this.app.lib._
|
|
1581
|
+
const teams = get(req, 'user.teams', [])
|
|
1582
|
+
const teamIds = teams.map(team => team.id + '')
|
|
1583
|
+
const aliases = teams.map(team => team.alias)
|
|
1584
|
+
return { teamIds, aliases }
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
/**
|
|
1588
|
+
* Rebuild the filter for the provided model.
|
|
1589
|
+
*
|
|
1590
|
+
* @async
|
|
1591
|
+
* @method
|
|
1592
|
+
* @param {object} model - The model object.
|
|
1593
|
+
* @param {object} [filter={}] - The filter object.
|
|
1594
|
+
* @param {object} [options={}] - Additional options.
|
|
1595
|
+
* @returns {Promise<object>} The rebuilt filter.
|
|
1596
|
+
*/
|
|
1597
|
+
rebuildFilter = async (model, filter = {}, options = {}) => {
|
|
1598
|
+
const { isEmpty, get, keys } = this.app.lib._
|
|
1599
|
+
const { req } = options
|
|
1600
|
+
const allowEmpty = !get(this, `app.${model.ns}.config.sumba.noEmptyQuery`, []).includes(model.name)
|
|
1601
|
+
const hasSiteId = model.hasProperty('siteId')
|
|
1602
|
+
const hasUserId = model.hasProperty('userId')
|
|
1603
|
+
const hasTeamId = model.hasProperty('teamId')
|
|
1604
|
+
const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
|
|
1605
|
+
const q = { $and: [] }
|
|
1606
|
+
|
|
1607
|
+
filter.query = filter.query ?? {}
|
|
1608
|
+
if (!isEmpty(filter.query)) {
|
|
1609
|
+
if (filter.query.$and) q.$and.push(...filter.query.$and)
|
|
1610
|
+
else q.$and.push(filter.query)
|
|
1611
|
+
}
|
|
1612
|
+
if (req.routeOptions.config.xSite) {
|
|
1613
|
+
filter.query = q
|
|
1614
|
+
return
|
|
1615
|
+
}
|
|
1616
|
+
if (hasSiteId) q.$and.push({ siteId: req.site.id + '' })
|
|
1617
|
+
if (aliases.includes('administrator')) {
|
|
1618
|
+
if (get(req, 'site.alias') === 'default') {
|
|
1619
|
+
filter.query = q
|
|
1620
|
+
return
|
|
1621
|
+
}
|
|
1622
|
+
const fields = keys(req.getSetting('sumba:queryGuard', {}))
|
|
1623
|
+
const results = []
|
|
1624
|
+
for (const field of fields) {
|
|
1625
|
+
if (!model.hasProperty(field)) continue
|
|
1626
|
+
const inSetting = this.filterModelFromSetting({ model, field, options })
|
|
1627
|
+
if (inSetting.results.length > 0) results.push(...inSetting.results)
|
|
1628
|
+
}
|
|
1629
|
+
if (results.length > 0) q.$and.push(...results)
|
|
1630
|
+
filter.query = q
|
|
1631
|
+
return
|
|
1632
|
+
}
|
|
1633
|
+
if (isEmpty(req.user)) {
|
|
1634
|
+
if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
|
|
1635
|
+
filter.query = q
|
|
1636
|
+
return
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
const condUserId = {
|
|
1640
|
+
$or: [
|
|
1641
|
+
{ userId: req.user.id + '' },
|
|
1642
|
+
{ userId: { $eq: null } }
|
|
1643
|
+
]
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
const condTeamId = {
|
|
1647
|
+
$or: [
|
|
1648
|
+
{ teamId: { $in: teamIds } },
|
|
1649
|
+
{ teamId: { $eq: null } }
|
|
1650
|
+
]
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
if (hasTeamId) {
|
|
1654
|
+
if (hasUserId) q.$and.push({ $or: [condTeamId, condUserId] })
|
|
1655
|
+
else q.$and.push(condTeamId)
|
|
1656
|
+
} else if (hasUserId) q.$and.push(condUserId)
|
|
1657
|
+
|
|
1658
|
+
await this.runQueryGuard({ model, q, teamIds, options, allowEmpty })
|
|
1659
|
+
await this.runAttribGuard({ model, teamIds, options })
|
|
1660
|
+
if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
|
|
1661
|
+
filter.query = q
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
/**
|
|
1665
|
+
* Apply query hook to the provided model.
|
|
1666
|
+
*
|
|
1667
|
+
* @async
|
|
1668
|
+
* @method
|
|
1669
|
+
* @param {object} model - The model object.
|
|
1670
|
+
* @param {string|number} id - The ID of the model.
|
|
1671
|
+
* @param {object} options - Additional options.
|
|
1672
|
+
* @returns {object} The result of the model hook.
|
|
1673
|
+
*/
|
|
1674
|
+
applyQueryHook = async (model, id, options = {}) => {
|
|
1675
|
+
const { isEmpty } = this.app.lib._
|
|
1676
|
+
const { req = {} } = options
|
|
1677
|
+
if (options.noAutoFilter || isEmpty(req) || isEmpty(req.site)) return
|
|
1678
|
+
|
|
1679
|
+
const filter = {}
|
|
1680
|
+
await this.rebuildFilter(model, filter, options)
|
|
1681
|
+
if (filter.query.$and) filter.query.$and.push({ id })
|
|
1682
|
+
else filter.query.id = id
|
|
1683
|
+
const row = await model.findOneRecord(filter, { count: false })
|
|
1684
|
+
if (!row) throw this.app.dobo.error('recordNotFound%s%s', id, this.name, { statusCode: 404 })
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
/**
|
|
1688
|
+
* Apply action hook to the provided model.
|
|
1689
|
+
*
|
|
1690
|
+
* @async
|
|
1691
|
+
* @method
|
|
1692
|
+
* @param {object} [opts={}] - The options object.
|
|
1693
|
+
* @param {object} opts.model - The model object.
|
|
1694
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1695
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1696
|
+
*/
|
|
1697
|
+
applyActionHook = async (opts = {}) => {
|
|
1698
|
+
const { model, options = {} } = opts
|
|
1699
|
+
const { req } = options
|
|
1700
|
+
if (!req) return
|
|
1701
|
+
if (!req.site) return
|
|
1702
|
+
|
|
1703
|
+
let action
|
|
1704
|
+
if (['findOneRecord', 'findRecord', 'countRecord', 'getRecord'].includes(options.action)) action = 'READ'
|
|
1705
|
+
else if (['createRecord', 'bulkCreateRecord'].includes(options.action)) action = 'CREATE'
|
|
1706
|
+
else if (['updateRecord', 'upsertRecord'].includes(options.action)) action = 'UPDATE'
|
|
1707
|
+
else if (['removeRecord'].includes(options.action)) action = 'REMOVE'
|
|
1708
|
+
else if (['findAllRecord'].includes(options.action)) action = 'EXPORT'
|
|
1709
|
+
if (!action) return
|
|
1710
|
+
|
|
1711
|
+
const allowed = await this.isActionAllowed(action, model, req)
|
|
1712
|
+
if (!allowed) throw this.error('accessDenied', { statusCode: 403 })
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/**
|
|
1716
|
+
* Check if the specified action is allowed for the given model and request. It retrieves the action guards, filters them based on the site ID, model name, and team IDs, and checks if the action is included in the allowed values. If any guard denies the action, it returns false; otherwise, it returns true.
|
|
1717
|
+
*
|
|
1718
|
+
* @async
|
|
1719
|
+
* @method
|
|
1720
|
+
* @param {string} action - The action to check. Available actions are: 'READ', 'CREATE', 'UPDATE', 'REMOVE' and 'EXPORT'.
|
|
1721
|
+
* @param {object} model - The model object.
|
|
1722
|
+
* @param {object} req - The request object.
|
|
1723
|
+
* @returns {Promise<boolean>} - Returns true if the action is allowed, otherwise false.
|
|
1724
|
+
*/
|
|
1725
|
+
isActionAllowed = async (action, model, req) => {
|
|
1726
|
+
const { includes } = this.app.lib.aneka
|
|
1727
|
+
if (!req) return true
|
|
1728
|
+
if (!req.site) return true
|
|
1729
|
+
const guards = await this.getActionGuards()
|
|
1730
|
+
const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
|
|
1731
|
+
if (aliases.includes('administrator')) return true
|
|
1732
|
+
const filterFn = item => {
|
|
1733
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1734
|
+
const byModel = item.models.includes(model.name)
|
|
1735
|
+
const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
|
|
1736
|
+
return bySiteId && byModel && byTeamId
|
|
1737
|
+
}
|
|
1738
|
+
let denied = false
|
|
1739
|
+
for (const item of guards.filter(filterFn)) {
|
|
1740
|
+
if (item.value.includes('*')) continue
|
|
1741
|
+
if (!item.value.includes(action)) denied = true
|
|
1742
|
+
}
|
|
1743
|
+
return !denied
|
|
531
1744
|
}
|
|
532
1745
|
}
|
|
533
1746
|
|
|
@@ -535,4 +1748,4 @@ async function factory (pkgName) {
|
|
|
535
1748
|
}
|
|
536
1749
|
|
|
537
1750
|
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>
|
|
1751
|
+
</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>
|