acebase-server 1.9.1 → 1.10.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/.vscode/launch.json +24 -0
- package/create-package-files +12 -0
- package/dist/cjs/auth.js +89 -0
- package/dist/cjs/auth.js.map +1 -0
- package/dist/cjs/cluster.js +57 -0
- package/dist/cjs/cluster.js.map +1 -0
- package/dist/cjs/index.js +9 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/middleware/404.js +15 -0
- package/dist/cjs/middleware/404.js.map +1 -0
- package/dist/cjs/middleware/cache.js +15 -0
- package/dist/cjs/middleware/cache.js.map +1 -0
- package/dist/cjs/middleware/connection.js +50 -0
- package/dist/cjs/middleware/connection.js.map +1 -0
- package/dist/cjs/middleware/context.js +21 -0
- package/dist/cjs/middleware/context.js.map +1 -0
- package/dist/cjs/middleware/cors.js +51 -0
- package/dist/cjs/middleware/cors.js.map +1 -0
- package/dist/cjs/middleware/swagger.js +18 -0
- package/dist/cjs/middleware/swagger.js.map +1 -0
- package/dist/cjs/middleware/user.js +58 -0
- package/dist/cjs/middleware/user.js.map +1 -0
- package/dist/cjs/oauth-providers/dropbox.js +109 -0
- package/dist/cjs/oauth-providers/dropbox.js.map +1 -0
- package/dist/cjs/oauth-providers/facebook.js +85 -0
- package/dist/cjs/oauth-providers/facebook.js.map +1 -0
- package/dist/cjs/oauth-providers/google.js +125 -0
- package/dist/cjs/oauth-providers/google.js.map +1 -0
- package/dist/cjs/oauth-providers/index.js +27 -0
- package/dist/cjs/oauth-providers/index.js.map +1 -0
- package/dist/cjs/oauth-providers/instagram.js +80 -0
- package/dist/cjs/oauth-providers/instagram.js.map +1 -0
- package/dist/cjs/oauth-providers/oauth-provider.js +3 -0
- package/dist/cjs/oauth-providers/oauth-provider.js.map +1 -0
- package/dist/cjs/oauth-providers/spotify.js +113 -0
- package/dist/cjs/oauth-providers/spotify.js.map +1 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/routes/auth-change-password.js +85 -0
- package/dist/cjs/routes/auth-change-password.js.map +1 -0
- package/dist/cjs/routes/auth-delete.js +51 -0
- package/dist/cjs/routes/auth-delete.js.map +1 -0
- package/dist/cjs/routes/auth-forgot-password.js +75 -0
- package/dist/cjs/routes/auth-forgot-password.js.map +1 -0
- package/dist/cjs/routes/auth-reset-password.js +94 -0
- package/dist/cjs/routes/auth-reset-password.js.map +1 -0
- package/dist/cjs/routes/auth-signin.js +47 -0
- package/dist/cjs/routes/auth-signin.js.map +1 -0
- package/dist/cjs/routes/auth-signout.js +60 -0
- package/dist/cjs/routes/auth-signout.js.map +1 -0
- package/dist/cjs/routes/auth-signup.js +141 -0
- package/dist/cjs/routes/auth-signup.js.map +1 -0
- package/dist/cjs/routes/auth-state.js +26 -0
- package/dist/cjs/routes/auth-state.js.map +1 -0
- package/dist/cjs/routes/auth-update.js +129 -0
- package/dist/cjs/routes/auth-update.js.map +1 -0
- package/dist/cjs/routes/auth-verify-email.js +67 -0
- package/dist/cjs/routes/auth-verify-email.js.map +1 -0
- package/dist/cjs/routes/auth.js +55 -0
- package/dist/cjs/routes/auth.js.map +1 -0
- package/dist/cjs/routes/data-exists.js +34 -0
- package/dist/cjs/routes/data-exists.js.map +1 -0
- package/dist/cjs/routes/data-export.js +49 -0
- package/dist/cjs/routes/data-export.js.map +1 -0
- package/dist/cjs/routes/data-get.js +67 -0
- package/dist/cjs/routes/data-get.js.map +1 -0
- package/dist/cjs/routes/data-import.js +55 -0
- package/dist/cjs/routes/data-import.js.map +1 -0
- package/dist/cjs/routes/data-index-create.js +45 -0
- package/dist/cjs/routes/data-index-create.js.map +1 -0
- package/dist/cjs/routes/data-index-delete.js +36 -0
- package/dist/cjs/routes/data-index-delete.js.map +1 -0
- package/dist/cjs/routes/data-index-list.js +35 -0
- package/dist/cjs/routes/data-index-list.js.map +1 -0
- package/dist/cjs/routes/data-query.js +71 -0
- package/dist/cjs/routes/data-query.js.map +1 -0
- package/dist/cjs/routes/data-reflect.js +89 -0
- package/dist/cjs/routes/data-reflect.js.map +1 -0
- package/dist/cjs/routes/data-schema-get.js +39 -0
- package/dist/cjs/routes/data-schema-get.js.map +1 -0
- package/dist/cjs/routes/data-schema-set.js +33 -0
- package/dist/cjs/routes/data-schema-set.js.map +1 -0
- package/dist/cjs/routes/data-schema-test.js +46 -0
- package/dist/cjs/routes/data-schema-test.js.map +1 -0
- package/dist/cjs/routes/data-schemas-list.js +35 -0
- package/dist/cjs/routes/data-schemas-list.js.map +1 -0
- package/dist/cjs/routes/data-set.js +72 -0
- package/dist/cjs/routes/data-set.js.map +1 -0
- package/dist/cjs/routes/data-sync-changes.js +68 -0
- package/dist/cjs/routes/data-sync-changes.js.map +1 -0
- package/dist/cjs/routes/data-sync-mutations.js +68 -0
- package/dist/cjs/routes/data-sync-mutations.js.map +1 -0
- package/dist/cjs/routes/data-transaction.js +120 -0
- package/dist/cjs/routes/data-transaction.js.map +1 -0
- package/dist/cjs/routes/data-update.js +71 -0
- package/dist/cjs/routes/data-update.js.map +1 -0
- package/dist/cjs/routes/data.js +63 -0
- package/dist/cjs/routes/data.js.map +1 -0
- package/dist/cjs/routes/docs.js +249 -0
- package/dist/cjs/routes/docs.js.map +1 -0
- package/dist/cjs/routes/meta-info.js +70 -0
- package/dist/cjs/routes/meta-info.js.map +1 -0
- package/dist/cjs/routes/meta-ping.js +12 -0
- package/dist/cjs/routes/meta-ping.js.map +1 -0
- package/dist/cjs/routes/meta-stats.js +28 -0
- package/dist/cjs/routes/meta-stats.js.map +1 -0
- package/dist/cjs/routes/meta.js +17 -0
- package/dist/cjs/routes/meta.js.map +1 -0
- package/dist/cjs/routes/oauth2-init.js +52 -0
- package/dist/cjs/routes/oauth2-init.js.map +1 -0
- package/dist/cjs/routes/oauth2-refresh.js +43 -0
- package/dist/cjs/routes/oauth2-refresh.js.map +1 -0
- package/dist/cjs/routes/oauth2-signin.js +262 -0
- package/dist/cjs/routes/oauth2-signin.js.map +1 -0
- package/dist/cjs/routes/webmanager.js +27 -0
- package/dist/cjs/routes/webmanager.js.map +1 -0
- package/dist/cjs/rules.js +175 -0
- package/dist/cjs/rules.js.map +1 -0
- package/dist/cjs/schema/user.js +26 -0
- package/dist/cjs/schema/user.js.map +1 -0
- package/dist/cjs/server.js +363 -0
- package/dist/cjs/server.js.map +1 -0
- package/dist/cjs/settings/email.js +5 -0
- package/dist/cjs/settings/email.js.map +1 -0
- package/dist/cjs/settings/index.js +159 -0
- package/dist/cjs/settings/index.js.map +1 -0
- package/dist/cjs/shared/clients.js +27 -0
- package/dist/cjs/shared/clients.js.map +1 -0
- package/dist/cjs/shared/email.js +7 -0
- package/dist/cjs/shared/email.js.map +1 -0
- package/{src/oauth-providers/oauth-provider.js → dist/cjs/shared/env.js} +3 -0
- package/dist/cjs/shared/env.js.map +1 -0
- package/dist/cjs/shared/error.js +35 -0
- package/dist/cjs/shared/error.js.map +1 -0
- package/dist/cjs/shared/http.js +21 -0
- package/dist/cjs/shared/http.js.map +1 -0
- package/dist/cjs/shared/password.js +46 -0
- package/dist/cjs/shared/password.js.map +1 -0
- package/dist/cjs/shared/rootpath.js +15 -0
- package/dist/cjs/shared/rootpath.js.map +1 -0
- package/dist/cjs/shared/signin.js +139 -0
- package/dist/cjs/shared/signin.js.map +1 -0
- package/dist/cjs/shared/simple-fetch.js +77 -0
- package/dist/cjs/shared/simple-fetch.js.map +1 -0
- package/dist/cjs/shared/tokens.js +79 -0
- package/dist/cjs/shared/tokens.js.map +1 -0
- package/dist/cjs/shared/validate.js +62 -0
- package/dist/cjs/shared/validate.js.map +1 -0
- package/dist/cjs/start.js +51 -0
- package/dist/cjs/start.js.map +1 -0
- package/dist/cjs/test.js +11 -0
- package/dist/cjs/test.js.map +1 -0
- package/dist/cjs/websocket/index.js +301 -0
- package/dist/cjs/websocket/index.js.map +1 -0
- package/dist/cjs/websocket/manager.js +16 -0
- package/dist/cjs/websocket/manager.js.map +1 -0
- package/dist/cjs/websocket/socket.io.js +79 -0
- package/dist/cjs/websocket/socket.io.js.map +1 -0
- package/dist/esm/auth.js +76 -0
- package/dist/esm/auth.js.map +1 -0
- package/{src → dist/esm}/cluster.js +9 -14
- package/dist/esm/cluster.js.map +1 -0
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/middleware/404.js +11 -0
- package/dist/esm/middleware/404.js.map +1 -0
- package/dist/esm/middleware/cache.js +11 -0
- package/dist/esm/middleware/cache.js.map +1 -0
- package/dist/esm/middleware/connection.js +46 -0
- package/dist/esm/middleware/connection.js.map +1 -0
- package/dist/esm/middleware/context.js +17 -0
- package/dist/esm/middleware/context.js.map +1 -0
- package/dist/esm/middleware/cors.js +45 -0
- package/dist/esm/middleware/cors.js.map +1 -0
- package/dist/esm/middleware/swagger.js +14 -0
- package/dist/esm/middleware/swagger.js.map +1 -0
- package/dist/esm/middleware/user.js +45 -0
- package/dist/esm/middleware/user.js.map +1 -0
- package/{src → dist/esm}/oauth-providers/dropbox.js +11 -9
- package/dist/esm/oauth-providers/dropbox.js.map +1 -0
- package/{src → dist/esm}/oauth-providers/facebook.js +6 -9
- package/dist/esm/oauth-providers/facebook.js.map +1 -0
- package/{src → dist/esm}/oauth-providers/google.js +8 -11
- package/dist/esm/oauth-providers/google.js.map +1 -0
- package/dist/esm/oauth-providers/index.js +19 -0
- package/dist/esm/oauth-providers/index.js.map +1 -0
- package/{src → dist/esm}/oauth-providers/instagram.js +6 -9
- package/dist/esm/oauth-providers/instagram.js.map +1 -0
- package/dist/esm/oauth-providers/oauth-provider.js +2 -0
- package/dist/esm/oauth-providers/oauth-provider.js.map +1 -0
- package/{src → dist/esm}/oauth-providers/spotify.js +7 -10
- package/dist/esm/oauth-providers/spotify.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/routes/auth-change-password.js +70 -0
- package/dist/esm/routes/auth-change-password.js.map +1 -0
- package/dist/esm/routes/auth-delete.js +36 -0
- package/dist/esm/routes/auth-delete.js.map +1 -0
- package/dist/esm/routes/auth-forgot-password.js +61 -0
- package/dist/esm/routes/auth-forgot-password.js.map +1 -0
- package/dist/esm/routes/auth-reset-password.js +78 -0
- package/dist/esm/routes/auth-reset-password.js.map +1 -0
- package/dist/esm/routes/auth-signin.js +34 -0
- package/dist/esm/routes/auth-signin.js.map +1 -0
- package/dist/esm/routes/auth-signout.js +46 -0
- package/dist/esm/routes/auth-signout.js.map +1 -0
- package/dist/esm/routes/auth-signup.js +126 -0
- package/dist/esm/routes/auth-signup.js.map +1 -0
- package/dist/esm/routes/auth-state.js +13 -0
- package/dist/esm/routes/auth-state.js.map +1 -0
- package/dist/esm/routes/auth-update.js +115 -0
- package/dist/esm/routes/auth-update.js.map +1 -0
- package/dist/esm/routes/auth-verify-email.js +52 -0
- package/dist/esm/routes/auth-verify-email.js.map +1 -0
- package/dist/esm/routes/auth.js +51 -0
- package/dist/esm/routes/auth.js.map +1 -0
- package/dist/esm/routes/data-exists.js +21 -0
- package/dist/esm/routes/data-exists.js.map +1 -0
- package/dist/esm/routes/data-export.js +36 -0
- package/dist/esm/routes/data-export.js.map +1 -0
- package/dist/esm/routes/data-get.js +53 -0
- package/dist/esm/routes/data-get.js.map +1 -0
- package/dist/esm/routes/data-import.js +42 -0
- package/dist/esm/routes/data-import.js.map +1 -0
- package/dist/esm/routes/data-index-create.js +31 -0
- package/dist/esm/routes/data-index-create.js.map +1 -0
- package/dist/esm/routes/data-index-delete.js +23 -0
- package/dist/esm/routes/data-index-delete.js.map +1 -0
- package/dist/esm/routes/data-index-list.js +22 -0
- package/dist/esm/routes/data-index-list.js.map +1 -0
- package/dist/esm/routes/data-query.js +57 -0
- package/dist/esm/routes/data-query.js.map +1 -0
- package/dist/esm/routes/data-reflect.js +76 -0
- package/dist/esm/routes/data-reflect.js.map +1 -0
- package/dist/esm/routes/data-schema-get.js +26 -0
- package/dist/esm/routes/data-schema-get.js.map +1 -0
- package/dist/esm/routes/data-schema-set.js +20 -0
- package/dist/esm/routes/data-schema-set.js.map +1 -0
- package/dist/esm/routes/data-schema-test.js +32 -0
- package/dist/esm/routes/data-schema-test.js.map +1 -0
- package/dist/esm/routes/data-schemas-list.js +22 -0
- package/dist/esm/routes/data-schemas-list.js.map +1 -0
- package/dist/esm/routes/data-set.js +57 -0
- package/dist/esm/routes/data-set.js.map +1 -0
- package/dist/esm/routes/data-sync-changes.js +54 -0
- package/dist/esm/routes/data-sync-changes.js.map +1 -0
- package/dist/esm/routes/data-sync-mutations.js +54 -0
- package/dist/esm/routes/data-sync-mutations.js.map +1 -0
- package/dist/esm/routes/data-transaction.js +104 -0
- package/dist/esm/routes/data-transaction.js.map +1 -0
- package/dist/esm/routes/data-update.js +56 -0
- package/dist/esm/routes/data-update.js.map +1 -0
- package/dist/esm/routes/data.js +59 -0
- package/dist/esm/routes/data.js.map +1 -0
- package/dist/esm/routes/docs.js +244 -0
- package/dist/esm/routes/docs.js.map +1 -0
- package/dist/esm/routes/meta-info.js +66 -0
- package/dist/esm/routes/meta-info.js.map +1 -0
- package/dist/esm/routes/meta-ping.js +8 -0
- package/dist/esm/routes/meta-ping.js.map +1 -0
- package/dist/esm/routes/meta-stats.js +15 -0
- package/dist/esm/routes/meta-stats.js.map +1 -0
- package/dist/esm/routes/meta.js +13 -0
- package/dist/esm/routes/meta.js.map +1 -0
- package/dist/esm/routes/oauth2-init.js +39 -0
- package/dist/esm/routes/oauth2-init.js.map +1 -0
- package/dist/esm/routes/oauth2-refresh.js +30 -0
- package/dist/esm/routes/oauth2-refresh.js.map +1 -0
- package/dist/esm/routes/oauth2-signin.js +248 -0
- package/dist/esm/routes/oauth2-signin.js.map +1 -0
- package/dist/esm/routes/webmanager.js +23 -0
- package/dist/esm/routes/webmanager.js.map +1 -0
- package/dist/esm/rules.js +171 -0
- package/dist/esm/rules.js.map +1 -0
- package/dist/esm/schema/user.js +21 -0
- package/dist/esm/schema/user.js.map +1 -0
- package/dist/esm/server.js +344 -0
- package/dist/esm/server.js.map +1 -0
- package/dist/esm/settings/email.js +4 -0
- package/dist/esm/settings/email.js.map +1 -0
- package/dist/esm/settings/index.js +152 -0
- package/dist/esm/settings/index.js.map +1 -0
- package/dist/esm/shared/clients.js +23 -0
- package/dist/esm/shared/clients.js.map +1 -0
- package/dist/esm/shared/email.js +6 -0
- package/dist/esm/shared/email.js.map +1 -0
- package/dist/esm/shared/env.js +4 -0
- package/dist/esm/shared/env.js.map +1 -0
- package/dist/esm/shared/error.js +27 -0
- package/dist/esm/shared/error.js.map +1 -0
- package/dist/esm/shared/http.js +16 -0
- package/dist/esm/shared/http.js.map +1 -0
- package/dist/esm/shared/password.js +39 -0
- package/dist/esm/shared/password.js.map +1 -0
- package/dist/esm/shared/rootpath.js +12 -0
- package/dist/esm/shared/rootpath.js.map +1 -0
- package/dist/esm/shared/signin.js +125 -0
- package/dist/esm/shared/signin.js.map +1 -0
- package/{src/oauth-providers → dist/esm/shared}/simple-fetch.js +7 -10
- package/dist/esm/shared/simple-fetch.js.map +1 -0
- package/dist/esm/shared/tokens.js +72 -0
- package/dist/esm/shared/tokens.js.map +1 -0
- package/dist/esm/shared/validate.js +42 -0
- package/dist/esm/shared/validate.js.map +1 -0
- package/dist/esm/start.js +48 -0
- package/dist/esm/start.js.map +1 -0
- package/dist/esm/test.js +9 -0
- package/dist/esm/test.js.map +1 -0
- package/dist/esm/websocket/index.js +288 -0
- package/dist/esm/websocket/index.js.map +1 -0
- package/dist/esm/websocket/manager.js +12 -0
- package/dist/esm/websocket/manager.js.map +1 -0
- package/dist/esm/websocket/socket.io.js +73 -0
- package/dist/esm/websocket/socket.io.js.map +1 -0
- package/dist/types/auth.d.ts +3 -0
- package/dist/types/cluster.d.ts +1 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/middleware/404.d.ts +7 -0
- package/dist/types/middleware/cache.d.ts +3 -0
- package/dist/types/middleware/connection.d.ts +7 -0
- package/dist/types/middleware/context.d.ts +3 -0
- package/dist/types/middleware/cors.d.ts +25 -0
- package/dist/types/middleware/swagger.d.ts +3 -0
- package/dist/types/middleware/user.d.ts +2 -0
- package/dist/types/oauth-providers/dropbox.d.ts +63 -0
- package/dist/types/oauth-providers/facebook.d.ts +45 -0
- package/dist/types/oauth-providers/google.d.ts +47 -0
- package/dist/types/oauth-providers/index.d.ts +18 -0
- package/dist/types/oauth-providers/instagram.d.ts +54 -0
- package/dist/types/oauth-providers/oauth-provider.d.ts +70 -0
- package/dist/types/oauth-providers/spotify.d.ts +57 -0
- package/dist/types/routes/auth-change-password.d.ts +20 -0
- package/dist/types/routes/auth-delete.d.ts +16 -0
- package/dist/types/routes/auth-forgot-password.d.ts +16 -0
- package/dist/types/routes/auth-reset-password.d.ts +23 -0
- package/dist/types/routes/auth-signin.d.ts +24 -0
- package/dist/types/routes/auth-signout.d.ts +14 -0
- package/dist/types/routes/auth-signup.d.ts +32 -0
- package/dist/types/routes/auth-state.d.ts +13 -0
- package/dist/types/routes/auth-update.d.ts +33 -0
- package/dist/types/routes/auth-verify-email.d.ts +21 -0
- package/dist/types/routes/auth.d.ts +6 -0
- package/dist/types/routes/data-exists.d.ts +9 -0
- package/dist/types/routes/data-export.d.ts +10 -0
- package/dist/types/routes/data-get.d.ts +14 -0
- package/dist/types/routes/data-import.d.ts +13 -0
- package/dist/types/routes/data-index-create.d.ts +51 -0
- package/dist/types/routes/data-index-delete.d.ts +17 -0
- package/dist/types/routes/data-index-list.d.ts +21 -0
- package/dist/types/routes/data-query.d.ts +49 -0
- package/dist/types/routes/data-reflect.d.ts +29 -0
- package/dist/types/routes/data-schema-get.d.ts +11 -0
- package/dist/types/routes/data-schema-set.d.ts +19 -0
- package/dist/types/routes/data-schema-test.d.ts +21 -0
- package/dist/types/routes/data-schemas-list.d.ts +11 -0
- package/dist/types/routes/data-set.d.ts +27 -0
- package/dist/types/routes/data-sync-changes.d.ts +28 -0
- package/dist/types/routes/data-sync-mutations.d.ts +28 -0
- package/dist/types/routes/data-transaction.d.ts +34 -0
- package/dist/types/routes/data-update.d.ts +27 -0
- package/dist/types/routes/data.d.ts +3 -0
- package/dist/types/routes/docs.d.ts +3 -0
- package/dist/types/routes/meta-info.d.ts +11 -0
- package/dist/types/routes/meta-ping.d.ts +7 -0
- package/dist/types/routes/meta-stats.d.ts +13 -0
- package/dist/types/routes/meta.d.ts +3 -0
- package/dist/types/routes/oauth2-init.d.ts +13 -0
- package/dist/types/routes/oauth2-refresh.d.ts +17 -0
- package/dist/types/routes/oauth2-signin.d.ts +15 -0
- package/dist/types/routes/webmanager.d.ts +3 -0
- package/dist/types/rules.d.ts +41 -0
- package/dist/types/schema/user.d.ts +85 -0
- package/dist/types/server.d.ts +106 -0
- package/dist/types/settings/email.d.ts +14 -0
- package/dist/types/settings/index.d.ts +165 -0
- package/dist/types/shared/clients.d.ts +44 -0
- package/dist/types/shared/email.d.ts +34 -0
- package/dist/types/shared/env.d.ts +42 -0
- package/dist/types/shared/error.d.ts +15 -0
- package/dist/types/shared/http.d.ts +14 -0
- package/dist/types/shared/password.d.ts +19 -0
- package/dist/types/shared/rootpath.d.ts +2 -0
- package/dist/types/shared/signin.d.ts +31 -0
- package/dist/types/shared/simple-fetch.d.ts +21 -0
- package/dist/types/shared/tokens.d.ts +23 -0
- package/dist/types/shared/validate.d.ts +22 -0
- package/dist/types/start.d.ts +1 -0
- package/dist/types/test.d.ts +1 -0
- package/dist/types/websocket/index.d.ts +2 -0
- package/dist/types/websocket/manager.d.ts +99 -0
- package/dist/types/websocket/socket.io.d.ts +10 -0
- package/package.json +23 -8
- package/src/auth.ts +87 -0
- package/src/cluster.ts +62 -0
- package/src/index.ts +2 -0
- package/src/middleware/404.ts +13 -0
- package/src/middleware/cache.ts +15 -0
- package/src/middleware/connection.ts +48 -0
- package/src/middleware/context.ts +23 -0
- package/src/middleware/cors.ts +49 -0
- package/src/middleware/swagger.ts +19 -0
- package/src/middleware/user.ts +51 -0
- package/src/{ts/oauth-providers → oauth-providers}/dropbox.ts +1 -1
- package/src/{ts/oauth-providers → oauth-providers}/facebook.ts +1 -1
- package/src/{ts/oauth-providers → oauth-providers}/google.ts +1 -1
- package/src/oauth-providers/index.ts +20 -0
- package/src/{ts/oauth-providers → oauth-providers}/instagram.ts +1 -1
- package/src/{ts/oauth-providers → oauth-providers}/oauth-provider.ts +0 -0
- package/src/{ts/oauth-providers → oauth-providers}/spotify.ts +1 -1
- package/src/routes/auth-change-password.ts +89 -0
- package/src/{ts/routes → routes}/auth-change-password.yaml +0 -2
- package/src/routes/auth-delete.ts +47 -0
- package/src/{ts/routes → routes}/auth-delete.yaml +0 -0
- package/src/routes/auth-forgot-password.ts +73 -0
- package/src/{ts/routes → routes}/auth-forgot-password.yaml +0 -0
- package/src/routes/auth-reset-password.ts +93 -0
- package/src/{ts/routes → routes}/auth-reset-password.yaml +0 -0
- package/src/routes/auth-signin.ts +55 -0
- package/src/{ts/routes → routes}/auth-signin.yaml +5 -5
- package/src/routes/auth-signout.ts +61 -0
- package/src/{ts/routes → routes}/auth-signout.yaml +0 -0
- package/src/routes/auth-signup.ts +161 -0
- package/src/{ts/routes → routes}/auth-signup.yaml +15 -0
- package/src/routes/auth-state.ts +20 -0
- package/src/{ts/routes → routes}/auth-state.yaml +0 -0
- package/src/routes/auth-update.ts +147 -0
- package/src/{ts/routes → routes}/auth-update.yaml +22 -2
- package/src/routes/auth-verify-email.ts +67 -0
- package/src/{ts/routes → routes}/auth-verify-email.yaml +0 -0
- package/src/routes/auth.ts +67 -0
- package/src/routes/data-exists.ts +31 -0
- package/src/routes/data-exists.yaml +44 -0
- package/src/routes/data-export.ts +51 -0
- package/src/routes/data-export.yaml +64 -0
- package/src/routes/data-get.ts +68 -0
- package/src/routes/data-get.yaml +54 -0
- package/src/routes/data-import.ts +56 -0
- package/src/routes/data-import.yaml +75 -0
- package/src/routes/data-index-create.ts +85 -0
- package/src/routes/data-index-create.yaml +105 -0
- package/src/routes/data-index-delete.ts +39 -0
- package/src/routes/data-index-delete.yaml +51 -0
- package/src/routes/data-index-list.ts +42 -0
- package/src/routes/data-index-list.yaml +80 -0
- package/src/routes/data-query.ts +97 -0
- package/src/routes/data-query.yaml +166 -0
- package/src/routes/data-reflect.ts +94 -0
- package/src/routes/data-reflect.yaml +124 -0
- package/src/routes/data-schema-get.ts +38 -0
- package/src/routes/data-schema-get.yaml +53 -0
- package/src/routes/data-schema-set.ts +38 -0
- package/src/routes/data-schema-set.yaml +60 -0
- package/src/routes/data-schema-test.ts +53 -0
- package/src/routes/data-schema-test.yaml +66 -0
- package/src/routes/data-schemas-list.ts +33 -0
- package/src/routes/data-schemas-list.yaml +41 -0
- package/src/routes/data-set.ts +76 -0
- package/src/routes/data-set.yaml +71 -0
- package/src/routes/data-sync-changes.ts +78 -0
- package/src/routes/data-sync-changes.yaml +67 -0
- package/src/routes/data-sync-mutations.ts +78 -0
- package/src/routes/data-sync-mutations.yaml +67 -0
- package/src/routes/data-transaction-finish.yaml +76 -0
- package/src/routes/data-transaction-start.yaml +58 -0
- package/src/routes/data-transaction.ts +144 -0
- package/src/routes/data-update.ts +77 -0
- package/src/routes/data-update.yaml +71 -0
- package/src/routes/data.ts +79 -0
- package/src/routes/docs.ts +249 -0
- package/src/routes/meta-info.ts +80 -0
- package/src/routes/meta-info.yaml +41 -0
- package/src/routes/meta-ping.ts +15 -0
- package/src/routes/meta-ping.yaml +23 -0
- package/src/routes/meta-stats.ts +31 -0
- package/src/routes/meta-stats.yaml +41 -0
- package/src/routes/meta.ts +18 -0
- package/src/routes/oauth2-init.ts +44 -0
- package/src/{ts/routes → routes}/oauth2-init.yaml +0 -0
- package/src/routes/oauth2-refresh.ts +39 -0
- package/src/{ts/routes → routes}/oauth2-refresh.yaml +0 -0
- package/src/routes/oauth2-signin.ts +281 -0
- package/src/{ts/routes → routes}/oauth2-signin.yaml +0 -0
- package/src/routes/webmanager.ts +29 -0
- package/src/rules.ts +196 -0
- package/src/schema/user.ts +99 -0
- package/src/server.ts +416 -0
- package/src/settings/email.ts +18 -0
- package/src/settings/index.ts +241 -0
- package/src/shared/clients.ts +31 -0
- package/src/shared/email.ts +33 -0
- package/src/shared/env.ts +38 -0
- package/src/shared/error.ts +37 -0
- package/src/shared/http.ts +24 -0
- package/src/shared/password.ts +41 -0
- package/src/shared/rootpath.ts +15 -0
- package/src/shared/signin.ts +143 -0
- package/src/{ts/oauth-providers → shared}/simple-fetch.ts +2 -2
- package/src/shared/tokens.ts +77 -0
- package/src/shared/validate.ts +53 -0
- package/src/{start.js → start.ts} +7 -5
- package/src/test.ts +10 -0
- package/src/websocket/index.ts +320 -0
- package/src/websocket/manager.ts +46 -0
- package/src/websocket/socket.io.ts +91 -0
- package/tsconfig-cjs.json +10 -0
- package/tsconfig.json +13 -5
- package/{src/webmanager → webmanager}/index.html +0 -0
- package/{src/webmanager → webmanager}/index.js +0 -0
- package/src/acebase-server.js +0 -3060
- package/src/index.d.ts +0 -212
- package/src/index.js +0 -2
- package/src/routes/docs.js +0 -97
- package/src/ts/routes/docs.ts +0 -100
package/src/acebase-server.js
DELETED
|
@@ -1,3060 +0,0 @@
|
|
|
1
|
-
const express = require('express');
|
|
2
|
-
const { EventEmitter } = require('events');
|
|
3
|
-
const { AceBase, SchemaValidationError } = require('acebase');
|
|
4
|
-
const { ID, Transport, DataSnapshot, PathInfo, Utils, DebugLogger, ColorStyle } = require('acebase-core');
|
|
5
|
-
const fs = require('fs');
|
|
6
|
-
const crypto = require('crypto');
|
|
7
|
-
|
|
8
|
-
class AceBaseServerHttpsSettings {
|
|
9
|
-
/**
|
|
10
|
-
*
|
|
11
|
-
* @param {{keyPath:string, certPath:string}|{ pfxPath:string, passphrase:string }} settings
|
|
12
|
-
*/
|
|
13
|
-
constructor(settings) {
|
|
14
|
-
this.enabled = typeof settings === "object" && settings.enabled !== false;
|
|
15
|
-
if (!this.enabled) { return; }
|
|
16
|
-
if (settings.keyPath) {
|
|
17
|
-
this.key = fs.readFileSync(settings.keyPath);
|
|
18
|
-
this.cert = fs.readFileSync(settings.certPath);
|
|
19
|
-
}
|
|
20
|
-
else if (settings.pfxPath) {
|
|
21
|
-
this.pfx = fs.readFileSync(settings.pfxPath);
|
|
22
|
-
this.passphrase = settings.passphrase;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
class AceBaseServerAuthenticationSettings {
|
|
28
|
-
/**
|
|
29
|
-
*
|
|
30
|
-
* @param {object} settings
|
|
31
|
-
* @param {boolean} [settings.enabled=true] if authorization is enabled, without authorization the entire db can be read and written to by anyone
|
|
32
|
-
* @param {boolean} [settings.allowUserSignup=false] If new users creation is allowed for anyone, or just the admin
|
|
33
|
-
* @param {number} [settings.newUserRateLimit=0] how many new users per hour per IP address. not implemented yet
|
|
34
|
-
* @param {number} [settings.tokensExpire=0] how many minutes before access tokens expire. 0 for no expiration. not implemented yet
|
|
35
|
-
* @param {string} [settings.defaultAccessRule='auth'] when the server runs for the first time, what defaults to use to generate the rules.json file with. Options are: 'auth' (only authenticated access to db, default), 'deny' (deny access to anyone except admin user), 'allow' (allow access to anyone)
|
|
36
|
-
* @param {boolean} [settings.defaultAdminPassword] when the server runs for the first time, what password to use for the admin user. If not supplied, a generated password will be used and shown ONCE in the console output.
|
|
37
|
-
* @param {boolean} [settings.separateDb=false] whether to use a separate database for auth and logging
|
|
38
|
-
*/
|
|
39
|
-
constructor(settings) {
|
|
40
|
-
if (typeof settings !== "object") { settings = {}; }
|
|
41
|
-
this.enabled = typeof settings.enabled === 'boolean' ? settings.enabled : true;
|
|
42
|
-
this.allowUserSignup = typeof settings.allowUserSignup === 'boolean' ? settings.allowUserSignup : false;
|
|
43
|
-
this.newUserRateLimit = typeof settings.newUserRateLimit === 'number' ? settings.newUserRateLimit : 0;
|
|
44
|
-
this.tokensExpire = typeof settings.tokensExpire === 'number' ? settings.tokensExpire : 0;
|
|
45
|
-
this.defaultAccessRule = settings.defaultAccessRule || AceBaseServerAuthenticationSettings.ACCESS_DEFAULT.ALLOW_AUTHENTICATED;
|
|
46
|
-
this.defaultAdminPassword = typeof settings.defaultAdminPassword === 'string' ? settings.defaultAdminPassword : undefined;
|
|
47
|
-
this.separateDb = typeof settings.separateDb === 'boolean'
|
|
48
|
-
? settings.separateDb
|
|
49
|
-
: typeof settings.seperateDb === 'boolean' ? seperateDb : false; // Handle previous _wrong_ spelling
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
static get ACCESS_DEFAULT() {
|
|
53
|
-
return {
|
|
54
|
-
DENY_ALL: 'deny',
|
|
55
|
-
ALLOW_ALL: 'allow',
|
|
56
|
-
ALLOW_AUTHENTICATED: 'auth'
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
class AceBaseServerEmailServerSettings {
|
|
62
|
-
/**
|
|
63
|
-
*
|
|
64
|
-
* @param {object} settings
|
|
65
|
-
* @param {string} settings.host
|
|
66
|
-
* @param {number} settings.port
|
|
67
|
-
* @param {string} [settings.username]
|
|
68
|
-
* @param {string} [settings.password]
|
|
69
|
-
* @param {boolean} [settings.secure]
|
|
70
|
-
* @
|
|
71
|
-
*/
|
|
72
|
-
constructor(settings) {
|
|
73
|
-
this.host = settings.host;
|
|
74
|
-
this.port = settings.port;
|
|
75
|
-
this.secure = settings.secure;
|
|
76
|
-
this.username = settings.username;
|
|
77
|
-
this.password = settings.password;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
class AceBaseEmailRequest {
|
|
82
|
-
/**
|
|
83
|
-
*
|
|
84
|
-
* @param {string} type email request type
|
|
85
|
-
*/
|
|
86
|
-
constructor(type) {
|
|
87
|
-
this.type = type;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
class AceBaseUserEmailRequest extends AceBaseEmailRequest {
|
|
92
|
-
/**
|
|
93
|
-
* @param {string} type
|
|
94
|
-
* @param {object} data
|
|
95
|
-
* @param {object} data.user
|
|
96
|
-
* @param {string} data.user.uid
|
|
97
|
-
* @param {string} data.user.email
|
|
98
|
-
* @param {string} data.user.username
|
|
99
|
-
* @param {string} data.user.displayName
|
|
100
|
-
* @param {any} data.user.settings
|
|
101
|
-
* @param {string} data.ip
|
|
102
|
-
* @param {Date} data.date
|
|
103
|
-
*/
|
|
104
|
-
constructor(type, data) {
|
|
105
|
-
super(type);
|
|
106
|
-
this.user = data.user;
|
|
107
|
-
this.ip = data.ip;
|
|
108
|
-
this.date = data.date;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
class AceBaseUserSignupEmailRequest extends AceBaseUserEmailRequest {
|
|
113
|
-
/**
|
|
114
|
-
*
|
|
115
|
-
* @param {AceBaseUserEmailRequest & { provider: string, activationCode: string, emailVerified: boolean }} data
|
|
116
|
-
*/
|
|
117
|
-
constructor(data) {
|
|
118
|
-
super('user_signup', data);
|
|
119
|
-
this.activationCode = data.activationCode;
|
|
120
|
-
this.emailVerified = data.emailVerified;
|
|
121
|
-
this.provider = data.provider;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
class AceBaseUserSignInEmailRequest extends AceBaseUserEmailRequest {
|
|
126
|
-
/**
|
|
127
|
-
*
|
|
128
|
-
* @param {AceBaseUserEmailRequest & { provider: string, activationCode: string, emailVerified: boolean }} data
|
|
129
|
-
*/
|
|
130
|
-
constructor(data) {
|
|
131
|
-
super('user_signin', data);
|
|
132
|
-
this.activationCode = data.activationCode;
|
|
133
|
-
this.emailVerified = data.emailVerified;
|
|
134
|
-
this.provider = data.provider;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
class AceBaseUserResetPasswordEmailRequest extends AceBaseUserEmailRequest {
|
|
139
|
-
/**
|
|
140
|
-
* @param {AceBaseUserEmailRequest & { resetCode: string }} data
|
|
141
|
-
*/
|
|
142
|
-
constructor(data) {
|
|
143
|
-
super('user_reset_password', data);
|
|
144
|
-
this.resetCode = data.resetCode;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
class AceBaseUserResetPasswordSuccessEmailRequest extends AceBaseUserEmailRequest{
|
|
149
|
-
/**
|
|
150
|
-
* @param {AceBaseUserResetPasswordSuccessEmailRequest} data
|
|
151
|
-
*/
|
|
152
|
-
constructor(data) {
|
|
153
|
-
super('user_reset_password_success', data);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
class AceBaseServerEmailSettings {
|
|
158
|
-
/**
|
|
159
|
-
*
|
|
160
|
-
* @param {object} settings
|
|
161
|
-
* @param {AceBaseServerEmailServerSettings} [settings.server] NOT IMPLEMENTED YET - Use send property for your own implementation
|
|
162
|
-
* @param {(request: AceBaseEmailRequest) => Promise<boolean>} [settings.send] Callback function to call when an e-mail needs to be sent
|
|
163
|
-
*
|
|
164
|
-
*/
|
|
165
|
-
constructor(settings) {
|
|
166
|
-
this.server = settings.server;
|
|
167
|
-
this.send = request => {
|
|
168
|
-
try {
|
|
169
|
-
const ret = settings.send(request);
|
|
170
|
-
if (ret instanceof Promise) { return ret; }
|
|
171
|
-
return Promise.resolve();
|
|
172
|
-
}
|
|
173
|
-
catch(err) {
|
|
174
|
-
return Promise.reject(err);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
class AceBaseServerTransactionSettings {
|
|
181
|
-
/**
|
|
182
|
-
* TODO: Use AceBaseTransactionLogSettings from 'acebase/src/storage-acebase.js'
|
|
183
|
-
* @param {AceBaseServerTransactionSettings} settings
|
|
184
|
-
*/
|
|
185
|
-
constructor(settings) {
|
|
186
|
-
settings = settings || { log: false }; // Keep default false until transaction logging is out of alpha/beta
|
|
187
|
-
this.log = settings.log === true;
|
|
188
|
-
this.maxAge = typeof settings.maxAge === 'number' ? settings.maxAge : 30; // 30 days
|
|
189
|
-
this.noWait = settings.noWait === true;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* @typedef IPCClientSettings
|
|
195
|
-
* @property {string} [host='localhost'] IPC Server host to connect to. Default is `"localhost"`
|
|
196
|
-
* @property {number} port IPC Server port number
|
|
197
|
-
* @property {boolean} [ssl=false] Whether to use a secure connection to the server. Strongly recommended if `host` is not `"localhost"`. Default is `false`
|
|
198
|
-
* @property {string} [token] Token used in the IPC Server configuration (optional). The server will refuse connections using the wrong token.
|
|
199
|
-
* @property {'master'|'worker'} role Determines the role of this IPC client. Only 1 process can be assigned the 'master' role, all other processes must use the role 'worker'
|
|
200
|
-
*/
|
|
201
|
-
|
|
202
|
-
class AceBaseServerSettings {
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
*
|
|
206
|
-
* @param {object} [settings]
|
|
207
|
-
* @param {string} [settings.logLevel='log']
|
|
208
|
-
* @param {string} [settings.host='localhost']
|
|
209
|
-
* @param {number} [settings.port=3000]
|
|
210
|
-
* @param {string} [settings.path='.']
|
|
211
|
-
* @param {string} [settings.maxPayloadSize='10mb']
|
|
212
|
-
* @param {string} [settings.allowOrigin='*']
|
|
213
|
-
* @param {AceBaseServerHttpsSettings} [settings.https] { keyPath:string, certPath:string} | { pfxPath:string, passphrase:string }
|
|
214
|
-
* @param {AceBaseServerAuthenticationSettings} [settings.auth]
|
|
215
|
-
* @param {AceBaseServerEmailSettings} [settings.email]
|
|
216
|
-
* @param {AceBaseServerTransactionSettings} [settings.transactions]
|
|
217
|
-
* @param {IPCClientSettings} [settings.ipc]
|
|
218
|
-
*
|
|
219
|
-
*/
|
|
220
|
-
constructor(settings) {
|
|
221
|
-
if (typeof settings !== "object") { settings = {}; }
|
|
222
|
-
this.logLevel = settings.logLevel || "log"; //"error";
|
|
223
|
-
this.host = settings.host || "localhost";
|
|
224
|
-
this.port = settings.port || 3000;
|
|
225
|
-
this.path = settings.path || '.';
|
|
226
|
-
this.https = new AceBaseServerHttpsSettings(settings.https);
|
|
227
|
-
this.authentication = new AceBaseServerAuthenticationSettings(settings.authentication);
|
|
228
|
-
this.maxPayloadSize = settings.maxPayloadSize || '10mb';
|
|
229
|
-
this.allowOrigin = settings.allowOrigin || '*';
|
|
230
|
-
this.email = typeof settings.email === 'object' ? new AceBaseServerEmailSettings(settings.email) : null;
|
|
231
|
-
this.transactions = new AceBaseServerTransactionSettings(settings.transactions);
|
|
232
|
-
this.ipc = settings.ipc;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
class AccessDeniedError extends Error { }
|
|
237
|
-
/**
|
|
238
|
-
* @typedef {object} DbUserAccountDetails
|
|
239
|
-
* @property {string} [uid] uid, not stored in database object (uid is the node's key)
|
|
240
|
-
* @property {string} [username] username
|
|
241
|
-
* @property {string} [email] email address
|
|
242
|
-
* @property {boolean} [email_verified] if the supplied e-mail address has been verified
|
|
243
|
-
* @property {boolean} [is_disabled] if the account has been disabled
|
|
244
|
-
* @property {string} [display_name]
|
|
245
|
-
* @property {object} [picture]
|
|
246
|
-
* @property {string} picture.url
|
|
247
|
-
* @property {number} picture.width
|
|
248
|
-
* @property {number} picture.height
|
|
249
|
-
* @property {string} password password hash
|
|
250
|
-
* @property {string} password_salt random password salt used to secure password hash
|
|
251
|
-
* @property {string} [password_reset_code] Code that allows a user to reset their password with
|
|
252
|
-
* @property {boolean} [change_password] TODO: whether the user has to change their password
|
|
253
|
-
* @property {Date} [change_password_requested] TODO: date/time the password reset was requested
|
|
254
|
-
* @property {Date} [change_password_before] TODO: date/time the user must have changed their password
|
|
255
|
-
* @property {Date} created date/time the account was created
|
|
256
|
-
* @property {string} [created_ip] creation ip address
|
|
257
|
-
* @property {Date} [last_signin] date/time of last sign in
|
|
258
|
-
* @property {string} [last_signin_ip] ip address of last sign in
|
|
259
|
-
* @property {Date} [prev_signin] date/time of previous sign in
|
|
260
|
-
* @property {string} [prev_signin_ip] ip address of previous sign in
|
|
261
|
-
* @property {Date} [last_signout] date/time user last signed out
|
|
262
|
-
* @property {string} [last_signout_ip] ip address of last sign out
|
|
263
|
-
* @property {string} [access_token] access token that allows access after signing in
|
|
264
|
-
* @property {Date} [access_token_created] date/time access token was generated
|
|
265
|
-
* @property {{ [key:string]: string|number|boolean }} settings additional settings for this user, can be used to store eg a profile picture uri
|
|
266
|
-
*/
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* @param {DbUserAccountDetails} account
|
|
270
|
-
*/
|
|
271
|
-
function getPublicAccountDetails(account) {
|
|
272
|
-
return {
|
|
273
|
-
uid: account.uid,
|
|
274
|
-
username: account.username,
|
|
275
|
-
email: account.email,
|
|
276
|
-
displayName: account.display_name,
|
|
277
|
-
picture: account.picture,
|
|
278
|
-
emailVerified: account.email_verified,
|
|
279
|
-
created: account.created,
|
|
280
|
-
prevSignin: account.prev_signin,
|
|
281
|
-
prevSigninIp: account.prev_signin_ip,
|
|
282
|
-
lastSignin: account.last_signin,
|
|
283
|
-
lastSigninIp: account.last_signin_ip,
|
|
284
|
-
changePassword: account.change_password,
|
|
285
|
-
changePasswordRequested: account.change_password_requested,
|
|
286
|
-
changePasswordBefore: account.change_password_before,
|
|
287
|
-
settings: account.settings
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
function createPublicAccessToken(uid, ip, dbToken, password) {
|
|
292
|
-
let obj = {
|
|
293
|
-
t:dbToken,
|
|
294
|
-
c:Date.now(),
|
|
295
|
-
u:uid,
|
|
296
|
-
i:ip
|
|
297
|
-
};
|
|
298
|
-
// let str = JSON.stringify(obj);
|
|
299
|
-
// str = Buffer.from(str).toString('base64');
|
|
300
|
-
// return 'a' + str; // version a
|
|
301
|
-
return 'b' + createSignedPublicToken(obj, password);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/**
|
|
305
|
-
*
|
|
306
|
-
* @param {string} accessToken
|
|
307
|
-
* @returns {{ access_token?: string, uid?: string, created?: number, ip?: string }}
|
|
308
|
-
*/
|
|
309
|
-
function decodePublicAccessToken(accessToken, password) {
|
|
310
|
-
try {
|
|
311
|
-
if (accessToken[0] === 'b') {
|
|
312
|
-
// New signed version
|
|
313
|
-
const obj = parseSignedPublicToken(accessToken.slice(1), password);
|
|
314
|
-
return {
|
|
315
|
-
access_token: obj.t,
|
|
316
|
-
uid: obj.u,
|
|
317
|
-
created: obj.c,
|
|
318
|
-
ip: obj.i
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
else if (accessToken[0] === 'a') {
|
|
322
|
-
// Old insecure version, allow until August 1, 2020
|
|
323
|
-
const deadline = (new Date('2020-08-01')).getTime();
|
|
324
|
-
if (Date.now() >= deadline) {
|
|
325
|
-
throw new Error('Old token version not allowed');
|
|
326
|
-
}
|
|
327
|
-
const str = Buffer.from(accessToken.slice(1), 'base64').toString();
|
|
328
|
-
const obj = JSON.parse(str);
|
|
329
|
-
return {
|
|
330
|
-
access_token: obj.t,
|
|
331
|
-
uid: obj.u,
|
|
332
|
-
created: obj.c,
|
|
333
|
-
ip: obj.i
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
catch(err) {
|
|
338
|
-
return {};
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
const generatePassword = () => {
|
|
343
|
-
return Array.prototype.reduce.call('abcedefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ012345789!@#$%&', (password, c, i, chars) => {
|
|
344
|
-
if (i > 15) { return password; }
|
|
345
|
-
return password + chars[Math.floor(Math.random() * chars.length)];
|
|
346
|
-
}, '');
|
|
347
|
-
};
|
|
348
|
-
|
|
349
|
-
const createPasswordHash = (password) => {
|
|
350
|
-
let length = 16;
|
|
351
|
-
let salt = crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
|
|
352
|
-
let hash = crypto.createHmac('sha512', salt).update(password).digest('hex');
|
|
353
|
-
return {
|
|
354
|
-
salt,
|
|
355
|
-
hash
|
|
356
|
-
}
|
|
357
|
-
};
|
|
358
|
-
const getOldPasswordHash = (password) => {
|
|
359
|
-
// Backward compatibility with old saltless md5 passwords.
|
|
360
|
-
// Becomes obsolete once all passwords have been updated
|
|
361
|
-
return crypto.createHash('md5').update(password).digest('hex');
|
|
362
|
-
};
|
|
363
|
-
const getPasswordHash = (password, salt) => {
|
|
364
|
-
return crypto.createHmac('sha512', salt).update(password).digest('hex');
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
const getSignature = (content, salt) => {
|
|
368
|
-
// Use fast md5 with salt to sign with. Large salt recommended!!
|
|
369
|
-
return crypto.createHash('md5').update(salt + content).digest('hex');
|
|
370
|
-
}
|
|
371
|
-
function createSignedPublicToken(obj, password) {
|
|
372
|
-
// Sign objects with an md5 hash. An attacker might see the content
|
|
373
|
-
// and generated hash, but will need to guess the salt used. This is
|
|
374
|
-
// not impossible but will take a very long time when using a large salt
|
|
375
|
-
const str = JSON.stringify(obj);
|
|
376
|
-
const checksum = getSignature(str, password);
|
|
377
|
-
return Buffer.from(JSON.stringify({ v: 1, cs: checksum, d: str })).toString('base64');
|
|
378
|
-
}
|
|
379
|
-
function parseSignedPublicToken(str, password) {
|
|
380
|
-
const json = Buffer.from(str, 'base64').toString('utf8');
|
|
381
|
-
const obj = JSON.parse(json);
|
|
382
|
-
if (obj.v !== 1) {
|
|
383
|
-
throw new Error(`Unsupported version`);
|
|
384
|
-
}
|
|
385
|
-
if (typeof obj.cs !== 'string' || typeof obj.d !== 'string') {
|
|
386
|
-
throw new Error('Invalid token');
|
|
387
|
-
}
|
|
388
|
-
const checksum = obj.cs;
|
|
389
|
-
if (checksum !== getSignature(obj.d, password)) {
|
|
390
|
-
throw new Error(`compromised object`);
|
|
391
|
-
}
|
|
392
|
-
return JSON.parse(obj.d);
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
class AceBaseServer extends EventEmitter {
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
*
|
|
399
|
-
* @param {string} dbname
|
|
400
|
-
* @param {AceBaseServerSettings} options
|
|
401
|
-
*/
|
|
402
|
-
constructor(dbname, options = new AceBaseServerSettings()) {
|
|
403
|
-
|
|
404
|
-
super();
|
|
405
|
-
this._ready = false;
|
|
406
|
-
|
|
407
|
-
options = new AceBaseServerSettings(options);
|
|
408
|
-
|
|
409
|
-
const app = express();
|
|
410
|
-
app.set('trust proxy', true); // When behind proxy server, req.ip and req.hostname will be set the right way
|
|
411
|
-
|
|
412
|
-
const corsOptions = {
|
|
413
|
-
origin: options.allowOrigin === '*' ? true : options.allowOrigin.split(/,\s*/),
|
|
414
|
-
methods: 'GET,PUT,POST,DELETE,OPTIONS',
|
|
415
|
-
allowedHeaders: 'Content-Type, Authorization, Content-Length, Accept, Origin, X-Requested-With, AceBase-Context' // Disabled so cors will allow all used request headers
|
|
416
|
-
};
|
|
417
|
-
|
|
418
|
-
// When updating socket.io to 3+, use this for cors instead:
|
|
419
|
-
// const cors = require('cors');
|
|
420
|
-
// app.use(cors(corsOptions));
|
|
421
|
-
|
|
422
|
-
// With socket.io 2.x:
|
|
423
|
-
const corsHandler = (req, res, next) => {
|
|
424
|
-
res.header('Access-Control-Allow-Origin', options.allowOrigin !== '*' ? options.allowOrigin : (req.headers.origin || '*'));
|
|
425
|
-
res.header('Access-Control-Allow-Methods', corsOptions.methods);
|
|
426
|
-
res.header('Access-Control-Allow-Headers', corsOptions.allowedHeaders);
|
|
427
|
-
res.header('Access-Control-Expose-Headers', 'Date, AceBase-Context'); // Prevent browsers from stripping these headers from the response for programmatic access in cross-origin requests
|
|
428
|
-
if (req.method === 'OPTIONS') {
|
|
429
|
-
res.status(200).end();
|
|
430
|
-
}
|
|
431
|
-
else {
|
|
432
|
-
next();
|
|
433
|
-
}
|
|
434
|
-
};
|
|
435
|
-
app.use(corsHandler);
|
|
436
|
-
|
|
437
|
-
// TODO: determine max socket payload using options.maxPayloadSize which is now only used for json POST data
|
|
438
|
-
// const maxPayloadBytes = ((payloadStr) => {
|
|
439
|
-
// const match = payloadStr.match(/^([0-9]+)(?:mb|kb|b)$/i);
|
|
440
|
-
// if (!match) { return 10e7; } // Socket.IO 2.x default (100MB), 3.x default is 1MB (1e6)
|
|
441
|
-
// const nr = +match[0], unit = match[1].toLowerCase();
|
|
442
|
-
// switch (unit) {
|
|
443
|
-
// case 'mb': return nr * 1e6;
|
|
444
|
-
// case 'kb': return nr * 1e3;
|
|
445
|
-
// case 'b': return nr;
|
|
446
|
-
// }
|
|
447
|
-
// }, options.maxPayloadSize);
|
|
448
|
-
|
|
449
|
-
const server = options.https.enabled ? require('https').createServer(options.https, app) : require('http').createServer(app);
|
|
450
|
-
const io = require('socket.io')(server, {
|
|
451
|
-
// See https://socket.io/docs/v2/server-initialization/ and https://socket.io/docs/v3/server-initialization/
|
|
452
|
-
pingInterval: 5000, // socket.io 2.x default is 25000
|
|
453
|
-
pingTimeout: 5000, // socket.io 2.x default is 5000, 3.x default = 20000
|
|
454
|
-
maxHttpBufferSize: 10e7, // Socket is closed if sent message exceeds this. Socket.io 2.x default is 10e7 (100MB)
|
|
455
|
-
|
|
456
|
-
// socket.io 2.x:
|
|
457
|
-
handlePreflightRequest: corsHandler
|
|
458
|
-
// socket.io 3+:
|
|
459
|
-
// cors: corsOptions
|
|
460
|
-
});
|
|
461
|
-
|
|
462
|
-
app.use(express.json({ limit: options.maxPayloadSize, extended: true }));
|
|
463
|
-
|
|
464
|
-
this.config = {
|
|
465
|
-
hostname: options.host,
|
|
466
|
-
port: options.port,
|
|
467
|
-
get url() {
|
|
468
|
-
return `http${this.https.enabled ? 's' : ''}://${this.hostname}:${this.port}`;
|
|
469
|
-
},
|
|
470
|
-
https: options.https,
|
|
471
|
-
authentication: options.authentication,
|
|
472
|
-
email: options.email,
|
|
473
|
-
get transactionLoggingEnabled() {
|
|
474
|
-
return options.transactions && options.transactions.log === true;
|
|
475
|
-
}
|
|
476
|
-
};
|
|
477
|
-
this.url = this.config.url; // Is this used?
|
|
478
|
-
this.debug = new DebugLogger(options.logLevel, `[${dbname}]`.colorize(ColorStyle.green));
|
|
479
|
-
|
|
480
|
-
const dbOptions = {
|
|
481
|
-
logLevel: options.logLevel,
|
|
482
|
-
info: 'realtime database server',
|
|
483
|
-
// NEW: Allow storage setting like AceBaseLocalSettings - could allow using other db backend (typed, but undocumented)
|
|
484
|
-
storage: options.storage || {
|
|
485
|
-
path: options.path,
|
|
486
|
-
removeVoidProperties: true,
|
|
487
|
-
},
|
|
488
|
-
transactions: options.transactions,
|
|
489
|
-
ipc: options.ipc
|
|
490
|
-
};
|
|
491
|
-
|
|
492
|
-
const db = new AceBase(dbname, dbOptions);
|
|
493
|
-
Object.defineProperty(this, 'db', { configurable: false, get: () => db }); // Expose to outside world
|
|
494
|
-
|
|
495
|
-
if (options.authentication.enabled) {
|
|
496
|
-
this.authProviders = {};
|
|
497
|
-
}
|
|
498
|
-
if (options.authentication.enabled && !options.https.enabled) {
|
|
499
|
-
this.debug.warn(`WARNING: Authentication is enabled, but the server is not using https. Any password and other data transmitted may be intercepted!`.colorize(ColorStyle.red));
|
|
500
|
-
}
|
|
501
|
-
else if (!options.https.enabled) {
|
|
502
|
-
this.debug.warn(`WARNING: Server is not using https, any data transmitted may be intercepted!`.colorize(ColorStyle.red));
|
|
503
|
-
}
|
|
504
|
-
if (!options.authentication.enabled) {
|
|
505
|
-
this.debug.warn(`WARNING: Authentication is disabled, *anyone* can do *anything* with your data!`.colorize(ColorStyle.red));
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
const otherDbsPath = `${options.path}/${dbname}.acebase`;
|
|
509
|
-
// const eventsDb = new AceBase('events', { logLevel: dbOptions.logLevel, storage: { path: otherDbsPath, removeVoidProperties: true } })
|
|
510
|
-
// const logsDb = new AceBase('logs', { logLevel: dbOptions.logLevel, storage: { path: otherDbsPath, removeVoidProperties: true } })
|
|
511
|
-
const authDb = (() => {
|
|
512
|
-
if (!options.authentication.enabled) {
|
|
513
|
-
return null;
|
|
514
|
-
}
|
|
515
|
-
switch(options.authentication.separateDb) {
|
|
516
|
-
case true: return new AceBase('auth', { logLevel: dbOptions.logLevel, storage: { path: otherDbsPath, removeVoidProperties: true, info: `${dbname} auth database` } });
|
|
517
|
-
case 'v2': /*NOT TESTED YET*/return new AceBase(dbname, { logLevel: dbOptions.logLevel, storage: { type: 'auth', path: options.path, removeVoidProperties: true, info: `${dbname} auth database` } });
|
|
518
|
-
default: return db;
|
|
519
|
-
}
|
|
520
|
-
})();
|
|
521
|
-
|
|
522
|
-
// To handle unhandled promise rejections so process will not die in future versions of node:
|
|
523
|
-
// process.on("unhandledRejection", (reason, p) => {
|
|
524
|
-
// this.debug.error("Unhandled promise rejection at: ", reason.stack);
|
|
525
|
-
// });
|
|
526
|
-
|
|
527
|
-
const readyPromises = [
|
|
528
|
-
db.ready(),
|
|
529
|
-
authDb && authDb !== db ? authDb.ready() : null
|
|
530
|
-
];
|
|
531
|
-
|
|
532
|
-
Promise.all(readyPromises)
|
|
533
|
-
.then(() => {
|
|
534
|
-
//this.debug.log(`Database "${dbname}" is ready to use`);
|
|
535
|
-
|
|
536
|
-
let accessRules = {};
|
|
537
|
-
const securityRef = authDb ? authDb === db ? db.ref('__auth__/security') : authDb.ref('security') : null;
|
|
538
|
-
const authRef = authDb ? authDb === db ? db.ref('__auth__/accounts') : authDb.ref('accounts') : null;
|
|
539
|
-
const logRef = authDb ? authDb === db ? db.ref('__log__') : authDb.ref('log') : null;
|
|
540
|
-
const rulesFilePath = `${options.path}/${dbname}.acebase/rules.json`;
|
|
541
|
-
|
|
542
|
-
const setupRules = () => {
|
|
543
|
-
// Check if there is a rules file, load it or generate default
|
|
544
|
-
fs.unwatchFile(rulesFilePath, setupRules); // If function was triggered because of file change, stop listening now. Listener will be setup again at end of function
|
|
545
|
-
|
|
546
|
-
const defaultAccessRule = (def => {
|
|
547
|
-
switch (def) {
|
|
548
|
-
case AceBaseServerAuthenticationSettings.ACCESS_DEFAULT.ALLOW_AUTHENTICATED: {
|
|
549
|
-
return 'auth !== null';
|
|
550
|
-
}
|
|
551
|
-
case AceBaseServerAuthenticationSettings.ACCESS_DEFAULT.ALLOW_ALL: {
|
|
552
|
-
return true;
|
|
553
|
-
}
|
|
554
|
-
case AceBaseServerAuthenticationSettings.ACCESS_DEFAULT.DENY_ALL: {
|
|
555
|
-
return false;
|
|
556
|
-
}
|
|
557
|
-
default: {
|
|
558
|
-
this.debug.error(`Unknown defaultAccessRule "${def}"`);
|
|
559
|
-
return false;
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
})(options.authentication.defaultAccessRule);
|
|
563
|
-
const defaultRules = {
|
|
564
|
-
rules: {
|
|
565
|
-
".read": defaultAccessRule,
|
|
566
|
-
".write": defaultAccessRule
|
|
567
|
-
}
|
|
568
|
-
};
|
|
569
|
-
if (!fs.existsSync(rulesFilePath)) {
|
|
570
|
-
// Default: deny access
|
|
571
|
-
accessRules = defaultRules;
|
|
572
|
-
// Write defaults
|
|
573
|
-
fs.writeFileSync(rulesFilePath, JSON.stringify(accessRules, null, 4));
|
|
574
|
-
}
|
|
575
|
-
else {
|
|
576
|
-
try {
|
|
577
|
-
const json = fs.readFileSync(rulesFilePath);
|
|
578
|
-
const obj = JSON.parse(json);
|
|
579
|
-
if (typeof obj !== 'object' || typeof obj.rules !== 'object') {
|
|
580
|
-
throw new Error(`malformed rules object`);
|
|
581
|
-
}
|
|
582
|
-
accessRules = obj;
|
|
583
|
-
}
|
|
584
|
-
catch (err) {
|
|
585
|
-
this.debug.error(`Failed to read rules from "${rulesFilePath}": ${err.message}`);
|
|
586
|
-
accessRules = defaultRules;
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// Convert string rules to functions that can be executed
|
|
591
|
-
const processRules = (path, parent, variables) => {
|
|
592
|
-
Object.keys(parent).forEach(key => {
|
|
593
|
-
let rule = parent[key];
|
|
594
|
-
if (['.read', '.write', '.validate'].includes(key) && typeof rule === 'string') {
|
|
595
|
-
// Convert to function
|
|
596
|
-
const text = rule;
|
|
597
|
-
rule = eval(`(env => { const { now, root, newData, data, auth, ${variables.join(', ')} } = env; return ${text}; })`);
|
|
598
|
-
rule.getText = () => {
|
|
599
|
-
return text;
|
|
600
|
-
}
|
|
601
|
-
parent[key] = rule;
|
|
602
|
-
}
|
|
603
|
-
else if (key === '.schema') {
|
|
604
|
-
// Add schema
|
|
605
|
-
db.schema.set(path, rule)
|
|
606
|
-
.catch(err => {
|
|
607
|
-
this.debug.error(`Error parsing ${path}/.schema: ${err.message}`)
|
|
608
|
-
});
|
|
609
|
-
|
|
610
|
-
// // Parse "typescript" schema
|
|
611
|
-
// const text = rule;
|
|
612
|
-
// /** @@type {TypeChecker} */
|
|
613
|
-
// let checker;
|
|
614
|
-
// try {
|
|
615
|
-
// checker = new TypeChecker(rule);
|
|
616
|
-
// }
|
|
617
|
-
// catch(err) {
|
|
618
|
-
// this.debug.error(`Error parsing ${path}/.schema: ${err.message}`)
|
|
619
|
-
// }
|
|
620
|
-
// rule = (value, partial) => {
|
|
621
|
-
// const result = checker.check(path, value, partial);
|
|
622
|
-
// return result;
|
|
623
|
-
// };
|
|
624
|
-
// rule.getText = () => {
|
|
625
|
-
// return text;
|
|
626
|
-
// };
|
|
627
|
-
// parent[key] = rule;
|
|
628
|
-
}
|
|
629
|
-
else if (key.startsWith('$')) {
|
|
630
|
-
variables.push(key);
|
|
631
|
-
}
|
|
632
|
-
if (typeof rule === 'object') {
|
|
633
|
-
processRules(`${path}/${key}`, rule, variables.slice());
|
|
634
|
-
}
|
|
635
|
-
});
|
|
636
|
-
};
|
|
637
|
-
processRules('', accessRules.rules, []);
|
|
638
|
-
|
|
639
|
-
// Watch file for changes
|
|
640
|
-
fs.watchFile(rulesFilePath, setupRules);
|
|
641
|
-
}
|
|
642
|
-
setupRules();
|
|
643
|
-
|
|
644
|
-
let _secureObjectsSalt;
|
|
645
|
-
if (options.authentication.enabled) {
|
|
646
|
-
// NEW: Make sure there is an administrator account in the database
|
|
647
|
-
// NOTE: the admin account is the only account with a non-generated uid: 'admin'
|
|
648
|
-
const p1 = securityRef.child('token_salt').transaction(snap => {
|
|
649
|
-
_secureObjectsSalt = snap.val();
|
|
650
|
-
if (!_secureObjectsSalt) {
|
|
651
|
-
let length = 256;
|
|
652
|
-
_secureObjectsSalt = crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
|
|
653
|
-
return _secureObjectsSalt;
|
|
654
|
-
}
|
|
655
|
-
});
|
|
656
|
-
readyPromises.push(p1);
|
|
657
|
-
|
|
658
|
-
const p2 = authRef.child('admin').transaction(snap => {
|
|
659
|
-
|
|
660
|
-
/** @type {DbUserAccountDetails} */
|
|
661
|
-
let adminAccount = snap.val();
|
|
662
|
-
if (adminAccount === null) {
|
|
663
|
-
// Use provided default password, or generate one:
|
|
664
|
-
const adminPassword = options.authentication.defaultAdminPassword || generatePassword();
|
|
665
|
-
|
|
666
|
-
const pwd = createPasswordHash(adminPassword);
|
|
667
|
-
adminAccount = {
|
|
668
|
-
username: 'admin',
|
|
669
|
-
email: null, // no email address for admin
|
|
670
|
-
display_name: `${dbname} AceBase admin`,
|
|
671
|
-
password: pwd.hash,
|
|
672
|
-
password_salt: pwd.salt,
|
|
673
|
-
change_password: true, // flags that password must be changed. Not implemented yet
|
|
674
|
-
created: new Date(),
|
|
675
|
-
access_token: null, // Will be set upon login, so bearer authentication strategy can find user with this token
|
|
676
|
-
};
|
|
677
|
-
this.debug.warn(`__________________________________________________________________`.colorize(ColorStyle.red));
|
|
678
|
-
this.debug.warn(``.colorize(ColorStyle.red));
|
|
679
|
-
this.debug.warn(`IMPORTANT: Admin account created`.colorize(ColorStyle.red));
|
|
680
|
-
this.debug.warn(`You need the admin account to remotely administer the database`.colorize(ColorStyle.red));
|
|
681
|
-
this.debug.warn(`Use the following credentials to authenticate an AceBaseClient:`.colorize(ColorStyle.red));
|
|
682
|
-
this.debug.warn(``);
|
|
683
|
-
this.debug.warn(` username: admin`.colorize(ColorStyle.red));
|
|
684
|
-
this.debug.warn(` password: ${adminPassword}`.colorize(ColorStyle.red));
|
|
685
|
-
this.debug.warn(``);
|
|
686
|
-
this.debug.warn(`THIS IS ONLY SHOWN ONCE!`.colorize(ColorStyle.red));
|
|
687
|
-
this.debug.warn(`__________________________________________________________________`.colorize(ColorStyle.red));
|
|
688
|
-
return adminAccount; // Save it
|
|
689
|
-
}
|
|
690
|
-
else if (options.authentication.defaultAdminPassword) {
|
|
691
|
-
// Check if the default password was changed
|
|
692
|
-
let passwordHash;
|
|
693
|
-
if (!adminAccount.password_salt) {
|
|
694
|
-
// Old md5 password hash?
|
|
695
|
-
passwordHash = getOldPasswordHash(options.authentication.defaultAdminPassword);
|
|
696
|
-
}
|
|
697
|
-
else {
|
|
698
|
-
passwordHash = getPasswordHash(options.authentication.defaultAdminPassword, adminAccount.password_salt);
|
|
699
|
-
}
|
|
700
|
-
if (adminAccount.password === passwordHash) {
|
|
701
|
-
this.debug.warn(`WARNING: default password for admin user was not changed!`.colorize(ColorStyle.red));
|
|
702
|
-
|
|
703
|
-
if (!adminAccount.password_salt) {
|
|
704
|
-
// Create new password hash
|
|
705
|
-
const pwd = createPasswordHash(options.authentication.defaultAdminPassword);
|
|
706
|
-
adminAccount.password = pwd.hash;
|
|
707
|
-
adminAccount.password_salt = pwd.salt;
|
|
708
|
-
return adminAccount; // Save it
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
})
|
|
713
|
-
.then(() => {
|
|
714
|
-
authDb.indexes.create(authRef.path, 'username');
|
|
715
|
-
authDb.indexes.create(authRef.path, 'email');
|
|
716
|
-
authDb.indexes.create(authRef.path, 'access_token');
|
|
717
|
-
});
|
|
718
|
-
readyPromises.push(p2);
|
|
719
|
-
|
|
720
|
-
/**
|
|
721
|
-
* @param {string} clientIp ip address of the user
|
|
722
|
-
* @param {string} code verification code sent to the user's email address
|
|
723
|
-
*/
|
|
724
|
-
this.verifyEmailAddress = (clientIp, code) => {
|
|
725
|
-
/** @type {{ uid: string }} */
|
|
726
|
-
let verification;
|
|
727
|
-
try {
|
|
728
|
-
verification = parseSignedPublicToken(code, _secureObjectsSalt);
|
|
729
|
-
}
|
|
730
|
-
catch(err) {
|
|
731
|
-
err.code = 'invalid_code';
|
|
732
|
-
return Promise.reject(err);
|
|
733
|
-
}
|
|
734
|
-
return authRef.child(verification.uid).get()
|
|
735
|
-
.then(snap => {
|
|
736
|
-
if (!snap.exists()) { const err = new Error(`Uknown user`); err.code = 'unknown_user'; throw err; }
|
|
737
|
-
/** @type {DbUserAccountDetails} */
|
|
738
|
-
let user = snap.val();
|
|
739
|
-
user.uid = snap.key;
|
|
740
|
-
|
|
741
|
-
// No need to do further checks, code was signed by us so we can trust the contents
|
|
742
|
-
// Mark account as verified
|
|
743
|
-
return snap.ref.update({ email_verified: true })
|
|
744
|
-
.then(ref => user);
|
|
745
|
-
});
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
/**
|
|
749
|
-
* @param {string} clientIp ip address of the user
|
|
750
|
-
* @param {string} code reset code that was sent to the user's email address
|
|
751
|
-
* @param {string} newPassword new password chosen by the user
|
|
752
|
-
*/
|
|
753
|
-
this.resetPassword = (clientIp, code, newPassword) => {
|
|
754
|
-
/** @type {{ uid: string, code: string }} */
|
|
755
|
-
let verification;
|
|
756
|
-
try {
|
|
757
|
-
verification = parseSignedPublicToken(code, _secureObjectsSalt);
|
|
758
|
-
}
|
|
759
|
-
catch(err) {
|
|
760
|
-
err.code = 'invalid_code';
|
|
761
|
-
return Promise.reject(err);
|
|
762
|
-
}
|
|
763
|
-
return authRef.child(verification.uid).get()
|
|
764
|
-
.then(snap => {
|
|
765
|
-
if (!snap.exists()) { const err = new Error(`Uknown user`); err.code = 'unknown_user'; throw err; }
|
|
766
|
-
/** @type {DbUserAccountDetails} */
|
|
767
|
-
let user = snap.val();
|
|
768
|
-
user.uid = snap.key;
|
|
769
|
-
|
|
770
|
-
if (user.password_reset_code !== verification.code) { const err = new Error(`Invalid code`); err.code = 'invalid_code'; throw err; }
|
|
771
|
-
if (newPassword.length < 8 || newPassword.includes(' ')) { const err = new Error(`Password must be at least 8 characters, and cannot contain spaces`); err.code = 'password_requirement_mismatch'; throw err; }
|
|
772
|
-
|
|
773
|
-
// Ok to change password
|
|
774
|
-
const pwd = createPasswordHash(newPassword);
|
|
775
|
-
return snap.ref.update({
|
|
776
|
-
password: pwd.hash,
|
|
777
|
-
password_salt: pwd.salt,
|
|
778
|
-
password_reset_code: null
|
|
779
|
-
})
|
|
780
|
-
.then(() => user);
|
|
781
|
-
})
|
|
782
|
-
.then(user => {
|
|
783
|
-
// Send confirmation email
|
|
784
|
-
const request = new AceBaseUserResetPasswordSuccessEmailRequest({
|
|
785
|
-
date: new Date(),
|
|
786
|
-
ip: clientIp,
|
|
787
|
-
user: {
|
|
788
|
-
uid: user.uid,
|
|
789
|
-
email: user.email,
|
|
790
|
-
username: user.username,
|
|
791
|
-
displayName: user.display_name,
|
|
792
|
-
settings: user.settings
|
|
793
|
-
}
|
|
794
|
-
});
|
|
795
|
-
this.config.email && this.config.email.send(request);
|
|
796
|
-
return user;
|
|
797
|
-
});
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
/**
|
|
802
|
-
*
|
|
803
|
-
* @param {DbUserAccountDetails} user
|
|
804
|
-
* @param {string} path
|
|
805
|
-
* @param {boolean} [write]
|
|
806
|
-
* @param {(details: { code: string, message: string, [key:string]: any }) => void} denyDetailsCallback
|
|
807
|
-
*/
|
|
808
|
-
const userHasAccess = (user, path, write = false, denyDetailsCallback = undefined) => {
|
|
809
|
-
// Process rules, find out if signed in user is allowed to read/write
|
|
810
|
-
// Defaults to false unless a rule is found that tells us otherwise
|
|
811
|
-
|
|
812
|
-
if (!options.authentication.enabled) {
|
|
813
|
-
// Authentication is disabled, anyone can do anything. Not really a smart thing to do!
|
|
814
|
-
return true;
|
|
815
|
-
}
|
|
816
|
-
else if (user && user.uid === 'admin') {
|
|
817
|
-
// Always allow admin access
|
|
818
|
-
// TODO: implement user.is_admin, so the default admin account can be disabled
|
|
819
|
-
return true;
|
|
820
|
-
}
|
|
821
|
-
else if (path.startsWith('__')) {
|
|
822
|
-
// NEW: with the auth database now integrated into the main database,
|
|
823
|
-
// deny access to private resources starting with '__' for non-admins
|
|
824
|
-
denyDetailsCallback && denyDetailsCallback({ code: 'private', message: `Access to private resource "${path}" not allowed` });
|
|
825
|
-
return false;
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
const env = { now: Date.now(), auth: user || null }; // IDEA: Add functions like "exists" and "value". These will be async (so that requires refactoring) and can be used like "await exists('./shared/' + auth.uid)" and "await value('./writable') === true"
|
|
829
|
-
const pathKeys = PathInfo.getPathKeys(path);
|
|
830
|
-
let rule = accessRules.rules;
|
|
831
|
-
let rulePath = [];
|
|
832
|
-
while(true) {
|
|
833
|
-
if (!rule) {
|
|
834
|
-
denyDetailsCallback && denyDetailsCallback({ code: 'no_rule', message: `No rules set for requested path "${path}", defaulting to false` });
|
|
835
|
-
return false;
|
|
836
|
-
}
|
|
837
|
-
let checkRule = write ? rule['.write'] : rule['.read'];
|
|
838
|
-
if (typeof checkRule === 'boolean') {
|
|
839
|
-
const allow = checkRule;
|
|
840
|
-
if (!allow) {
|
|
841
|
-
denyDetailsCallback && denyDetailsCallback({ code: 'rule', message: `Access denied to path "${path}" by set rule`, rule: checkRule, rulePath: rulePath.join('/') });
|
|
842
|
-
}
|
|
843
|
-
return allow;
|
|
844
|
-
}
|
|
845
|
-
if (typeof checkRule === 'function') {
|
|
846
|
-
try {
|
|
847
|
-
// Execute rule function
|
|
848
|
-
let allow = checkRule(env);
|
|
849
|
-
if (!allow) {
|
|
850
|
-
denyDetailsCallback && denyDetailsCallback({ code: 'rule', message: `Access denied to path "${path}" by set rule`, rule: checkRule.getText(), rulePath: rulePath.join('/') });
|
|
851
|
-
}
|
|
852
|
-
return allow;
|
|
853
|
-
}
|
|
854
|
-
catch(err) {
|
|
855
|
-
// If rule execution throws an exception, don't allow. Can happen when rule is "auth.uid === '...'", and auth is null because the user is not signed in
|
|
856
|
-
denyDetailsCallback && denyDetailsCallback({ code: 'exception', message: `Access denied to path "${path}" by set rule`, rule: checkRule.getText(), rulePath: rulePath.join('/'), details: err });
|
|
857
|
-
return false;
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
if (pathKeys.length === 0) {
|
|
861
|
-
return false;
|
|
862
|
-
}
|
|
863
|
-
let nextKey = pathKeys.shift();
|
|
864
|
-
// if nextKey is '*' or '$something', rule[nextKey] will be undefined (or match a variable) so there is no
|
|
865
|
-
// need to change things here for usage of wildcard paths in subscriptions
|
|
866
|
-
if (typeof rule[nextKey] === 'undefined') {
|
|
867
|
-
// Check if current rule has a wildcard child
|
|
868
|
-
const wildcardKey = Object.keys(rule).find(key => key ==='*' || key[0] === '$');
|
|
869
|
-
if (wildcardKey) { env[wildcardKey] = nextKey; }
|
|
870
|
-
nextKey = wildcardKey;
|
|
871
|
-
}
|
|
872
|
-
nextKey && rulePath.push(nextKey);
|
|
873
|
-
rule = rule[nextKey];
|
|
874
|
-
}
|
|
875
|
-
};
|
|
876
|
-
|
|
877
|
-
const sendNotAuthenticatedError = (res, code, message) => {
|
|
878
|
-
res.statusCode = 401; // Unauthorized (not unauthenticated)
|
|
879
|
-
res.statusMessage = 'Not Authenticated';
|
|
880
|
-
res.send({ code, message });
|
|
881
|
-
};
|
|
882
|
-
|
|
883
|
-
const sendUnauthorizedError = (res, code, message) => {
|
|
884
|
-
res.statusCode = 403; // Forbidden
|
|
885
|
-
res.statusMessage = 'Unauthorized';
|
|
886
|
-
res.send({ code, message });
|
|
887
|
-
};
|
|
888
|
-
|
|
889
|
-
const sendError = (res, err) => {
|
|
890
|
-
if (typeof err.code === 'string') {
|
|
891
|
-
res.status(400).send({ code: err.code, message: err.message }); // Bad Request
|
|
892
|
-
}
|
|
893
|
-
else {
|
|
894
|
-
res.status(500).send({ code: 'unknown', message: 'server error', details: err.message }); // Internal server error
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
/** @type {Map<string, User>} Maps uid's to users */
|
|
899
|
-
const _authCache = new Map();
|
|
900
|
-
|
|
901
|
-
/**
|
|
902
|
-
*
|
|
903
|
-
* @param {string} type 'username', 'email' or 'access_token'
|
|
904
|
-
* @param {string} username (or email when param type === 'email')
|
|
905
|
-
* @param {string} password
|
|
906
|
-
* @param {(err: Error, user?: DbUserAccountDetails, details?: { code: string, message: string }) => void} callback
|
|
907
|
-
*/
|
|
908
|
-
const signIn = function(req, type, username, password, callback) {
|
|
909
|
-
let tokenDetails;
|
|
910
|
-
if (type === 'access_token') {
|
|
911
|
-
tokenDetails = decodePublicAccessToken(username, _secureObjectsSalt);
|
|
912
|
-
if (!tokenDetails.access_token) {
|
|
913
|
-
const code = 'invalid_token';
|
|
914
|
-
logRef.push({ action: `signin`, type, [type]: username, success: false, code, ip: req.ip, date: new Date() });
|
|
915
|
-
return callback(null, false, { code, message: `Incorrect ${type}` });
|
|
916
|
-
}
|
|
917
|
-
username = tokenDetails.access_token;
|
|
918
|
-
}
|
|
919
|
-
return authRef.query()
|
|
920
|
-
.filter(type, '==', username)
|
|
921
|
-
.get()
|
|
922
|
-
.then(snaps => {
|
|
923
|
-
if (snaps.length === 0) {
|
|
924
|
-
const code = 'not_found';
|
|
925
|
-
logRef.push({ action: `signin`, type, [type]: username, success: false, code, ip: req.ip, date: new Date() });
|
|
926
|
-
return callback(null, false, { code, message: `Incorrect ${type}` });
|
|
927
|
-
}
|
|
928
|
-
else if (snaps.length > 1) {
|
|
929
|
-
const code = 'duplicate';
|
|
930
|
-
logRef.push({ action: `signin`, type, [type]: username, success: false, code, count: snaps.length, ip: req.ip, date: new Date() });
|
|
931
|
-
return callback(null, false, { code, message: `${snaps.length} users found with the same ${type}. Contact your database administrator` });
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
/** @type {DataSnapshot} */
|
|
935
|
-
const snap = snaps[0];
|
|
936
|
-
/** @type {DbUserAccountDetails} */
|
|
937
|
-
const user = snap.val();
|
|
938
|
-
user.uid = snap.key;
|
|
939
|
-
|
|
940
|
-
if (user.is_disabled === true) {
|
|
941
|
-
return callback(null, false, { code: 'account_disabled', message: 'Your account has been disabled. Contact your database administrator' });
|
|
942
|
-
}
|
|
943
|
-
if (type === 'access_token' && tokenDetails.uid !== user.uid) {
|
|
944
|
-
const code = 'token_mismatch';
|
|
945
|
-
logRef.push({ action: `signin`, type, [type]: username, ip: req.ip, date: new Date(), success: false, reason: code });
|
|
946
|
-
return callback(null, false, { code, message: 'Sign in again' });
|
|
947
|
-
}
|
|
948
|
-
if (type !== 'access_token') {
|
|
949
|
-
let hash = user.password_salt ? getPasswordHash(password, user.password_salt) : getOldPasswordHash(password);
|
|
950
|
-
if (user.password !== hash) {
|
|
951
|
-
const code = 'wrong_password';
|
|
952
|
-
logRef.push({ action: `signin`, type, [type]: username, ip: req.ip, date: new Date(), success: false, reason: code });
|
|
953
|
-
return callback(null, false, { code, message: 'Incorrect password' });
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
// Keep track of properties to update, both in db and in our object
|
|
958
|
-
const updates = {
|
|
959
|
-
// Update prev / last sign in stats
|
|
960
|
-
prev_signin: user.last_signin,
|
|
961
|
-
prev_signin_ip: user.last_signin_ip,
|
|
962
|
-
last_signin: new Date(),
|
|
963
|
-
last_signin_ip: req.ip
|
|
964
|
-
};
|
|
965
|
-
|
|
966
|
-
if (!user.password_salt) {
|
|
967
|
-
// OLD md5 password hash, convert to new salted hash
|
|
968
|
-
let pwd = createPasswordHash(password);
|
|
969
|
-
updates.password = pwd.hash;
|
|
970
|
-
updates.password_salt = pwd.salt;
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
if (type !== 'access_token' && !user.access_token) {
|
|
974
|
-
// Generate access token
|
|
975
|
-
updates.access_token = ID.generate();
|
|
976
|
-
updates.access_token_created = new Date();
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
// Update user object
|
|
980
|
-
Object.assign(user, updates);
|
|
981
|
-
|
|
982
|
-
// Update db
|
|
983
|
-
return snap.ref.update(updates)
|
|
984
|
-
.then(() => {
|
|
985
|
-
|
|
986
|
-
// Log history item
|
|
987
|
-
logRef.push({ action: `signin`, type, [type]: username, ip: req.ip, date: new Date(), success: true });
|
|
988
|
-
|
|
989
|
-
// Add to cache
|
|
990
|
-
_authCache.set(user.uid, user);
|
|
991
|
-
|
|
992
|
-
// Bind user to current request
|
|
993
|
-
req.user = user;
|
|
994
|
-
|
|
995
|
-
return callback(null, user);
|
|
996
|
-
});
|
|
997
|
-
})
|
|
998
|
-
.catch(err => {
|
|
999
|
-
logRef.push({ action: `signin`, type, [type]: username, ip: req.ip, date: new Date(), success: false, code: 'unexpected', message: err.message })
|
|
1000
|
-
return callback(err);
|
|
1001
|
-
});
|
|
1002
|
-
};
|
|
1003
|
-
|
|
1004
|
-
server.on("error", (err) => {
|
|
1005
|
-
this.debug.log(err);
|
|
1006
|
-
});
|
|
1007
|
-
|
|
1008
|
-
app.use((req, res, next) => {
|
|
1009
|
-
// Setup AceBase context, to allow clients to pass contextual info with data updates,
|
|
1010
|
-
// that will be sent along to data event subscribers on affected data.
|
|
1011
|
-
const context = req.get('AceBase-Context');
|
|
1012
|
-
try {
|
|
1013
|
-
req.context = context && JSON.parse(context);
|
|
1014
|
-
}
|
|
1015
|
-
catch(err) {
|
|
1016
|
-
this.debug.error(`Failed to parse AceBase-Context header: "${context}" in request at ${req.url} from client ${req.ip}`);
|
|
1017
|
-
}
|
|
1018
|
-
// console.log(`Received request on path ` + req.path);
|
|
1019
|
-
next();
|
|
1020
|
-
});
|
|
1021
|
-
|
|
1022
|
-
if (options.authentication.enabled) {
|
|
1023
|
-
// Add authentication middleware and API endpoints
|
|
1024
|
-
|
|
1025
|
-
app.use((req, res, next) => {
|
|
1026
|
-
let authorization = req.get('Authorization');
|
|
1027
|
-
if (typeof authorization !== 'string' && 'auth_token' in req.query) {
|
|
1028
|
-
// Enables browser calls to be authenticated
|
|
1029
|
-
if (req.path.startsWith('/export/')) {
|
|
1030
|
-
// For now, only allow this if the intention is to call '/export' api call
|
|
1031
|
-
// In the future, use these prerequisites:
|
|
1032
|
-
// - user must be currently authenticated (in cache)
|
|
1033
|
-
// - ip address must match the token
|
|
1034
|
-
authorization = 'Bearer ' + req.query.auth_token;
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
if (typeof authorization === 'string' && authorization.startsWith('Bearer ')) {
|
|
1038
|
-
const token = authorization.slice(7);
|
|
1039
|
-
let tokenDetails;
|
|
1040
|
-
try {
|
|
1041
|
-
tokenDetails = decodePublicAccessToken(token, _secureObjectsSalt);
|
|
1042
|
-
if (!tokenDetails.uid || !tokenDetails.access_token) { throw new Error('invalid token'); }
|
|
1043
|
-
}
|
|
1044
|
-
catch(err) {
|
|
1045
|
-
return sendNotAuthenticatedError(res, 'invalid_token', 'The passed token is invalid. Sign in again');
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
// Is this token cached?
|
|
1049
|
-
const cachedUser = _authCache.get(tokenDetails.uid);
|
|
1050
|
-
if (cachedUser) {
|
|
1051
|
-
// Bind user to current request
|
|
1052
|
-
req.user = cachedUser;
|
|
1053
|
-
|
|
1054
|
-
if (req.user && req.user.is_disabled === true) {
|
|
1055
|
-
return sendNotAuthenticatedError(res, 'account_disabled', 'Your account has been disabled. Contact your database administrator');
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
return next();
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
// Not cached, query database to get user for this token
|
|
1062
|
-
return signIn(req, 'access_token', token, null, (err, user, details) => {
|
|
1063
|
-
if (err) {
|
|
1064
|
-
return sendNotAuthenticatedError(res, details.code, details.message);
|
|
1065
|
-
}
|
|
1066
|
-
next();
|
|
1067
|
-
});
|
|
1068
|
-
}
|
|
1069
|
-
next();
|
|
1070
|
-
});
|
|
1071
|
-
|
|
1072
|
-
app.get(`/auth/${dbname}/state`, (req, res) => {
|
|
1073
|
-
if (req.user) {
|
|
1074
|
-
res.send({ signed_in: true, user: req.user });
|
|
1075
|
-
}
|
|
1076
|
-
else {
|
|
1077
|
-
res.send({ signed_in: false });
|
|
1078
|
-
}
|
|
1079
|
-
});
|
|
1080
|
-
|
|
1081
|
-
app.post(`/auth/${dbname}/signin`, (req, res) => {
|
|
1082
|
-
// if (!this.config.authentication.enabled) {
|
|
1083
|
-
// res.statusCode = 405;
|
|
1084
|
-
// return res.send('Disabled');
|
|
1085
|
-
// }
|
|
1086
|
-
|
|
1087
|
-
const details = req.body;
|
|
1088
|
-
const clientId = details.client_id || null; // NEW in AceBaseClient v0.9.4
|
|
1089
|
-
|
|
1090
|
-
/**
|
|
1091
|
-
*
|
|
1092
|
-
* @param {Error} err
|
|
1093
|
-
* @param {DbUserAccountDetails} user
|
|
1094
|
-
* @param {{ code: string, message: string }} details
|
|
1095
|
-
*/
|
|
1096
|
-
const handle = (err, user, details) => {
|
|
1097
|
-
const client = typeof clientId === 'string' ? clients.get(clientId) : null;
|
|
1098
|
-
if (client) {
|
|
1099
|
-
// Bind user to client socket
|
|
1100
|
-
client.user = user || null;
|
|
1101
|
-
}
|
|
1102
|
-
if (err) {
|
|
1103
|
-
return sendError(res, err);
|
|
1104
|
-
}
|
|
1105
|
-
if (!user) {
|
|
1106
|
-
return sendNotAuthenticatedError(res, details.code, details.message)
|
|
1107
|
-
}
|
|
1108
|
-
res.send({
|
|
1109
|
-
access_token: createPublicAccessToken(user.uid, req.ip, user.access_token, _secureObjectsSalt),
|
|
1110
|
-
user: getPublicAccountDetails(user)
|
|
1111
|
-
});
|
|
1112
|
-
};
|
|
1113
|
-
if (details.method === 'token') {
|
|
1114
|
-
return signIn(req, 'access_token', details.access_token, null, handle);
|
|
1115
|
-
}
|
|
1116
|
-
else if (details.method === 'email') {
|
|
1117
|
-
return signIn(req, 'email', details.email, details.password, handle);
|
|
1118
|
-
}
|
|
1119
|
-
else {
|
|
1120
|
-
return signIn(req, 'username', details.username, details.password, handle);
|
|
1121
|
-
}
|
|
1122
|
-
});
|
|
1123
|
-
|
|
1124
|
-
app.post(`/auth/${dbname}/signout`, (req, res) => {
|
|
1125
|
-
if (!req.user) {
|
|
1126
|
-
// Strange request.. User wasn't signed in
|
|
1127
|
-
res.send('Bye!');
|
|
1128
|
-
return;
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
const client = typeof req.client_id === 'string' ? clients.get(req.client_id) : null; // NEW in AceBaseClient v0.9.4
|
|
1132
|
-
if (client) {
|
|
1133
|
-
// Remove user binding from client socket
|
|
1134
|
-
client.user = null;
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
const signOutEverywhere = typeof req.body === 'object' && req.body.everywhere === true; // NEW in AceBaseClient v0.9.14
|
|
1138
|
-
// TODO: if signOutEverywhere, immediately tell other connected clients to sign out (now they will remain signed in until they retry with access token)
|
|
1139
|
-
|
|
1140
|
-
// Remove token from cache
|
|
1141
|
-
signOutEverywhere && _authCache.delete(req.user.uid);
|
|
1142
|
-
|
|
1143
|
-
// Remove token from user's auth node
|
|
1144
|
-
return authRef.child(req.user.uid)
|
|
1145
|
-
.transaction(snap => {
|
|
1146
|
-
if (!snap.exists()) { return; }
|
|
1147
|
-
|
|
1148
|
-
/** @type {AceBaseUserAccount} */
|
|
1149
|
-
let user = snap.val();
|
|
1150
|
-
if (signOutEverywhere) {
|
|
1151
|
-
user.access_token = null;
|
|
1152
|
-
}
|
|
1153
|
-
user.last_signout = new Date();
|
|
1154
|
-
user.last_signout_ip = req.ip;
|
|
1155
|
-
return user;
|
|
1156
|
-
})
|
|
1157
|
-
.then(() => {
|
|
1158
|
-
logRef.push({ action: 'signout', success: true, uid: req.user.uid, ip: req.ip, date: new Date() });
|
|
1159
|
-
res.send('Bye!');
|
|
1160
|
-
})
|
|
1161
|
-
.catch(err => {
|
|
1162
|
-
logRef.push({ action: 'signout', success: false, code: 'unexpected', message: err.message, uid: req.user.uid, ip: req.ip, date: new Date() });
|
|
1163
|
-
res.statusCode = 500;
|
|
1164
|
-
res.send({ code: 'unexpected', message: err.message });
|
|
1165
|
-
});
|
|
1166
|
-
});
|
|
1167
|
-
|
|
1168
|
-
app.post(`/auth/${dbname}/forgot_password`, (req, res) => {
|
|
1169
|
-
const details = req.body;
|
|
1170
|
-
return Promise.resolve()
|
|
1171
|
-
.then(() => {
|
|
1172
|
-
if (!this.config.email || typeof this.config.email.send !== 'function') {
|
|
1173
|
-
const err = new Error('Server email settings have not been configured');
|
|
1174
|
-
err.code = 'server_email_config';
|
|
1175
|
-
throw err;
|
|
1176
|
-
}
|
|
1177
|
-
if (typeof details !== 'object' || typeof details.email !== 'string' || details.email.length === 0) {
|
|
1178
|
-
const err = new Error('Invalid details');
|
|
1179
|
-
err.code = 'invalid_details';
|
|
1180
|
-
throw err;
|
|
1181
|
-
}
|
|
1182
|
-
return authRef.query().filter('email', '==', details.email).get()
|
|
1183
|
-
})
|
|
1184
|
-
.then(snaps => {
|
|
1185
|
-
if (snaps.length !== 1) {
|
|
1186
|
-
const err = new Error('Email address not found, or duplicate entries found');
|
|
1187
|
-
err.code = 'invalid_email';
|
|
1188
|
-
throw err;
|
|
1189
|
-
}
|
|
1190
|
-
const snap = snaps[0];
|
|
1191
|
-
/** @type {DbUserAccountDetails} */
|
|
1192
|
-
const user = snap.val();
|
|
1193
|
-
user.uid = snap.key;
|
|
1194
|
-
user.password_reset_code = ID.generate();
|
|
1195
|
-
|
|
1196
|
-
// Request a password reset email to be sent:
|
|
1197
|
-
const request = new AceBaseUserResetPasswordEmailRequest({
|
|
1198
|
-
date: new Date(),
|
|
1199
|
-
ip: req.ip,
|
|
1200
|
-
resetCode: createSignedPublicToken({ uid: user.uid, code: user.password_reset_code }, _secureObjectsSalt),
|
|
1201
|
-
user: {
|
|
1202
|
-
email: user.email,
|
|
1203
|
-
uid: user.uid,
|
|
1204
|
-
username: user.username,
|
|
1205
|
-
settings: user.settings,
|
|
1206
|
-
displayName: user.display_name
|
|
1207
|
-
}
|
|
1208
|
-
});
|
|
1209
|
-
return Promise.all([
|
|
1210
|
-
this.config.email.send(request),
|
|
1211
|
-
snap.ref.update({ password_reset_code: user.password_reset_code })
|
|
1212
|
-
])
|
|
1213
|
-
})
|
|
1214
|
-
.then(() => {
|
|
1215
|
-
logRef.push({ action: 'forgot_password', success: true, email: details.email, ip: req.ip, date: new Date() });
|
|
1216
|
-
res.send('OK');
|
|
1217
|
-
})
|
|
1218
|
-
.catch(err => {
|
|
1219
|
-
logRef.push({ action: 'forgot_password', success: false, code: err.code || err.message, email: details.email, ip: req.ip, date: new Date() });
|
|
1220
|
-
sendError(res, err);
|
|
1221
|
-
})
|
|
1222
|
-
});
|
|
1223
|
-
|
|
1224
|
-
app.post(`/auth/${dbname}/verify_email`, (req, res) => {
|
|
1225
|
-
const details = req.body;
|
|
1226
|
-
return this.verifyEmailAddress(req.ip, details.code)
|
|
1227
|
-
.then(user => {
|
|
1228
|
-
logRef.push({ action: 'verify_email', success: true, ip: req.ip, date: new Date(), uid: user.uid });
|
|
1229
|
-
res.send('OK');
|
|
1230
|
-
})
|
|
1231
|
-
.catch(err => {
|
|
1232
|
-
logRef.push({ action: 'verify_email', success: false, code: err.code, message: err.message, ip: req.ip, date: new Date(), uid: details.uid });
|
|
1233
|
-
sendError(res, err);
|
|
1234
|
-
});
|
|
1235
|
-
});
|
|
1236
|
-
|
|
1237
|
-
app.post(`/auth/${dbname}/reset_password`, (req, res) => {
|
|
1238
|
-
const details = req.body;
|
|
1239
|
-
return this.resetPassword(req.ip, details.code, details.password)
|
|
1240
|
-
.then(user => {
|
|
1241
|
-
logRef.push({ action: 'reset_password', success: true, ip: req.ip, date: new Date(), uid: user.uid });
|
|
1242
|
-
res.send('OK');
|
|
1243
|
-
})
|
|
1244
|
-
.catch(err => {
|
|
1245
|
-
logRef.push({ action: 'reset_password', success: false, code: err.code, message: err.message, ip: req.ip, date: new Date(), uid: details.uid });
|
|
1246
|
-
sendError(res, err);
|
|
1247
|
-
});
|
|
1248
|
-
});
|
|
1249
|
-
|
|
1250
|
-
app.post(`/auth/${dbname}/change_password`, (req, res) => {
|
|
1251
|
-
let access_token = req.user && req.user.access_token;
|
|
1252
|
-
const details = req.body;
|
|
1253
|
-
|
|
1254
|
-
if (typeof details !== 'object' || typeof details.uid !== 'string' || typeof details.password !== 'string' || typeof details.new_password !== 'string') {
|
|
1255
|
-
logRef.push({ action: 'change_password', success: false, code: 'invalid_details', ip: req.ip, date: new Date() });
|
|
1256
|
-
res.status(400).send('Bad Request'); // Bad Request
|
|
1257
|
-
return;
|
|
1258
|
-
}
|
|
1259
|
-
if (details.new_password.length < 8 || details.new_password.includes(' ') || !/[0-9]/.test(details.new_password) || !/[a-z]/.test(details.new_password) || !/[A-Z]/.test(details.new_password)) {
|
|
1260
|
-
logRef.push({ action: 'change_password', success: false, code: 'new_password_denied', ip: req.ip, date: new Date(), uid: details.uid });
|
|
1261
|
-
const err = 'Invalid new password, must be at least 8 characters and contain a combination of numbers and letters (both lower and uppercase)';
|
|
1262
|
-
res.status(422).send(err);// Unprocessable Entity
|
|
1263
|
-
return;
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
let publicAccessToken;
|
|
1267
|
-
return authRef.child(details.uid)
|
|
1268
|
-
.transaction(snap => {
|
|
1269
|
-
if (!snap.exists()) {
|
|
1270
|
-
let err = new Error(`Unknown uid`);
|
|
1271
|
-
err.code = 'unknown_uid';
|
|
1272
|
-
throw err;
|
|
1273
|
-
}
|
|
1274
|
-
/** @type {DbUserAccountDetails} */
|
|
1275
|
-
let user = snap.val();
|
|
1276
|
-
user.uid = snap.key;
|
|
1277
|
-
let hash = user.password_salt ? getPasswordHash(details.password, user.password_salt) : getOldPasswordHash(details.password);
|
|
1278
|
-
if (user.password !== hash) {
|
|
1279
|
-
let err = new Error(`Wrong password`);
|
|
1280
|
-
err.code = 'wrong_password';
|
|
1281
|
-
throw err;
|
|
1282
|
-
}
|
|
1283
|
-
if (access_token && access_token !== user.access_token) {
|
|
1284
|
-
let err = new Error(`Cannot change password while signed in as other user, or with an old token`);
|
|
1285
|
-
err.code = 'wrong_access_token';
|
|
1286
|
-
throw err;
|
|
1287
|
-
}
|
|
1288
|
-
let pwd = createPasswordHash(details.new_password);
|
|
1289
|
-
const updates = {
|
|
1290
|
-
access_token: ID.generate(),
|
|
1291
|
-
access_token_created: new Date(),
|
|
1292
|
-
password: pwd.hash,
|
|
1293
|
-
password_salt: pwd.salt
|
|
1294
|
-
};
|
|
1295
|
-
// Update user object
|
|
1296
|
-
Object.assign(user, updates);
|
|
1297
|
-
// Set or update cache
|
|
1298
|
-
_authCache.set(user.uid, user);
|
|
1299
|
-
// Create new public access token
|
|
1300
|
-
publicAccessToken = createPublicAccessToken(user.uid, req.ip, user.access_token, _secureObjectsSalt);
|
|
1301
|
-
|
|
1302
|
-
return user; // Update db
|
|
1303
|
-
})
|
|
1304
|
-
.then(userRef => {
|
|
1305
|
-
res.send({ access_token: publicAccessToken }); // Client must use this new access token from now on
|
|
1306
|
-
})
|
|
1307
|
-
.catch(err => {
|
|
1308
|
-
logRef.push({ action: 'change_pwd', success: false, code: err.code, ip: req.ip, date: new Date(), uid: details.uid });
|
|
1309
|
-
sendError(res, err);
|
|
1310
|
-
});
|
|
1311
|
-
});
|
|
1312
|
-
|
|
1313
|
-
const isValid = {
|
|
1314
|
-
email(email) {
|
|
1315
|
-
return /[a-z0-9_.+]+@([a-z0-9\-]+\.)+[a-z]{2,}/i.test(email);
|
|
1316
|
-
},
|
|
1317
|
-
async newEmailAddress(email) {
|
|
1318
|
-
const exists = await authRef.query().filter('email', '==', email).exists();
|
|
1319
|
-
return !exists;
|
|
1320
|
-
},
|
|
1321
|
-
username(username) {
|
|
1322
|
-
return username !== 'admin' && typeof username === 'string' && username.length >= 5 && /^[a-z0-9]+$/.test(username);
|
|
1323
|
-
},
|
|
1324
|
-
async newUsername(username) {
|
|
1325
|
-
const exists = await authRef.query().filter('username', '==', username).exists();
|
|
1326
|
-
return !exists;
|
|
1327
|
-
},
|
|
1328
|
-
displayName(displayName) {
|
|
1329
|
-
return typeof displayName === 'string' && displayName.length >= 5;
|
|
1330
|
-
},
|
|
1331
|
-
password(password) {
|
|
1332
|
-
// return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0 && /[0-9]/.test(password) && /[a-z]/.test(password) && /[A-Z]/.test(password);
|
|
1333
|
-
return typeof password === 'string' && password.length >= 8 && password.indexOf(' ') < 0; // Let client application set their own password rules. Keep minimum length of 8 and no spaces requirement.
|
|
1334
|
-
},
|
|
1335
|
-
picture(picture) {
|
|
1336
|
-
return picture === null || (typeof picture === 'object' && typeof picture.url === 'string' && typeof picture.width === 'number' && typeof picture.height === 'number');
|
|
1337
|
-
},
|
|
1338
|
-
settings(settings) {
|
|
1339
|
-
return typeof settings === 'undefined'
|
|
1340
|
-
|| (
|
|
1341
|
-
typeof settings === 'object'
|
|
1342
|
-
&& Object.keys(settings).length <= 100 // max 100 settings
|
|
1343
|
-
&& Object.keys(settings).map(key => typeof settings[key]).every(t => ['string','number','boolean'].indexOf(t) >= 0) // only string, number, boolean values
|
|
1344
|
-
&& Object.keys(settings).filter(key => typeof settings[key] === 'string').every(key => settings[key].length <= 250) // strings values <= 250 chars
|
|
1345
|
-
);
|
|
1346
|
-
}
|
|
1347
|
-
};
|
|
1348
|
-
const validationErrors = {
|
|
1349
|
-
email: { code: 'invalid_email', message: 'Invalid email address' },
|
|
1350
|
-
username: { code: 'invalid_username', message: 'Invalid username, must be at least 5 characters and can only contain lowercase characters a-z and 0-9' },
|
|
1351
|
-
emailExists: { code: 'email_conflict', message: 'Account with email address exists already' },
|
|
1352
|
-
usernameExists: { code: 'username_conflict', message: 'Account with username exists already' },
|
|
1353
|
-
emailOrUsernameExists: { code: 'conflict', message: `Account with username and/or email already exists` },
|
|
1354
|
-
displayName: { code: 'invalid_display_name', message: 'Invalid display_name, must be at least 5 characters' },
|
|
1355
|
-
password: { code: 'invalid_password', message: 'Invalid password, must be at least 8 characters and cannot contain spaces' },
|
|
1356
|
-
picture: { code: 'invalid_picture', message: 'Invalid picture, must be an object with url, width and height properties'},
|
|
1357
|
-
settings: { code: 'invalid_settings', message: 'Invalid settings, must be an object and contain only string, number and/or boolean values. Additionaly, string values can have a maximum length of 250, and a maximum of 100 settings can be added' }
|
|
1358
|
-
};
|
|
1359
|
-
|
|
1360
|
-
app.post(`/auth/${dbname}/signup`, async (req, res) => {
|
|
1361
|
-
if (!this.config.authentication.allowUserSignup && (!req.user || req.user.username !== 'admin')) {
|
|
1362
|
-
logRef.push({ action: 'signup', success: false, code: 'user_signup_disabled', ip: req.ip, date: new Date() });
|
|
1363
|
-
res.statusCode = 403; // Forbidden
|
|
1364
|
-
return res.send({ code: 'admin_only', message: 'Only admin is allowed to create users' });
|
|
1365
|
-
}
|
|
1366
|
-
|
|
1367
|
-
// Create user if it doesn't exist yet.
|
|
1368
|
-
// TODO: Rate-limit nr of signups per IP to prevent abuse
|
|
1369
|
-
|
|
1370
|
-
const details = req.body;
|
|
1371
|
-
|
|
1372
|
-
if (typeof details.displayName === 'undefined' && typeof details.display_name === 'string') {
|
|
1373
|
-
// Allow display_name to be sent also (which is used in update endpoint)
|
|
1374
|
-
details.displayName = details.display_name;
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
// Check if sent details are ok
|
|
1378
|
-
let err;
|
|
1379
|
-
if (!details.username && !details.email) {
|
|
1380
|
-
err = { code: 'missing_details', message: 'No username or email provided' };
|
|
1381
|
-
}
|
|
1382
|
-
else if (details.email && !isValid.email(details.email)) {
|
|
1383
|
-
err = validationErrors.email;
|
|
1384
|
-
}
|
|
1385
|
-
else if (details.email && !await isValid.newEmailAddress(details.email)) {
|
|
1386
|
-
err = validationErrors.emailExists;
|
|
1387
|
-
}
|
|
1388
|
-
else if (details.username && !isValid.username(details.username)) {
|
|
1389
|
-
err = validationErrors.username;
|
|
1390
|
-
}
|
|
1391
|
-
else if (details.username && !await isValid.newUsername(details.username)) {
|
|
1392
|
-
err = validationErrors.usernameExists;
|
|
1393
|
-
}
|
|
1394
|
-
else if (!isValid.displayName(details.displayName)) {
|
|
1395
|
-
err = validationErrors.displayName;
|
|
1396
|
-
}
|
|
1397
|
-
else if (!isValid.password(details.password)) {
|
|
1398
|
-
err = validationErrors.password;
|
|
1399
|
-
}
|
|
1400
|
-
else if (!isValid.settings(details.settings)) {
|
|
1401
|
-
err = validationErrors.settings;
|
|
1402
|
-
}
|
|
1403
|
-
|
|
1404
|
-
if (err && [validationErrors.emailExists, validationErrors.usernameExists].includes(err)) {
|
|
1405
|
-
logRef.push({ action: 'signup', success: false, code: 'conflict', ip: req.ip, date: new Date(), username: details.username, email: details.email });
|
|
1406
|
-
res.statusCode = 409; // conflict
|
|
1407
|
-
return res.send(validationErrors.emailOrUsernameExists);
|
|
1408
|
-
}
|
|
1409
|
-
else if (err) {
|
|
1410
|
-
// Log failure
|
|
1411
|
-
logRef.push({ action: 'signup', success: false, code: err.code, ip: req.ip, date: new Date() });
|
|
1412
|
-
res.statusCode = 422; // Unprocessable Entity
|
|
1413
|
-
return res.send(err);
|
|
1414
|
-
}
|
|
1415
|
-
|
|
1416
|
-
try {
|
|
1417
|
-
// Ok, create user
|
|
1418
|
-
let pwd = createPasswordHash(details.password);
|
|
1419
|
-
/** @type {DbUserAccountDetails} */
|
|
1420
|
-
const user = {
|
|
1421
|
-
username: details.username,
|
|
1422
|
-
email: details.email,
|
|
1423
|
-
email_verified: false,
|
|
1424
|
-
display_name: details.displayName,
|
|
1425
|
-
password: pwd.hash,
|
|
1426
|
-
password_salt: pwd.salt,
|
|
1427
|
-
created: new Date(),
|
|
1428
|
-
created_ip: req.ip,
|
|
1429
|
-
access_token: ID.generate(),
|
|
1430
|
-
access_token_created: new Date(),
|
|
1431
|
-
last_signin: new Date(),
|
|
1432
|
-
last_signin_ip: req.ip,
|
|
1433
|
-
settings: details.settings || {}
|
|
1434
|
-
};
|
|
1435
|
-
|
|
1436
|
-
const userRef = await authRef.push(user);
|
|
1437
|
-
const uid = userRef.key;
|
|
1438
|
-
user.uid = uid;
|
|
1439
|
-
|
|
1440
|
-
// Log success
|
|
1441
|
-
logRef.push({ action: 'signup', success: true, ip: req.ip, date: new Date(), uid });
|
|
1442
|
-
|
|
1443
|
-
// Cache the user
|
|
1444
|
-
_authCache.set(user.uid, user);
|
|
1445
|
-
|
|
1446
|
-
// Request welcome e-mail to be sent
|
|
1447
|
-
const request = new AceBaseUserSignupEmailRequest({
|
|
1448
|
-
user: {
|
|
1449
|
-
uid: user.uid,
|
|
1450
|
-
username: user.username,
|
|
1451
|
-
email: user.email,
|
|
1452
|
-
displayName: user.display_name,
|
|
1453
|
-
settings: user.settings
|
|
1454
|
-
},
|
|
1455
|
-
date: user.created,
|
|
1456
|
-
ip: user.created_ip,
|
|
1457
|
-
provider: 'acebase',
|
|
1458
|
-
activationCode: createSignedPublicToken({ uid: user.uid }, _secureObjectsSalt), // , email: user.email, code: user.email_verification_code
|
|
1459
|
-
emailVerified: false
|
|
1460
|
-
});
|
|
1461
|
-
|
|
1462
|
-
this.config.email && this.config.email.send(request).catch(err => {
|
|
1463
|
-
logRef.push({ action: 'signup_email', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, request });
|
|
1464
|
-
});
|
|
1465
|
-
|
|
1466
|
-
// Return the positive news
|
|
1467
|
-
const isAdmin = req.user && req.user.uid === 'admin';
|
|
1468
|
-
res.send({
|
|
1469
|
-
access_token: isAdmin ? '' : createPublicAccessToken(user.uid, req.ip, user.access_token, _secureObjectsSalt),
|
|
1470
|
-
user: getPublicAccountDetails(user)
|
|
1471
|
-
});
|
|
1472
|
-
}
|
|
1473
|
-
catch(err) {
|
|
1474
|
-
logRef.push({ action: 'signup', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, username: details.username, email: details.email });
|
|
1475
|
-
sendError(res, err);
|
|
1476
|
-
}
|
|
1477
|
-
});
|
|
1478
|
-
|
|
1479
|
-
app.post(`/auth/${dbname}/update`, async (req, res) => {
|
|
1480
|
-
let details = req.body;
|
|
1481
|
-
|
|
1482
|
-
if (!req.user) {
|
|
1483
|
-
logRef.push({ action: 'update', success: false, code: 'unauthenticated_update', update_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1484
|
-
return sendNotAuthenticatedError(res, 'unauthenticated_update', 'Sign in to change details');
|
|
1485
|
-
}
|
|
1486
|
-
|
|
1487
|
-
const uid = details.uid || req.user.uid;
|
|
1488
|
-
|
|
1489
|
-
if (req.user.uid !== 'admin' && (uid !== req.user.uid || typeof details.is_disabled === 'boolean')) {
|
|
1490
|
-
logRef.push({ action: 'update', success: false, code: 'unauthorized_update', auth_uid: req.user.uid, update_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1491
|
-
return sendUnauthorizedError(res, 'unauthorized_update', 'You are not authorized to perform this update. This attempt has been logged.');
|
|
1492
|
-
}
|
|
1493
|
-
|
|
1494
|
-
if (typeof details.display_name === 'undefined' && typeof details.displayName === 'string') {
|
|
1495
|
-
// Allow displayName to be sent also (which is used in signup endpoint)
|
|
1496
|
-
details.display_name = details.displayName;
|
|
1497
|
-
}
|
|
1498
|
-
|
|
1499
|
-
// Check if sent details are ok
|
|
1500
|
-
let err;
|
|
1501
|
-
if (details.email && !isValid.email(details.email)) {
|
|
1502
|
-
err = validationErrors.email;
|
|
1503
|
-
}
|
|
1504
|
-
else if (details.email && !await isValid.newEmailAddress(details.email)) {
|
|
1505
|
-
err = validationErrors.emailExists;
|
|
1506
|
-
}
|
|
1507
|
-
else if (details.username && !isValid.username(details.username)) {
|
|
1508
|
-
err = validationErrors.username;
|
|
1509
|
-
}
|
|
1510
|
-
else if (details.username && !await isValid.newUsername(details.username)) {
|
|
1511
|
-
err = validationErrors.usernameExists;
|
|
1512
|
-
}
|
|
1513
|
-
else if (details.display_name && !isValid.displayName(details.display_name)) {
|
|
1514
|
-
err = validationErrors.displayName;
|
|
1515
|
-
}
|
|
1516
|
-
else if (details.picture && !isValid.picture(details.picture)) {
|
|
1517
|
-
err = validationErrors.picture;
|
|
1518
|
-
}
|
|
1519
|
-
else if (!isValid.settings(details.settings)) {
|
|
1520
|
-
err = validationErrors.settings;
|
|
1521
|
-
}
|
|
1522
|
-
if (err) {
|
|
1523
|
-
// Log failure
|
|
1524
|
-
logRef.push({ action: 'update', success: false, code: err.code, auth_uid: req.user.uid, update_uid: uid, ip: req.ip, date: new Date() });
|
|
1525
|
-
res.status(422).send(err); // Unprocessable Entity
|
|
1526
|
-
return;
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
let user;
|
|
1530
|
-
return authRef.child(uid)
|
|
1531
|
-
.transaction(snap => {
|
|
1532
|
-
if (!snap.exists()) {
|
|
1533
|
-
const code = 'user_not_found';
|
|
1534
|
-
logRef.push({ action: 'update', success: false, code, auth_uid: req.user.uid, update_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1535
|
-
|
|
1536
|
-
res.statusCode = 404; // Not Found
|
|
1537
|
-
res.send({ code, message: `No user found with uid ${uid}` });
|
|
1538
|
-
return;
|
|
1539
|
-
}
|
|
1540
|
-
user = snap.val();
|
|
1541
|
-
if (details.email && details.email !== user.email) {
|
|
1542
|
-
user.email = details.email;
|
|
1543
|
-
user.email_verified = false; // TODO: send verification email
|
|
1544
|
-
}
|
|
1545
|
-
if (details.username) { user.username = details.username; }
|
|
1546
|
-
if (details.display_name) { user.display_name = details.display_name; }
|
|
1547
|
-
if (details.picture) { user.picture = details.picture; }
|
|
1548
|
-
if (details.settings) {
|
|
1549
|
-
if (typeof user.settings !== 'object') {
|
|
1550
|
-
user.settings = {};
|
|
1551
|
-
}
|
|
1552
|
-
Object.keys(details.settings).forEach(key => {
|
|
1553
|
-
user.settings[key] = details.settings[key];
|
|
1554
|
-
});
|
|
1555
|
-
if (!isValid.settings(user.settings)) {
|
|
1556
|
-
err = validationErrors.settings;
|
|
1557
|
-
logRef.push({ action: 'update', success: false, code: 'too_many_settings', auth_uid: req.user.uid, update_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1558
|
-
res.statusCode = 422; // Unprocessable Entity
|
|
1559
|
-
res.send(err);
|
|
1560
|
-
return;
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
if (typeof details.is_disabled === 'boolean') {
|
|
1564
|
-
user.is_disabled = details.is_disabled;
|
|
1565
|
-
}
|
|
1566
|
-
|
|
1567
|
-
return user; // Update db user
|
|
1568
|
-
})
|
|
1569
|
-
.then(() => {
|
|
1570
|
-
// Update cache
|
|
1571
|
-
_authCache.set(user.uid, user);
|
|
1572
|
-
// Send merged results back
|
|
1573
|
-
res.send({ user: getPublicAccountDetails(user) });
|
|
1574
|
-
})
|
|
1575
|
-
.catch(err => {
|
|
1576
|
-
logRef.push({ action: 'update', success: false, code: 'unexpected', message: err.message, auth_uid: req.user.uid, update_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1577
|
-
// res.statusCode = 500;
|
|
1578
|
-
// res.send({ code: 'unexpected', message: err.message });
|
|
1579
|
-
sendError(res, err);
|
|
1580
|
-
});
|
|
1581
|
-
});
|
|
1582
|
-
|
|
1583
|
-
app.post(`/auth/${dbname}/delete`, (req, res) => {
|
|
1584
|
-
let details = req.body;
|
|
1585
|
-
|
|
1586
|
-
if (!req.user) {
|
|
1587
|
-
logRef.push({ action: 'delete', success: false, code: 'unauthenticated_delete', delete_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1588
|
-
return sendNotAuthenticatedError(res, 'unauthenticated_delete', 'You are not authorized to perform this operation, your attempt has been logged');
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
if (req.user.uid !== 'admin' && (details.uid !== req.user.uid || typeof details.is_disabled === 'boolean')) {
|
|
1592
|
-
logRef.push({ action: 'delete', success: false, code: 'unauthorized_delete', auth_uid: req.user.uid, delete_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1593
|
-
return sendUnauthorizedError(res, 'unauthorized_delete', 'You are not authorized to perform this operation, your attempt has been logged');
|
|
1594
|
-
}
|
|
1595
|
-
|
|
1596
|
-
const uid = details.uid || req.user.uid;
|
|
1597
|
-
if (uid === 'admin') {
|
|
1598
|
-
logRef.push({ action: 'delete', success: false, code: 'unauthorized_delete', auth_uid: req.user.uid, delete_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1599
|
-
return sendUnauthorizedError(res, 'unauthorized_delete', 'The admin account cannot be deleted, your attempt has been logged');
|
|
1600
|
-
}
|
|
1601
|
-
return authRef.child(uid)
|
|
1602
|
-
.remove()
|
|
1603
|
-
.then(() => {
|
|
1604
|
-
logRef.push({ action: 'delete', success: true, auth_uid: req.user.uid, delete_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1605
|
-
res.send('Farewell');
|
|
1606
|
-
})
|
|
1607
|
-
.catch(err => {
|
|
1608
|
-
logRef.push({ action: 'delete', success: false, code: 'unexpected', auth_uid: req.user.uid, delete_uid: details.uid, ip: req.ip, date: new Date() });
|
|
1609
|
-
res.statusCode = 500;
|
|
1610
|
-
res.send({ code: 'unexpected', message: err.message });
|
|
1611
|
-
})
|
|
1612
|
-
});
|
|
1613
|
-
|
|
1614
|
-
app.get(`/oauth2/${dbname}/init`, async (req, res) => {
|
|
1615
|
-
try {
|
|
1616
|
-
const providerName = req.query.provider;
|
|
1617
|
-
const callbackUrl = req.query.callbackUrl;
|
|
1618
|
-
const options = Object.keys(req.query).filter(key => key.startsWith('option_')).reduce((options, key) => {
|
|
1619
|
-
const name = key.slice(7);
|
|
1620
|
-
let value = req.query[key];
|
|
1621
|
-
if (['true','false'].includes(value)) { value = value === 'true'; }
|
|
1622
|
-
else if (/^\-?[0-9]+$/.test(value)) { value = parseInt(value); }
|
|
1623
|
-
options[name] = value;
|
|
1624
|
-
return options;
|
|
1625
|
-
}, {});
|
|
1626
|
-
const signedInUid = req.user && req.user.uid;
|
|
1627
|
-
const provider = this.authProviders[providerName];
|
|
1628
|
-
if (!provider) {
|
|
1629
|
-
throw new Error(`Provider ${providerName} is not available, or not properly configured by the db admin`);
|
|
1630
|
-
}
|
|
1631
|
-
// Create secure state so it cannot be tampered with. hash it with a server-only known salt: the generated admin password salt
|
|
1632
|
-
await this.ready();
|
|
1633
|
-
const state = createSignedPublicToken({ flow: 'redirect', provider: providerName, uid: signedInUid, callbackUrl }, _secureObjectsSalt);
|
|
1634
|
-
const clientAuthUrl = await provider.init({ redirect_url: `${req.protocol}://${req.headers.host}/oauth2/${dbname}/signin`, state, options });
|
|
1635
|
-
res.send({ redirectUrl: clientAuthUrl });
|
|
1636
|
-
}
|
|
1637
|
-
catch(err) {
|
|
1638
|
-
res.status(500).send(err.message);
|
|
1639
|
-
}
|
|
1640
|
-
});
|
|
1641
|
-
|
|
1642
|
-
app.get(`/oauth2/${dbname}/signin`, async (req, res) => {
|
|
1643
|
-
// This is where the user is redirected to by the provider after signin or error
|
|
1644
|
-
try {
|
|
1645
|
-
const state = parseSignedPublicToken(req.query.state, _secureObjectsSalt); //JSON.parse(Buffer.from(req.query.state, "base64").toString("utf8"));
|
|
1646
|
-
if (req.query.error) {
|
|
1647
|
-
if (state.flow === 'socket') {
|
|
1648
|
-
const client = clients.get(state.client_id);
|
|
1649
|
-
client.socket.emit('oauth2-signin', { error: req.query.error, reason: req.query.error_reason, description: req.query.error_description, provider: state.provider });
|
|
1650
|
-
}
|
|
1651
|
-
else {
|
|
1652
|
-
const callbackUrl = `${state.callbackUrl}?provider=${state.provider}&error=${req.query.error}&reason=${req.query.error_reason}&description=${req.query.error_description}`;
|
|
1653
|
-
res.redirect(callbackUrl);
|
|
1654
|
-
}
|
|
1655
|
-
return;
|
|
1656
|
-
}
|
|
1657
|
-
|
|
1658
|
-
// Got authorization code
|
|
1659
|
-
const authCode = req.query.code;
|
|
1660
|
-
const provider = this.authProviders[state.provider];
|
|
1661
|
-
|
|
1662
|
-
// Get access & refresh tokens
|
|
1663
|
-
const tokens = await provider.getAccessToken({ type: 'auth', auth_code: authCode, redirect_url: `${req.protocol}://${req.headers.host}/oauth2/${dbname}/signin` });
|
|
1664
|
-
|
|
1665
|
-
let user_details;
|
|
1666
|
-
// TODO: Have we got an id_token?
|
|
1667
|
-
// if (tokens.id_token) {
|
|
1668
|
-
// // decode, extract user information
|
|
1669
|
-
// }
|
|
1670
|
-
// else {
|
|
1671
|
-
user_details = await provider.getUserInfo(tokens.access_token);
|
|
1672
|
-
// }
|
|
1673
|
-
|
|
1674
|
-
if (user_details.picture && user_details.picture.length > 0) {
|
|
1675
|
-
// Download it, convert to base64
|
|
1676
|
-
const best = user_details.picture.sort((a,b) => a.width * a.height > b.width * b.height ? -1 : 1)[0]
|
|
1677
|
-
// TODO: Let client do this instead:
|
|
1678
|
-
const { fetch } = require('./oauth-providers/simple-fetch');
|
|
1679
|
-
await fetch(best.url)
|
|
1680
|
-
.then(async response => {
|
|
1681
|
-
const contentType = response.headers.get('Content-Type');
|
|
1682
|
-
if (contentType === 'image/png') { //state.provider === 'google' &&
|
|
1683
|
-
// Don't accept image/png, because it's probably a placeholder image. Google does this by creating a png with people's initials
|
|
1684
|
-
user_details.picture = [];
|
|
1685
|
-
return;
|
|
1686
|
-
}
|
|
1687
|
-
const image = await response.arrayBuffer();
|
|
1688
|
-
let buff = new Buffer.from(image);
|
|
1689
|
-
best.url = `data:${contentType};base64,${buff.toString('base64')}`;
|
|
1690
|
-
user_details.picture = [best]; // Only keep the best one
|
|
1691
|
-
})
|
|
1692
|
-
.catch(err => {
|
|
1693
|
-
this.debug.warn(`Could not fetch profile picture from "${best.url}": `, err);
|
|
1694
|
-
user_details.picture = null;
|
|
1695
|
-
});
|
|
1696
|
-
}
|
|
1697
|
-
|
|
1698
|
-
const getProviderSettings = () => {
|
|
1699
|
-
// Returns an object with all info (except picture) the provider has about the user
|
|
1700
|
-
const settings = {
|
|
1701
|
-
[`${state.provider}_id`]: user_details.id,
|
|
1702
|
-
[`${state.provider}_email`]: user_details.email,
|
|
1703
|
-
[`${state.provider}_email_verified`]: user_details.email_verified,
|
|
1704
|
-
[`${state.provider}_name`]: user_details.name,
|
|
1705
|
-
[`${state.provider}_display_name`]: user_details.display_name,
|
|
1706
|
-
};
|
|
1707
|
-
Object.keys(user_details.other).forEach(key => {
|
|
1708
|
-
settings[`${state.provider}_${key}`] = user_details.other[key];
|
|
1709
|
-
});
|
|
1710
|
-
return settings;
|
|
1711
|
-
};
|
|
1712
|
-
const providerUsername = `${state.provider}:${user_details.id}`;
|
|
1713
|
-
|
|
1714
|
-
// Check if this user exists in the database
|
|
1715
|
-
let snaps;
|
|
1716
|
-
let addToExistingAccount = true;
|
|
1717
|
-
if (typeof state.uid === 'string') {
|
|
1718
|
-
// Use the signed in uid to link this account to. This allows multiple auth provider
|
|
1719
|
-
// accounts (with different email addresses) to be linked to the account the user
|
|
1720
|
-
// is signed into, and also allows multiple AceBase users to link to the same provider
|
|
1721
|
-
// accounts, eg if a client app allows users to link their own account to a shared
|
|
1722
|
-
// family Spotify / Dropbox account.
|
|
1723
|
-
let snap = await authRef.child(state.uid).get();
|
|
1724
|
-
if (!snap.exists()) {
|
|
1725
|
-
// This is wrong!
|
|
1726
|
-
throw new Error(`Invalid uid`);
|
|
1727
|
-
}
|
|
1728
|
-
snaps = [snap];
|
|
1729
|
-
let user = snap.val();
|
|
1730
|
-
addToExistingAccount = user.email === user_details.email;
|
|
1731
|
-
}
|
|
1732
|
-
else {
|
|
1733
|
-
const query = authRef.query();
|
|
1734
|
-
if (user_details.email) {
|
|
1735
|
-
query.filter('email', '==', user_details.email);
|
|
1736
|
-
}
|
|
1737
|
-
else {
|
|
1738
|
-
// User did not allow reading e-mail address, or provider does not have one (eg whatsapp?)
|
|
1739
|
-
// Switch to using a generated username such as "facebook-3292389234" instead
|
|
1740
|
-
query.filter('username', '==', providerUsername);
|
|
1741
|
-
}
|
|
1742
|
-
snaps = await query.get();
|
|
1743
|
-
}
|
|
1744
|
-
if (snaps.length === 0 && user_details.email) {
|
|
1745
|
-
// Try again with providerUsername, use might previously have denied access to email,
|
|
1746
|
-
// and now has granted access. In that case, we'll already have an account with the
|
|
1747
|
-
// generated providerUsername
|
|
1748
|
-
snaps = await authRef.query().filter('username', '==', providerUsername).get();
|
|
1749
|
-
}
|
|
1750
|
-
/** @type {DbUserAccountDetails} */
|
|
1751
|
-
let user;
|
|
1752
|
-
if (snaps.length === 1) {
|
|
1753
|
-
const uid = snaps[0].key;
|
|
1754
|
-
user = snaps[0].val();
|
|
1755
|
-
user.uid = uid;
|
|
1756
|
-
|
|
1757
|
-
if (addToExistingAccount) {
|
|
1758
|
-
// Update user details
|
|
1759
|
-
user.email_verified = user.email_verified || user_details.email_verified;
|
|
1760
|
-
user.email = user.email || user_details.email;
|
|
1761
|
-
if (user_details.picture && user_details.picture.length > 0) {
|
|
1762
|
-
user.picture = user_details.picture[0];
|
|
1763
|
-
}
|
|
1764
|
-
await authRef.child(uid).update({
|
|
1765
|
-
email: user.email || null,
|
|
1766
|
-
email_verified: user.email_verified,
|
|
1767
|
-
last_signin: new Date(),
|
|
1768
|
-
last_signin_ip: req.ip,
|
|
1769
|
-
picture: user.picture
|
|
1770
|
-
});
|
|
1771
|
-
}
|
|
1772
|
-
// Add provider details
|
|
1773
|
-
await authRef.child(uid).child('settings').update(getProviderSettings());
|
|
1774
|
-
|
|
1775
|
-
// Log success
|
|
1776
|
-
logRef.push({ action: 'oauth2_signin', success: true, ip: req.ip, date: new Date(), uid });
|
|
1777
|
-
|
|
1778
|
-
// Cache the user
|
|
1779
|
-
_authCache.set(user.uid, user);
|
|
1780
|
-
|
|
1781
|
-
// Request signin e-mail to be sent
|
|
1782
|
-
const request = new AceBaseUserSignInEmailRequest({
|
|
1783
|
-
user: {
|
|
1784
|
-
uid: user.uid,
|
|
1785
|
-
username: user.username,
|
|
1786
|
-
email: user.email,
|
|
1787
|
-
displayName: user.display_name,
|
|
1788
|
-
settings: user.settings
|
|
1789
|
-
},
|
|
1790
|
-
date: user.created,
|
|
1791
|
-
ip: req.ip,
|
|
1792
|
-
activationCode: user.email_verified ? null : createSignedPublicToken({ uid: user.uid }, _secureObjectsSalt), //, email: user.email, code: user.email_verification_code
|
|
1793
|
-
emailVerified: user.email_verified,
|
|
1794
|
-
provider: state.provider
|
|
1795
|
-
});
|
|
1796
|
-
|
|
1797
|
-
this.config.email && this.config.email.send(request).catch(err => {
|
|
1798
|
-
logRef.push({ action: 'oauth2_login_email', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, request });
|
|
1799
|
-
});
|
|
1800
|
-
}
|
|
1801
|
-
else if (snaps.length === 0) {
|
|
1802
|
-
// User does not exist, create
|
|
1803
|
-
|
|
1804
|
-
if (!this.config.authentication.allowUserSignup) {
|
|
1805
|
-
logRef.push({ action: 'oauth2_signup', success: false, code: 'user_signup_disabled', provider: state.provider, email: user_details.email, date: new Date() });
|
|
1806
|
-
res.statusCode = 403; // Forbidden
|
|
1807
|
-
return res.send({ code: 'admin_only', message: 'Only admin is allowed to create users' });
|
|
1808
|
-
}
|
|
1809
|
-
|
|
1810
|
-
// Create user with Generated password
|
|
1811
|
-
let pwd = createPasswordHash(generatePassword());
|
|
1812
|
-
user = {
|
|
1813
|
-
username: typeof user_details.email === 'undefined' ? providerUsername : null, // provider-accountid usernames for external accounts without email address
|
|
1814
|
-
email: user_details.email || null,
|
|
1815
|
-
email_verified: user_details.email_verified, // trust provider's verification
|
|
1816
|
-
display_name: user_details.display_name,
|
|
1817
|
-
password: pwd.hash,
|
|
1818
|
-
password_salt: pwd.salt,
|
|
1819
|
-
created: new Date(),
|
|
1820
|
-
created_ip: req.ip,
|
|
1821
|
-
access_token: ID.generate(),
|
|
1822
|
-
access_token_created: new Date(),
|
|
1823
|
-
last_signin: new Date(),
|
|
1824
|
-
last_signin_ip: req.ip,
|
|
1825
|
-
picture: user_details.picture && user_details.picture[0],
|
|
1826
|
-
settings: getProviderSettings()
|
|
1827
|
-
};
|
|
1828
|
-
|
|
1829
|
-
const userRef = await authRef.push(user);
|
|
1830
|
-
const uid = userRef.key;
|
|
1831
|
-
user.uid = uid;
|
|
1832
|
-
|
|
1833
|
-
// Log success
|
|
1834
|
-
logRef.push({ action: 'oauth2_signup', success: true, ip: req.ip, date: new Date(), uid });
|
|
1835
|
-
|
|
1836
|
-
// Cache the user
|
|
1837
|
-
_authCache.set(user.uid, user);
|
|
1838
|
-
|
|
1839
|
-
// Request welcome e-mail to be sent
|
|
1840
|
-
const request = new AceBaseUserSignupEmailRequest({
|
|
1841
|
-
user: {
|
|
1842
|
-
uid: user.uid,
|
|
1843
|
-
username: user.username,
|
|
1844
|
-
email: user.email,
|
|
1845
|
-
displayName: user.display_name,
|
|
1846
|
-
settings: user.settings
|
|
1847
|
-
},
|
|
1848
|
-
date: user.created,
|
|
1849
|
-
ip: user.created_ip,
|
|
1850
|
-
activationCode: user.email_verified ? null : createSignedPublicToken({ uid: user.uid }, _secureObjectsSalt), //, email: user.email, code: user.email_verification_code
|
|
1851
|
-
emailVerified: user.email_verified,
|
|
1852
|
-
provider: state.provider
|
|
1853
|
-
});
|
|
1854
|
-
|
|
1855
|
-
this.config.email && this.config.email.send(request).catch(err => {
|
|
1856
|
-
logRef.push({ action: 'oauth2_signup_email', success: false, code: 'unexpected', ip: req.ip, date: new Date(), error: err.message, request });
|
|
1857
|
-
});
|
|
1858
|
-
}
|
|
1859
|
-
else {
|
|
1860
|
-
// More than 1?!!
|
|
1861
|
-
if (state.flow === 'socket') {
|
|
1862
|
-
const client = clients.get(state.client_id);
|
|
1863
|
-
client.socket.emit('oauth2-signin', { action: 'error', error: 'account_duplicates' });
|
|
1864
|
-
return res.send(`<html><script>window.close()</script><body>You can <a href="javascript:window.close()">close</a> this page</body></html>`)
|
|
1865
|
-
}
|
|
1866
|
-
else {
|
|
1867
|
-
const callbackUrl = `${state.callbackUrl}?provider=${state.provider}&error=account_duplicates`;
|
|
1868
|
-
return res.redirect(callbackUrl);
|
|
1869
|
-
}
|
|
1870
|
-
}
|
|
1871
|
-
|
|
1872
|
-
let result = {
|
|
1873
|
-
provider: {
|
|
1874
|
-
name: state.provider,
|
|
1875
|
-
access_token: tokens.access_token,
|
|
1876
|
-
refresh_token: tokens.refresh_token,
|
|
1877
|
-
expires_in: tokens.expires_in
|
|
1878
|
-
},
|
|
1879
|
-
access_token: createPublicAccessToken(user.uid, req.ip, user.access_token, _secureObjectsSalt),
|
|
1880
|
-
|
|
1881
|
-
// Disabled sending user details because:
|
|
1882
|
-
// 1) they might be too big to send as redirect header,
|
|
1883
|
-
// 2) client should verify the sent access token and get user details from the server
|
|
1884
|
-
// user: getPublicAccountDetails(user)
|
|
1885
|
-
};
|
|
1886
|
-
|
|
1887
|
-
if (state.flow === 'socket') {
|
|
1888
|
-
const client = clients.get(state.client_id);
|
|
1889
|
-
client.socket.emit('oauth2-signin', { action: 'success', result });
|
|
1890
|
-
res.send(`<html><script>window.close()</script><body>You can <a href="javascript:window.close()">close</a> this page</body></html>`)
|
|
1891
|
-
}
|
|
1892
|
-
else {
|
|
1893
|
-
const base64Result = Buffer.from(JSON.stringify(result)).toString('base64');
|
|
1894
|
-
const callbackUrl = `${state.callbackUrl}?result=${base64Result}`;
|
|
1895
|
-
res.redirect(callbackUrl);
|
|
1896
|
-
}
|
|
1897
|
-
}
|
|
1898
|
-
catch(err) {
|
|
1899
|
-
res.status(500).send(err.message);
|
|
1900
|
-
}
|
|
1901
|
-
});
|
|
1902
|
-
|
|
1903
|
-
app.get(`/oauth2/${dbname}/refresh`, async (req, res) => {
|
|
1904
|
-
try {
|
|
1905
|
-
const providerName = req.query.provider;
|
|
1906
|
-
const refreshToken = req.query.refresh_token;
|
|
1907
|
-
const provider = this.authProviders[providerName];
|
|
1908
|
-
if (!provider) {
|
|
1909
|
-
throw new Error(`Provider ${provider} is not available, or not properly configured by the db admin`);
|
|
1910
|
-
}
|
|
1911
|
-
if (!refreshToken) {
|
|
1912
|
-
throw new Error(`No refresh_token passed`);
|
|
1913
|
-
}
|
|
1914
|
-
// Get new access & refresh tokens
|
|
1915
|
-
const tokens = await provider.getAccessToken({ type: 'refresh', refresh_token: refreshToken });
|
|
1916
|
-
res.send({
|
|
1917
|
-
provider: {
|
|
1918
|
-
name: providerName,
|
|
1919
|
-
access_token: tokens.access_token,
|
|
1920
|
-
refresh_token: tokens.refresh_token,
|
|
1921
|
-
expires_in: tokens.expires_in
|
|
1922
|
-
}
|
|
1923
|
-
});
|
|
1924
|
-
}
|
|
1925
|
-
catch(err) {
|
|
1926
|
-
res.status(500).send(err.message);
|
|
1927
|
-
}
|
|
1928
|
-
});
|
|
1929
|
-
}
|
|
1930
|
-
|
|
1931
|
-
// If environment is development, add API docs
|
|
1932
|
-
if (process.env.NODE_ENV === 'development') {
|
|
1933
|
-
this.debug.warn('DEVELOPMENT MODE: adding API docs endpoint at /docs');
|
|
1934
|
-
const addAPIDocsRoute = require('./routes/docs').default;
|
|
1935
|
-
addAPIDocsRoute(app);
|
|
1936
|
-
}
|
|
1937
|
-
|
|
1938
|
-
const webManagerDir = `/webmanager/`;
|
|
1939
|
-
app.get('/', (req, res) => {
|
|
1940
|
-
res.redirect(webManagerDir);
|
|
1941
|
-
});
|
|
1942
|
-
|
|
1943
|
-
app.get(`${webManagerDir}*`, (req, res) => {
|
|
1944
|
-
const filePath = req.path.slice(webManagerDir.length);
|
|
1945
|
-
if (filePath.length === 0) {
|
|
1946
|
-
// Send default file
|
|
1947
|
-
res.sendFile(__dirname + '/webmanager/index.html');
|
|
1948
|
-
}
|
|
1949
|
-
else {
|
|
1950
|
-
res.sendFile(__dirname + '/webmanager/' + filePath);
|
|
1951
|
-
}
|
|
1952
|
-
});
|
|
1953
|
-
|
|
1954
|
-
app.get(`/ping/${dbname}`, (req, res) => {
|
|
1955
|
-
// For simple connectivity check
|
|
1956
|
-
res.end('pong');
|
|
1957
|
-
});
|
|
1958
|
-
|
|
1959
|
-
app.get(`/info/${dbname}`, (req, res) => {
|
|
1960
|
-
const info = {
|
|
1961
|
-
version: '1.9.1', // TODO: Load from package.json
|
|
1962
|
-
time: Date.now(),
|
|
1963
|
-
process: process.pid
|
|
1964
|
-
};
|
|
1965
|
-
if (req.user && req.user.uid === 'admin') {
|
|
1966
|
-
const os = require('os');
|
|
1967
|
-
const numberToByteSize = number => {
|
|
1968
|
-
return Math.round((number / 1024 / 1024) * 100) / 100 + 'MB';
|
|
1969
|
-
}
|
|
1970
|
-
const sPerMinute = 60;
|
|
1971
|
-
const sPerHour = sPerMinute * 60;
|
|
1972
|
-
const sPerDay = sPerHour * 24;
|
|
1973
|
-
const numberToTime = number => {
|
|
1974
|
-
const days = Math.floor(number / sPerDay);
|
|
1975
|
-
number -= sPerDay * days;
|
|
1976
|
-
const hours = Math.floor(number / sPerHour);
|
|
1977
|
-
number -= hours * sPerHour;
|
|
1978
|
-
const minutes = Math.floor(number / sPerMinute);
|
|
1979
|
-
number -= minutes * sPerMinute;
|
|
1980
|
-
const seconds = Math.floor(number);
|
|
1981
|
-
return `${days}d${hours}h${minutes}m${seconds}s`;
|
|
1982
|
-
};
|
|
1983
|
-
const mem = process.memoryUsage();
|
|
1984
|
-
const adminInfo = {
|
|
1985
|
-
dbname: dbname,
|
|
1986
|
-
platform: os.platform(),
|
|
1987
|
-
arch: os.arch(),
|
|
1988
|
-
release: os.release(),
|
|
1989
|
-
host: os.hostname(),
|
|
1990
|
-
uptime: numberToTime(os.uptime()),
|
|
1991
|
-
load: os.loadavg(),
|
|
1992
|
-
mem: {
|
|
1993
|
-
total: numberToByteSize(os.totalmem()),
|
|
1994
|
-
free: numberToByteSize(os.freemem()),
|
|
1995
|
-
process: {
|
|
1996
|
-
arrayBuffers: numberToByteSize(mem.arrayBuffers),
|
|
1997
|
-
external: numberToByteSize(mem.external),
|
|
1998
|
-
heapTotal: numberToByteSize(mem.heapTotal),
|
|
1999
|
-
heapUsed: numberToByteSize(mem.heapUsed),
|
|
2000
|
-
residentSet: numberToByteSize(mem.rss)
|
|
2001
|
-
}
|
|
2002
|
-
},
|
|
2003
|
-
cpus: os.cpus(),
|
|
2004
|
-
network: os.networkInterfaces()
|
|
2005
|
-
}
|
|
2006
|
-
Object.assign(info, adminInfo);
|
|
2007
|
-
}
|
|
2008
|
-
// for (let i = 0; i < 1000000000; i++) {
|
|
2009
|
-
// let j = Math.pow(i, 2);
|
|
2010
|
-
// }
|
|
2011
|
-
res.send(info);
|
|
2012
|
-
});
|
|
2013
|
-
|
|
2014
|
-
app.get(`/data/${dbname}/*`, async (req, res) => {
|
|
2015
|
-
// Request data
|
|
2016
|
-
const path = req.path.substr(dbname.length + 7); //.replace(/^\/+/g, '').replace(/\/+$/g, '');
|
|
2017
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2018
|
-
return;
|
|
2019
|
-
}
|
|
2020
|
-
|
|
2021
|
-
const options = {};
|
|
2022
|
-
if (req.query.include) {
|
|
2023
|
-
options.include = req.query.include.split(',');
|
|
2024
|
-
}
|
|
2025
|
-
if (req.query.exclude) {
|
|
2026
|
-
options.exclude = req.query.exclude.split(',');
|
|
2027
|
-
}
|
|
2028
|
-
if (typeof req.query.child_objects === "boolean") {
|
|
2029
|
-
options.child_objects = req.query.child_objects;
|
|
2030
|
-
}
|
|
2031
|
-
|
|
2032
|
-
if (path === '') {
|
|
2033
|
-
// If user has access to the root of database (NOT recommended for others than admin...)
|
|
2034
|
-
// Do not return private server data. If the admin user wants access, they should use
|
|
2035
|
-
// direct requests on those paths (GET /data/dbname/__auth__), or use reflection
|
|
2036
|
-
|
|
2037
|
-
if (options.include) {
|
|
2038
|
-
// Remove all includes for private paths
|
|
2039
|
-
options.include = options.include.filter(path => !path.startsWith('__'));
|
|
2040
|
-
}
|
|
2041
|
-
// Add private paths to exclude
|
|
2042
|
-
options.exclude = [...options.exclude || [], '__auth__', '__log__'];
|
|
2043
|
-
}
|
|
2044
|
-
|
|
2045
|
-
try {
|
|
2046
|
-
// const snap = await db.ref(path).get(options);
|
|
2047
|
-
// const value = snap.val(), context = snap.context();
|
|
2048
|
-
const { value, context } = await db.api.get(path, options);
|
|
2049
|
-
if (!this.config.transactionLoggingEnabled) {
|
|
2050
|
-
delete context.acebase_cursor;
|
|
2051
|
-
}
|
|
2052
|
-
const serialized = Transport.serialize(value);
|
|
2053
|
-
|
|
2054
|
-
res.setHeader('AceBase-Context', JSON.stringify(context));
|
|
2055
|
-
res.send({
|
|
2056
|
-
exists: value !== null,
|
|
2057
|
-
val: serialized.val,
|
|
2058
|
-
map: serialized.map
|
|
2059
|
-
});
|
|
2060
|
-
}
|
|
2061
|
-
catch (err) {
|
|
2062
|
-
res.status(500).send(err);
|
|
2063
|
-
}
|
|
2064
|
-
});
|
|
2065
|
-
|
|
2066
|
-
app.get(`/reflect/${dbname}/*`, (req, res) => {
|
|
2067
|
-
// Reflection API
|
|
2068
|
-
// if (!req.user || req.user.username !== 'admin') {
|
|
2069
|
-
// return sendUnauthorizedError(res, 'admin_only', 'only admin can use reflection api');
|
|
2070
|
-
// }
|
|
2071
|
-
const path = req.path.substr(dbname.length + 10);
|
|
2072
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2073
|
-
return;
|
|
2074
|
-
}
|
|
2075
|
-
const impersonatedAccess = {
|
|
2076
|
-
uid: (!req.user || req.user.username !== 'admin') ? null : req.query.impersonate,
|
|
2077
|
-
read: {
|
|
2078
|
-
allow: false,
|
|
2079
|
-
error: null
|
|
2080
|
-
},
|
|
2081
|
-
write: {
|
|
2082
|
-
allow: false,
|
|
2083
|
-
error: null
|
|
2084
|
-
}
|
|
2085
|
-
};
|
|
2086
|
-
const impersonatedUser = impersonatedAccess.uid === 'anonymous' ? null : { uid: impersonatedAccess.uid };
|
|
2087
|
-
if (impersonatedAccess.uid) {
|
|
2088
|
-
impersonatedAccess.read.allow = userHasAccess(impersonatedUser, path, false, denyDetails => {
|
|
2089
|
-
impersonatedAccess.read.error = { code: denyDetails.code, message: denyDetails.message };
|
|
2090
|
-
});
|
|
2091
|
-
impersonatedAccess.write.allow = userHasAccess(impersonatedUser, path, true, denyDetails => {
|
|
2092
|
-
impersonatedAccess.write.error = { code: denyDetails.code, message: denyDetails.message };
|
|
2093
|
-
});
|
|
2094
|
-
}
|
|
2095
|
-
const type = req.query.type;
|
|
2096
|
-
const args = {};
|
|
2097
|
-
Object.keys(req.query).forEach(key => {
|
|
2098
|
-
if (!['type','impersonate'].includes(key)) {
|
|
2099
|
-
let val = req.query[key];
|
|
2100
|
-
if (/^(?:true|false|[0-9]+)$/.test(val)) { val = JSON.parse(val); }
|
|
2101
|
-
args[key] = val;
|
|
2102
|
-
}
|
|
2103
|
-
});
|
|
2104
|
-
|
|
2105
|
-
db.ref(path)
|
|
2106
|
-
.reflect(type, args)
|
|
2107
|
-
.then(result => {
|
|
2108
|
-
if (impersonatedAccess.uid) {
|
|
2109
|
-
result.impersonation = impersonatedAccess;
|
|
2110
|
-
let list;
|
|
2111
|
-
if (type === 'children') {
|
|
2112
|
-
list = result.list;
|
|
2113
|
-
}
|
|
2114
|
-
else if (type === 'info') {
|
|
2115
|
-
list = typeof result.children === 'object' ? result.children.list : [];
|
|
2116
|
-
}
|
|
2117
|
-
list && list.forEach(childInfo => {
|
|
2118
|
-
childInfo.access = {
|
|
2119
|
-
read: userHasAccess(impersonatedUser, PathInfo.getChildPath(path, childInfo.key), false),
|
|
2120
|
-
write: userHasAccess(impersonatedUser, PathInfo.getChildPath(path, childInfo.key), true)
|
|
2121
|
-
};
|
|
2122
|
-
});
|
|
2123
|
-
}
|
|
2124
|
-
res.send(result);
|
|
2125
|
-
})
|
|
2126
|
-
.catch(err => {
|
|
2127
|
-
res.statusCode = 500;
|
|
2128
|
-
res.send(err);
|
|
2129
|
-
});
|
|
2130
|
-
});
|
|
2131
|
-
|
|
2132
|
-
app.get(`/export/${dbname}/*`, async (req, res) => {
|
|
2133
|
-
// Export API
|
|
2134
|
-
const path = req.path.slice(dbname.length + 9);
|
|
2135
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2136
|
-
return;
|
|
2137
|
-
}
|
|
2138
|
-
const format = req.query.format || 'json';
|
|
2139
|
-
const type_safe = req.query.type_safe !== '0';
|
|
2140
|
-
|
|
2141
|
-
const write = async (chunk) => {
|
|
2142
|
-
let ok = res.write(chunk);
|
|
2143
|
-
if (!ok) {
|
|
2144
|
-
await new Promise(resolve => res.once('drain', resolve));
|
|
2145
|
-
}
|
|
2146
|
-
};
|
|
2147
|
-
|
|
2148
|
-
const ref = db.ref(path);
|
|
2149
|
-
res.setHeader('Content-Disposition', `attachment; filename=${ref.key || 'export'}.json`); // Will be treated as a download in browser
|
|
2150
|
-
|
|
2151
|
-
try {
|
|
2152
|
-
await ref.export(write, { format, type_safe });
|
|
2153
|
-
}
|
|
2154
|
-
catch (err) {
|
|
2155
|
-
this.debug.error(`Error exporting data for path "/${path}": `, err);
|
|
2156
|
-
if (!res.headersSent) {
|
|
2157
|
-
res.statusCode = 500;
|
|
2158
|
-
res.send(err);
|
|
2159
|
-
}
|
|
2160
|
-
}
|
|
2161
|
-
finally {
|
|
2162
|
-
res.end();
|
|
2163
|
-
}
|
|
2164
|
-
});
|
|
2165
|
-
|
|
2166
|
-
app.post(`/import/${dbname}/*`, async (req, res) => {
|
|
2167
|
-
// Import API
|
|
2168
|
-
const path = req.path.slice(dbname.length + 9);
|
|
2169
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2170
|
-
return;
|
|
2171
|
-
}
|
|
2172
|
-
const format = req.query.format || 'json';
|
|
2173
|
-
const suppress_events = req.query.suppress_events === '1';
|
|
2174
|
-
|
|
2175
|
-
req.pause(); // Switch to non-flowing mode so we can use .read() upon request
|
|
2176
|
-
let eof = false;
|
|
2177
|
-
req.once('end', () => { eof = true; });
|
|
2178
|
-
const read = async (length) => {
|
|
2179
|
-
let chunk = req.read();
|
|
2180
|
-
if (chunk === null && !eof) {
|
|
2181
|
-
await new Promise(resolve => req.once('readable', resolve));
|
|
2182
|
-
chunk = req.read();
|
|
2183
|
-
}
|
|
2184
|
-
console.log(`Received chunk: `, chunk);
|
|
2185
|
-
return chunk;
|
|
2186
|
-
};
|
|
2187
|
-
|
|
2188
|
-
const ref = db.ref(path);
|
|
2189
|
-
try {
|
|
2190
|
-
await ref.import(read, { format, suppress_events });
|
|
2191
|
-
res.send({ success: true });
|
|
2192
|
-
}
|
|
2193
|
-
catch (err) {
|
|
2194
|
-
this.debug.error(`Error importing data for path "/${path}": `, err);
|
|
2195
|
-
if (!res.headersSent) {
|
|
2196
|
-
res.statusCode = 500;
|
|
2197
|
-
res.send({ success: false, reason: err.message });
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
finally {
|
|
2201
|
-
res.end();
|
|
2202
|
-
}
|
|
2203
|
-
});
|
|
2204
|
-
|
|
2205
|
-
app.get(`/exists/${dbname}/*`, (req, res) => {
|
|
2206
|
-
// Exists query
|
|
2207
|
-
const path = req.path.substr(dbname.length + 9);
|
|
2208
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2209
|
-
return;
|
|
2210
|
-
}
|
|
2211
|
-
|
|
2212
|
-
db.ref(path)
|
|
2213
|
-
.exists()
|
|
2214
|
-
.then(exists => {
|
|
2215
|
-
res.send({ exists });
|
|
2216
|
-
})
|
|
2217
|
-
.catch(err => {
|
|
2218
|
-
res.statusCode = 500;
|
|
2219
|
-
res.send(err);
|
|
2220
|
-
});
|
|
2221
|
-
});
|
|
2222
|
-
|
|
2223
|
-
app.get(`/stats/${dbname}`, (req, res) => {
|
|
2224
|
-
// Get database stats
|
|
2225
|
-
db.api.stats()
|
|
2226
|
-
.then(stats => {
|
|
2227
|
-
res.send(stats);
|
|
2228
|
-
})
|
|
2229
|
-
.catch(err => {
|
|
2230
|
-
res.statusCode = 500;
|
|
2231
|
-
res.send(err);
|
|
2232
|
-
});
|
|
2233
|
-
});
|
|
2234
|
-
|
|
2235
|
-
app.post(`/data/${dbname}/*`, async (req, res) => {
|
|
2236
|
-
// update data
|
|
2237
|
-
const path = req.path.substr(dbname.length + 7);
|
|
2238
|
-
if (!userHasAccess(req.user, path, true, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2239
|
-
return;
|
|
2240
|
-
}
|
|
2241
|
-
|
|
2242
|
-
try {
|
|
2243
|
-
const data = req.body;
|
|
2244
|
-
const val = Transport.deserialize(data);
|
|
2245
|
-
|
|
2246
|
-
// Schema validation moved to storage, no need to check here but an early check won't do no harm!
|
|
2247
|
-
let validation = await db.schema.check(path, val, true);
|
|
2248
|
-
if (!validation.ok) {
|
|
2249
|
-
throw new SchemaValidationError(validation.reason);
|
|
2250
|
-
}
|
|
2251
|
-
|
|
2252
|
-
await db.ref(path)
|
|
2253
|
-
.context(req.context)
|
|
2254
|
-
.update(val);
|
|
2255
|
-
|
|
2256
|
-
res.send({ success: true });
|
|
2257
|
-
}
|
|
2258
|
-
catch(err) {
|
|
2259
|
-
if (err instanceof SchemaValidationError) {
|
|
2260
|
-
logRef && logRef.push({ action: 'update_data', success: false, code: 'schema_validation_failed', path, error: err.reason });
|
|
2261
|
-
res.status(422).send({ code: 'schema_validation_failed', message: err.message });
|
|
2262
|
-
}
|
|
2263
|
-
else {
|
|
2264
|
-
this.debug.error(`failed to update "${path}":`, err);
|
|
2265
|
-
logRef && logRef.push({ action: 'update_data', success: false, code: `unknown_error`, path, error: err.message });
|
|
2266
|
-
sendError(res, err);
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
});
|
|
2270
|
-
|
|
2271
|
-
app.put(`/data/${dbname}/*`, async (req, res) => {
|
|
2272
|
-
// Set data
|
|
2273
|
-
const path = req.path.substr(dbname.length + 7);
|
|
2274
|
-
if (!userHasAccess(req.user, path, true, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2275
|
-
return;
|
|
2276
|
-
}
|
|
2277
|
-
|
|
2278
|
-
try {
|
|
2279
|
-
const data = req.body;
|
|
2280
|
-
const val = Transport.deserialize(data);
|
|
2281
|
-
|
|
2282
|
-
// Schema validation moved to storage, no need to check here but an early check won't do no harm!
|
|
2283
|
-
const validation = await db.schema.check(path, val, false);
|
|
2284
|
-
if (!validation.ok) {
|
|
2285
|
-
throw new SchemaValidationError(validation.reason);
|
|
2286
|
-
}
|
|
2287
|
-
|
|
2288
|
-
await db.ref(path)
|
|
2289
|
-
.context(req.context)
|
|
2290
|
-
.set(val);
|
|
2291
|
-
|
|
2292
|
-
res.send({ success: true });
|
|
2293
|
-
}
|
|
2294
|
-
catch(err) {
|
|
2295
|
-
if (err instanceof SchemaValidationError) {
|
|
2296
|
-
logRef && logRef.push({ action: 'set_data', success: false, code: 'schema_validation_failed', path, error: err.reason });
|
|
2297
|
-
res.status(422).send({ code: 'schema_validation_failed', message: err.message });
|
|
2298
|
-
}
|
|
2299
|
-
else {
|
|
2300
|
-
this.debug.error(`failed to set "${path}":`, err);
|
|
2301
|
-
logRef && logRef.push({ action: 'set_data', success: false, code: 'unknown_error', path, error: err.message });
|
|
2302
|
-
sendError(res, err);
|
|
2303
|
-
}
|
|
2304
|
-
};
|
|
2305
|
-
});
|
|
2306
|
-
|
|
2307
|
-
app.post(`/query/${dbname}/*`, async (req, res) => {
|
|
2308
|
-
// Execute query
|
|
2309
|
-
const path = req.path.substr(dbname.length + 8);
|
|
2310
|
-
if (!userHasAccess(req.user, path, false, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2311
|
-
return;
|
|
2312
|
-
}
|
|
2313
|
-
|
|
2314
|
-
const data = Transport.deserialize(req.body);
|
|
2315
|
-
if (typeof data !== 'object' || typeof data.query !== 'object' || typeof data.options !== 'object') {
|
|
2316
|
-
return sendError(res, { code: 'invalid_request', message: 'Invalid query request' });
|
|
2317
|
-
}
|
|
2318
|
-
const query = data.query;
|
|
2319
|
-
const options = data.options;
|
|
2320
|
-
if (options.monitor === true) {
|
|
2321
|
-
options.monitor = { add: true, change: true, remove: true };
|
|
2322
|
-
}
|
|
2323
|
-
if (typeof options.monitor === 'object' && (options.monitor.add || options.monitor.change || options.monitor.remove)) {
|
|
2324
|
-
const queryId = data.query_id;
|
|
2325
|
-
const clientId = data.client_id;
|
|
2326
|
-
const client = clients.get(clientId);
|
|
2327
|
-
client.realtimeQueries[queryId] = { path, query, options };
|
|
2328
|
-
|
|
2329
|
-
const sendEvent = event => {
|
|
2330
|
-
const client = clients.get(clientId);
|
|
2331
|
-
if (!client) { return false; } // Not connected, stop subscription
|
|
2332
|
-
if (!userHasAccess(client.user, event.path, false)) {
|
|
2333
|
-
return false; // Access denied, stop subscription
|
|
2334
|
-
}
|
|
2335
|
-
event.query_id = queryId;
|
|
2336
|
-
const data = Transport.serialize(event);
|
|
2337
|
-
client.socket.emit('query-event', data);
|
|
2338
|
-
}
|
|
2339
|
-
options.eventHandler = sendEvent;
|
|
2340
|
-
}
|
|
2341
|
-
try {
|
|
2342
|
-
const { results, context } = await db.api.query(path, query, options);
|
|
2343
|
-
if (!this.config.transactionLoggingEnabled) {
|
|
2344
|
-
delete context.acebase_cursor;
|
|
2345
|
-
}
|
|
2346
|
-
const response = {
|
|
2347
|
-
count: results.length,
|
|
2348
|
-
list: results // []
|
|
2349
|
-
};
|
|
2350
|
-
res.setHeader('AceBase-Context', JSON.stringify(context));
|
|
2351
|
-
res.send(Transport.serialize(response));
|
|
2352
|
-
}
|
|
2353
|
-
catch(err) {
|
|
2354
|
-
sendError(res, { code: 'unknown', message: err.message });
|
|
2355
|
-
}
|
|
2356
|
-
});
|
|
2357
|
-
|
|
2358
|
-
app.get(`/index/${dbname}`, async (req, res) => {
|
|
2359
|
-
// Get all indexes
|
|
2360
|
-
if (!req.user || req.user.username !== 'admin') {
|
|
2361
|
-
return sendUnauthorizedError(res, 'admin_only', 'only admin can perform index operations');
|
|
2362
|
-
}
|
|
2363
|
-
|
|
2364
|
-
try {
|
|
2365
|
-
const indexes = await db.indexes.get()
|
|
2366
|
-
res.contentType('application/json').send(indexes);
|
|
2367
|
-
}
|
|
2368
|
-
catch(err) {
|
|
2369
|
-
sendError(err);
|
|
2370
|
-
}
|
|
2371
|
-
});
|
|
2372
|
-
|
|
2373
|
-
app.post(`/index/${dbname}`, async (req, res) => {
|
|
2374
|
-
// create / remove / rebuild index
|
|
2375
|
-
if (!req.user || req.user.username !== 'admin') {
|
|
2376
|
-
return sendUnauthorizedError(res, 'admin_only', 'only admin can perform index operations');
|
|
2377
|
-
}
|
|
2378
|
-
|
|
2379
|
-
try {
|
|
2380
|
-
const data = req.body;
|
|
2381
|
-
if (data.action === 'create') {
|
|
2382
|
-
await db.indexes.create(data.path, data.key, data.options)
|
|
2383
|
-
}
|
|
2384
|
-
// else if (data.action === 'rebuild') {
|
|
2385
|
-
// // TODO
|
|
2386
|
-
// }
|
|
2387
|
-
// else if (data.action === 'remove') {
|
|
2388
|
-
// // TODO
|
|
2389
|
-
// }
|
|
2390
|
-
else {
|
|
2391
|
-
throw new Error('Invalid action');
|
|
2392
|
-
}
|
|
2393
|
-
res.contentType('application/json').send({ success: true });
|
|
2394
|
-
}
|
|
2395
|
-
catch(err) {
|
|
2396
|
-
this.debug.error(`failed to perform index action`, err);
|
|
2397
|
-
sendError(res, err);
|
|
2398
|
-
}
|
|
2399
|
-
});
|
|
2400
|
-
|
|
2401
|
-
app.get(`/schema/${dbname}`, async (req, res) => {
|
|
2402
|
-
// Get all defined schemas
|
|
2403
|
-
if (!req.user || req.user.username !== 'admin') {
|
|
2404
|
-
return sendUnauthorizedError(res, 'admin_only', 'only admin can perform schema operations');
|
|
2405
|
-
}
|
|
2406
|
-
try {
|
|
2407
|
-
const schemas = await db.schema.all();
|
|
2408
|
-
res.contentType('application/json').send(schemas);
|
|
2409
|
-
}
|
|
2410
|
-
catch(err) {
|
|
2411
|
-
sendError(res, err);
|
|
2412
|
-
}
|
|
2413
|
-
});
|
|
2414
|
-
|
|
2415
|
-
app.get(`/schema/${dbname}/*`, async (req, res) => {
|
|
2416
|
-
// Get defined schema for a specifc path
|
|
2417
|
-
if (!req.user || req.user.username !== 'admin') {
|
|
2418
|
-
return sendUnauthorizedError(res, 'admin_only', 'only admin can perform schema operations');
|
|
2419
|
-
}
|
|
2420
|
-
try {
|
|
2421
|
-
const path = req.path.substr(dbname.length + 9);
|
|
2422
|
-
const schema = await db.schema.get(path);
|
|
2423
|
-
res.contentType('application/json').send(schema);
|
|
2424
|
-
}
|
|
2425
|
-
catch(err) {
|
|
2426
|
-
sendError(res, err);
|
|
2427
|
-
}
|
|
2428
|
-
});
|
|
2429
|
-
|
|
2430
|
-
app.post(`/schema/${dbname}`, async (req, res) => {
|
|
2431
|
-
// defines a schema
|
|
2432
|
-
if (!req.user || req.user.username !== 'admin') {
|
|
2433
|
-
return sendUnauthorizedError(res, 'admin_only', 'only admin can perform schema operations');
|
|
2434
|
-
}
|
|
2435
|
-
|
|
2436
|
-
try {
|
|
2437
|
-
const data = req.body;
|
|
2438
|
-
if (data.action === 'set') {
|
|
2439
|
-
const { path, schema } = data;
|
|
2440
|
-
await db.schema.set(path, schema);
|
|
2441
|
-
}
|
|
2442
|
-
else {
|
|
2443
|
-
throw new Error(`Invalid action`);
|
|
2444
|
-
}
|
|
2445
|
-
res.contentType('application/json').send({ success: true });
|
|
2446
|
-
}
|
|
2447
|
-
catch(err) {
|
|
2448
|
-
sendError(res, err);
|
|
2449
|
-
}
|
|
2450
|
-
});
|
|
2451
|
-
|
|
2452
|
-
app.get(`/sync/mutations/${dbname}`, async (req, res) => {
|
|
2453
|
-
// Gets mutations for specific path(s) and event combinations since given cursor
|
|
2454
|
-
if (!this.config.transactionLoggingEnabled) {
|
|
2455
|
-
return sendError(res, { code: 'no_transaction_logging', message: 'Transaction logging not enabled' });
|
|
2456
|
-
}
|
|
2457
|
-
try {
|
|
2458
|
-
const data = req.query;
|
|
2459
|
-
let targets = typeof data.path === 'string'
|
|
2460
|
-
? [{ path: data.path, events: ['value'] }]
|
|
2461
|
-
: typeof data.for === 'string'
|
|
2462
|
-
? JSON.parse(data.for)
|
|
2463
|
-
: null;
|
|
2464
|
-
if (targets === null) {
|
|
2465
|
-
return sendError(res, { code: 'invalid_request', message: 'Invalid mutations request' });
|
|
2466
|
-
}
|
|
2467
|
-
if (targets.length === 0) {
|
|
2468
|
-
targets.push({ path: '', events: ['value'] });
|
|
2469
|
-
}
|
|
2470
|
-
// Filter out any requested paths user does not have access to.
|
|
2471
|
-
targets = targets.filter(target => {
|
|
2472
|
-
let path = target.path;
|
|
2473
|
-
if (target.events.every(event => /^(?:notify_)?child_/.test(event))) { //if (!target.events.some(event => ['value','notify_value','mutations','mutated'].includes(event))) {
|
|
2474
|
-
// Only child_ events, check if they have access to children instead
|
|
2475
|
-
path = PathInfo.get(path).childPath('*');
|
|
2476
|
-
}
|
|
2477
|
-
return userHasAccess(req.user, path, false);
|
|
2478
|
-
});
|
|
2479
|
-
if (targets.length === 0) {
|
|
2480
|
-
return sendUnauthorizedError(res, 'not_authorized', 'User is not authorized to access this data');
|
|
2481
|
-
}
|
|
2482
|
-
|
|
2483
|
-
const { cursor, timestamp } = data;
|
|
2484
|
-
const result = await db.api.getMutations({ for: targets, cursor, timestamp });
|
|
2485
|
-
|
|
2486
|
-
res.setHeader('AceBase-Context', JSON.stringify({ acebase_cursor: result.new_cursor }));
|
|
2487
|
-
res.contentType('application/json');
|
|
2488
|
-
res.send(result.mutations);
|
|
2489
|
-
}
|
|
2490
|
-
catch(err) {
|
|
2491
|
-
sendError(res, err);
|
|
2492
|
-
}
|
|
2493
|
-
});
|
|
2494
|
-
|
|
2495
|
-
app.get(`/sync/changes/${dbname}`, async (req, res) => {
|
|
2496
|
-
// Gets effective changes for specific path(s) and event combinations since given cursor
|
|
2497
|
-
if (!this.config.transactionLoggingEnabled) {
|
|
2498
|
-
return sendError(res, { code: 'no_transaction_logging', message: 'Transaction logging not enabled' });
|
|
2499
|
-
}
|
|
2500
|
-
try {
|
|
2501
|
-
const data = req.query;
|
|
2502
|
-
let targets = typeof data.path === 'string'
|
|
2503
|
-
? [{ path: data.path, events: ['value'] }]
|
|
2504
|
-
: typeof data.for === 'string'
|
|
2505
|
-
? JSON.parse(data.for)
|
|
2506
|
-
: null;
|
|
2507
|
-
if (targets === null) {
|
|
2508
|
-
return sendError(res, { code: 'invalid_request', message: 'Invalid mutations request' });
|
|
2509
|
-
}
|
|
2510
|
-
if (targets.length === 0) {
|
|
2511
|
-
targets.push({ path: '', events: ['value'] });
|
|
2512
|
-
}
|
|
2513
|
-
// Filter out any requested paths user does not have access to.
|
|
2514
|
-
targets = targets.filter(target => {
|
|
2515
|
-
let path = target.path;
|
|
2516
|
-
if (target.events.every(event => /^(?:notify_)?child_/.test(event))) { //if (!target.events.some(event => ['value','notify_value','mutations','mutated'].includes(event))) {
|
|
2517
|
-
// Only child_ events, check if they have access to children instead
|
|
2518
|
-
path = PathInfo.get(path).childPath('*');
|
|
2519
|
-
}
|
|
2520
|
-
return userHasAccess(req.user, path, false);
|
|
2521
|
-
});
|
|
2522
|
-
if (targets.length === 0) {
|
|
2523
|
-
return sendUnauthorizedError(res, 'not_authorized', 'User is not authorized to access this data');
|
|
2524
|
-
}
|
|
2525
|
-
|
|
2526
|
-
const { cursor, timestamp } = data;
|
|
2527
|
-
const result = await db.api.getChanges({ for: targets, cursor, timestamp });
|
|
2528
|
-
|
|
2529
|
-
res.setHeader('AceBase-Context', JSON.stringify({ acebase_cursor: result.new_cursor }));
|
|
2530
|
-
res.contentType('application/json');
|
|
2531
|
-
res.send(result.changes);
|
|
2532
|
-
}
|
|
2533
|
-
catch(err) {
|
|
2534
|
-
sendError(res, err);
|
|
2535
|
-
}
|
|
2536
|
-
});
|
|
2537
|
-
|
|
2538
|
-
const _transactions = new Map();
|
|
2539
|
-
app.post(`/transaction/${dbname}/start`, (req, res) => {
|
|
2540
|
-
const data = req.body;
|
|
2541
|
-
|
|
2542
|
-
if (!userHasAccess(req.user, data.path, true, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2543
|
-
return;
|
|
2544
|
-
}
|
|
2545
|
-
|
|
2546
|
-
// Start transaction
|
|
2547
|
-
const tx = {
|
|
2548
|
-
id: ID.generate(),
|
|
2549
|
-
started: Date.now(),
|
|
2550
|
-
path: data.path,
|
|
2551
|
-
context: req.context,
|
|
2552
|
-
finish: undefined
|
|
2553
|
-
};
|
|
2554
|
-
_transactions.set(tx.id, tx);
|
|
2555
|
-
|
|
2556
|
-
this.debug.verbose(`Transaction ${tx.id} starting...`);
|
|
2557
|
-
// const ref = db.ref(tx.path);
|
|
2558
|
-
const donePromise = db.api.transaction(tx.path, val => {
|
|
2559
|
-
this.debug.verbose(`Transaction ${tx.id} started with value: `, val);
|
|
2560
|
-
const currentValue = Transport.serialize(val);
|
|
2561
|
-
const promise = new Promise((resolve) => {
|
|
2562
|
-
tx.finish = (val) => {
|
|
2563
|
-
this.debug.verbose(`Transaction ${tx.id} finishing with value: `, val);
|
|
2564
|
-
resolve(val);
|
|
2565
|
-
return donePromise;
|
|
2566
|
-
};
|
|
2567
|
-
});
|
|
2568
|
-
res.send({ id: tx.id, value: currentValue });
|
|
2569
|
-
return promise;
|
|
2570
|
-
}, { context: tx.context });
|
|
2571
|
-
});
|
|
2572
|
-
|
|
2573
|
-
app.post(`/transaction/${dbname}/finish`, (req, res) => {
|
|
2574
|
-
const data = req.body;
|
|
2575
|
-
|
|
2576
|
-
const tx = _transactions.get(data.id);
|
|
2577
|
-
if (!tx) {
|
|
2578
|
-
res.statusCode = 410; // Gone
|
|
2579
|
-
res.send(`transaction not found`);
|
|
2580
|
-
return;
|
|
2581
|
-
}
|
|
2582
|
-
_transactions.delete(data.id);
|
|
2583
|
-
|
|
2584
|
-
if (!userHasAccess(req.user, data.path, true, denyDetails => sendUnauthorizedError(res, denyDetails.code, denyDetails.message))) {
|
|
2585
|
-
return;
|
|
2586
|
-
}
|
|
2587
|
-
|
|
2588
|
-
// Finish transaction
|
|
2589
|
-
const newValue = Transport.deserialize(data.value);
|
|
2590
|
-
tx.finish(newValue)
|
|
2591
|
-
.then(() => {
|
|
2592
|
-
res.send('done');
|
|
2593
|
-
})
|
|
2594
|
-
.catch(err => {
|
|
2595
|
-
res.statusCode = 500;
|
|
2596
|
-
res.send(err.message);
|
|
2597
|
-
});
|
|
2598
|
-
});
|
|
2599
|
-
|
|
2600
|
-
/**
|
|
2601
|
-
* Extend the server API with your own custom functions. Your handler will be listening
|
|
2602
|
-
* on path /ext/[db name]/[ext_path].
|
|
2603
|
-
* @example
|
|
2604
|
-
* // Server side:
|
|
2605
|
-
* const _quotes = [...];
|
|
2606
|
-
* server.extend('get', 'quotes/random', (req, res) => {
|
|
2607
|
-
* let index = Math.round(Math.random() * _quotes.length);
|
|
2608
|
-
* res.send(quotes[index]);
|
|
2609
|
-
* })
|
|
2610
|
-
* // Client side:
|
|
2611
|
-
* client.callExtension('get', 'quotes/random')
|
|
2612
|
-
* .then(quote => {
|
|
2613
|
-
* console.log(`Got random quote: ${quote}`);
|
|
2614
|
-
* })
|
|
2615
|
-
* @param {'get'|'put'|'post'|'delete'} method
|
|
2616
|
-
* @param {string} ext_path
|
|
2617
|
-
* @param {(req: Express.Request, res: Express.Response)} handler
|
|
2618
|
-
*/
|
|
2619
|
-
this.extend = (method, ext_path, handler) => {
|
|
2620
|
-
app[method.toLowerCase()](`/ext/${dbname}/${ext_path}`, handler);
|
|
2621
|
-
}
|
|
2622
|
-
|
|
2623
|
-
Promise.all(readyPromises).then(() => {
|
|
2624
|
-
server.listen(this.config.port, this.config.hostname, () => {
|
|
2625
|
-
this.debug.log(`"${dbname}" database server running at ${this.config.url}`);
|
|
2626
|
-
this._ready = true;
|
|
2627
|
-
this.emit(`ready`);
|
|
2628
|
-
});
|
|
2629
|
-
});
|
|
2630
|
-
|
|
2631
|
-
// Websocket implementation:
|
|
2632
|
-
const clients = {
|
|
2633
|
-
list: [],
|
|
2634
|
-
get(id) {
|
|
2635
|
-
return this.list.find(client => client.id === id);
|
|
2636
|
-
},
|
|
2637
|
-
add(socket) {
|
|
2638
|
-
const client = {
|
|
2639
|
-
socket,
|
|
2640
|
-
id: socket.id,
|
|
2641
|
-
subscriptions: {},
|
|
2642
|
-
realtimeQueries: {},
|
|
2643
|
-
transactions: {},
|
|
2644
|
-
user: null
|
|
2645
|
-
};
|
|
2646
|
-
this.list.push(client);
|
|
2647
|
-
return client;
|
|
2648
|
-
},
|
|
2649
|
-
/**
|
|
2650
|
-
* @param {string|object} client | client id or object
|
|
2651
|
-
*/
|
|
2652
|
-
remove(client) {
|
|
2653
|
-
let index = -1;
|
|
2654
|
-
if (typeof client === "object") {
|
|
2655
|
-
index = this.list.indexOf(client);
|
|
2656
|
-
}
|
|
2657
|
-
else {
|
|
2658
|
-
index = this.list.findIndex(c => c.id === client);
|
|
2659
|
-
}
|
|
2660
|
-
if (index >= 0) {
|
|
2661
|
-
this.list.splice(index, 1);
|
|
2662
|
-
}
|
|
2663
|
-
}
|
|
2664
|
-
};
|
|
2665
|
-
|
|
2666
|
-
this.shutdown = async () => {
|
|
2667
|
-
this.debug.warn('shutting down server');
|
|
2668
|
-
fs.unwatchFile(rulesFilePath, setupRules);
|
|
2669
|
-
await new Promise((resolve) => {
|
|
2670
|
-
server.close(resolve);
|
|
2671
|
-
clients.list.slice().forEach(client => {
|
|
2672
|
-
client.socket.disconnect(true);
|
|
2673
|
-
});
|
|
2674
|
-
});
|
|
2675
|
-
this.debug.warn('closing database');
|
|
2676
|
-
await db.close(); // TODO: Check what happens if shutdown was triggered by SIGINT. Maybe already closed?
|
|
2677
|
-
this.debug.warn('shutdown complete');
|
|
2678
|
-
|
|
2679
|
-
// Emit events to let the outside world know we shut down.
|
|
2680
|
-
// This is especially important if this instance was running in a Node.js cluster: the process will
|
|
2681
|
-
// not exit automatically after this shutdown because Node.js' IPC channel between worker and master is still open.
|
|
2682
|
-
// By sending these events, the cluster manager can determine if it should (and when to) execute process.exit()
|
|
2683
|
-
this.emit('shutdown'); // Emit on AceBaseServer instance
|
|
2684
|
-
process.emit('acebase-server-shutdown'); // Emit on process
|
|
2685
|
-
try {
|
|
2686
|
-
process.send && process.send('acebase-server-shutdown'); // Send to master process when running in a Node.js cluster
|
|
2687
|
-
}
|
|
2688
|
-
catch(err) {
|
|
2689
|
-
// IPC Channel has apparently been closed already
|
|
2690
|
-
}
|
|
2691
|
-
};
|
|
2692
|
-
process.on('SIGINT', () => this.shutdown());
|
|
2693
|
-
|
|
2694
|
-
let paused = false;
|
|
2695
|
-
this.pause = async () => {
|
|
2696
|
-
if (paused) { throw new Error('Server is already paused'); }
|
|
2697
|
-
server.close();
|
|
2698
|
-
this.debug.warn(`Paused "${dbname}" database server at ${this.config.url}`);
|
|
2699
|
-
this.emit('pause');
|
|
2700
|
-
paused = true;
|
|
2701
|
-
}
|
|
2702
|
-
|
|
2703
|
-
this.resume = async () => {
|
|
2704
|
-
if (!paused) { throw new Error('Server is not paused'); }
|
|
2705
|
-
return new Promise(resolve => {
|
|
2706
|
-
server.listen(this.config.port, this.config.hostname, () => {
|
|
2707
|
-
this.debug.warn(`Resumed "${dbname}" database server at ${this.config.url}`);
|
|
2708
|
-
this.emit('resume');
|
|
2709
|
-
paused = false;
|
|
2710
|
-
resolve();
|
|
2711
|
-
});
|
|
2712
|
-
})
|
|
2713
|
-
}
|
|
2714
|
-
|
|
2715
|
-
/** @type {Map<string, Client>} */
|
|
2716
|
-
// const clientsNew = new Map();
|
|
2717
|
-
|
|
2718
|
-
io.sockets.on("connection", socket => {
|
|
2719
|
-
const client = clients.add(socket);
|
|
2720
|
-
client.signInToken = ID.generate();
|
|
2721
|
-
this.debug.verbose(`New socket connected, total: ${clients.list.length}`);
|
|
2722
|
-
socket.emit("welcome");
|
|
2723
|
-
|
|
2724
|
-
socket.on("disconnect", data => {
|
|
2725
|
-
// We lost one
|
|
2726
|
-
// const client = clients.get(socket.id);
|
|
2727
|
-
// if (!client) { return; } // Disconnected a client we did not know? Don't crash, just ignore.
|
|
2728
|
-
const subscribedPaths = Object.keys(client.subscriptions);
|
|
2729
|
-
if (subscribedPaths.length > 0) {
|
|
2730
|
-
// TODO: Substitute the original callbacks to cache them
|
|
2731
|
-
// if the client then reconnects within a certain time,
|
|
2732
|
-
// we can send the missed notifications
|
|
2733
|
-
//
|
|
2734
|
-
// subscribedPaths.forEach(path => {
|
|
2735
|
-
// client.subscriptions[path].forEach(subscr => {
|
|
2736
|
-
// subscr.callback
|
|
2737
|
-
// })
|
|
2738
|
-
// });
|
|
2739
|
-
|
|
2740
|
-
let remove = [];
|
|
2741
|
-
subscribedPaths.forEach(path => {
|
|
2742
|
-
remove.push(...client.subscriptions[path]);
|
|
2743
|
-
});
|
|
2744
|
-
remove.forEach(subscr => {
|
|
2745
|
-
// Unsubscribe them at db level and remove from our list
|
|
2746
|
-
db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.ref(subscr.path).off(subscr.event, subscr.callback);
|
|
2747
|
-
let pathSubs = client.subscriptions[subscr.path];
|
|
2748
|
-
pathSubs.splice(pathSubs.indexOf(subscr), 1);
|
|
2749
|
-
});
|
|
2750
|
-
}
|
|
2751
|
-
clients.remove(client);
|
|
2752
|
-
this.debug.verbose(`Socket disconnected, total: ${clients.list.length}`);
|
|
2753
|
-
});
|
|
2754
|
-
|
|
2755
|
-
socket.on("reconnect", data => {
|
|
2756
|
-
let prevSocketId = data.id;
|
|
2757
|
-
clients.list.push(client);
|
|
2758
|
-
this.debug.verbose(`Socket reconnected, total: ${clients.list.length}`);
|
|
2759
|
-
// TODO: implement cached notification sending
|
|
2760
|
-
});
|
|
2761
|
-
|
|
2762
|
-
socket.on("signin", accessToken => {
|
|
2763
|
-
// client sends this request once user has been signed in, binds the user to the socket,
|
|
2764
|
-
// deprecated since client v0.9.4, which sends client_id with signin api call
|
|
2765
|
-
// const client = clients.get(socket.id);
|
|
2766
|
-
let uid;
|
|
2767
|
-
try {
|
|
2768
|
-
uid = decodePublicAccessToken(accessToken, _secureObjectsSalt).uid;
|
|
2769
|
-
client.user = _authCache.get(uid) || null;
|
|
2770
|
-
}
|
|
2771
|
-
catch(err) {
|
|
2772
|
-
// no way to bind the user
|
|
2773
|
-
this.debug.error(`websocket: invalid access token passed to signin: ${accessToken}`);
|
|
2774
|
-
}
|
|
2775
|
-
});
|
|
2776
|
-
|
|
2777
|
-
socket.on("signout", data => {
|
|
2778
|
-
// deprecated since client v0.9.4, which sends client_id with signout api call
|
|
2779
|
-
// const client = clients.get(socket.id);
|
|
2780
|
-
client.user = null;
|
|
2781
|
-
});
|
|
2782
|
-
|
|
2783
|
-
socket.on("oauth2-signin", async request => {
|
|
2784
|
-
// acebase-client does not use socket oauth flow yet
|
|
2785
|
-
try {
|
|
2786
|
-
const providerName = typeof request === 'string' ? request : request.provider;
|
|
2787
|
-
const provider = this.authProviders[providerName];
|
|
2788
|
-
const state = Buffer.from(JSON.stringify({ flow: 'socket', provider: providerName, client_id: client.id })).toString('base64');
|
|
2789
|
-
const clientAuthUrl = await provider.init({ redirectUrl: `${req.protocol}://${req.headers.host}/ouath2/${dbname}/signin`, state, options: request.options });
|
|
2790
|
-
socket.emit('oauth2-signin', { action: 'auth', url: clientAuthUrl });
|
|
2791
|
-
}
|
|
2792
|
-
catch(err) {
|
|
2793
|
-
this.debug.error(`websocket: cannot sign in with oauth provider ${providerName}`);
|
|
2794
|
-
socket.emit('oauth2-signin', { error: err.message });
|
|
2795
|
-
}
|
|
2796
|
-
});
|
|
2797
|
-
|
|
2798
|
-
const acknowlegdeRequest = (requestId) => {
|
|
2799
|
-
// Send acknowledgement
|
|
2800
|
-
socket.emit('result', {
|
|
2801
|
-
success: true,
|
|
2802
|
-
req_id: requestId
|
|
2803
|
-
});
|
|
2804
|
-
};
|
|
2805
|
-
const failRequest = (requestId, code) => {
|
|
2806
|
-
// Send error
|
|
2807
|
-
socket.emit('result', {
|
|
2808
|
-
success: false,
|
|
2809
|
-
reason: code,
|
|
2810
|
-
req_id: requestId
|
|
2811
|
-
});
|
|
2812
|
-
};
|
|
2813
|
-
|
|
2814
|
-
socket.on("subscribe", data => {
|
|
2815
|
-
// Client wants to subscribe to events on a node
|
|
2816
|
-
this.debug.verbose(`Client ${socket.id} subscribes to event "${data.event}" on path "/${data.path}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
|
|
2817
|
-
const subscriptionPath = data.path;
|
|
2818
|
-
const isSubscribed = () => subscriptionPath in client.subscriptions && client.subscriptions[subscriptionPath].some(s => s.event === data.event)
|
|
2819
|
-
if (isSubscribed()) {
|
|
2820
|
-
return acknowlegdeRequest(data.req_id);
|
|
2821
|
-
}
|
|
2822
|
-
|
|
2823
|
-
// Get client
|
|
2824
|
-
// const client = clients.get(socket.id);
|
|
2825
|
-
|
|
2826
|
-
if (!userHasAccess(client.user, subscriptionPath, false)) {
|
|
2827
|
-
logRef.push({ action: 'subscribe', success: false, code: 'access_denied', uid: client.user ? client.user.uid : '-', path: subscriptionPath });
|
|
2828
|
-
return failRequest(data.req_id, 'access_denied');
|
|
2829
|
-
}
|
|
2830
|
-
|
|
2831
|
-
const callback = (err, path, currentValue, previousValue, context) => {
|
|
2832
|
-
if (!isSubscribed()) {
|
|
2833
|
-
// Not subscribed anymore. Cancel sending
|
|
2834
|
-
return;
|
|
2835
|
-
}
|
|
2836
|
-
if (!userHasAccess(client.user, path, false)) {
|
|
2837
|
-
if (!subscriptionPath.includes('*') && !subscriptionPath.includes('$')) {
|
|
2838
|
-
// Could potentially be very many callbacks, so
|
|
2839
|
-
// DISABLED: logRef.push({ action: `access_revoked`, uid: client.user ? client.user.uid : '-', path: subscriptionPath });
|
|
2840
|
-
// Only log when user subscribes again
|
|
2841
|
-
failRequest(data.req_id, 'access_denied');
|
|
2842
|
-
}
|
|
2843
|
-
return;
|
|
2844
|
-
}
|
|
2845
|
-
if (err) {
|
|
2846
|
-
return;
|
|
2847
|
-
}
|
|
2848
|
-
let val = Transport.serialize({
|
|
2849
|
-
current: currentValue,
|
|
2850
|
-
previous: previousValue
|
|
2851
|
-
});
|
|
2852
|
-
this.debug.verbose(`Sending data event "${data.event}" for path "/${path}" to client ${socket.id}`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
|
|
2853
|
-
// TODO: let large data events notify the client, then let them download the data manually so it doesn't have to be transmitted through the websocket
|
|
2854
|
-
socket.emit('data-event', {
|
|
2855
|
-
subscr_path: subscriptionPath,
|
|
2856
|
-
path,
|
|
2857
|
-
event: data.event,
|
|
2858
|
-
val,
|
|
2859
|
-
context
|
|
2860
|
-
});
|
|
2861
|
-
};
|
|
2862
|
-
// const client = clients.get(socket.id);
|
|
2863
|
-
|
|
2864
|
-
let pathSubs = client.subscriptions[subscriptionPath];
|
|
2865
|
-
if (!pathSubs) { pathSubs = client.subscriptions[subscriptionPath] = []; }
|
|
2866
|
-
|
|
2867
|
-
let subscr = { path: subscriptionPath, event: data.event, callback };
|
|
2868
|
-
pathSubs.push(subscr);
|
|
2869
|
-
|
|
2870
|
-
db.api.subscribe(subscriptionPath, data.event, callback);
|
|
2871
|
-
|
|
2872
|
-
acknowlegdeRequest(data.req_id);
|
|
2873
|
-
});
|
|
2874
|
-
|
|
2875
|
-
socket.on("query_unsubscribe", data => {
|
|
2876
|
-
// Client unsubscribing from realtime query events
|
|
2877
|
-
this.debug.verbose(`Client ${socket.id} is unsubscribing from realtime query "${data.query_id}"`);
|
|
2878
|
-
// const client = clients.get(socket.id);
|
|
2879
|
-
delete client.realtimeQueries[data.query_id];
|
|
2880
|
-
acknowlegdeRequest(data.req_id);
|
|
2881
|
-
});
|
|
2882
|
-
|
|
2883
|
-
socket.on("unsubscribe", data => {
|
|
2884
|
-
// Client unsubscribes from events on a node
|
|
2885
|
-
this.debug.verbose(`Client ${socket.id} is unsubscribing from event "${data.event || '(any)'}" on path "/${data.path}"`.colorize([ColorStyle.bgWhite, ColorStyle.black]));
|
|
2886
|
-
|
|
2887
|
-
// const client = clients.get(socket.id);
|
|
2888
|
-
let pathSubs = client.subscriptions[data.path];
|
|
2889
|
-
if (!pathSubs) {
|
|
2890
|
-
// We have no knowledge of any active subscriptions on this path
|
|
2891
|
-
return acknowlegdeRequest(data.req_id);
|
|
2892
|
-
}
|
|
2893
|
-
let remove = pathSubs;
|
|
2894
|
-
if (data.event) {
|
|
2895
|
-
// Unsubscribe from a specific event
|
|
2896
|
-
remove = pathSubs.filter(subscr => subscr.event === data.event);
|
|
2897
|
-
}
|
|
2898
|
-
remove.forEach(subscr => {
|
|
2899
|
-
// Unsubscribe them at db level and remove from our list
|
|
2900
|
-
//this.debug.verbose(` - unsubscribing from event ${subscr.event} with${subscr.callback ? "" : "out"} callback on path "${data.path}"`);
|
|
2901
|
-
db.api.unsubscribe(subscr.path, subscr.event, subscr.callback); //db.api.unsubscribe(data.path, subscr.event, subscr.callback);
|
|
2902
|
-
pathSubs.splice(pathSubs.indexOf(subscr), 1);
|
|
2903
|
-
});
|
|
2904
|
-
if (pathSubs.length === 0) {
|
|
2905
|
-
// No subscriptions left on this path, remove the path entry
|
|
2906
|
-
delete client.subscriptions[data.path];
|
|
2907
|
-
}
|
|
2908
|
-
return acknowlegdeRequest(data.req_id);
|
|
2909
|
-
});
|
|
2910
|
-
|
|
2911
|
-
socket.on("transaction", data => {
|
|
2912
|
-
this.debug.verbose(`Client ${socket.id} is sending ${data.action} transaction request on path "${data.path}"`);
|
|
2913
|
-
// const client = clients.get(socket.id);
|
|
2914
|
-
|
|
2915
|
-
if (data.action === "start") {
|
|
2916
|
-
const tx = {
|
|
2917
|
-
id: data.id,
|
|
2918
|
-
started: Date.now(),
|
|
2919
|
-
path: data.path,
|
|
2920
|
-
context: data.context,
|
|
2921
|
-
finish: undefined
|
|
2922
|
-
};
|
|
2923
|
-
|
|
2924
|
-
if (!userHasAccess(client.user, data.path, true)) {
|
|
2925
|
-
// throw new AccessDeniedError(`access_denied`);
|
|
2926
|
-
socket.emit("tx_error", { id: tx.id, reason: 'access_denied' }); // what if message is dropped? We should implement an ack/retry mechanism
|
|
2927
|
-
}
|
|
2928
|
-
|
|
2929
|
-
// Start a transaction
|
|
2930
|
-
client.transactions[data.id] = tx;
|
|
2931
|
-
this.debug.verbose(`Transaction ${tx.id} starting...`);
|
|
2932
|
-
// const ref = db.ref(tx.path);
|
|
2933
|
-
const donePromise = db.api.transaction(tx.path, val => {
|
|
2934
|
-
this.debug.verbose(`Transaction ${tx.id} started with value: `, val);
|
|
2935
|
-
const currentValue = Transport.serialize(val);
|
|
2936
|
-
const promise = new Promise((resolve) => {
|
|
2937
|
-
tx.finish = (val) => {
|
|
2938
|
-
this.debug.verbose(`Transaction ${tx.id} finishing with value: `, val);
|
|
2939
|
-
resolve(val);
|
|
2940
|
-
return donePromise;
|
|
2941
|
-
};
|
|
2942
|
-
});
|
|
2943
|
-
socket.emit("tx_started", { id: tx.id, value: currentValue }); // what if message is dropped? We should implement an ack/retry mechanism
|
|
2944
|
-
return promise;
|
|
2945
|
-
}, { context: tx.context });
|
|
2946
|
-
}
|
|
2947
|
-
|
|
2948
|
-
if (data.action === "finish") {
|
|
2949
|
-
// Finish transaction
|
|
2950
|
-
// TODO: check what happens if undefined is returned
|
|
2951
|
-
const tx = client.transactions[data.id];
|
|
2952
|
-
delete client.transactions[data.id];
|
|
2953
|
-
|
|
2954
|
-
try {
|
|
2955
|
-
if (!tx) {
|
|
2956
|
-
throw new Error('transaction_not_found');
|
|
2957
|
-
}
|
|
2958
|
-
if (!userHasAccess(client.user, data.path, true)) {
|
|
2959
|
-
throw new Error('access_denied');
|
|
2960
|
-
}
|
|
2961
|
-
const newValue = Transport.deserialize(data.value);
|
|
2962
|
-
tx.finish(newValue)
|
|
2963
|
-
.then(res => {
|
|
2964
|
-
this.debug.verbose(`Transaction ${tx.id} finished`);
|
|
2965
|
-
socket.emit("tx_completed", { id: tx.id });
|
|
2966
|
-
})
|
|
2967
|
-
.catch(err => {
|
|
2968
|
-
socket.emit("tx_error", { id: tx.id, reason: err.message });
|
|
2969
|
-
});
|
|
2970
|
-
}
|
|
2971
|
-
catch (err) {
|
|
2972
|
-
tx.finish(); // Finish with undefined, canceling the transaction
|
|
2973
|
-
socket.emit('tx_error', {
|
|
2974
|
-
id: data.id,
|
|
2975
|
-
reason: err.message,
|
|
2976
|
-
data
|
|
2977
|
-
});
|
|
2978
|
-
}
|
|
2979
|
-
}
|
|
2980
|
-
|
|
2981
|
-
});
|
|
2982
|
-
|
|
2983
|
-
});
|
|
2984
|
-
});
|
|
2985
|
-
}
|
|
2986
|
-
|
|
2987
|
-
/**
|
|
2988
|
-
*
|
|
2989
|
-
* @param {()=>void} [callback] (optional) callback function that is called when ready. You can also use the returned promise
|
|
2990
|
-
* @returns {Promise<void>} returns a promise that resolves when ready
|
|
2991
|
-
*/
|
|
2992
|
-
ready(callback = undefined) {
|
|
2993
|
-
if (this._ready) {
|
|
2994
|
-
// ready event was emitted before
|
|
2995
|
-
callback && callback();
|
|
2996
|
-
return Promise.resolve();
|
|
2997
|
-
}
|
|
2998
|
-
else {
|
|
2999
|
-
// Wait for ready event
|
|
3000
|
-
let resolve;
|
|
3001
|
-
const promise = new Promise(res => resolve = res);
|
|
3002
|
-
this.once("ready", () => {
|
|
3003
|
-
resolve();
|
|
3004
|
-
callback && callback();
|
|
3005
|
-
});
|
|
3006
|
-
return promise;
|
|
3007
|
-
}
|
|
3008
|
-
}
|
|
3009
|
-
|
|
3010
|
-
verifyEmailAddress(code) {
|
|
3011
|
-
throw new Error(`authentication is not enabled`);
|
|
3012
|
-
}
|
|
3013
|
-
|
|
3014
|
-
configAuthProvider(providerName, settings) {
|
|
3015
|
-
if (!this.config.authentication.enabled) {
|
|
3016
|
-
throw new Error(`Authentication is not enabled`);
|
|
3017
|
-
}
|
|
3018
|
-
try {
|
|
3019
|
-
const { AuthProvider } = require('./oauth-providers/' + providerName);
|
|
3020
|
-
const provider = new AuthProvider(settings);
|
|
3021
|
-
this.authProviders[providerName] = provider;
|
|
3022
|
-
return provider;
|
|
3023
|
-
}
|
|
3024
|
-
catch(err) {
|
|
3025
|
-
throw new Error(`Failed to configure provider ${providerName}: ${err.message}`)
|
|
3026
|
-
}
|
|
3027
|
-
}
|
|
3028
|
-
|
|
3029
|
-
/**
|
|
3030
|
-
* Shuts down the server. Stops listening for incoming connections, breaks current connections and closes the database.
|
|
3031
|
-
*/
|
|
3032
|
-
async shutdown() {
|
|
3033
|
-
// Overridden by constructor once the server is started.
|
|
3034
|
-
// If this code executes, the server's not running yet.
|
|
3035
|
-
await this.ready();
|
|
3036
|
-
await this.shutdown(); // Now has new implementation
|
|
3037
|
-
}
|
|
3038
|
-
}
|
|
3039
|
-
|
|
3040
|
-
if (__filename.replace(/\\/g,"/").endsWith("/acebase-server.js") && process.argv[2] === "start") {
|
|
3041
|
-
// If one executed "node server.js start [hostname] [port]"
|
|
3042
|
-
const dbname = process.argv[3] || process.env.DBNAME || "default";
|
|
3043
|
-
const host = process.argv[4] || process.env.HOST || "0.0.0.0";
|
|
3044
|
-
const port = process.argv[5] || process.env.PORT || 3000;
|
|
3045
|
-
const options = { host , port };
|
|
3046
|
-
const server = new AceBaseServer(dbname, options);
|
|
3047
|
-
server.once("ready", () => {
|
|
3048
|
-
server.debug.log(`AceBase server running`);
|
|
3049
|
-
process.send('ready'); // When using pm2, you can use --wait-ready flag (see https://pm2.keymetrics.io/docs/usage/signals-clean-restart/)
|
|
3050
|
-
});
|
|
3051
|
-
}
|
|
3052
|
-
|
|
3053
|
-
module.exports = {
|
|
3054
|
-
AceBaseServer,
|
|
3055
|
-
AceBaseServerSettings,
|
|
3056
|
-
AceBaseEmailRequest,
|
|
3057
|
-
AceBaseUserSignupEmailRequest,
|
|
3058
|
-
AceBaseUserResetPasswordEmailRequest,
|
|
3059
|
-
AceBaseUserResetPasswordSuccessEmailRequest
|
|
3060
|
-
};
|