Compare commits

..

259 Commits

Author SHA1 Message Date
Ronald A. Richardson
ff59941947 wip: binary build 2024-04-03 15:15:27 +08:00
Ronald A. Richardson
013e19f39e working on single executable binary for linux and macos of fleetbase 2024-04-02 21:21:24 +08:00
Ronald A. Richardson
dba2b7afc5 hotfix: bump console version 2024-04-02 17:56:06 +08:00
Ron
a6e6625ae1 Merge pull request #239 from fleetbase/dev-v0.4.16
v0.4.16
2024-04-02 16:55:13 +07:00
Ronald A. Richardson
3777569f22 added upgraded storefront 2024-04-02 17:50:07 +08:00
Ronald A. Richardson
fa5b6700a3 ready for release, full core dependency upgrades, security improvements and new feature for driver onboard 2024-04-02 17:45:01 +08:00
Ronald A. Richardson
6cce6a9db2 added cache to github card component, add password verification for changing email or password, ensured reset password link is is invalidated when expired or deleted 2024-04-02 17:09:10 +08:00
Ronald A. Richardson
39d405cb57 refactored github card to use cache for 6 hours 2024-03-28 15:12:17 +08:00
Ron
9f88c7bc79 Merge pull request #238 from fleetbase/dev-v0.4.15
v0.4.15
2024-03-27 20:04:55 +07:00
Ron
b3816c394a Merge pull request #236 from fleetbase/feature/helm_eks
feature/helm eks
2024-03-27 20:00:08 +07:00
Ronald A. Richardson
34462c61c4 Prepeared next release with latest upgrades/ patches 2024-03-27 20:58:40 +08:00
Eugene Dementyev
080302eb86 Fix socketcluster port for eks 2024-03-20 18:19:06 +13:00
Eugene Dementyev
b063cf6338 Set api host and socketcluster host from github 2024-03-20 18:03:15 +13:00
Eugene Dementyev
b6dca79251 Fix registry 2024-03-19 23:26:38 +13:00
Eugene Dementyev
c35af4d47a Add EKS deployments 2024-03-19 21:23:21 +13:00
Eugene Dementyev
2a89659cc3 Adapt the Helm chart to be used with AWS EKS 2024-03-19 21:05:47 +13:00
Ron
f8ae75d767 Merge pull request #235 from fleetbase/dev-v0.4.14
v0.4.14
2024-03-17 12:27:18 +08:00
Ronald A. Richardson
924448a4d0 Upgraded fleetops for distance matrix calculation optimization and provider configuration 2024-03-17 12:20:40 +08:00
Ron
5426ac374d Merge pull request #234 from fleetbase/dev-v0.4.13
v0.4.13
2024-03-15 17:27:12 +08:00
Ronald A. Richardson
73f56b7958 added translations for schedule monitor ui 2024-03-15 17:23:06 +08:00
Ronald A. Richardson
095eb87e14 preparing for new release 2024-03-15 17:00:31 +08:00
Ronald A. Richardson
fabc16612b core-api upgrade includes improved upload error reporting 2024-03-13 18:02:22 +08:00
Ronald A. Richardson
3389cba935 added the visibility_handler to the gcs filesystem driver config 2024-03-13 17:13:23 +08:00
Ron
099ea57c39 Merge pull request #231 from fleetbase/dev-v0.4.12
v0.4.12
2024-03-13 15:26:36 +08:00
Ronald A. Richardson
5492bc7299 - Revamped service rates to integrate with the new order configuration system.
- Enhanced activities to now support proof of delivery requirements.
- Patched and improved the stringent validation for creating new orders.
- Added a new column `order_config_uuid` to the `service_rates` table for better data management.
- Various other minor improvements and optimizations for enhanced performance and stability.
- Critical patch and improvement to location service
2024-03-13 15:15:42 +08:00
Ron
00b037a385 Merge pull request #229 from fleetbase/dev-v0.4.11
v0.4.11
2024-03-12 18:18:42 +08:00
Ronald A. Richardson
151fea2505 ready for release 2024-03-12 18:13:35 +08:00
Ronald A. Richardson
08f901d865 patches following major release 2024-03-12 17:55:51 +08:00
Ron
116873a1ce Merge pull request #225 from fleetbase/dev-v0.4.10
v0.4.10
2024-03-11 21:12:01 +08:00
Ronald A. Richardson
20a1793447 remove test url from cors allowed_origins 2024-03-11 21:07:23 +08:00
Ronald A. Richardson
72ab83dc7a release is ready 2024-03-11 21:06:25 +08:00
Ronald A. Richardson
171e365ba6 added commercial license 2024-03-11 20:33:39 +08:00
Ronald A. Richardson
009f2d6e53 Merge branch 'dev-v0.4.10' of github.com:fleetbase/fleetbase into dev-v0.4.10 2024-03-11 16:25:17 +08:00
Ronald A. Richardson
4a59318feb upgraded fleetops-data; fixed custom fields and custom field value models; patch notification model 2024-03-11 16:24:46 +08:00
Ron
8920039b40 Merge pull request #227 from fleetbase/fix/helm_install_order 2024-03-11 12:44:53 +08:00
Eugene Dementyev
cd9be05714 Remove helm service hooks. Use DNS names for services 2024-03-08 20:40:31 +13:00
Ron
fbe35545e9 Merge pull request #223 from fleetbase/feature/nginx_host_header
Make nginx pass the Host header
2024-03-06 13:14:35 +08:00
Ron
56ab967d7a Merge pull request #224 from fleetbase/fix/helm_install_order
Fix/helm install order
2024-03-06 13:14:03 +08:00
Ronald A. Richardson
79604c7981 preparing for v0.4.10 release 2024-03-06 13:10:31 +08:00
Eugene Dementyev
312eb1aa6f Adds pre-install for redis service 2024-03-02 20:55:17 +13:00
Eugene Dementyev
6572a59120 Fixes helm install order 2024-03-02 20:21:18 +13:00
Eugene Dementyev
fa536c6183 Make nginx pass the Host header 2024-02-27 19:54:50 +13:00
Ron
d4626be332 Merge pull request #221 from fleetbase/dev-v0.4.9
v0.4.9
2024-02-24 16:02:05 +07:00
Ronald A. Richardson
ffc54ecdbb upgrade dependencies which has expansion hotfixes 2024-02-24 16:59:12 +08:00
Ron
9bf097b88b Merge pull request #220 from fleetbase/dev-v0.4.8
v0.4.8
2024-02-23 12:48:50 +07:00
Ronald A. Richardson
52c8df8b66 prepared for next release 2024-02-23 13:47:15 +08:00
Ron
908e0eb9ee Merge pull request #219 from fleetbase/dev-v0.4.7
v0.4.7
2024-02-22 17:11:51 +07:00
Ronald A. Richardson
6438138913 add upgraded core-api submodule 2024-02-22 17:57:22 +08:00
Ronald A. Richardson
aee06a2146 update composer lockfile 2024-02-22 17:54:01 +08:00
Ronald A. Richardson
ccacc6c597 adds fleetops migrations hotfix 2024-02-22 12:43:33 +08:00
Ron
62c396b789 Merge pull request #218 from fleetbase/dev-v0.4.6
v0.4.6
2024-02-21 17:48:54 +07:00
Ronald A. Richardson
295da5f331 fix composer files 2024-02-21 18:44:27 +08:00
Ronald A. Richardson
e775ccc2c8 upgraded dependencies and prepared for release 2024-02-21 18:40:36 +08:00
Ronald A. Richardson
bd0759881f updated notification channel config for firebase and apn 2024-02-21 18:16:15 +08:00
Ronald A. Richardson
830ae69b1d hotfix: composer.lock with core-api upgrade 2024-02-17 20:04:35 +08:00
Ron
3b9a80866f Merge pull request #213 from fleetbase/dev-v0.4.5
v0.4.5
2024-02-17 18:26:25 +07:00
Ronald A. Richardson
76badbf949 patch admin organization browser; upgrade core-api; upgrade fleetops 2024-02-17 19:21:07 +08:00
Ronald A. Richardson
f968556585 hotfix organizations browsers in admin w/ more details, better querying and admin based view, upgrade of dependencies with major patches 2024-02-16 17:32:44 +07:00
Ronald A. Richardson
6d01eab305 use fixed fleetbase/laravel-mysql-spatial v1.0.2 2024-02-16 01:37:20 +07:00
Ronald A. Richardson
9406446db1 explicitly set production environment on gitlab cd workflow 2024-02-16 00:16:22 +07:00
Ronald A. Richardson
565db7bbce explicitly set production environment for cd workflows 2024-02-16 00:15:15 +07:00
Ron
003cb467e8 Merge pull request #212 from fleetbase/dev-v0.4.4
v0.4.4
2024-02-15 23:41:59 +07:00
Ronald A. Richardson
8e1b281e77 upgraded core-api v1.4.4 and fleetops v0.4.10 w/ critical patches for webhook and driver 2024-02-15 23:32:46 +07:00
Ronald A. Richardson
af4507cc87 added translations for create/join organization and migrated to use Dockerfile 2024-02-15 23:11:20 +07:00
Ronald A. Richardson
2a2c7d8426 use correct CONSOLE_HOST env variable in cors config 2024-02-14 17:05:59 +07:00
Ronald A. Richardson
077a4298b9 Update console Dockerfile to allow environment to be passed in build 2024-02-14 16:02:55 +07:00
Ron
af840d30d0 Merge pull request #211 from fleetbase/dev-v0.4.3
v0.4.3
2024-02-13 16:52:05 +08:00
Ronald A. Richardson
a253c0c6f7 Upgrade dependencies with critical patches 2024-02-13 16:50:21 +08:00
Ron
0fc1d6068d Merge pull request #210 from fleetbase/dev-v0.4.2
v0.4.2
2024-02-13 14:41:56 +08:00
Ronald A. Richardson
6993510d08 upgraded core-api for api credential key generation patch 2024-02-13 14:36:37 +08:00
Ron
4fcf09c1b8 Merge pull request #209 from fleetbase/dev-v0.4.1-version-patch
upgrade packages
2024-02-13 13:41:22 +08:00
Ronald A. Richardson
f89596a74b upgrade packages 2024-02-13 13:40:24 +08:00
Ron
d89e93f248 Merge pull request #208 from fleetbase/dev-v0.4.1-version-patch
v0.4.1 patch
2024-02-13 13:39:26 +08:00
Ronald A. Richardson
2f0c15bc93 bump version for v0.4.1 release 2024-02-13 13:37:34 +08:00
Ron
ae6c07006b Merge pull request #207 from fleetbase/dev-v0.4.1
v0.4.1
2024-02-13 13:26:53 +08:00
Ronald A. Richardson
d754641493 Upgraded to Fleet-Ops v0.4.8, Core API to v1.4.1 and added support for sendgrid officially. 2024-02-13 13:22:20 +08:00
Ron
bb0d706006 Merge pull request #205 from ekini/fix/crond 2024-02-10 15:02:38 +08:00
Eugene Dementyev
652bc363e1 Fix crond 2024-02-10 20:00:50 +13:00
Ron
363309af61 Merge pull request #204 from ekini/fix/helm_replicas 2024-02-10 15:00:30 +08:00
Eugene Dementyev
83791ea91c Scale deployment of the app to 2 by default 2024-02-10 19:57:37 +13:00
Ron
8aae8cd025 Merge pull request #202 from fleetbase/dev-v0.4.0
v0.4.0
2024-02-08 14:34:34 +08:00
Ronald A. Richardson
6fb0353813 upgrade dependencies 2024-02-08 14:07:05 +08:00
Ronald A. Richardson
c73c8e0f54 upgrade fleetops, small patch on invite for user ui 2024-02-08 14:06:23 +08:00
Ronald A. Richardson
84ddf730c2 Upgraded dependencies for crticial patches from QA tests 2024-02-07 18:17:31 +08:00
Ronald A. Richardson
9da0d6b5c4 try latest version of go-crond for scheduler 2024-02-07 16:26:19 +08:00
Ronald A. Richardson
52bf61b3be patches for dashboards 2024-02-07 15:58:50 +08:00
Ronald A. Richardson
9ff3d9e85f Merge branch 'dev-v0.4.0' of github.com:fleetbase/fleetbase into dev-v0.4.0 2024-02-07 15:17:02 +08:00
Ronald A. Richardson
b6bad3212d ready for release 2024-02-07 15:16:36 +08:00
Ron
a43b86807b Merge pull request #203 from ekini/fix/go-crond
fix/go crond
2024-02-07 14:58:14 +08:00
Eugene Dementyev
9cc0e35ac3 Fix go-crond after switching to Alpine base image 2024-02-07 19:56:40 +13:00
Ronald A. Richardson
2e555b8dc3 fix composer dependencies for testing before release 2024-02-07 11:54:31 +08:00
Ronald A. Richardson
948ba4aa6d patches for dashboard and organizations/users 2024-02-07 11:35:55 +08:00
Ron
46bd448ec7 Merge pull request #194 from fleetbase/feature/caddy-server
Fleetbase Upgrade to PHP 8.2 and use FrankenPHP & Caddy
2024-02-06 15:19:25 +08:00
Ronald A. Richardson
e588242cb9 Merge branch 'feature/caddy-server' of github.com:fleetbase/fleetbase into feature/caddy-server 2024-02-06 15:18:25 +08:00
Ronald A. Richardson
58600a357a Merge branch 'dev-v0.4.0' into feature/caddy-server 2024-02-06 15:15:27 +08:00
Ron
4dd8a7b2ff Merge pull request #198 from fleetbase/feature/organizations-page-for-admin
Organizations page for admin
2024-02-06 15:12:04 +08:00
Ron
54803909a4 Merge pull request #197 from fleetbase/dashboard
customizable widget based dashboard
2024-02-06 15:11:32 +08:00
Ronald A. Richardson
e437ee04fb preparing for next big release 2024-02-06 15:08:11 +08:00
TemuulenBM
80d2ebb544 deleted company-user model 2024-02-06 15:00:28 +08:00
TemuulenBM
300e157bc1 fixed router.js 2024-02-06 14:33:22 +08:00
Ronald A. Richardson
26509008dc upgrade dependencies full upgrades completed for l10 php8.2 2024-02-06 14:30:18 +08:00
TemuulenBM
4119eb1717 fixed conflicts 2024-02-06 14:14:39 +08:00
Ronald A. Richardson
27661a3888 include core-api patch 2024-02-06 13:09:42 +08:00
Ronald A. Richardson
a4f69409fd remove reference to internal and private packages 2024-02-05 19:39:22 +08:00
Ronald A. Richardson
da9caf57f1 fix composer lockfiles 2024-02-05 19:37:34 +08:00
Ronald A. Richardson
acfa34b09f copy composer lockfile during build 2024-02-05 19:15:09 +08:00
Ronald A. Richardson
356b5076e5 removed composer-auth.json secret usage and move to using auth key env variable in builds 2024-02-05 19:10:42 +08:00
Ronald A. Richardson
038382928b oops fixed a typo 2024-02-05 19:09:16 +08:00
Ronald A. Richardson
f459f2e7e3 fix cd for docker-bake.hcl 2024-02-05 19:07:04 +08:00
Ronald A. Richardson
7f9b09f673 fix docker bake build for cd 2024-02-05 19:04:42 +08:00
Ronald A. Richardson
440040fecb made github auth token environment variable for docker build 2024-02-05 19:01:20 +08:00
Turtuvshin
bc31bf4c4c Refactor dashboard service to handle default dashboard creation 2024-02-05 18:34:54 +08:00
Ronald A. Richardson
def361c2af fixed docker setup for deployment 2024-02-05 18:34:24 +08:00
TemuulenBM
be382fcbd3 added translation 2024-02-05 16:35:44 +08:00
Turtuvshin
f42de06dcf Refactor widget position update logic 2024-02-05 14:38:37 +08:00
Turtuvshin
dc2b4e1aee Fix widget position update bug 2024-02-05 14:19:24 +08:00
Turtuvshin
c7348766df set min width and height 2024-02-05 13:35:38 +08:00
Turtuvshin
e67149db89 fixed default dashboard actions and remove widget function 2024-02-05 13:35:00 +08:00
Turtuvshin
4765bcfbd9 fixed gridstack item remove 2024-02-05 13:33:38 +08:00
TemuulenBM
019be89e06 fixed router and rewrite route as a standart 2024-02-05 11:45:24 +08:00
Eugene Dementyev
db0c56d8f0 Fix dumpautoload 2024-02-04 19:45:16 +13:00
Eugene Dementyev
8de660d51a Fix the deploy script. Change the cd accordingly.
Reformat the action file
2024-02-04 19:27:20 +13:00
Ronald A. Richardson
67f22aafbe retry workflow with absolute path deploy script 2024-02-03 18:40:28 +08:00
Ronald A. Richardson
1ff89ca16a try to debug ecs-tool run dir 2024-02-03 18:37:11 +08:00
Ronald A. Richardson
c6777efb2d use new app dir in httpd container 2024-02-03 18:23:47 +08:00
Ronald A. Richardson
7d1f594f87 update Dockerfile to not copy submodule packages as well as update cd with absolute path for the deploy script 2024-02-03 18:06:56 +08:00
Ron
da6485987a Merge pull request #199 from ekini/feature/caddy-server
feature/caddy server
2024-02-03 13:46:30 +08:00
Eugene Dementyev
b623d613f1 Fixup httpd config and Caddyfile 2024-02-03 12:04:35 +13:00
Turtuvshin
d1a77c95d0 fixed grid item change events 2024-02-02 20:51:48 +08:00
Ronald A. Richardson
bc7c6c12ad set port on proxy pass to 8000 2024-02-02 18:11:26 +08:00
TemuulenBM
50bfe55583 created Organizations page for admin 2024-02-02 18:04:43 +08:00
Ronald A. Richardson
bd1a61912f added back httpd container to use proxy_pass to frankenphp/octane until nginx container can be removed from infra 2024-02-02 13:30:56 +08:00
Ronald A. Richardson
9d49730d52 updated dashboard ui/ux and updated universe method names in implementation 2024-02-02 12:02:58 +08:00
Ronald A. Richardson
fd38f2bef6 remove .DS_Store files 2024-02-02 10:44:47 +08:00
Ronald A. Richardson
0fa3a25d59 removed accidental adds 2024-02-02 10:43:52 +08:00
Ronald A. Richardson
0917d7cce9 merged w/ latest 2024-02-02 10:38:05 +08:00
Turtuvshin
d33aa21418 removed yarn lock 2024-02-02 10:33:44 +08:00
Ron
e8f5638cad Merge pull request #192 from fleetbase/dev-v0.3.10
v0.3.10
2024-02-01 20:05:22 +08:00
Ronald A. Richardson
e216f11f7c all dependencies up to date 2024-02-01 19:57:40 +08:00
Ronald A. Richardson
41064be1ff fixed up for release 2024-02-01 19:28:40 +08:00
Ron
ae17ccb199 Merge pull request #195 from ekini/fix/socketcluster_port
Helm: Fix the socketcluster port to fix broadcasting
2024-02-01 19:14:54 +08:00
Ronald A. Richardson
0fbf901c9d Merge branch 'dev-v0.3.10' of github.com:fleetbase/fleetbase into dev-v0.3.10 2024-02-01 19:12:42 +08:00
Ronald A. Richardson
00806d4f0c checking in comments implementation 2024-02-01 19:11:17 +08:00
TemuulenBM
683353517d fixed conflict 2024-02-01 18:25:57 +08:00
TemuulenBM
27b1af6c40 fixed conflict 2024-02-01 18:25:10 +08:00
Turtuvshin
ab8cbf9ea6 submodule changes 2024-02-01 18:19:02 +08:00
Temuulen
e8249adddd Merge pull request #196 from fleetbase/feature/organizations-page-for-admin
Feature/organizations page for admin
2024-02-01 18:13:44 +08:00
Turtuvshin
b2c44842ce changed composer 2024-02-01 18:08:36 +08:00
Turtuvshin
f9e6c8d50d refactor dashboard components 2024-02-01 18:01:46 +08:00
TemuulenBM
6cd0625753 Refactor user model retrieval
This commit refactors the way the user model is retrieved in the
organization-users.js file. Instead of using findAll, it now uses
query to filter users based on the company_id. This change was
necessary to improve the performance of the user retrieval process
and to ensure that only relevant users are returned (#1234).
2024-02-01 18:01:35 +08:00
Ron
21ea3f5644 Merge branch 'dev-v0.3.10' into feature/organizations-page-for-admin 2024-02-01 13:37:06 +08:00
TemuulenBM
727b2e399f merged 2024-02-01 13:34:35 +08:00
TemuulenBM
ec913f82d7 Merge branch 'main' of github.com:fleetbase/fleetbase into feature/organizations-page-for-admin 2024-02-01 13:31:03 +08:00
Turtuvshin
9bb2ea15e0 Update widget panel styling and add icons to available widgets 2024-02-01 13:17:49 +08:00
Ronald A. Richardson
575e4e0952 update docker-bake file to build without httpd 2024-01-31 17:40:33 +08:00
Ronald A. Richardson
f2058e0d58 Working version w/ added queue for docker development 2024-01-31 17:36:28 +08:00
Turtuvshin
9669e917ab Add logic to automatically enable edit mode when current dashboard has no widgets 2024-01-31 16:39:20 +08:00
Turtuvshin
2b6a200811 Update grid options for dashboard components 2024-01-31 16:33:37 +08:00
Turtuvshin
1d92764958 Add dashboard metric component and initialize widgets 2024-01-31 15:56:39 +08:00
Turtuvshin
13db00c39f Refactor widget configurations in initialize widgets 2024-01-31 13:47:45 +08:00
Ronald A. Richardson
eedeb8f209 add user timezone to onboard create account request 2024-01-31 11:15:14 +08:00
Turtuvshin
bac95cca00 disabled to resize without editing 2024-01-31 11:06:21 +08:00
Turtuvshin
520e9771b4 switch dashboard 2024-01-31 01:37:59 +08:00
Ronald A. Richardson
75742de7ac configured for l10x and octane 2024-01-30 20:13:16 +08:00
Ronald A. Richardson
8628695b0b working with laravel octane 2024-01-30 20:07:22 +08:00
Turtuvshin
74fd369854 Fix dashboard component and initialize widget options
This commit fixes an issue in the dashboard component where a redundant line of code was removed. Additionally, the initialize-widgets file was updated to include title and value options for various dashboard components.
2024-01-30 18:53:04 +08:00
Turtuvshin
5d43df0e1b Add dashboard and dashboard widget serializers 2024-01-30 17:48:56 +08:00
Turtuvshin
c96a3eb2bf Add delete functionality to dashboard component 2024-01-30 16:01:59 +08:00
Turtuvshin
4424ed1754 Update dashboard create and widget-panel templates 2024-01-30 16:01:46 +08:00
Turtuvshin
6c8b09db61 improved ui 2024-01-30 14:15:42 +08:00
Turtuvshin
8d5e649646 create dashboard 2024-01-30 13:43:42 +08:00
Turtuvshin
6844e61dd4 add, remove, edit widgets 2024-01-29 18:28:53 +08:00
Eugene Dementyev
7acf97a5e0 Helm: Fix the socketcluster port to fix broadcasting 2024-01-27 11:06:25 +13:00
Ronald A. Richardson
6a68c85d94 configured and setup to run api using frankenphp/Caddyserver 2024-01-26 18:39:02 +08:00
Ron
914a5abacb Merge pull request #193 from fleetbase/feature/reset-password
fixed reset-password flow
2024-01-26 15:42:14 +08:00
TemuulenBM
fdcd3bb805 fixed reset-password flow 2024-01-26 14:50:27 +08:00
Ronald A. Richardson
5a4d6846b5 improved accoutn verification with ability to manually trigger resend of code 2024-01-26 14:41:36 +08:00
Turtuvshin
2e8a6de7ea Add dashboard widget model and update dashboard model 2024-01-26 01:33:05 +08:00
Ron
f52c1a17b8 Merge pull request #191 from fleetbase/dev-v0.3.9
v0.3.9
2024-01-25 20:04:33 +08:00
Ronald A. Richardson
c44e9186d5 ready for release 2024-01-25 20:04:01 +08:00
Ronald A. Richardson
02408b3a12 Merge branch 'dev-v0.3.10' of github.com:fleetbase/fleetbase into dev-v0.3.10 2024-01-25 19:38:55 +08:00
Ronald A. Richardson
a3d3cb05cf preparing for next release 2024-01-25 19:38:20 +08:00
Ron
604365fc5f Merge pull request #188 from ekini/feature/helm_services
Add scheduler and events to deployments
2024-01-25 19:12:39 +08:00
Ron
5d47dc676f Merge pull request #190 from fleetbase/fix-onboard-form
Fix onboard form
2024-01-25 19:11:58 +08:00
Ronald A. Richardson
50b58a5955 preparing next release 2024-01-25 19:10:17 +08:00
Munkh-erdene Damdinbazar
948db173c9 fixed verify email 2024-01-25 15:53:27 +08:00
Munkh-erdene Damdinbazar
4f56e04166 fixed onboard translations 2024-01-25 15:25:32 +08:00
Eugene Dementyev
d9705bf4f4 Add scheduler and events to deployments 2024-01-25 20:05:42 +13:00
Ron
5535067d87 Merge pull request #186 from fleetbase/dev-v0.3.8
v0.3.8
2024-01-24 18:25:53 +08:00
Ronald A. Richardson
aab4e9f1f6 remove incomplete mongolian translations 2024-01-24 18:22:24 +08:00
Ronald A. Richardson
43329a0ed2 bump package verison v0.3.8 2024-01-24 18:15:10 +08:00
Ronald A. Richardson
427816d2dd fix submodules, update dependency lockfiles 2024-01-24 18:14:48 +08:00
Ronald A. Richardson
3d9d5cbe9d Merge branch 'dev-v0.3.8' of github.com:fleetbase/fleetbase into dev-v0.3.8 2024-01-24 15:54:25 +08:00
Ronald A. Richardson
3fc5bdb32e hotfix organization 2fa settings as should not display method selection 2024-01-24 15:53:18 +08:00
Munkh-erdene Damdinbazar
a60f75655d Merge branch 'dev-v0.3.8' of github.com:fleetbase/fleetbase into dev-v0.3.8 2024-01-24 14:46:46 +08:00
Munkh-erdene Damdinbazar
0984af400a fixed some typo errors on templates and translation file 2024-01-24 14:45:21 +08:00
Ronald A. Richardson
7f900fe218 now using fleetbase intl lint module 2024-01-24 14:31:17 +08:00
Ronald A. Richardson
3aaf382384 added intl linter for console 2024-01-24 11:46:16 +08:00
Ronald A. Richardson
f589b1cf0a added intl linter script to console 2024-01-24 11:44:26 +08:00
Ronald A. Richardson
bce1cbf22d increase veirification timeout before recommending resend 2024-01-24 11:42:28 +08:00
Ron
6327603857 Merge pull request #187 from fleetbase/hotfix-s3deploy-dockerfile
Hotfix s3deploy dockerfile
2024-01-24 11:09:55 +08:00
Ronald A. Richardson
7204ddb3a9 Upgrade the console dockerfile to use node 18, patch the .s3deploy file to set correct cache-control header for json and xml files 2024-01-24 11:07:32 +08:00
Turtuvshin
3a72cacc5c fixed gridstack 2024-01-23 18:56:45 +08:00
Munkh-erdene Damdinbazar
2bc9745b95 add missing translation 2024-01-23 11:51:46 +08:00
Turtuvshin
fc1e610a54 fixed widget panel 2024-01-22 19:14:34 +08:00
Ron
4a2b3e094f Merge pull request #178 from fleetbase/feature-intl
feature: Internationalization
2024-01-22 18:51:23 +08:00
Ronald A. Richardson
313906d36a added locale switcher to change language of fleetbase 2024-01-22 18:50:09 +08:00
Ronald A. Richardson
d1d5b87c21 merged with latest changes for next release 2024-01-22 17:17:31 +08:00
Ronald A. Richardson
8dc7d9ff87 Improved the app styling of enforcement alert 2024-01-22 17:00:28 +08:00
TemuulenBM
008faa1ca7 corrected based on request 2024-01-22 16:20:13 +08:00
TemuulenBM
6aab30b358 remove all ds store files 2024-01-22 15:26:36 +08:00
Temuulen
30ab3aab09 Merge pull request #170 from fleetbase/feature-2FA
feature: 2FA
2024-01-22 14:54:41 +08:00
TemuulenBM
df3c93803d merged 2fa with latest release 2024-01-22 14:52:56 +08:00
TemuulenBM
3d1e20439f fixed styling for two-fa enforcement alert 2024-01-22 14:46:38 +08:00
TemuulenBM
646f10713f Merge branch 'feature-2FA' of github.com:fleetbase/fleetbase into feature-2FA 2024-01-19 20:09:25 +08:00
TemuulenBM
5db723b003 Created two-fa-enforcement component 2024-01-19 20:04:27 +08:00
Ron
74770883fe Merge pull request #185 from fleetbase/dev-v0.3.7
v0.3.7
2024-01-19 19:51:33 +08:00
Ronald A. Richardson
3ebedab90a keep CACHE_DRIVER=null for docker build 2024-01-19 19:48:19 +08:00
Ronald A. Richardson
d0864e822b keep Dockerfile php 7.4 2024-01-19 19:44:11 +08:00
Ronald A. Richardson
f8b564acc9 upgraded dependencies with critical patches 2024-01-19 19:40:46 +08:00
Ronald A. Richardson
fd604c99e0 Critical patches for user verification during onboard and driver creation and loign 2024-01-19 19:27:25 +08:00
Ron
bc0ba3e3fb Merge pull request #184 from fleetbase/dev-v0.3.6
v0.3.6
2024-01-18 19:10:39 +08:00
Ronald A. Richardson
ecbbe002cc updated router.js 2024-01-18 19:10:15 +08:00
Ronald A. Richardson
1f068a890a fix translation file in console 2024-01-18 19:02:16 +08:00
Ronald A. Richardson
3aa365e7ef almost ready for release 2024-01-18 18:59:53 +08:00
Ronald A. Richardson
bb1444dc31 improved and enforced email verification flows 2024-01-18 16:42:42 +08:00
TemuulenBM
09996a4398 Completed validate and change password flow for account
Succesfully implemented Organization Auth settings that is enforces all users to enable or disable 2fa
2024-01-17 19:23:03 +08:00
Bayarbold8
22043a53e3 restore to main storefront 2024-01-17 15:53:00 +08:00
Bayarbold8
acde54c6ae merged with latest 2024-01-17 15:52:23 +08:00
Bayarbold8
e6961089ca iam-engine storefront finished 2024-01-17 14:54:11 +08:00
Ronald A. Richardson
880facdaef merged with latest 2024-01-17 13:55:15 +08:00
Ronald A. Richardson
87c1a56fd1 fix enforce toggle action 2024-01-17 12:14:19 +08:00
Bayarbold8
dba816463f storefront and iam-engine completed 2024-01-17 11:48:56 +08:00
Ronald A. Richardson
270371ce9c refactor for two auth flow and settings 2024-01-16 18:52:52 +08:00
Ronald A. Richardson
9f37b15d8a few patches for 2fa implementation 2024-01-15 18:36:31 +08:00
Turtuvshin
59f01832ef added grid stack 2024-01-15 17:30:56 +08:00
TemuulenBM
3ac3ad97f3 updated router.map and added tests 2024-01-15 17:12:44 +08:00
Ronald A. Richardson
ad067bd32c merged and updated to latest v0.3.5 2024-01-15 16:52:54 +08:00
TemuulenBM
9bd0cc17d9 Latest push 2024-01-15 16:13:58 +08:00
Ron
fc947d833a Merge pull request #181 from fleetbase/dev-v0.3.5
v0.3.6
2024-01-12 18:39:09 +08:00
Ronald A. Richardson
ff159a04ee upgraded dependencies to latest versions which contain critical patches for API 2024-01-12 18:31:29 +08:00
TemuulenBM
c5ac611000 Tried to verify after verification code is sent 2024-01-12 18:14:24 +08:00
Bayarbold8
863e27bd7b storefront translation finished 2024-01-11 15:32:49 +08:00
TemuulenBM
63c9bc0880 verified resend code 2024-01-10 18:06:44 +08:00
Bayarbold8
6183378717 fixed some mistakes 2024-01-10 13:47:23 +08:00
TemuulenBM
ea35a6f81f Succesfully implemented verify-code process 2024-01-09 18:44:13 +08:00
TemuulenBM
5fb4851544 implemented countdown component in two-fa controller template and succesfully sent sms to user 2024-01-08 18:04:43 +08:00
TemuulenBM
e348b02611 Created 2fa validate session 2024-01-05 18:01:52 +08:00
mm3ddd
3f779969c3 created more translation keys 2024-01-04 18:12:14 +08:00
TemuulenBM
9a23c64dde updated login function within 2fa 2024-01-04 18:06:40 +08:00
mm3ddd
b2098d0cb8 added translation keys for install and invite for user 2024-01-04 13:27:28 +08:00
TemuulenBM
850cc1e20d Fixed 2FA Config component 2024-01-03 17:58:17 +08:00
Ronald A. Richardson
6dd7ca401c complete i18n for auth routes 2024-01-03 17:56:59 +08:00
Ronald A. Richardson
fa51d03cfd (fix) use correct translation key in forgot password route 2024-01-03 17:35:15 +08:00
Ronald A. Richardson
092ebf0589 updated translation file, added translation key for forgot password route 2024-01-03 17:29:18 +08:00
TemuulenBM
d314964776 updated 2fa page 2023-12-26 17:52:25 +08:00
TemuulenBM
9c1655167d created frontend for saving 2023-12-25 18:05:22 +08:00
TemuulenBM
16e59f3465 Created 2FA page 2023-12-21 18:02:09 +08:00
TemuulenBM
f9d362b1be Created Authentication component for 2FA config 2023-12-20 18:00:35 +08:00
221 changed files with 19819 additions and 6745 deletions

View File

@@ -14,6 +14,7 @@ concourse/
infra/*
vagrant/*
docker/Dockerfile
docker/database/
deploy/*
media/*
data/*
@@ -23,4 +24,4 @@ docker-compose-prod.yml
docker-compose.yml
$virtualenv.tar.gz
$node_modules.tar.gz
docker-compose.override.yml
docker-compose.override.yml

View File

@@ -2,14 +2,15 @@ name: Fleetbase CI/CD
on:
push:
branches: [ "deploy/*" ]
branches: ["deploy/*"]
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
group: ${{ github.ref }}
cancel-in-progress: true
env:
PROJECT: ${{ secrets.PROJECT }}
GITHUB_AUTH_KEY: ${{ secrets._GITHUB_AUTH_TOKEN }}
jobs:
build_service:
@@ -17,59 +18,52 @@ jobs:
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
contents: read # This is required for actions/checkout
steps:
- name: Checkout Code
uses: actions/checkout@v3
with:
submodules: recursive
- name: Checkout Code
uses: actions/checkout@v3
with:
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Set Dynamic ENV Vars
run: |
- name: Set Dynamic ENV Vars
run: |
SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_NUMBER }}:role/${{ env.PROJECT }}-${{ env.STACK }}-deployer
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_NUMBER }}:role/${{ env.PROJECT }}-${{ env.STACK }}-deployer
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Prepare Composer Auth Secret
run: |
if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
echo '{"github-oauth": {"github.com": "'${{ secrets._GITHUB_AUTH_TOKEN }}'"}}' > composer-auth.json
else
echo '{}' > composer-auth.json
fi
- name: Build and Release
uses: docker/bake-action@v2
env:
REGISTRY: ${{ steps.login-ecr.outputs.registry }}/${{ env.PROJECT }}-${{ env.STACK }}
VERSION: ${{ env.VERSION }}
GITHUB_AUTH_KEY: ${{ env.GITHUB_AUTH_KEY }}
CACHE: type=gha
with:
push: true
files: |
./docker-bake.hcl
- name: Build and Release
uses: docker/bake-action@v2
env:
REGISTRY: ${{ steps.login-ecr.outputs.registry }}/${{ env.PROJECT }}-${{ env.STACK }}
VERSION: ${{ env.VERSION }}
CACHE: type=gha
with:
push: true
files: |
./docker-bake.hcl
- name: Download ecs-tool
run: |
- name: Download ecs-tool
run: |
wget -O ecs-tool.tar.gz https://github.com/springload/ecs-tool/releases/download/1.9.6/ecs-tool_1.9.6_linux_amd64.tar.gz && tar -xvf ecs-tool.tar.gz ecs-tool
- name: Deploy the images 🚀
run: |-
- name: Deploy the images 🚀
run: |-
set -eu
# run deploy.sh script before deployments
env "ECS_RUN.SERVICE=app" "ECS_RUN.LAUNCH_TYPE=FARGATE" ./ecs-tool run -l "ecs-tool" --image_tag '{container_name}-${{ env.VERSION }}' --cluster ${{ env.PROJECT }}-${{ env.STACK }} --task_definition ${{ env.PROJECT }}-${{ env.STACK }}-app --container_name app ./deploy.sh
@@ -81,29 +75,29 @@ jobs:
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
contents: read # This is required for actions/checkout
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: true
- name: Checkout
uses: actions/checkout@v3
with:
submodules: true
- name: Set Dynamic ENV Vars
run: |
- name: Set Dynamic ENV Vars
run: |
SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_NUMBER }}:role/${{ env.PROJECT }}-${{ env.STACK }}-deployer
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_NUMBER }}:role/${{ env.PROJECT }}-${{ env.STACK }}-deployer
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Get infra-provided configuration
run: |
- name: Get infra-provided configuration
run: |
set -eu
wget -O- https://github.com/springload/ssm-parent/releases/download/1.8.0/ssm-parent_1.8.0_linux_amd64.tar.gz | tar xvzf - ssm-parent
@@ -112,52 +106,52 @@ jobs:
# remove double quotes and pipe into the env
cat /tmp/dotenv.file | sed -e 's/"//g' >> $GITHUB_ENV
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 8
run_install: false
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 8
run_install: false
- name: Get pnpm Store Directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- name: Get pnpm Store Directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm Cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- uses: actions/cache@v3
name: Setup pnpm Cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Check for _GITHUB_AUTH_TOKEN and create .npmrc
run: |
if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
echo "//npm.pkg.github.com/:_authToken=${{ secrets._GITHUB_AUTH_TOKEN }}" > .npmrc
fi
working-directory: ./console
- name: Check for _GITHUB_AUTH_TOKEN and create .npmrc
run: |
if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
echo "//npm.pkg.github.com/:_authToken=${{ secrets._GITHUB_AUTH_TOKEN }}" > .npmrc
fi
working-directory: ./console
- name: Install dependencies
run: pnpm install
working-directory: ./console
- name: Install dependencies
run: pnpm install
working-directory: ./console
- name: Build
run: |
set -eu
- name: Build
run: |
set -eu
pnpm build
working-directory: ./console
- name: Deploy Console 🚀
run: |
pnpm build --environment production
working-directory: ./console
- name: Deploy Console 🚀
run: |
set -u
DEPLOY_BUCKET=${STATIC_DEPLOY_BUCKET:-${{ env.PROJECT }}-${{ env.STACK }}}

170
.github/workflows/eks-cd.yml vendored Normal file
View File

@@ -0,0 +1,170 @@
name: Fleetbase EKS CI/CD
on:
push:
branches: ["eksdeploy/*"]
concurrency:
group: ${{ github.ref }}
cancel-in-progress: true
env:
PROJECT: ${{ secrets.PROJECT }}
GITHUB_AUTH_KEY: ${{ secrets._GITHUB_AUTH_TOKEN }}
jobs:
build_service:
name: Build and Deploy the Service
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
steps:
- name: Checkout Code
uses: actions/checkout@v3
with:
submodules: recursive
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Set Dynamic ENV Vars
run: |
SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.EKS_DEPLOYER_ROLE }}
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build and Release
uses: docker/bake-action@v2
env:
REGISTRY: ${{ steps.login-ecr.outputs.registry }}/${{ env.PROJECT }}-${{ env.STACK }}
VERSION: ${{ env.VERSION }}
GITHUB_AUTH_KEY: ${{ env.GITHUB_AUTH_KEY }}
CACHE: type=gha
with:
push: true
files: |
./docker-bake.hcl
- name: Update kube config
run: aws eks update-kubeconfig --name ${{ secrets.EKS_CLUSTER_NAME }} --region ${{ secrets.AWS_REGION }}
- name: Deploy the images 🚀
env:
REGISTRY: ${{ steps.login-ecr.outputs.registry }}/${{ env.PROJECT }}-${{ env.STACK }}
run: |-
set -eu
# run deploy.sh script before deployments
helm upgrade -i ${{ env.PROJECT }} infra/helm -n ${{ env.PROJECT}}-${{ env.STACK }} --set image.repository=${{ env.REGISTRY }} \
--set image.tag=${{ env.VERSION }} --set 'api_host=${{ secrets.API_HOST }}' --set 'socketcluster_host=${{ secrets.SOCKETCLUSTER_HOST }}' \
--set gcp=false --set 'ingress.annotations.kubernetes\.io/ingress\.class=null' --set 'ingress.annotations.alb\.ingress\.kubernetes\.io/scheme=internet-facing' \
--set serviceAccount.name=default --set serviceAccount.create=false --set ingress.className=alb \
--set 'ingress.annotations.alb\.ingress\.kubernetes\.io/listen-ports=[{"HTTPS":443}]' \
--set service.type=NodePort
build_frontend:
name: Build and Deploy the Console
needs: [build_service]
runs-on: ubuntu-latest
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: true
- name: Set Dynamic ENV Vars
run: |
SHORT_COMMIT=$(echo $GITHUB_SHA | cut -c -8)
echo "VERSION=${SHORT_COMMIT}" >> $GITHUB_ENV
echo "STACK=$(basename $GITHUB_REF)" >> $GITHUB_ENV
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: ${{ secrets.EKS_DEPLOYER_ROLE }}
role-session-name: github
aws-region: ${{ secrets.AWS_REGION }}
- name: Get infra-provided configuration
run: |
set -eu
wget -O- https://github.com/springload/ssm-parent/releases/download/1.8.0/ssm-parent_1.8.0_linux_amd64.tar.gz | tar xvzf - ssm-parent
./ssm-parent -n /actions/${{ env.PROJECT }}/${{ env.STACK }}/configuration dotenv /tmp/dotenv.file
# remove double quotes and pipe into the env
cat /tmp/dotenv.file | sed -e 's/"//g' >> $GITHUB_ENV
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
- uses: pnpm/action-setup@v2
name: Install pnpm
id: pnpm-install
with:
version: 8
run_install: false
- name: Get pnpm Store Directory
id: pnpm-cache
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm Cache
with:
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Check for _GITHUB_AUTH_TOKEN and create .npmrc
run: |
if [[ -n "${{ secrets._GITHUB_AUTH_TOKEN }}" ]]; then
echo "//npm.pkg.github.com/:_authToken=${{ secrets._GITHUB_AUTH_TOKEN }}" > .npmrc
fi
working-directory: ./console
- name: Install dependencies
run: pnpm install
working-directory: ./console
- name: Build
env:
API_HOST: ${{ secrets.API_HOST }}
SOCKETCLUSTER_HOST: ${{ secrets.SOCKETCLUSTER_HOST }}
SOCKETCLUSTER_PORT: "443" # it uses common ingress so port 443
run: |
set -eu
pnpm build --environment production
working-directory: ./console
- name: Deploy Console 🚀
run: |
set -u
DEPLOY_BUCKET=${STATIC_DEPLOY_BUCKET:-${{ env.PROJECT }}-${{ env.STACK }}}
# this value will come from the dotenv above
echo "Deploying to $DEPLOY_BUCKET"
wget -O- https://github.com/bep/s3deploy/releases/download/v2.11.0/s3deploy_2.11.0_linux-amd64.tar.gz | tar xzv -f - s3deploy
./s3deploy -region ${AWS_REGION} -source console/dist -bucket ${DEPLOY_BUCKET}

View File

@@ -173,7 +173,7 @@ jobs:
run: |
set -eu
pnpm build
pnpm build --environment production
working-directory: ./console
- name: Deploy Console 🚀

1
.gitignore vendored
View File

@@ -27,6 +27,7 @@ verdaccio/storage
packages/billing
packages/flespi
packages/loconav
packages/internals
packages/projectargus-engine
# wip
packages/solid

View File

@@ -7,7 +7,11 @@ routes:
headers:
Cache-Control: "max-age=600, no-transform, public"
gzip: false
- route: "^.+\\.(html|xml|json)$"
- route: "^.+\\.(xml|json)$"
headers:
Cache-Control: "max-age=600, no-transform, public"
gzip: true
- route: "^.+\\.(html)$"
headers:
Cache-Control: "public, max-age=0, must-revalidate"
gzip: true

11
COMMERCIAL_LICENSE.md Normal file
View File

@@ -0,0 +1,11 @@
FLEETBASE DUAL LICENSE
COPYRIGHT (C) 2024 FLEETBASE PTE LTD.
PERMISSION IS HEREBY GRANTED, FREE OF CHARGE, TO ANY PERSON OBTAINING A COPY OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO USE THE SOFTWARE FOR NON-COMMERCIAL PURPOSES ONLY. NON-COMMERCIAL PURPOSES INCLUDE INTERNAL OPERATIONS, ACADEMIC RESEARCH, PERSONAL PROJECTS, OR ANY OTHER USE THAT IS NOT INTENDED FOR COMMERCIAL GAIN.
FOR VERSIONS 0.4.10 ONWARDS, YOU ARE PERMITTED TO USE THE SOFTWARE FOR NON-COMMERCIAL PURPOSES FREE OF CHARGE. HOWEVER, COMMERCIAL USE OF THIS SOFTWARE, INCLUDING BUT NOT LIMITED TO BUILDING SAAS PLATFORMS, OFFERING SERVICES TO THIRD PARTIES, OR INTEGRATING WITH COMMERCIAL PRODUCTS, REQUIRES THE PURCHASE OF A COMMERCIAL LICENSE FROM FLEETBASE PTE LTD.
FOR INQUIRIES REGARDING COMMERCIAL LICENSING OR ANY OTHER QUESTIONS RELATED TO FLEETBASE, PLEASE CONTACT HELLO@FLEETBASE.IO.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

12
Caddyfile Normal file
View File

@@ -0,0 +1,12 @@
{
frankenphp
order php_server before file_server
}
http://:8000 {
root * /fleetbase/api/public
encode zstd gzip
php_server {
resolve_root_symlink
}
}

21
LICENSE
View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 Fleetbase Pte Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

21
LICENSE.md Normal file
View File

@@ -0,0 +1,21 @@
MIT LICENSE
COPYRIGHT (C) 2023 FLEETBASE PTE LTD
PERMISSION IS HEREBY GRANTED, FREE OF CHARGE, TO ANY PERSON OBTAINING A COPY
OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO DEAL
IN THE SOFTWARE WITHOUT RESTRICTION, INCLUDING WITHOUT LIMITATION THE RIGHTS
TO USE, COPY, MODIFY, MERGE, PUBLISH, DISTRIBUTE, SUBLICENSE, AND/OR SELL
COPIES OF THE SOFTWARE, AND TO PERMIT PERSONS TO WHOM THE SOFTWARE IS
FURNISHED TO DO SO, SUBJECT TO THE FOLLOWING CONDITIONS:
THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN ALL
COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
api/.gitignore vendored
View File

@@ -13,4 +13,7 @@ npm-debug.log
yarn-error.log
/.idea
/.vscode
.composer.dev.json
.composer.dev.json
/caddy
frankenphp
frankenphp-worker.php

View File

@@ -16,7 +16,7 @@ class Kernel extends HttpKernel
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,

View File

@@ -8,37 +8,30 @@
],
"license": "MIT",
"require": {
"php": "^7.3|^8.0",
"fleetbase/core-api": "^1.3.5",
"fleetbase/fleetops-api": "^0.3.7",
"fleetbase/storefront-api": "^0.2.5",
"fleetbase/billing-api": "^0.0.5",
"fruitcake/laravel-cors": "^2.0",
"php": "^8.0",
"fleetbase/core-api": "^1.4.16",
"fleetbase/fleetops-api": "^0.4.24",
"fleetbase/storefront-api": "^0.3.7",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.75",
"laravel/sanctum": "^2.11",
"laravel/tinker": "^2.5",
"league/flysystem-aws-s3-v3": "^1.0",
"laravel/framework": "^10.0",
"laravel/octane": "^2.3",
"laravel/tinker": "^2.9",
"league/flysystem-aws-s3-v3": "^3.0",
"maatwebsite/excel": "^3.1",
"phpoffice/phpspreadsheet": "^1.28",
"predis/predis": "^2.1",
"psr/http-factory-implementation": "*"
"psr/http-factory-implementation": "*",
"s-ichikawa/laravel-sendgrid-driver": "^4.0"
},
"require-dev": {
"facade/ignition": "^2.5",
"spatie/laravel-ignition": "^2.0",
"fakerphp/faker": "^1.9.1",
"kitloong/laravel-migrations-generator": "^6.10",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^5.10",
"phpunit/phpunit": "^9.5.10"
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.0"
},
"repositories": [
{
"type": "vcs",
"url": "git@github.com:fleetbase/billing.git"
}
],
"autoload": {
"psr-4": {
"App\\": "app/",
@@ -91,6 +84,7 @@
}
},
"config": {
"secure-http": false,
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
@@ -98,6 +92,6 @@
"php-http/discovery": true
}
},
"minimum-stability": "dev",
"minimum-stability": "stable",
"prefer-stable": true
}

8573
api/composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -21,13 +21,13 @@ return [
'allowed_methods' => ['*'],
'allowed_origins' => array_filter(['http://localhost:4200', env('CONSOLE_HOST'), Utils::addWwwToUrl(env('CONSOLE_URL'))]),
'allowed_origins' => array_filter(['http://localhost:4200', env('CONSOLE_HOST'), Utils::addWwwToUrl(env('CONSOLE_HOST'))]),
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'exposed_headers' => ['x-compressed-json', 'access-console-sandbox', 'access-console-sandbox-key'],
'max_age' => 0,

View File

@@ -13,7 +13,7 @@ return [
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
'default' => env('FILESYSTEM_DRIVER', 'public'),
/*
|--------------------------------------------------------------------------
@@ -58,6 +58,7 @@ return [
'bucket' => env('GOOGLE_CLOUD_STORAGE_BUCKET', env('AWS_BUCKET')),
'path_prefix' => env('GOOGLE_CLOUD_STORAGE_PATH_PREFIX', null),
'storage_api_uri' => env('GOOGLE_CLOUD_STORAGE_API_URI', env('AWS_URL')),
'visibility_handler' => \League\Flysystem\GoogleCloudStorage\UniformBucketLevelAccessVisibility::class,
],
],

223
api/config/octane.php Normal file
View File

@@ -0,0 +1,223 @@
<?php
use Laravel\Octane\Contracts\OperationTerminated;
use Laravel\Octane\Events\RequestHandled;
use Laravel\Octane\Events\RequestReceived;
use Laravel\Octane\Events\RequestTerminated;
use Laravel\Octane\Events\TaskReceived;
use Laravel\Octane\Events\TaskTerminated;
use Laravel\Octane\Events\TickReceived;
use Laravel\Octane\Events\TickTerminated;
use Laravel\Octane\Events\WorkerErrorOccurred;
use Laravel\Octane\Events\WorkerStarting;
use Laravel\Octane\Events\WorkerStopping;
use Laravel\Octane\Listeners\CollectGarbage;
use Laravel\Octane\Listeners\DisconnectFromDatabases;
use Laravel\Octane\Listeners\EnsureUploadedFilesAreValid;
use Laravel\Octane\Listeners\EnsureUploadedFilesCanBeMoved;
use Laravel\Octane\Listeners\FlushOnce;
use Laravel\Octane\Listeners\FlushTemporaryContainerInstances;
use Laravel\Octane\Listeners\FlushUploadedFiles;
use Laravel\Octane\Listeners\ReportException;
use Laravel\Octane\Listeners\StopWorkerIfNecessary;
use Laravel\Octane\Octane;
return [
/*
|--------------------------------------------------------------------------
| Octane Server
|--------------------------------------------------------------------------
|
| This value determines the default "server" that will be used by Octane
| when starting, restarting, or stopping your server via the CLI. You
| are free to change this to the supported server of your choosing.
|
| Supported: "roadrunner", "swoole", "frankenphp"
|
*/
'server' => env('OCTANE_SERVER', 'frankenphp'),
/*
|--------------------------------------------------------------------------
| Force HTTPS
|--------------------------------------------------------------------------
|
| When this configuration value is set to "true", Octane will inform the
| framework that all absolute links must be generated using the HTTPS
| protocol. Otherwise your links may be generated using plain HTTP.
|
*/
'https' => env('OCTANE_HTTPS', false),
/*
|--------------------------------------------------------------------------
| Octane Listeners
|--------------------------------------------------------------------------
|
| All of the event listeners for Octane's events are defined below. These
| listeners are responsible for resetting your application's state for
| the next request. You may even add your own listeners to the list.
|
*/
'listeners' => [
WorkerStarting::class => [
EnsureUploadedFilesAreValid::class,
EnsureUploadedFilesCanBeMoved::class,
],
RequestReceived::class => [
...Octane::prepareApplicationForNextOperation(),
...Octane::prepareApplicationForNextRequest(),
//
],
RequestHandled::class => [
//
],
RequestTerminated::class => [
// FlushUploadedFiles::class,
],
TaskReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],
TaskTerminated::class => [
//
],
TickReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],
TickTerminated::class => [
//
],
OperationTerminated::class => [
FlushOnce::class,
FlushTemporaryContainerInstances::class,
// DisconnectFromDatabases::class,
// CollectGarbage::class,
],
WorkerErrorOccurred::class => [
ReportException::class,
StopWorkerIfNecessary::class,
],
WorkerStopping::class => [
//
],
],
/*
|--------------------------------------------------------------------------
| Warm / Flush Bindings
|--------------------------------------------------------------------------
|
| The bindings listed below will either be pre-warmed when a worker boots
| or they will be flushed before every new request. Flushing a binding
| will force the container to resolve that binding again when asked.
|
*/
'warm' => [
...Octane::defaultServicesToWarm(),
],
'flush' => [
//
],
/*
|--------------------------------------------------------------------------
| Octane Swoole Tables
|--------------------------------------------------------------------------
|
| While using Swoole, you may define additional tables as required by the
| application. These tables can be used to store data that needs to be
| quickly accessed by other workers on the particular Swoole server.
|
*/
'tables' => [
'example:1000' => [
'name' => 'string:1000',
'votes' => 'int',
],
],
/*
|--------------------------------------------------------------------------
| Octane Swoole Cache Table
|--------------------------------------------------------------------------
|
| While using Swoole, you may leverage the Octane cache, which is powered
| by a Swoole table. You may set the maximum number of rows as well as
| the number of bytes per row using the configuration options below.
|
*/
'cache' => [
'rows' => 1000,
'bytes' => 10000,
],
/*
|--------------------------------------------------------------------------
| File Watching
|--------------------------------------------------------------------------
|
| The following list of files and directories will be watched when using
| the --watch option offered by Octane. If any of the directories and
| files are changed, Octane will automatically reload your workers.
|
*/
'watch' => [
'app',
'bootstrap',
'config',
'database',
'public/**/*.php',
'resources/**/*.php',
'routes',
'composer.lock',
'.env',
],
/*
|--------------------------------------------------------------------------
| Garbage Collection Threshold
|--------------------------------------------------------------------------
|
| When executing long-lived PHP scripts such as Octane, memory can build
| up before being cleared by PHP. You can force Octane to run garbage
| collection if your application consumes this amount of megabytes.
|
*/
'garbage' => 50,
/*
|--------------------------------------------------------------------------
| Maximum Execution Time
|--------------------------------------------------------------------------
|
| The following setting configures the maximum execution time for requests
| being handled by Octane. You may set this value to 0 to indicate that
| there isn't a specific time limit on Octane request execution time.
|
*/
'max_execution_time' => 30,
];

View File

@@ -1,4 +1,4 @@
#!/bin/bash
#!/bin/sh
# Exit the script as soon as a command fails
set -e
@@ -13,4 +13,10 @@ php artisan migrate --force
php artisan sandbox:migrate --force
# Seed database
php artisan fleetbase:seed
php artisan fleetbase:seed
# Restart queue
php artisan queue:restart
# Sync scheduler
php artisan schedule-monitor:sync

5622
api/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -30,7 +30,7 @@ module.exports = {
'ember/no-empty-glimmer-component-classes': 'off',
'ember/no-get': 'off',
'ember/classic-decorator-no-classic-methods': 'off',
'node/no-unpublished-require': [
'n/no-unpublished-require': [
'error',
{
allowModules: [

1
console/.gitignore vendored
View File

@@ -4,6 +4,7 @@
# dependencies
/node_modules/
/scripts/node_modules/
# misc
/.env*

View File

@@ -1,5 +1,8 @@
'use strict';
module.exports = {
extends: ['stylelint-config-standard', 'stylelint-prettier/recommended'],
extends: ['stylelint-config-standard', 'stylelint-prettier/recommended'],
rules: {
'import-notation': null,
},
};

View File

@@ -6,7 +6,6 @@ module.exports = {
'no-bare-strings': 'off',
'no-invalid-interactive': 'off',
'no-yield-only': 'off',
'no-down-event-binding': 'off',
'table-groups': 'off',
'link-href-attributes': 'off',
'require-input-label': 'off',

View File

@@ -1,5 +1,5 @@
# ---- Build Stage ----
FROM node:16.20-alpine AS builder
FROM node:18.15.0-alpine AS builder
# Set the working directory in the container to /app
WORKDIR /app
@@ -8,6 +8,9 @@ WORKDIR /app
RUN mkdir -p ~/.pnpm
ENV PNPM_HOME /root/.pnpm
# Set environment
ARG ENVIRONMENT=production
# Add the pnpm global bin to the PATH
ENV PATH /root/.pnpm/bin:$PATH
@@ -33,7 +36,7 @@ RUN pnpm install
COPY console .
# Build the application
RUN pnpm build
RUN pnpm build --environment $ENVIRONMENT
# ---- Serve Stage ----
FROM nginx:alpine

View File

@@ -14,7 +14,7 @@ export default class App extends Application {
async ready() {
const extensions = await loadExtensions();
this.extensions = extensions;
this.engines = mapEngines(extensions);
}

View File

@@ -0,0 +1 @@
{{yield}}

View File

@@ -0,0 +1,3 @@
import Component from '@glimmer/component';
export default class Configure2faComponent extends Component {}

View File

@@ -7,6 +7,31 @@
<InputGroup @name="S3 URL" @value={{this.s3Url}} disabled={{this.isLoading}} />
<InputGroup @name="S3 Endpoint" @value={{this.s3Endpoint}} disabled={{this.isLoading}} />
{{/if}}
{{#if (eq this.driver "gcs")}}
{{#if this.isGoogleCloudStorageEnvConfigued}}
<div class="border border-yellow-900 shadow-sm rounded-lg bg-yellow-200 mb-4">
<div class="px-3 py-2 text-sm text-yellow-900 flex items-center">
<FaIcon @icon="triangle-exclamation" @size="md" class="mr-1.5" />
Warning! GCS is already configured in the server environment. Changing values below may break this.
</div>
</div>
{{/if}}
<InputGroup @name="GCS Bucket" @value={{this.gcsBucket}} disabled={{this.isLoading}} />
<InputGroup @name="GCS Service Account Key File" @wrapperClass="">
<div class="flex flex-row items-center mb-0i">
<UploadButton @name="firebase-service-account" @accept="text/plain,text/javascript,application/json" @onFileAdded={{this.uploadGcsCredentialsFile}} @buttonText="Upload Service Account JSON" @icon="upload" class="w-auto m-0i mt-0i" />
{{#if this.gcsCredentialsFile}}
<div class="ml-2.5 text-sm dark:text-white text-black flex flex-row items-center border border-blue-500 rounded-lg px-2 py-0.5 -mt-1">
<FaIcon @icon="file-text" @size="sm" class="mr-2 dark:text-white text-black" />
<span>{{this.gcsCredentialsFile.original_filename}}</span>
<a href="javascript:;" class="text-red-500 ml-2" {{on "click" this.removeGcsCredentialsFile}}>
<FaIcon @icon="times" class="text-red-500" />
</a>
</div>
{{/if}}
</div>
</InputGroup>
{{/if}}
{{#if this.testResponse}}
<div class="animate-pulse flex flex-row items-center rounded-lg border {{if (eq this.testResponse.status 'error') 'border-red-900 bg-red-800 text-red-100' 'border-green-900 bg-green-800 text-green-100'}} shadow-sm my-2 px-4 py-2">
<FaIcon @icon={{if (eq this.testResponse.status 'error') 'triangle-exclamation' 'circle-check'}} class="mr-1.5 {{if (eq this.testResponse.status 'error') 'text-red-200' 'text-green-200'}}" />

View File

@@ -6,6 +6,7 @@ import { action } from '@ember/object';
export default class ConfigureFilesystemComponent extends Component {
@service fetch;
@service notifications;
@service currentUser;
@tracked isLoading = false;
@tracked testResponse;
@tracked disks = [];
@@ -13,6 +14,10 @@ export default class ConfigureFilesystemComponent extends Component {
@tracked s3Bucket = null;
@tracked s3Url = null;
@tracked s3Endpoint = null;
@tracked gcsBucket = null;
@tracked gcsCredentialsFileId = null;
@tracked gcsCredentialsFile = null;
@tracked isGoogleCloudStorageEnvConfigued = false;
/**
* Creates an instance of ConfigureFilesystemComponent.
@@ -59,6 +64,8 @@ export default class ConfigureFilesystemComponent extends Component {
url: this.s3Url,
endpoint: this.s3Endpoint,
},
gcsCredentialsFileId: this.gcsCredentialsFileId,
gcsBucket: this.gcsBucket,
})
.then(() => {
this.notifications.success('Filesystem configuration saved.');
@@ -82,4 +89,31 @@ export default class ConfigureFilesystemComponent extends Component {
this.isLoading = false;
});
}
@action removeGcsCredentialsFile() {
this.gcsCredentialsFileId = undefined;
this.gcsCredentialsFile = undefined;
}
@action uploadGcsCredentialsFile(file) {
try {
this.fetch.uploadFile.perform(
file,
{
path: 'gcs',
subject_uuid: this.currentUser.companyId,
subject_type: 'company',
type: 'gcs_credentials',
},
(uploadedFile) => {
console.log('uploadedFile', uploadedFile);
this.gcsCredentialsFileId = uploadedFile.id;
this.gcsCredentialsFile = uploadedFile;
console.log('this.gcsCredentialsFile', this.gcsCredentialsFile);
}
);
} catch (error) {
this.notifications.serverError(error);
}
}
}

View File

@@ -6,7 +6,7 @@
<Textarea class="form-input w-full" @value={{this.apn.private_key_content}} placeholder="APN Private Key" rows="10" disabled={{this.isLoading}} />
</InputGroup> --}}
<InputGroup @wrapperClass="flex flex-row items-center">
<UploadButton @name="apn-key" @accept="text/plain,application/x-pem-file,application/x-pkcs12,application/x-x509-ca-cert,.p12,.pem,.p8" @onFileAdded={{this.uploadApnKey}} @buttonText="Upload P8 Key File" @uploadIcon="upload" class="w-auto m-0i mt-0i" />
<UploadButton @name="apn-key" @accept="text/plain,application/x-pem-file,application/x-pkcs12,application/x-x509-ca-cert,.p12,.pem,.p8" @onFileAdded={{this.uploadApnKey}} @buttonText="Upload P8 Key File" @icon="upload" class="w-auto m-0i mt-0i" />
{{#if this.apn.private_key_file}}
<div class="ml-2.5 text-sm dark:text-white text-black flex flex-row items-center border border-blue-500 rounded-lg px-2 py-0.5 -mt-1">
<FaIcon @icon="file-text" @size="sm" class="mr-2 dark:text-white text-black" />
@@ -15,16 +15,32 @@
</div>
{{/if}}
</InputGroup>
<InputGroup>
<InputGroup @wrapperClass="mb-0i">
<Checkbox @label="APN Production" @value={{this.apn.production}} @onToggle={{fn (mut this.apn.production)}} @disabled={{this.isLoading}} />
</InputGroup>
</ContentPanel>
<ContentPanel @title="Firebase Configutation" @open={{true}} @pad={{true}} @panelBodyClass="bg-white dark:bg-gray-800">
<InputGroup @wrapperClass="flex flex-row items-center mb-0i">
<UploadButton @name="firebase-service-account" @accept="text/plain,text/javascript,application/json" @onFileAdded={{this.uploadFirebaseCredentials}} @buttonText="Upload Service Account JSON" @icon="upload" class="w-auto m-0i mt-0i" />
{{#if this.firebase.credentials_file}}
<div class="ml-2.5 text-sm dark:text-white text-black flex flex-row items-center border border-blue-500 rounded-lg px-2 py-0.5 -mt-1">
<FaIcon @icon="file-text" @size="sm" class="mr-2 dark:text-white text-black" />
<span>{{this.firebase.credentials_file.original_filename}}</span>
<a href="javascript:;" class="text-red-500 ml-2" {{on "click" this.removeFirebaseCredentialsFile}}><FaIcon @icon="times" class="text-red-500" /></a>
</div>
{{/if}}
</InputGroup>
</ContentPanel>
<ContentPanel @title="Test Push Notification" @open={{true}} @pad={{true}} @panelBodyClass="bg-white dark:bg-gray-900">
{{#if this.testResponse}}
<div class="animate-pulse flex flex-row items-center rounded-lg border {{if (eq this.testResponse.status 'error') 'border-red-900 bg-red-800 text-red-100' 'border-green-900 bg-green-800 text-green-100'}} shadow-sm my-2 px-4 py-2">
<FaIcon @icon={{if (eq this.testResponse.status 'error') 'triangle-exclamation' 'circle-check'}} class="mr-1.5 {{if (eq this.testResponse.status 'error') 'text-red-200' 'text-green-200'}}" />
<span class="text-xs">{{this.this.testResponse.message}}</span>
</div>
{{/if}}
<div class="mt-3 rounded-lg bg-gray-900 shadow-inner p-3">
<div class="">
<div class="flex flex-col space-y-2">
<div class="flex flex-row items-center">
<div class="text-sm w-40">Title:</div>
@@ -47,6 +63,8 @@
</div>
</ContentPanel>
<Spacer @height="300px" />
<EmberWormhole @to="next-view-section-subheader-actions">
<Button @type="primary" @size="sm" @icon="save" @text="Save Changes" @onClick={{this.save}} @disabled={{this.isLoading}} @isLoading={{this.isLoading}} />
</EmberWormhole>

View File

@@ -18,14 +18,13 @@ export default class ConfigureNotificationChannelsComponent extends Component {
team_id: '',
app_bundle_id: '',
private_key_path: '',
_private_key_path: '',
private_key_file_id: '',
private_key_file: null,
production: true,
};
@tracked fcm = {
firebase_credentials_json: '',
firebase_database_url: '',
firebase_project_name: '',
@tracked firebase = {
credentials: '',
};
constructor() {
@@ -38,26 +37,36 @@ export default class ConfigureNotificationChannelsComponent extends Component {
apnConfig.private_key_file = null;
apnConfig.private_key_file_id = '';
apnConfig.private_key_path = '';
apnConfig._private_key_path = '';
this.apn = apnConfig;
}
@action removeFirebaseCredentialsFile() {
const firebaseConfig = this.firebase;
firebaseConfig.credentials_file = null;
firebaseConfig.credentials_file_id = '';
firebaseConfig.credentials = '';
this.firebase = firebaseConfig;
}
@action uploadApnKey(file) {
try {
this.fetch.uploadFile.perform(
file,
{
disk: 'local',
path: `apn`,
path: 'apn',
subject_uuid: this.currentUser.companyId,
subject_type: `company`,
type: `apn_key`,
subject_type: 'company',
type: 'apn_key',
},
(uploadedFile) => {
const apnConfig = this.apn;
apnConfig.private_key_file = uploadedFile;
apnConfig.private_key_file_id = uploadedFile.id;
apnConfig.private_key_path = uploadedFile.path;
apnConfig._private_key_path = uploadedFile.path;
this.apn = apnConfig;
}
@@ -67,6 +76,30 @@ export default class ConfigureNotificationChannelsComponent extends Component {
}
}
@action uploadFirebaseCredentials(file) {
try {
this.fetch.uploadFile.perform(
file,
{
path: 'firebase',
subject_uuid: this.currentUser.companyId,
subject_type: 'company',
type: 'firebase_credentials',
},
(uploadedFile) => {
const firebaseConfig = this.firebase;
firebaseConfig.credentials_file = uploadedFile;
firebaseConfig.credentials_file_id = uploadedFile.id;
firebaseConfig.credentials_file_path = uploadedFile.path;
this.firebase = firebaseConfig;
}
);
} catch (error) {
this.notifications.serverError(error);
}
}
@action setConfigValues(config) {
for (const key in config) {
if (this[key] !== undefined) {
@@ -94,9 +127,13 @@ export default class ConfigureNotificationChannelsComponent extends Component {
const apnConfig = this.apn;
delete apnConfig.private_key_file;
const firebaseConfig = this.firebase;
delete firebaseConfig.credentials_file;
this.fetch
.post('settings/notification-channels-config', {
apn: apnConfig,
firebase: firebaseConfig,
})
.then(() => {
this.notifications.success("Notification channel's configuration saved.");
@@ -112,6 +149,7 @@ export default class ConfigureNotificationChannelsComponent extends Component {
this.fetch
.post('settings/test-notification-channels-config', {
apn: this.apn,
firebase: this.firebase,
title: this.testTitle,
message: this.testMessage,
apnToken: this.apnToken,

View File

@@ -0,0 +1 @@
<div id="console-wormhole" />

View File

@@ -1,7 +1,99 @@
<div class="fleetbase-dashboard-grid">
<div class="grid grid-cols-1 md:grid-cols-12 gap-4">
{{#each this.dashboards as |dashboard index|}}
<Dashboard::Create @index={{index}} @dashboard={{dashboard}} />
{{/each}}
<div class="fleetbase-dashboard-grid flex items-center justify-between mb-4 mt-6 px-14">
<div class="left-section">
<h1 class="text-lg font-bold">{{this.dashboard.currentDashboard.name}}</h1>
</div>
<div class="fleetbase-dashboard-actions right-section ml-4 flex items-center">
<div class="fleetbase-model-select fleetbase-power-select ember-model-select h-10">
<DropdownButton
class="h-10"
@text={{if this.dashboard.currentDashboard.name this.dashboard.currentDashboard.name (t "component.dashboard.select-dashboard")}}
@textClass="text-sm mr-2"
@buttonClass="flex-row-reverse w-44 justify-between"
@icon="caret-down"
@iconClass="mr-0i"
@size="sm"
@iconPrefix="fas"
@triggerClass="hidden md:flex"
as |dd|
>
<div class="next-dd-menu mt-1 mx-0" aria-labelledby="user-menu">
<div class="p-1">
{{#each this.dashboard.dashboards as |dashboard|}}
<a href="javascript:;" class="next-dd-item" {{on "click" (dropdown-fn dd this.selectDashboard dashboard)}}>
<div class="flex-1 flex flex-row items-center">
<div class="w-6">
<FaIcon @icon="desktop" />
</div>
<span>{{dashboard.name}}</span>
</div>
<div>
{{#if (eq this.dashboard.currentDashboard.id dashboard.id)}}
<FaIcon @icon="check" class="text-green-500" />
{{/if}}
</div>
</a>
{{/each}}
</div>
</div>
</DropdownButton>
</div>
<div class="ml-2 relative h-10">
<DropdownButton class="h-10" @icon="ellipsis-h" @size="sm" @iconPrefix="fas" @triggerClass="hidden md:flex" as |dd|>
<div class="next-dd-menu mt-1 mx-0" aria-labelledby="user-menu">
<div class="p-1">
<a href="javascript:;" class="next-dd-item" {{on "click" (dropdown-fn dd this.createDashboard)}}>
<div class="w-6">
<FaIcon @icon="add" />
</div>
<span>{{t "component.dashboard.create-new-dashboard"}}</span>
</a>
{{#unless (eq this.dashboard.currentDashboard.user_uuid "system")}}
<a href="javascript:;" class="next-dd-item" {{on "click" (dropdown-fn dd this.onChangeEdit true)}}>
<div class="w-6">
<FaIcon @icon="edit" />
</div>
<span>{{t "component.dashboard.edit-layout"}}</span>
</a>
<a href="javascript:;" class="next-dd-item" {{on "click" (dropdown-fn dd this.onAddingWidget true)}}>
<div class="w-6">
<FaIcon @icon="add" />
</div>
<span>{{t "component.dashboard.add-widgets"}}</span>
</a>
<a href="javascript:;" class="next-dd-item" {{on "click" (dropdown-fn dd this.deleteDashboard this.dashboard.currentDashboard)}}>
<div class="w-6">
<FaIcon @icon="trash" />
</div>
<span>{{t "component.dashboard.delete-dashboard"}}</span>
</a>
{{/unless}}
</div>
</div>
</DropdownButton>
</div>
{{#if this.dashboard.isEditingDashboard}}
<div class="ml-2 h-10">
<Button @type="magic" @icon="save" @helpText={{t "component.dashboard.save-dashboard"}} @onClick={{fn this.onChangeEdit false}} class="h-10" />
</div>
{{/if}}
</div>
</div>
<div class="px-10">
<Dashboard::Create @isEdit={{this.dashboard.isEditingDashboard}} @isAddingWidget={{this.dashboard.isAddingWidget}} @dashboard={{this.dashboard.currentDashboard}} />
{{#if this.dashboard.isAddingWidget}}
<EmberWormhole @to="console-home-wormhole">
<Dashboard::WidgetPanel
@isOpen={{this.dashboard.isAddingWidget}}
@onLoad={{this.setWidgetSelectorPanelContext}}
@dashboard={{this.dashboard.currentDashboard}}
@onClose={{fn this.onAddingWidget false}}
/>
</EmberWormhole>
{{/if}}
</div>

View File

@@ -1,48 +1,140 @@
import Component from '@glimmer/component';
import loadExtensions from '@fleetbase/ember-core/utils/load-extensions';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isArray } from '@ember/array';
import { tracked } from '@glimmer/tracking';
import { task } from 'ember-concurrency-decorators';
import { inject as service } from '@ember/service';
/**
* DashboardComponent for managing dashboards in an Ember application.
* This component handles actions such as selecting, creating, deleting dashboards,
* and managing widget selectors and dashboard editing states.
*
* @extends Component
*/
export default class DashboardComponent extends Component {
@service fetch;
@tracked extensions;
@tracked dashboards = [];
@tracked isLoading;
/**
* Ember Data store service.
* @type {Service}
*/
@service store;
/**
* Internationalization service for managing translations.
* @type {Service}
*/
@service intl;
/**
* Notifications service for displaying alerts or confirmations.
* @type {Service}
*/
@service notifications;
/**
* Modals manager service for handling modal dialogs.
* @type {Service}
*/
@service modalsManager;
/**
* Fetch service for handling HTTP requests.
* @type {Service}
*/
@service fetch;
/**
* Dashboard service for business logic related to dashboards.
* @type {Service}
*/
@service dashboard;
/**
* Creates an instance of DashboardComponent.
* @memberof DashboardComponent
*/
constructor() {
super(...arguments);
this.loadExtensions();
this.dashboard.loadDashboards.perform();
}
@action async loadExtensions() {
this.extensions = await loadExtensions();
this.loadDashboardBuilds.perform();
/**
* Action to select a dashboard.
* @param {Object} dashboard - The dashboard to be selected.
*/
@action selectDashboard(dashboard) {
this.dashboard.selectDashboard.perform(dashboard);
}
@task *loadDashboard(extension) {
this.isLoading = extension.extension;
let dashboardBuild;
try {
dashboardBuild = yield this.fetch.get(extension.fleetbase.dashboard, {}, { namespace: '' });
} catch {
return;
}
if (isArray(dashboardBuild)) {
this.dashboards = [...this.dashboards, ...dashboardBuild.map((build) => ({ ...build, extension }))];
}
/**
* Sets the context for the widget selector panel.
* @param {Object} widgetSelectorContext - The context object for the widget selector.
*/
@action setWidgetSelectorPanelContext(widgetSelectorContext) {
this.widgetSelectorContext = widgetSelectorContext;
}
@task({ enqueue: true, maxConcurrency: 1 }) *loadDashboardBuilds() {
const extensionsWithDashboards = this.extensions.filter((extension) => typeof extension.fleetbase?.dashboard === 'string');
/**
* Creates a new dashboard.
* @param {Object} dashboard - The dashboard to be created.
* @param {Object} [options={}] - Optional parameters for dashboard creation.
*/
@action createDashboard(dashboard, options = {}) {
this.modalsManager.show('modals/create-dashboard', {
title: this.intl.t('component.dashboard.create-a-new-dashboard'),
acceptButtonText: this.intl.t('component.dashboard.confirm-create-dashboard'),
confirm: async (modal, done) => {
modal.startLoading();
for (let i = 0; i < extensionsWithDashboards.length; i++) {
const extension = extensionsWithDashboards[i];
yield this.loadDashboard.perform(extension);
// Get the name from the modal options
const { name } = modal.getOptions();
await this.dashboard.createDashboard.perform(name);
done();
},
...options,
});
}
/**
* Deletes a dashboard.
* @param {Object} dashboard - The dashboard to be deleted.
* @param {Object} [options={}] - Optional parameters for dashboard deletion.
*/
@action deleteDashboard(dashboard, options = {}) {
if (this.dashboard.dashboards?.length === 1) {
return this.notifications.error(this.intl.t('component.dashboard.you-cannot-delete-this-dashboard'));
}
this.modalsManager.confirm({
title: this.intl.t('component.dashboard.are-you-sure-you-want-delete-dashboard', { dashboardName: dashboard.name }),
confirm: async (modal, done) => {
modal.startLoading();
await this.dashboard.deleteDashboard.perform(dashboard);
done();
},
...options,
});
}
/**
* Action to handle the addition of a widget.
* @param {boolean} [state=true] - The state to set for adding a widget.
*/
@action onAddingWidget(state = true) {
this.dashboard.onAddingWidget(state);
}
/**
* Sets the current dashboard.
* @param {Object} dashboard - The dashboard to be set as current.
*/
@action setCurrentDashboard(dashboard) {
this.dashboard.setCurrentDashboard.perform(dashboard);
}
/**
* Changes the editing state of the dashboard.
* @param {boolean} [state=true] - The state to set for editing the dashboard.
*/
@action onChangeEdit(state = true) {
this.dashboard.onChangeEdit(state);
}
}

View File

@@ -1,6 +1,6 @@
<div class="dashboard-component-count lg:col-span-2">
<h3 class="text-sm dark:text-gray-100 text-black mb-4">{{@options.title}}</h3>
<h1 class="text-3xl font-bold dark:text-gray-100 text-black mb-4">
{{this.displayValue}}
<div class="dashboard-component-count lg:col-span-2 h-full {{@options.wrapperClass}}">
<h3 class="text-sm dark:text-gray-100 text-black mb-4 {{@options.titleClass}}">{{this.title}}</h3>
<h1 class="text-3xl font-bold dark:text-gray-100 text-black {{@options.valueClass}}">
{{this.value}}
</h1>
</div>

View File

@@ -1,5 +1,5 @@
import Component from '@glimmer/component';
import { computed } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import formatCurrency from '@fleetbase/ember-ui/utils/format-currency';
import formatMeters from '@fleetbase/ember-ui/utils/format-meters';
import formatBytes from '@fleetbase/ember-ui/utils/format-bytes';
@@ -7,11 +7,40 @@ import formatDuration from '@fleetbase/ember-ui/utils/format-duration';
import formatDate from '@fleetbase/ember-ui/utils/format-date';
export default class DashboardCountComponent extends Component {
@computed('args.options.{currency,dateFormat,format,value}') get displayValue() {
let format = this.args.options?.format;
let currency = this.args.options?.currency;
let dateFormat = this.args.options?.dateFormat;
let value = this.args.options?.value;
/**
* The title of the metric count.
*
* @memberof WidgetKeyMetricsCountComponent
*/
@tracked title;
/**
* The value to render
*
* @memberof WidgetKeyMetricsCountComponent
*/
@tracked value;
/**
* Creates an instance of WidgetKeyMetricsCountComponent.
* @param {EngineInstance} owner
* @param {Object} { options }
* @memberof WidgetKeyMetricsCountComponent
*/
constructor(owner, { options, title }) {
super(...arguments);
this.title = title;
this.createRenderValueFromOptions(options);
}
/**
* Creates the value to render using the options provided.
*
* @param {Object} [options={}]
* @memberof WidgetKeyMetricsCountComponent
*/
createRenderValueFromOptions(options = {}) {
let { format, currency, dateFormat, value } = options;
switch (format) {
case 'money':
@@ -38,6 +67,6 @@ export default class DashboardCountComponent extends Component {
break;
}
return value;
this.value = value;
}
}

View File

@@ -1,18 +1,14 @@
<div class="col-span-{{or @dashboard.size 12}}">
<div class="dashboard-title flex flex-col lg:flex-row lg:items-center">
<div class="flex flex-row items-center mb-2 lg:mb-0">
{{#if this.isLoading}}
<Spinner class="mr-2i" />
{{/if}}
<h2 class="text-sm font-bold dark:text-gray-100 text-black">{{@dashboard.title}}</h2>
</div>
<div>
<Dashboard::QueryParams @params={{@dashboard.queryParams}} @onChange={{this.onQueryParamsChanged}} />
</div>
</div>
<div class="grid grid-cols-2 lg:grid-cols-12 gap-4">
{{#each this.dashboard.widgets as |widget|}}
{{component (concat "dashboard/" widget.component) options=widget.options}}
<div class="fleetbase-dashboard-grid" ...attributes>
<GridStack @options={{this.gridOptions}} @onChange={{this.onChangeGrid}}>
{{#each @dashboard.widgets as |widget|}}
<GridStackItem id={{widget.id}} @options={{spread-widget-options (hash id=widget.id options=widget.grid_options)}} class="relative">
{{component widget.component options=widget.options}}
{{#if @isEdit}}
<div class="absolute top-2 right-2">
<Button @type="default" @icon="trash" @helpText={{"Remove widget from the dashboard"}} @onClick={{fn this.removeWidget widget}} />
</div>
{{/if}}
</GridStackItem>
{{/each}}
</div>
</GridStack>
</div>

View File

@@ -1,41 +1,99 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, computed } from '@ember/object';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isArray } from '@ember/array';
import { task } from 'ember-concurrency-decorators';
/**
* Component responsible for creating and managing the dashboard layout.
* Provides functionalities such as toggling widget float, changing grid layout, and removing widgets.
*
* @extends Component
*/
export default class DashboardCreateComponent extends Component {
@service fetch;
@tracked isLoading = false;
@tracked dashboard;
/**
* Notifications service for displaying alerts or errors.
* @type {Service}
*/
@service notifications;
constructor() {
super(...arguments);
this.dashboard = this.args.dashboard;
/**
* Tracked array to keep track of widgets that have been updated.
* @type {Array}
*/
@tracked updatedWidgets = [];
/**
* Action to toggle the floating state of widgets on the grid.
*/
@action toggleFloat() {
this.shouldFloat = !this.shouldFloat;
}
@action onQueryParamsChanged(changedParams) {
this.reloadDashboard.perform(changedParams);
/**
* Handles changes to the grid layout, such as repositioning or resizing widgets.
* Iterates over each widget event detail and updates the corresponding widget's properties if necessary.
*
* @param {Event} event - Event containing details about the grid change.
* @action
*/
@action onChangeGrid(event) {
const { dashboard } = this.args;
event.detail.forEach((currentWidgetEvent) => {
const alreadyUpdated = this.updatedWidgets.find((item) => item.id === currentWidgetEvent.id);
if (alreadyUpdated || !this.dashboard) {
return;
}
const changedWidget = dashboard.widgets.find((widget) => widget.id === currentWidgetEvent.id);
if (!changedWidget) {
return;
}
const { x, y, w, h } = currentWidgetEvent;
const response = changedWidget.updateProperties({
grid_options: { x, y, w, h },
});
if (response) {
this.updatedWidgets.push(changedWidget);
}
});
}
@task *reloadDashboard(params) {
const { extension } = this.args.dashboard;
const index = this.args.index;
let dashboards = [];
/**
* Removes a specified widget from the dashboard.
* Performs a removal operation on the dashboard and handles any errors that occur during the process.
*
* @param {Object} widget - The widget object to be removed.
* @action
*/
@action removeWidget(widget) {
const { dashboard } = this.args;
this.isLoading = true;
try {
dashboards = yield this.fetch.get(extension.fleetbase.dashboard, params, { namespace: '' });
} catch {
return;
if (dashboard) {
dashboard.removeWidget(widget.id).catch((error) => {
this.notifications.serverError(error);
});
}
}
this.isLoading = false;
if (isArray(dashboards)) {
this.dashboard = dashboards.objectAt(index);
}
/**
* Computed property that returns grid options based on the current edit state.
* Configures grid behavior such as floating, animation, and drag and resize capabilities.
*
* @computed
* @returns {Object} An object containing grid configuration options.
*/
@computed('args.isEdit') get gridOptions() {
return {
float: true,
animate: true,
acceptWidgets: true,
alwaysShowResizeHandle: this.args.isEdit,
disableDrag: !this.args.isEdit,
disableResize: !this.args.isEdit,
resizable: { handles: 'all' },
cellHeight: 30,
};
}
}

View File

@@ -0,0 +1,18 @@
<div class="col-span-{{or @dashboard.size 12}}">
<div class="dashboard-title flex flex-col lg:flex-row lg:items-center">
<div class="flex flex-row items-center mb-2 lg:mb-0">
{{#if this.isLoading}}
<Spinner class="mr-2i" />
{{/if}}
<h2 class="text-sm font-bold dark:text-gray-100 text-black">{{this.dashboard.title}}</h2>
</div>
<div>
<Dashboard::QueryParams @params={{this.dashboard.queryParams}} @onChange={{this.onQueryParamsChanged}} />
</div>
</div>
<div class="grid grid-cols-2 lg:grid-cols-12 gap-4">
{{#each this.dashboard.widgets as |widget|}}
{{component (concat "dashboard/" widget.component) options=widget.options}}
{{/each}}
</div>
</div>

View File

@@ -0,0 +1,39 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { isArray } from '@ember/array';
import { task } from 'ember-concurrency-decorators';
export default class MetricComponent extends Component {
@service fetch;
@tracked isLoading = false;
@tracked dashboard;
constructor() {
super(...arguments);
this.loadDashboard.perform();
}
@action onQueryParamsChanged(changedParams) {
this.loadDashboard.perform(changedParams);
}
@task *loadDashboard(params) {
let dashboards = [];
this.isLoading = true;
try {
dashboards = yield this.fetch.get(this.args.options.endpoint, params, { namespace: '' });
} catch {
return;
}
this.isLoading = false;
if (isArray(dashboards)) {
this.dashboard = dashboards.objectAt(0);
}
}
}

View File

@@ -0,0 +1,31 @@
<Overlay @isOpen={{@isOpen}} @onLoad={{this.setOverlayContext}} @position="right" @noBackdrop={{true}} @fullHeight={{true}} @width={{or this.width @width "400px"}}>
<Overlay::Header @title={{t "component.dashboard-widget-panel.select-widgets"}} @hideStatusDot={{true}} @titleWrapperClass="leading-5">
<div class="flex flex-1 justify-end">
<Button @type="default" @icon="times" @helpText={{t "component.dashboard-widget-panel.close-and-save"}} @onClick={{this.onPressClose}} />
</div>
</Overlay::Header>
<Overlay::Body @wrapperClass="new-service-rate-overlay-body px-4 space-y-4 pt-4">
<div class="grid grid-cols-1 gap-4 text-xs dark:text-gray-100">
{{#each this.availableWidgets as |widget|}}
<div
class="rounded-lg border border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 transition-all duration-300 ease-in-out shadow-md px-4 py-2 cursor-pointer"
{{on "click" (fn this.addWidgetToDashboard widget)}}
>
<div class="flex flex-row items-center leading-6 mb-2.5">
<div class="w-8 flex items-center justify-start">
<FaIcon @icon={{widget.icon}} class="text-lg text-gray-600 dark:text-gray-300" />
</div>
<p class="text-sm truncate font-semibold dark:text-gray-100 text-gray-800">
{{t "component.dashboard-widget-panel.widget-name" widgetName=widget.name}}
</p>
</div>
<div>
<p class="text-xs dark:text-gray-100 text-gray-800">{{widget.description}}</p>
</div>
</div>
{{/each}}
</div>
<Spacer @height="300px" />
</Overlay::Body>
</Overlay>

View File

@@ -0,0 +1,60 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class DashboardWidgetPanelComponent extends Component {
@service universe;
@tracked availableWidgets = [];
@tracked dashboard;
@tracked isOpen = true;
@service notifications;
/**
* Constructs the component and applies initial state.
*/
constructor(owner, { dashboard }) {
super(...arguments);
this.availableWidgets = this.universe.getDashboardWidgets();
this.dashboard = dashboard;
}
/**
* Sets the overlay context.
*
* @action
* @param {OverlayContextObject} overlayContext
*/
@action setOverlayContext(overlayContext) {
this.context = overlayContext;
if (typeof this.args.onLoad === 'function') {
this.args.onLoad(...arguments);
}
}
@action addWidgetToDashboard(widget) {
// If widget is a component definition/class
if (typeof widget.component === 'function') {
widget.component = widget.component.name;
}
this.args.dashboard.addWidget(widget).catch((error) => {
this.notifications.serverError(error);
});
}
/**
* Handles cancel button press.
*
* @action
*/
@action onPressClose() {
this.isOpen = false;
if (typeof this.args.onClose === 'function') {
this.args.onClose();
}
}
}

View File

@@ -1,11 +1,15 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, computed } from '@ember/object';
import { computed } from '@ember/object';
import { isArray } from '@ember/array';
import { isBlank } from '@ember/utils';
import { task } from 'ember-concurrency';
import { storageFor } from 'ember-local-storage';
import { add, isPast } from 'date-fns';
import fetch from 'fetch';
export default class GithubCardComponent extends Component {
@storageFor('local-cache') localCache;
@tracked data;
@tracked tags;
@tracked isLoading = false;
@@ -30,29 +34,47 @@ export default class GithubCardComponent extends Component {
constructor() {
super(...arguments);
this.loadRepositoryData();
this.loadRepositoryTags();
this.getRepositoryData.perform();
this.getRepositoryTags.perform();
}
@action loadRepositoryData() {
this.isLoading = true;
@task *getRepositoryData() {
// Check if cached data and expiration are available
const cachedData = this.localCache.get('fleetbase-github-data');
const expiration = this.localCache.get('fleetbase-github-data-expiration');
return fetch('https://api.github.com/repos/fleetbase/fleetbase')
.then((response) => {
return response.json().then((data) => {
this.data = data;
});
})
.finally(() => {
this.isLoading = false;
});
// Check if the cached data is still valid
if (cachedData && expiration && !isPast(new Date(expiration))) {
// Use cached data
this.data = cachedData;
} else {
// Fetch new data
const response = yield fetch('https://api.github.com/repos/fleetbase/fleetbase');
if (response.ok) {
this.data = yield response.json();
this.localCache.set('fleetbase-github-data', this.data);
this.localCache.set('fleetbase-github-data-expiration', add(new Date(), { hours: 6 }));
}
}
}
@action loadRepositoryTags() {
return fetch('https://api.github.com/repos/fleetbase/fleetbase/tags').then((response) => {
return response.json().then((data) => {
this.tags = data;
});
});
@task *getRepositoryTags() {
// Check if cached tags and expiration are available
const cachedTags = this.localCache.get('fleetbase-github-tags');
const expiration = this.localCache.get('fleetbase-github-tags-expiration');
// Check if the cached tags are still valid
if (cachedTags && expiration && !isPast(new Date(expiration))) {
// Use cached tags
this.tags = cachedTags;
} else {
// Fetch new tags
const response = yield fetch('https://api.github.com/repos/fleetbase/fleetbase/tags');
if (response.ok) {
this.tags = yield response.json();
this.localCache.set('fleetbase-github-tags', this.tags);
this.localCache.set('fleetbase-github-tags-expiration', add(new Date(), { hours: 6 }));
}
}
}
}

View File

@@ -0,0 +1,30 @@
<div class="next-user-button" ...attributes>
<BasicDropdown @defaultClass={{@wrapperClass}} @onOpen={{@onOpen}} @onClose={{@onClose}} @verticalPosition={{@verticalPosition}} @horizontalPosition={{@horizontalPosition}} @renderInPlace={{or @renderInPlace true}} @initiallyOpened={{@initiallyOpened}} as |dd|>
<dd.Trigger class={{@triggerClass}}>
<div class="next-org-button-trigger flex-shrink-0 {{if dd.isOpen 'is-open'}}">
<FaIcon @icon="globe" @size="sm" />
</div>
</dd.Trigger>
<dd.Content class={{@contentClass}}>
<div class="next-dd-menu {{@dropdownMenuClass}} {{if dd.isOpen 'is-open'}}">
{{#each-in this.availableLocales as |key country|}}
<div class="px-1">
<a href="javascript:;" class="next-dd-item" {{on "click" (fn this.changeLocale key)}}>
<div class="flex flex-row items-center justify-between w-full">
<div class="flex-1">
<span class="mr-1">{{country.emoji}}</span>
<span>{{country.language}}</span>
</div>
{{#if (eq this.currentLocale key)}}
<div>
<FaIcon @icon="check" class="text-green-400" />
</div>
{{/if}}
</div>
</a>
</div>
{{/each-in}}
</div>
</dd.Content>
</BasicDropdown>
</div>

View File

@@ -0,0 +1,144 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { task } from 'ember-concurrency-decorators';
export default class LocaleSelectorComponent extends Component {
/**
* Inject the intl service.
*
* @memberof LocaleSelectorComponent
*/
@service intl;
/**
* Inject the intl service.
*
* @memberof LocaleSelectorComponent
*/
@service fetch;
/**
* Tracks all the available locales.
*
* @memberof LocaleSelectorComponent
*/
@tracked locales = [];
/**
* All available countries data.
*
* @memberof LocaleSelectorComponent
*/
@tracked countries = [];
/**
* The current locale in use.
*
* @memberof LocaleSelectorComponent
*/
@tracked currentLocale;
/**
* Creates an instance of LocaleSelectorComponent.
* @memberof LocaleSelectorComponent
*/
constructor() {
super(...arguments);
this.locales = this.intl.locales;
this.currentLocale = this.intl.primaryLocale;
this.loadAvailableCountries.perform();
// Check for locale change
this.intl.onLocaleChanged(() => {
this.currentLocale = this.intl.primaryLocale;
});
}
/**
* Handles the change of locale.
* @param {string} selectedLocale - The selected locale.
* @returns {void}
* @memberof LocaleSelectorComponent
* @method changeLocale
* @instance
* @action
*/
@action changeLocale(selectedLocale) {
this.currentLocale = selectedLocale;
this.intl.setLocale(selectedLocale);
// Persist to server
this.saveUserLocale.perform(selectedLocale);
}
/**
* Loads available countries asynchronously.
* @returns {void}
* @memberof LocaleSelectorComponent
* @method loadAvailableCountries
* @instance
* @task
* @generator
*/
@task *loadAvailableCountries() {
this.countries = yield this.fetch.get('lookup/countries', { columns: ['name', 'cca2', 'flag', 'emoji', 'languages'] });
this.availableLocales = this._createAvailableLocaleMap();
}
/**
* Saves the user's selected locale to the server.
* @param {string} locale - The user's selected locale.
* @returns {void}
* @memberof LocaleSelectorComponent
* @method saveUserLocale
* @instance
* @task
* @generator
*/
@task *saveUserLocale(locale) {
yield this.fetch.post('users/locale', { locale });
}
/**
* Creates a map of available locales.
* @private
* @returns {Object} - The map of available locales.
* @memberof LocaleSelectorComponent
* @method _createAvailableLocaleMap
* @instance
*/
_createAvailableLocaleMap() {
const localeMap = {};
for (let i = 0; i < this.locales.length; i++) {
const locale = this.locales.objectAt(i);
localeMap[locale] = this._findCountryDataForLocale(locale);
}
return localeMap;
}
/**
* Finds country data for a given locale.
* @private
* @param {string} locale - The locale to find country data for.
* @returns {Object|null} - The country data or null if not found.
* @memberof LocaleSelectorComponent
* @method _findCountryDataForLocale
* @instance
*/
_findCountryDataForLocale(locale) {
const localeCountry = locale.split('-')[1];
const country = this.countries.find((country) => country.cca2.toLowerCase() === localeCountry);
if (country) {
// get the language
country.language = Object.values(country.languages)[0];
}
return country;
}
}

View File

@@ -0,0 +1,5 @@
<Modal::Default @modalIsOpened={{@modalIsOpened}} @options={{@options}} @confirm={{@onConfirm}} @decline={{@onDecline}}>
<div class="modal-body-container">
<InputGroup @name="Dashboard name" @value={{@options.name}} @helpText="Enter the name of your dashboard" />
</div>
</Modal::Default>

View File

@@ -0,0 +1,13 @@
<Modal::Default @modalIsOpened={{@modalIsOpened}} @options={{@options}} @confirm={{@onConfirm}} @decline={{@onDecline}}>
<div class="px-5">
{{#if @options.body}}
<p class="dark:text-gray-400 text-gray-700 mb-4">{{@options.body}}</p>
{{/if}}
<InputGroup>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<InputGroup @name="Password" @type="password" @value={{this.password}} @wrapperClass="mb-0i" />
<InputGroup @name="Confirm Password" @type="password" @value={{this.confirmPassword}} @wrapperClass="mb-0i" />
</div>
</InputGroup>
</div>
</Modal::Default>

View File

@@ -0,0 +1,49 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default class ModalsValidatePasswordComponent extends Component {
@service fetch;
@service notifications;
@tracked options = {};
@tracked password;
@tracked confirmPassword;
constructor(owner, { options }) {
super(...arguments);
this.options = options;
this.setupOptions();
}
setupOptions() {
this.options.title = 'Validate Current Password';
this.options.acceptButtonText = 'Validate Password';
this.options.declineButtonHidden = true;
this.options.confirm = (modal) => {
modal.startLoading();
return this.validatePassword.perform();
};
}
@task *validatePassword() {
let isPasswordValid = false;
try {
yield this.fetch.post('users/validate-password', {
password: this.password,
password_confirmation: this.confirmPassword,
});
isPasswordValid = true;
} catch (error) {
this.notifications.serverError(error, 'Invalid current password.');
}
if (typeof this.options.onValidated === 'function') {
this.options.onValidated(isPasswordValid);
}
return isPasswordValid;
}
}

View File

@@ -0,0 +1,14 @@
{{#if this.shouldRender}}
<InfoBlock @icon="triangle-exclamation" class="two-fa-enforcement-alert bg-yellow-100 border-2 border-yellow-600 dark:border-yellow-500 rounded-lg py-3.5 px-5">
<div class="flex flex-row justify-between">
<div class="flex-1 pr-2">
<p class="text-sm dark:text-yellow-900 mb-2">
{{t "component.two-fa-enforcement-alert.message"}}
</p>
</div>
<div class="flex-shrink-0">
<Button id="two-fa-setup-button" @text={{t "component.two-fa-enforcement-alert.button-text"}} @icon="shield-halved" @type="warning" @buttonType="button" @onClick={{this.transitionToTwoFactorSettings}} />
</div>
</div>
</InfoBlock>
{{/if}}

View File

@@ -0,0 +1,74 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { task } from 'ember-concurrency-decorators';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
/**
* Glimmer component for handling notification enforcement.
*
* @class EnforceNotificationComponent
* @extends Component
*/
export default class TwoFaEnforcementAlertComponent extends Component {
/**
* Flag to determine whether the component should render or not.
*
* @property {boolean} shouldRender
* @default false
* @tracked
*/
@tracked shouldRender = false;
/**
* Ember Router service for transitioning between routes.
*
* @type {RouterService}
*/
@service router;
/**
* Fetch service for making HTTP requests.
*
* @property {FetchService} fetch
* @inject
*/
@service fetch;
/**
* Constructor method for the ConsoleAccountAuthController.
*
* @constructor
*/
constructor() {
super(...arguments);
this.checkTwoFactorEnforcement.perform();
}
/**
* Transition to the users auth page.
*
* @method transitionToTwoFa
* @memberof ConsoleHomeController
*/
@action transitionToTwoFactorSettings() {
this.router.transitionTo('console.account.auth');
}
@task *checkTwoFactorEnforcement() {
const shouldRender = yield this.fetch.get('two-fa/enforce').catch((error) => {
this.notifications.serverError(error);
});
/**
* Task to check whether two-factor authentication enforcement is required.
*
* @method checkTwoFactorEnforcement
* @memberof TwoFaEnforcementAlertComponent
* @task
*/
if (shouldRender) {
this.shouldRender = shouldRender.shouldEnforce;
}
}
}

View File

@@ -0,0 +1,31 @@
<div class="flex items-center space-x-4">
<label class="text-base font-medium">Enable Two-Factor Authentication</label>
<Toggle @isToggled={{this.isTwoFaEnabled}} @onToggle={{this.onTwoFaToggled}} />
</div>
{{#if this.isTwoFaEnabled}}
<div class="mt-6">
{{#if this.showEnforceOption}}
<div class="flex items-center space-x-4 mb-6">
<label class="text-base font-medium">Require Users to Set-Up 2FA</label>
<Toggle @isToggled={{this.isTwoFaEnforced}} @onToggle={{this.onTwoFaEnforcedToggled}} />
</div>
{{/if}}
{{#if this.showMethodSelection}}
<label class="text-base font-medium">Choose an authentication method</label>
<p class="text-sm text-gray-600 dark:text-gray-300 mt-1">In addition to your username and password, you'll have to enter a code (delivered via app or SMS) to sign in to your account</p>
{{#each @twoFaMethods as |method|}}
<div class="border rounded-lg px-4 py-3 mt-2 transition duration-300 {{if (eq this.selectedTwoFaMethod method.key) 'border-blue-500' 'border-gray-200 dark:border-gray-700'}}">
<input type="radio" name="2fa-method" id="{{method.name}}" checked={{eq this.selectedTwoFaMethod method.key}} {{on "change" (fn this.onTwoFaSelected method.key)}} />
<label for="{{method.name}}">
{{method.name}}
{{#if method.recommended}}
<span class="bg-blue-500 rounded-xl text-white px-2 py-1 ml-2 text-xs font-semibold">Recommended</span>
{{/if}}
<p class="text-sm text-gray-600 dark:text-gray-300 mt-1">{{method.description}}</p>
</label>
</div>
{{/each}}
{{/if}}
</div>
{{/if}}

View File

@@ -0,0 +1,169 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { isArray } from '@ember/array';
import { inject as service } from '@ember/service';
/**
* Default Two-Factor Authentication method when not explicitly selected.
*
* @property {string} DEFAULT_2FA_METHOD
* @private
*/
const DEFAULT_2FA_METHOD = 'email';
/**
* Glimmer component for managing Two-Factor Authentication settings.
*
* @class TwoFaSettingsComponent
* @extends Component
*/
export default class TwoFaSettingsComponent extends Component {
/**
* The fetch service for making HTTP requests.
*
* @property {Service} fetch
* @public
*/
@service fetch;
/**
* The notifications service for displaying user notifications.
*
* @property {Service} notifications
* @public
*/
@service notifications;
/**
* The currently selected Two-Factor Authentication method.
*
* @property {string} selectedTwoFaMethod
* @public
*/
@tracked selectedTwoFaMethod;
/**
* Indicates whether Two-Factor Authentication is currently enabled.
*
* @property {boolean} isTwoFaEnabled
* @public
*/
@tracked isTwoFaEnabled;
/**
* Indicates whether Two-Factor Authentication is required for all users.
*
* @property {boolean} isTwoFaEnforced
* @public
*/
@tracked isTwoFaEnforced;
/**
* Indicates whether the settings should render an option to `enforce`
* Enforce is a flag that indicates that users either under a company or system must setup 2FA.
*
* @property {boolean} showEnforceOption
* @public
*/
@tracked showEnforceOption;
/**
* Indicates whether the settings should render an option to select 2fa `mn=ethod`
* Method is a flag that indicates which method users can receive a 2FA code from.
*
* @property {boolean} showEnforceOption
* @public
*/
@tracked showMethodSelection;
/**
* Class constructor to initialize the component.
*
* @constructor
* @param {Object} owner - The owner of the component.
* @param {Object} options - Options passed during component instantiation.
* @param {Object} options.twoFaSettings - The current Two-Factor Authentication settings.
* @param {Array} options.twoFaMethods - Available Two-Factor Authentication methods.
*/
constructor(owner, { twoFaSettings, twoFaMethods, showEnforceOption, showMethodSelection = true }) {
super(...arguments);
const userSelectedMethod = isArray(twoFaMethods) ? twoFaMethods.find(({ key }) => key === twoFaSettings.method) : null;
this.showMethodSelection = showMethodSelection === true;
this.showEnforceOption = showEnforceOption === true;
this.isTwoFaEnabled = twoFaSettings.enabled === true;
this.isTwoFaEnforced = twoFaSettings.enforced === true;
this.selectedTwoFaMethod = userSelectedMethod ? userSelectedMethod.key : DEFAULT_2FA_METHOD;
}
/**
* Action handler for toggling Two-Factor Authentication.
*
* @method onTwoFaToggled
* @param {boolean} isTwoFaEnabled - Indicates whether Two-Factor Authentication is enabled.
* @return {void}
* @public
*/
@action onTwoFaToggled(isTwoFaEnabled) {
this.isTwoFaEnabled = isTwoFaEnabled;
if (isTwoFaEnabled) {
const recommendedMethod = isArray(this.args.twoFaMethods) ? this.args.twoFaMethods.find((method) => method.recommended) : null;
if (recommendedMethod) {
this.selectedTwoFaMethod = recommendedMethod.key;
}
} else {
this.selectedTwoFaMethod = null;
}
if (typeof this.args.onTwoFaToggled === 'function') {
this.args.onTwoFaToggled(...arguments);
}
if (typeof this.args.onTwoFaMethodSelected === 'function') {
this.args.onTwoFaMethodSelected(this.selectedTwoFaMethod);
}
}
/**
* Action handler for toggling Two-Factor Authentication.
*
* @method onTwoFaEnforcedToggled
* @param {boolean} isTwoFaEnforced - Indicates whether Two-Factor Authentication is enabled.
* @return {void}
* @public
*/
@action onTwoFaEnforcedToggled(isTwoFaEnforced) {
this.isTwoFaEnforced = isTwoFaEnforced;
if (typeof this.args.onTwoFaEnforcedToggled === 'function') {
this.args.onTwoFaEnforcedToggled(...arguments);
}
}
/**
* Action handler for selecting a Two-Factor Authentication method.
*
* @method onTwoFaSelected
* @param {string} method - The selected Two-Factor Authentication method.
* @return {void}
* @public
*/
@action onTwoFaSelected(method) {
this.selectedTwoFaMethod = method;
if (typeof this.args.onTwoFaMethodSelected === 'function') {
this.args.onTwoFaMethodSelected(...arguments);
}
}
@action onRequireUsersToSetUpToggled(isTwoFaEnforced) {
this.isTwoFaEnforced = isTwoFaEnforced;
if (typeof this.args.onTwoFaEnforcedToggled === 'function') {
this.args.onTwoFaEnforcedToggled(isTwoFaEnforced);
}
}
}

View File

@@ -18,6 +18,13 @@ export default class AuthForgotPasswordController extends Controller {
*/
@service notifications;
/**
* Inject the `intl` service
*
* @memberof AuthForgotPasswordController
*/
@service intl;
/**
* The email variable
*
@@ -55,7 +62,7 @@ export default class AuthForgotPasswordController extends Controller {
this.fetch
.post('auth/get-magic-reset-link', { email })
.then(() => {
this.notifications.success('Check your email to continue!');
this.notifications.success(this.intl.t('auth.forgot-password.success-message'));
this.isSent = true;
})
.catch((error) => {

View File

@@ -33,7 +33,6 @@ export default class AuthLoginController extends Controller {
*/
@service session;
/**
* Inject the `router` service
*
@@ -41,6 +40,20 @@ export default class AuthLoginController extends Controller {
*/
@service router;
/**
* Inject the `intl` service
*
* @var {Service}
*/
@service intl;
/**
* Inject the `fetch` service
*
* @var {Service}
*/
@service fetch;
/**
* Whether or not to remember the users session
*
@@ -97,29 +110,62 @@ export default class AuthLoginController extends Controller {
*/
@tracked failedAttempts = 0;
/**
* Authenticate the user
*
* @void
*/
@tracked token;
@action async login(event) {
// firefox patch
event.preventDefault();
// get user credentials
const { email, password, rememberMe } = this;
const { identity, password, rememberMe } = this;
// If no password error
if (!identity) {
return this.notifications.warning(this.intl.t('auth.login.no-identity-notification'));
}
// If no password error
if (!password) {
return this.notifications.warning(this.intl.t('auth.login.no-identity-notification'));
}
// start loader
this.set('isLoading', true);
// set where to redirect on login
this.setRedirect();
// send request to check for 2fa
try {
await this.session.authenticate('authenticator:fleetbase', { email, password }, rememberMe);
let { twoFaSession, isTwoFaEnabled } = await this.session.checkForTwoFactor(identity);
if (isTwoFaEnabled) {
return this.session.store
.persist({ identity })
.then(() => {
return this.router.transitionTo('auth.two-fa', { queryParams: { token: twoFaSession } }).then(() => {
this.reset('success');
});
})
.catch((error) => {
this.notifications.serverError(error);
this.reset('error');
throw error;
});
}
} catch (error) {
return this.notifications.serverError(error);
}
try {
await this.session.authenticate('authenticator:fleetbase', { identity, password }, rememberMe);
} catch (error) {
this.failedAttempts++;
// Handle unverified user
if (error.toString().includes('not verified')) {
return this.sendUserForEmailVerification(identity);
}
return this.failure(error);
}
@@ -146,6 +192,30 @@ export default class AuthLoginController extends Controller {
});
}
/**
* Creates an email verification session and transitions user to verification route.
*
* @param {String} email
* @return {Promise<Transition>}
* @memberof AuthLoginController
*/
sendUserForEmailVerification(email) {
return this.fetch.post('auth/create-verification-session', { email, send: true }).then(({ token }) => {
return this.session.store.persist({ email }).then(() => {
this.notifications.warning(this.intl.t('auth.login.unverified-notification'));
return this.router
.transitionTo('auth.verification', {
queryParams: {
token,
},
})
.then(() => {
this.reset('error');
});
});
});
}
/**
* Sets correct route to send user to after login.
*
@@ -185,7 +255,7 @@ export default class AuthLoginController extends Controller {
* @void
*/
slowConnection() {
this.notifications.error('Experiencing connectivity issues.');
this.notifications.error(this.intl.t('auth.login.slow-connection-message'));
}
/**

View File

@@ -1,7 +1,7 @@
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { task } from 'ember-concurrency';
export default class AuthResetPasswordController extends Controller {
/**
@@ -25,6 +25,13 @@ export default class AuthResetPasswordController extends Controller {
*/
@service router;
/**
* Inject the `intl` service
*
* @memberof AuthResetPasswordController
*/
@service intl;
/**
* The code param.
*
@@ -47,38 +54,23 @@ export default class AuthResetPasswordController extends Controller {
@tracked password_confirmation;
/**
* Loading stae of password reset.
* The reset password task.
*
* @memberof AuthResetPasswordController
*/
@tracked isLoading;
/**
* The reset password action.
*
* @memberof AuthResetPasswordController
*/
@action resetPassword(event) {
// firefox patch
@task *resetPassword(event) {
event.preventDefault();
const { code, password, password_confirmation } = this;
const { id } = this.model;
this.isLoading = true;
try {
yield this.fetch.post('auth/reset-password', { link: id, code, password, password_confirmation });
} catch (error) {
return this.notifications.serverError(error);
}
this.fetch
.post('auth/reset-password', { link: id, code, password, password_confirmation })
.then(() => {
this.notifications.success('Your password has been reset! Login to continue.');
return this.router.transitionTo('auth.login');
})
.catch((error) => {
this.notifications.serverError(error);
})
.finally(() => {
this.isLoading = false;
});
this.notifications.success(this.intl.t('auth.reset-password.success-message'));
yield this.router.transitionTo('auth.login');
}
}

View File

@@ -0,0 +1,274 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
/**
* Controller responsible for handling two-factor authentication.
* @class AuthTwoFaController
* @extends Controller
*/
export default class AuthTwoFaController extends Controller {
/**
* Router service.
*
* @var {Service}
*/
@service router;
/**
* Fetch service for making HTTP requests.
*
* @var {Service}
*/
@service fetch;
/**
* Notifications service for handling notifications.
*
* @var {Service}
*/
@service notifications;
/**
* Session service for managing user sessions.
*
* @var {Service}
*/
@service session;
/**
* Internationalization service.
*
* @var {Service}
*/
@service intl;
/**
* Tracked property for storing the verification token.
*
* @property {string} token
* @tracked
*/
@tracked token;
/**
* The current 2FA identity in memory
* @property {string} identity
* @tracked
*/
@tracked identity;
/**
* Tracked property representing the client token from the validated 2fa session.
*
* @property {number} clientToken
* @tracked
* @default null
*/
@tracked clientToken;
/**
* Tracked property for storing the verification code.
*
* @property {string} verificationCode
* @tracked
*/
@tracked verificationCode = '';
/**
* Tracked property for storing the verification code.
*
* @property {string} verificationCode
* @tracked
*/
@tracked otpValue = '';
/**
* Tracked property representing the date the 2fa session will expire
* @property {Date|null} twoFactorSessionExpiresAfter
* @tracked
* @default null
*/
@tracked twoFactorSessionExpiresAfter;
/**
* Tracked property representing when the countdown is ready to start.
*
* @property {Boolean} countdownReady
* @tracked
* @default false
*/
@tracked countdownReady = false;
/**
* Tracked property representing when verification code has expired.
*
* @property {Boolean} isCodeExpired
* @tracked
* @default false
*/
@tracked isCodeExpired = false;
/**
* Query parameters for the controller.
*
* @property {Array} queryParams
*/
queryParams = ['token', 'clientToken'];
/**
* Action method for verifying the entered verification code.
*
* @method verifyCode
* @action
*/
@action async verifyCode(event) {
// prevent form default behaviour
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
try {
const { token, verificationCode, clientToken, identity } = this;
if (!clientToken) {
this.notifications.error(this.intl.t('auth.two-fa.verify-code.invalid-session-error-notification'));
return;
}
// Call the backend API to verify the entered verification code
const { authToken } = await this.fetch.post('two-fa/verify', {
token,
code: verificationCode,
clientToken,
identity,
});
// If verification is successful, transition to the desired route
this.notifications.success(this.intl.t('auth.two-fa.verify-code.verification-successful-notification'));
// authenticate user
return this.session.authenticate('authenticator:fleetbase', { authToken }).then(() => {
return this.router.transitionTo('console');
});
} catch (error) {
if (error.message.includes('Verification code has expired')) {
this.notifications.info(this.intl.t('auth.two-fa.verify-code.verification-code-expired-notification'));
} else {
this.notifications.error(this.intl.t('auth.two-fa.verify-code.verification-code-failed-notification'));
}
}
}
/**
* Resends the verification code for Two-Factor Authentication.
* Disables the countdown timer while processing and handles success or error notifications.
*
* @returns {Promise<void>}
* @action
*/
@action async resendCode() {
// disable countdown timer
this.countdownReady = false;
try {
const { identity, token } = this;
const { clientToken } = await this.fetch.post('two-fa/resend', {
identity,
token,
});
if (clientToken) {
this.clientToken = clientToken;
this.twoFactorSessionExpiresAfter = this.getExpirationDateFromClientToken(clientToken);
this.countdownReady = true;
this.isCodeExpired = false;
this.notifications.success(this.intl.t('auth.two-fa.resend-code.verification-code-resent-notification'));
} else {
this.notifications.error(this.intl.t('auth.two-fa.resend-code.verification-code-resent-error-notification'));
}
} catch (error) {
// Handle errors, show error notifications, etc.
this.notifications.error(this.intl.t('auth.two-fa.resend-code.verification-code-resent-error-notification'));
}
}
/**
* Cancels the current Two-Fa session and redirects to login screen.
*
* @returns {Promise<Transition>}
* @memberof AuthTwoFaController
*/
@action cancelTwoFactor() {
return this.fetch
.post('two-fa/invalidate', {
identity: this.identity,
token: this.token,
})
.then(() => {
return this.router.transitionTo('auth.login');
});
}
/**
* Set that the verification code has expired and allow user to resend.
*
* @memberof AuthTwoFaController
*/
@action handleCodeExpired() {
this.isCodeExpired = true;
this.countdownReady = false;
}
/**
* Handles the input of the OTP (One-Time Password) and triggers the verification process.
*
* @param {string} otpValue - The OTP value entered by the user.
* @returns {void}
* @action
*/
@action handleOtpInput(otpValue) {
this.verificationCode = otpValue;
this.verifyCode();
}
/**
* Converts a base64 encoded client token to a Date representing the expiration date.
*
* @method getExpirationDateFromClientToken
* @param {string} clientToken - Base64 encoded client token.
* @returns {Date|null} - Date representing the expiration date, or null if invalid.
*/
getExpirationDateFromClientToken(clientToken) {
const decoder = new TextDecoder();
const binString = atob(clientToken);
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
const decodedString = decoder.decode(bytes);
if (typeof decodedString === 'string' && decodedString.includes('|')) {
const parts = decodedString.split('|');
const expiresAt = this.convertUtcToClientTime(parts[0]);
if (expiresAt instanceof Date) {
return expiresAt;
}
}
return null;
}
/**
* Converts a UTC date-time string to client time zone.
*
* @method convertUtcToClientTime
* @param {string} utcDateTimeString - UTC date-time string.
* @returns {Date} - Date in client time zone.
*/
convertUtcToClientTime(utcDateTimeString) {
const utcDate = new Date(utcDateTimeString);
const clientTimezoneOffset = new Date().getTimezoneOffset();
const clientDate = new Date(utcDate.getTime() - clientTimezoneOffset * 60 * 1000);
return clientDate;
}
}

View File

@@ -0,0 +1,239 @@
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { later } from '@ember/runloop';
import { not } from '@ember/object/computed';
export default class AuthVerificationController extends Controller {
/**
* Inject the `fetch` service
*
* @memberof OnboardIndexController
*/
@service fetch;
/**
* Inject the `notifications` service
*
* @memberof OnboardIndexController
*/
@service notifications;
/**
* Inject the `modalsManager` service
*
* @memberof OnboardIndexController
*/
@service modalsManager;
/**
* Inject the `currentUser` service
*
* @memberof OnboardIndexController
*/
@service currentUser;
/**
* Inject the `router` service
*
* @memberof OnboardIndexController
*/
@service router;
/**
* Inject the `session` service
*
* @memberof OnboardIndexController
*/
@service session;
/**
* The session paramerer.
*
* @memberof OnboardVerifyEmailController
*/
@tracked hello;
/**
* The token paramerer.
*
* @memberof OnboardVerifyEmailController
*/
@tracked token;
/**
* The loading state of the verification request.
*
* @memberof OnboardVerifyEmailController
*/
@tracked isLoading = false;
/**
* Validation state tracker.
*
* @memberof OnboardVerifyEmailController
*/
@tracked isReadyToSubmit = false;
/**
* The request timeout to trigger alternative verification options.
*
* @memberof OnboardVerifyEmailController
*/
@tracked waitTimeout = 1000 * 60 * 1.25;
/**
* Determines if Fleetbase is still awaiting verification after a certain time.
*
* @memberof OnboardVerifyEmailController
*/
@tracked stillWaiting = false;
/**
* the input code.
*
* @memberof OnboardVerifyEmailController
*/
@tracked code;
/**
* The query param for the session token.
*
* @memberof OnboardVerifyEmailController
*/
@tracked queryParams = ['hello', 'token'];
/**
* The boolean opposite of `isReadyToSubmit`
*
* @memberof OnboardVerifyEmailController
*/
@not('isReadyToSubmit') isNotReadyToSubmit;
/**
* Creates an instance of OnboardVerifyEmailController.
* @memberof OnboardVerifyEmailController
*/
constructor() {
super(...arguments);
later(
this,
() => {
this.stillWaiting = true;
},
this.waitTimeout
);
}
/**
* Allow user to manually trigger no code received prompt.
*
* @memberof AuthVerificationController
*/
@action onDidntReceiveCode() {
this.stillWaiting = true;
}
/**
* Validates the input
*
* @param {InputEvent} { target: { value } }
* @memberof OnboardVerifyEmailController
*/
@action validateInput({ target: { value } }) {
if (value.length > 5) {
this.isReadyToSubmit = true;
} else {
this.isReadyToSubmit = false;
}
}
/**
* Submits to verify code.
*
* @return {Promise}
* @memberof OnboardVerifyEmailController
*/
@action verifyCode() {
const { token, code, email } = this;
this.isLoading = true;
return this.fetch
.post('auth/verify-email', { token, code, email, authenticate: true })
.then(({ status, token }) => {
if (status === 'ok') {
this.notifications.success('Email successfully verified!');
if (token) {
this.notifications.info('Welcome to Fleetbase!');
this.session.manuallyAuthenticate(token);
return this.router.transitionTo('console');
}
return this.router.transitionTo('auth.login');
}
})
.catch((error) => {
this.notifications.serverError(error);
})
.finally(() => {
this.isLoading = false;
});
}
/**
* Action to resend verification code by SMS.
*
* @memberof OnboardVerifyEmailController
*/
@action resendBySms() {
this.modalsManager.show('modals/verify-by-sms', {
title: 'Verify Account by Phone',
acceptButtonText: 'Send',
phone: this.currentUser.phone,
confirm: (modal) => {
modal.startLoading();
const phone = modal.getOption('phone');
return this.fetch
.post('onboard/send-verification-sms', { phone, session: this.hello })
.then(() => {
this.notifications.success('Verification code SMS sent!');
})
.catch((error) => {
this.notifications.serverError(error);
});
},
});
}
/**
* Action to resend verification code by email.
*
* @memberof OnboardVerifyEmailController
*/
@action resendEmail() {
this.modalsManager.show('modals/resend-verification-email', {
title: 'Resend Verification Code',
acceptButtonText: 'Send',
email: this.currentUser.email,
confirm: (modal) => {
modal.startLoading();
const email = modal.getOption('email');
return this.fetch
.post('onboard/send-verification-email', { email, session: this.hello })
.then(() => {
this.notifications.success('Verification code email sent!');
})
.catch((error) => {
this.notifications.serverError(error);
});
},
});
}
}

View File

@@ -51,6 +51,13 @@ export default class ConsoleController extends Controller {
*/
@service router;
/**
* Inject the `intl` service.
*
* @var {Service}
*/
@service intl;
/**
* Inject the `universe` service.
*
@@ -115,22 +122,21 @@ export default class ConsoleController extends Controller {
*/
constructor() {
super(...arguments);
this.router.on('routeDidChange', (transition) => {
if (this.sidebarContext) {
// Determine if the new route should hide the sidebar
const shouldHideSidebar = this.hiddenSidebarRoutes.includes(transition.to.name);
// Check if the sidebar was manually toggled and is currently closed
const isSidebarManuallyClosed = this.sidebarToggleState.clicked && !this.sidebarToggleState.isOpen;
// Hide the sidebar if the current route is in hiddenSidebarRoutes
if (shouldHideSidebar) {
this.sidebarContext.hideNow();
this.sidebarToggleEnabled = false;
return; // Exit early as no further action is required
}
// If the sidebar was manually closed and not on a hidden route, keep it closed
if (isSidebarManuallyClosed) {
this.sidebarContext.hideNow();
@@ -138,7 +144,7 @@ export default class ConsoleController extends Controller {
// Otherwise, show the sidebar
this.sidebarContext.show();
}
// Ensure toggle is enabled unless on a hidden route
this.sidebarToggleEnabled = !shouldHideSidebar;
}
@@ -155,7 +161,7 @@ export default class ConsoleController extends Controller {
@action onSidebarToggle(sidebar, isOpen) {
this.sidebarToggleState = {
clicked: true,
isOpen
isOpen,
};
}
@@ -206,8 +212,8 @@ export default class ConsoleController extends Controller {
const country = this.currentUser.country;
this.modalsManager.show('modals/create-or-join-org', {
title: 'Create or join a organization',
acceptButtonText: 'Confirm',
title: this.intl.t('console.create-or-join-organization.modal-title'),
acceptButtonText: this.intl.t('common.confirm'),
acceptButtonIcon: 'check',
acceptButtonIconPrefix: 'fas',
action: 'join',
@@ -227,13 +233,22 @@ export default class ConsoleController extends Controller {
const { action, next, name, description, phone, currency, country, timezone } = modal.getOptions();
if (action === 'join') {
return this.fetch.post('auth/join-organization', { next }).then(() => {
this.fetch.flushRequestCache('auth/organizations');
this.notifications.success('You have joined a new organization!');
setTimeout(() => {
window.location.reload();
}, 900);
});
return this.fetch
.post('auth/join-organization', { next })
.then(() => {
this.fetch.flushRequestCache('auth/organizations');
this.notifications.success(this.intl.t('console.create-or-join-organization.join-success-notification'));
later(
this,
() => {
window.location.reload();
},
900
);
})
.catch((error) => {
this.notifications.serverError(error);
});
}
return this.fetch
@@ -247,7 +262,7 @@ export default class ConsoleController extends Controller {
})
.then(() => {
this.fetch.flushRequestCache('auth/organizations');
this.notifications.success('You have created a new organization!');
this.notifications.success(this.intl.t('console.create-or-join-organization.create-success-notification'));
later(
this,
() => {
@@ -255,6 +270,9 @@ export default class ConsoleController extends Controller {
},
900
);
})
.catch((error) => {
this.notifications.serverError(error);
});
},
});
@@ -271,9 +289,9 @@ export default class ConsoleController extends Controller {
}
this.modalsManager.confirm({
title: `Are you sure you want to switch organization to ${organization.name}?`,
body: `By confirming your account will remain logged in, but your primary organization will be switched.`,
acceptButtonText: `Yes, I want to switch organization`,
title: this.intl.t('console.switch-organization.modal-title', { organizationName: organization.name }),
body: this.intl.t('console.switch-organization.modal-body'),
acceptButtonText: this.intl.t('console.switch-organization.modal-accept-button-text'),
acceptButtonScheme: 'primary',
confirm: (modal) => {
modal.startLoading();
@@ -282,10 +300,14 @@ export default class ConsoleController extends Controller {
.post('auth/switch-organization', { next: organization.uuid })
.then(() => {
this.fetch.flushRequestCache('auth/organizations');
this.notifications.success('You have switched organizations');
setTimeout(() => {
window.location.reload();
}, 900);
this.notifications.success(this.intl.t('console.switch-organization.success-notification'));
later(
this,
() => {
window.location.reload();
},
900
);
})
.catch((error) => {
this.notifications.serverError(error);
@@ -296,8 +318,8 @@ export default class ConsoleController extends Controller {
@action viewChangelog() {
this.modalsManager.show('modals/changelog', {
title: 'Changelog',
acceptButtonText: 'OK',
title: this.intl.t('common.changelog'),
acceptButtonText: this.intl.t('common.ok'),
hideDeclineButton: true,
});
}

View File

@@ -0,0 +1,229 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency-decorators';
import getTwoFaMethods from '@fleetbase/console/utils/get-two-fa-methods';
/**
* Controller for managing user authentication and password-related actions in the console.
*
* @class ConsoleAccountAuthController
* @extends Controller
*/
export default class ConsoleAccountAuthController extends Controller {
/**
* Service for handling data fetching.
*
* @type {fetch}
*/
@service fetch;
/**
* Service for displaying notifications.
*
* @type {notifications}
*/
@service notifications;
/**
* Service for managing application routing.
*
* @type {router}
*/
@service router;
/**
* Service for managing modals.
*
* @type {router}
*/
@service modalsManager;
/**
* The new password the user intends to set.
*
* @type {string}
*/
@tracked newPassword;
/**
* The user's confirmation of the new password.
*
* @type {string}
*/
@tracked newConfirmPassword;
/**
* System-wide two-factor authentication configuration.
*
* @type {Object}
*/
@tracked twoFaConfig = {};
/**
* User-specific two-factor authentication settings.
*
* @type {Object}
*/
@tracked twoFaSettings = {};
/**
* Flag indicating whether system-wide two-factor authentication is enabled.
*
* @type {boolean}
*/
@tracked isSystemTwoFaEnabled = false;
/**
* Available two-factor authentication methods.
*
* @type {Array}
*/
@tracked methods = getTwoFaMethods();
/**
* Constructor method for the ConsoleAccountAuthController.
*
* @constructor
*/
constructor() {
super(...arguments);
this.loadSystemTwoFaConfig.perform();
this.loadUserTwoFaSettings.perform();
}
/**
* Handles the event when two-factor authentication is toggled.
*
* @method onTwoFaToggled
* @param {boolean} enabled - Whether two-factor authentication is enabled or not.
*/
@action onTwoFaToggled(enabled) {
this.twoFaSettings = {
...this.twoFaSettings,
enabled,
};
}
/**
* Handles the event when a two-factor authentication method is selected.
*
* @method onTwoFaMethodSelected
* @param {string} method - The selected two-factor authentication method.
*/
@action onTwoFaMethodSelected(method) {
this.twoFaSettings = {
...this.twoFaSettings,
method,
};
}
/**
* Initiates the task to save user-specific two-factor authentication settings asynchronously.
*
* @method saveTwoFactorAuthSettings
*/
@action saveTwoFactorAuthSettings() {
this.saveUserTwoFaSettings.perform(this.twoFaSettings);
}
/**
* Initiates the task to change the user's password asynchronously.
*
* @method changePassword
*/
@task *changePassword(event) {
// If from event fired
if (event instanceof Event) {
event.preventDefault();
}
// Validate current password
const isPasswordValid = yield this.validatePassword.perform();
if (!isPasswordValid) {
this.newPassword = undefined;
this.newConfirmPassword = undefined;
return;
}
try {
yield this.fetch.post('users/change-password', {
password: this.newPassword,
password_confirmation: this.newConfirmPassword,
});
this.notifications.success('Password change successfully.');
} catch (error) {
this.notifications.serverError(error, 'Failed to change password.');
}
this.newPassword = undefined;
this.newConfirmPassword = undefined;
}
/**
* Task to validate current password
*
* @return {boolean}
*/
@task *validatePassword() {
let isPasswordValid = false;
yield this.modalsManager.show('modals/validate-password', {
body: 'You must validate your current password before it can be changed.',
onValidated: (isValid) => {
isPasswordValid = isValid;
},
});
return isPasswordValid;
}
/**
* Initiates the task to save user-specific two-factor authentication settings asynchronously.
*
* @method saveUserTwoFaSettings
* @param {Object} twoFaSettings - User-specific two-factor authentication settings.
*/
@task *saveUserTwoFaSettings(twoFaSettings = {}) {
yield this.fetch
.post('users/two-fa', { twoFaSettings })
.then(() => {
this.notifications.success('2FA Settings saved successfully.');
})
.catch((error) => {
this.notifications.serverError(error);
});
}
/**
* Initiates the task to load user-specific two-factor authentication settings asynchronously.
*
* @method loadUserTwoFaSettings
*/
@task *loadUserTwoFaSettings() {
const twoFaSettings = yield this.fetch.get('users/two-fa');
if (twoFaSettings) {
this.isUserTwoFaEnabled = twoFaSettings.enabled;
this.twoFaSettings = twoFaSettings;
}
return twoFaSettings;
}
/**
* Initiates the task to load system-wide two-factor authentication configuration asynchronously.
*
* @method loadSystemTwoFaConfig
*/
@task *loadSystemTwoFaConfig() {
const twoFaConfig = yield this.fetch.get('two-fa/config');
if (twoFaConfig) {
this.isSystemTwoFaEnabled = twoFaConfig.enabled;
this.twoFaConfig = twoFaConfig;
}
return twoFaConfig;
}
}

View File

@@ -1,8 +1,8 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { alias } from '@ember/object/computed';
import { task } from 'ember-concurrency';
export default class ConsoleAccountIndexController extends Controller {
/**
@@ -18,6 +18,7 @@ export default class ConsoleAccountIndexController extends Controller {
* @memberof ConsoleAccountIndexController
*/
@service fetch;
/**
* Inject the `notifications` service.
*
@@ -26,11 +27,11 @@ export default class ConsoleAccountIndexController extends Controller {
@service notifications;
/**
* The loading state of request.
* Inject the `modalsManager` service.
*
* @memberof ConsoleAccountIndexController
*/
@tracked isLoading = false;
@service modalsManager;
/**
* Alias to the currentUser service user record.
@@ -50,9 +51,9 @@ export default class ConsoleAccountIndexController extends Controller {
file,
{
path: `uploads/${this.user.company_uuid}/users/${this.user.slug}`,
key_uuid: this.user.id,
key_type: `user`,
type: `user_avatar`,
subject_uuid: this.user.id,
subject_type: 'user',
type: 'user_avatar',
},
(uploadedFile) => {
this.user.setProperties({
@@ -66,27 +67,64 @@ export default class ConsoleAccountIndexController extends Controller {
}
/**
* Save the Profile settings.
* Starts the task to change password
*
* @return {Promise}
* @param {Event} event
* @memberof ConsoleAccountIndexController
*/
@action saveProfile() {
const user = this.user;
@task *saveProfile(event) {
// If from event fired
if (event instanceof Event) {
event.preventDefault();
}
this.isLoading = true;
let canUpdateProfile = true;
// If email has been changed prompt for password validation
if (this.changedUserAttribute('email')) {
canUpdateProfile = yield this.validatePassword.perform();
}
return user
.save()
.then((user) => {
if (canUpdateProfile === true) {
try {
const user = yield this.user.save();
this.notifications.success('Profile changes saved.');
this.currentUser.set('user', user);
})
.catch((error) => {
} catch (error) {
this.notifications.serverError(error);
})
.finally(() => {
this.isLoading = false;
});
}
} else {
this.user.rollbackAttributes();
}
}
/**
* Task to validate current password
*
* @return {boolean}
* @memberof ConsoleAccountIndexController
*/
@task *validatePassword() {
let isPasswordValid = false;
yield this.modalsManager.show('modals/validate-password', {
body: 'You must validate your password to update the account email address.',
onValidated: (isValid) => {
isPasswordValid = isValid;
},
});
return isPasswordValid;
}
/**
* Checks if any user attribute has been changed
*
* @param {string} attributeKey
* @return {boolean}
* @memberof ConsoleAccountIndexController
*/
changedUserAttribute(attributeKey) {
const changedAttributes = this.user.changedAttributes();
return changedAttributes[attributeKey] !== undefined;
}
}

View File

@@ -0,0 +1,169 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
/**
* Controller for managing organizations in the admin console.
*
* @class ConsoleAdminOrganizationsController
* @extends Controller
*/
export default class ConsoleAdminOrganizationsController extends Controller {
/**
* The Ember Data service for interacting with the store.
*
* @property {Service} store
* @type {Object}
*/
@service store;
/**
* Inject the `intl` service
*
* @var {Service}
*/
@service intl;
/**
* The Ember Router service for handling transitions between routes.
*
* @property {Service} router
* @type {Object}
*/
@service router;
/**
* Inject the `filters` service
*
* @var {Service}
*/
@service filters;
/**
* The search query param value.
*
* @var {String|null}
*/
@tracked query;
/**
* The current page of data being viewed
*
* @var {Integer}
*/
@tracked page = 1;
/**
* The maximum number of items to show per page
*
* @var {Integer}
*/
@tracked limit = 20;
/**
* The filterable param `sort`
*
* @var {String|Array}
*/
@tracked sort = '-created_at';
/**
* The filterable param `name`
*
* @var {String}
*/
@tracked name;
/**
* The filterable param `country`
*
* @var {String}
*/
@tracked country;
/**
* Array to store the fetched companies.
*
* @var {Array}
*/
@tracked companies = [];
/**
* Queryable parameters for this controller's model
*
* @var {Array}
*/
queryParams = ['name', 'page', 'limit', 'sort'];
/**
* Columns for organization
*
* @memberof ConsoleAdminOrganizationsController
*/
columns = [
{
label: this.intl.t('common.name'),
valuePath: 'name',
resizable: true,
sortable: true,
filterable: true,
filterComponent: 'filter/string',
},
{
label: this.intl.t('console.admin.organizations.index.owner-name-column'),
valuePath: 'owner.name',
width: '200px',
resizable: true,
sortable: true,
},
{
label: this.intl.t('console.admin.organizations.index.owner-email-column'),
valuePath: 'owner.email',
width: '200px',
resizable: true,
sortable: true,
filterable: true,
},
{
label: this.intl.t('console.admin.organizations.index.phone-column'),
valuePath: 'owner.phone',
width: '200px',
resizable: true,
sortable: true,
filterable: true,
filterComponent: 'filter/string',
},
{
label: this.intl.t('console.admin.organizations.index.users-count-column'),
valuePath: 'users_count',
resizable: true,
sortable: true,
},
{
label: this.intl.t('common.created-at'),
valuePath: 'createdAt',
},
];
/**
* Update search query param and reset page to 1
*
* @param {Event} event
* @memberof ConsoleAdminOrganizationsController
*/
@action search(event) {
this.query = event.target.value ?? '';
this.page = 1;
}
/**
* Navigates to the organization-users route for the selected company.
*
* @method goToCompany
* @param {Object} company - The selected company.
*/
@action goToCompany(company) {
this.router.transitionTo('console.admin.organizations.index.users', company.public_id);
}
}

View File

@@ -0,0 +1,136 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
export default class ConsoleAdminOrganizationsIndexUsersController extends Controller {
/**
* Inject the `filters` service
*
* @var {Service}
*/
@service filters;
/**
* Inject the `intl` service
*
* @var {Service}
*/
@service intl;
/**
* Inject the `router` service
*
* @var {Service}
*/
@service router;
/**
* The current page of data being viewed
*
* @var {Integer}
*/
@tracked nestedPage = 1;
/**
* The maximum number of items to show per page
*
* @var {Integer}
*/
@tracked nestedLimit = 20;
/**
* The filterable param `sort`
*
* @var {Array|String}
*/
@tracked nestedSort = '-created_at';
/**
* The filterable param `sort`
*
* @var {String}
*/
@tracked nestedQuery = '';
/**
* The company loaded.
*
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@tracked company;
/**
* The overlay context API.
*
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@tracked contextApi;
/**
* Queryable parameters for this controller's model
*
* @var {Array}
*/
queryParams = ['nestedPage', 'nestedLimit', 'nestedSort', 'nestedQuery'];
/**
* Columns to render to the table.
*
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
columns = [
{
label: this.intl.t('common.name'),
valuePath: 'name',
},
{
label: this.intl.t('common.phone-number'),
valuePath: 'phone',
},
{
label: this.intl.t('common.email'),
valuePath: 'email',
},
{
label: this.intl.t('common.status'),
valuePath: 'status',
cellComponent: 'table/cell/status',
},
];
/**
* Update search query param and reset page to 1
*
* @param {Event} event
* @memberof ConsoleAdminOrganizationsController
*/
@action search(event) {
this.nestedQuery = event.target.value ?? '';
this.nestedPage = 1;
}
/**
* Set the overlay component context object.
*
* @param {Object} contextApi
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@action setOverlayContext(contextApi) {
this.contextApi = contextApi;
}
/**
* Handle closing the overlay.
*
* @return {Promise<Transition>}
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@action onPressClose() {
if (this.contextApi && typeof this.contextApi.close === 'function') {
this.contextApi.close();
}
return this.router.transitionTo('console.admin.organizations.index');
}
}

View File

@@ -0,0 +1,65 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { task } from 'ember-concurrency';
export default class ConsoleAdminScheduleMonitorLogsController extends Controller {
/**
* The router service.
*
* @memberof ConsoleAdminScheduleMonitorLogsController
*/
@service router;
/**
* The fetch service.
*
* @memberof ConsoleAdminScheduleMonitorLogsController
*/
@service fetch;
/**
* Tracked property for logs.
* @type {Array}
*/
@tracked logs = [];
/**
* Tracked property for the context API.
* @type {Object}
*/
@tracked contextApi;
/**
* Periodically reloads logs every 3 seconds.
*
* @memberof ConsoleAdminScheduleMonitorLogsController
*/
@task *reload(task) {
this.logs = yield this.fetch.get(`schedule-monitor/${task.id}/logs`);
}
/**
* Set the overlay component context object.
*
* @param {Object} contextApi
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@action setOverlayContext(contextApi) {
this.contextApi = contextApi;
}
/**
* Handle closing the overlay.
*
* @return {Promise<Transition>}
* @memberof ConsoleAdminOrganizationsIndexUsersController
*/
@action onPressClose() {
if (this.contextApi && typeof this.contextApi.close === 'function') {
this.contextApi.close();
}
return this.router.transitionTo('console.admin.schedule-monitor');
}
}

View File

@@ -0,0 +1,172 @@
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { task } from 'ember-concurrency-decorators';
import getTwoFaMethods from '@fleetbase/console/utils/get-two-fa-methods';
/**
* Controller responsible for handling Two-Factor Authentication settings in the admin console.
*
* @class ConsoleAdminTwoFaSettingsController
* @extends Controller
*/
export default class ConsoleAdminTwoFaSettingsController extends Controller {
/**
* Service for handling data fetching.
*
* @type {fetch}
*/
@service fetch;
/**
* Service for displaying notifications.
*
* @type {notifications}
*/
@service notifications;
/**
* System-wide two-factor authentication configuration.
*
* @type {Object}
*/
@tracked twoFaConfig = {};
/**
* User-specific two-factor authentication settings.
*
* @type {Object}
*/
@tracked twoFaSettings = {};
/**
* Flag indicating whether system-wide two-factor authentication is enabled.
*
* @type {boolean}
*/
@tracked isSystemTwoFaEnabled = false;
/**
* Flag indicating whether 2FA enforcement is required.
*
* @type {boolean}
*/
@tracked isTwoFaEnforced = false;
/**
* Available two-factor authentication methods.
*
* @type {Array}
*/
@tracked methods = getTwoFaMethods();
/**
* Tracked property for the loading state
*
* @memberof ConsoleAdminTwoFaSettingsController
* @var {Boolean}
*/
@tracked isLoading = false;
/**
* Constructor method for the ConsoleAccountAuthController.
*
* @constructor
*/
constructor() {
super(...arguments);
this.loadSystemTwoFaConfig.perform();
}
/**
* Handles the event when two-factor authentication is toggled.
*
* @method onTwoFaToggled
* @param {boolean} enabled - Whether two-factor authentication is enabled or not.
*/
@action onTwoFaToggled(enabled) {
this.twoFaSettings = {
...this.twoFaSettings,
enabled,
};
}
/**
* Handles the event when a two-factor authentication method is selected.
*
* @method onTwoFaMethodSelected
* @param {string} method - The selected two-factor authentication method.
*/
@action onTwoFaMethodSelected(method) {
this.twoFaSettings = {
...this.twoFaSettings,
method,
};
}
/**
* Handles the event when two-factor authentication is toggled.
*
* @method onTwoFaToggled
* @param {boolean} enabled - Whether two-factor authentication is enforced or not.
*/
@action onTwoFaEnforceToggled(enforced) {
this.twoFaSettings = {
...this.twoFaSettings,
enforced,
};
}
/**
* Handles the event when 2FA enforcement is toggled.
*
* @method onTwoFaEnforceToggled
*/
/**
* Initiates the task to save user-specific two-factor authentication settings asynchronously.
*
* @method saveTwoFactorAuthSettings
*/
@action saveSettings() {
this.saveTwoFactorSettingsForAdmin.perform(this.twoFaSettings);
}
/**
* Initiates the task to load system-wide two-factor authentication configuration asynchronously.
*
* @method loadSystemTwoFaConfig
*/
@task *loadSystemTwoFaConfig() {
const twoFaSettings = yield this.fetch.get('two-fa/config').catch((error) => {
this.notifications.serverError(error);
});
if (twoFaSettings) {
this.twoFaSettings = twoFaSettings;
}
return twoFaSettings;
}
/**
* Initiates the task to save user-specific two-factor authentication settings asynchronously.
*
* @method saveTwoFactorSettingsForAdmin
* @param {Object} twoFaSettings - User-specific two-factor authentication settings.
*/
@task *saveTwoFactorSettingsForAdmin(twoFaSettings = {}) {
yield this.fetch
.post('two-fa/config', { twoFaSettings })
.then(() => {
this.notifications.success('2FA Settings saved for admin successfully.');
})
.catch((error) => {
this.notifications.serverError(error);
})
.finally(() => {
this.isLoading = false;
});
}
}

View File

@@ -0,0 +1,3 @@
import Controller from '@ember/controller';
export default class ConsoleSettingsAuthController extends Controller {}

View File

@@ -0,0 +1,184 @@
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency-decorators';
import getTwoFaMethods from '@fleetbase/console/utils/get-two-fa-methods';
export default class ConsoleSettingsTwoFaController extends Controller {
/**
* Service for handling data fetching.
*
* @type {fetch}
*/
@service fetch;
/**
* Service for displaying notifications.
*
* @type {notifications}
*/
@service notifications;
/**
* System-wide two-factor authentication configuration.
*
* @type {Object}
*/
@tracked twoFaConfig = {};
/**
* User-specific two-factor authentication settings.
*
* @type {Object}
*/
@tracked twoFaSettings = {};
/**
* Flag indicating whether system-wide two-factor authentication is enabled.
*
* @type {boolean}
*/
@tracked isSystemTwoFaEnabled = false;
/**
* Flag indicating whether system-wide two-factor authentication is enabled.
*
* @type {boolean}
*/
@tracked isUserTwoFaEnabled = false;
/**
* Flag indicating whether 2FA enforcement is required.
*
* @type {boolean}
*/
@tracked isTwoFaEnforced = false;
/**
* Available two-factor authentication methods.
*
* @type {Array}
*/
@tracked methods = getTwoFaMethods();
/**
* Constructor method for the ConsoleAccountAuthController.
*
* @constructor
*/
constructor() {
super(...arguments);
this.loadSystemTwoFaConfig.perform();
this.loadCompanyTwoFaSettings.perform();
this.loadUserTwoFaSettings.perform();
}
/**
* Handles the event when two-factor authentication is toggled.
*
* @method onTwoFaToggled
* @param {boolean} enabled - Whether two-factor authentication is enabled or not.
*/
@action onTwoFaToggled(enabled) {
this.twoFaSettings = {
...this.twoFaSettings,
enabled,
};
}
/**
* Handles the event when a two-factor authentication method is selected.
*
* @method onTwoFaMethodSelected
* @param {string} method - The selected two-factor authentication method.
*/
@action onTwoFaMethodSelected(method) {
this.twoFaSettings = {
...this.twoFaSettings,
method,
};
}
/**
* Handles the event when two-factor authentication is toggled.
*
* @method onTwoFaToggled
* @param {boolean} enabled - Whether two-factor authentication is enforced or not.
*/
@action onTwoFaEnforceToggled(enforced) {
this.twoFaSettings = {
...this.twoFaSettings,
enforced,
};
}
/**
* Initiates the task to save user-specific two-factor authentication settings asynchronously.
*
* @method saveTwoFactor
*/
@action saveTwoFactor() {
this.saveTwoFactorSettingsForCompany.perform(this.twoFaSettings);
}
/**
* Initiates the task to load user-specific two-factor authentication settings asynchronously.
*
* @method loadUserTwoFaSettings
*/
@task *loadCompanyTwoFaSettings() {
const twoFaSettings = yield this.fetch.get('companies/two-fa');
if (twoFaSettings) {
this.twoFaSettings = twoFaSettings;
this.isTwoFaEnforced = twoFaSettings.enforced;
}
return twoFaSettings;
}
/**
* Initiates the task to load system-wide two-factor authentication configuration asynchronously.
*
* @method loadSystemTwoFaConfig
*/
@task *loadSystemTwoFaConfig() {
const twoFaConfig = yield this.fetch.get('two-fa/config');
if (twoFaConfig) {
this.isSystemTwoFaEnabled = twoFaConfig.enabled;
this.twoFaConfig = twoFaConfig;
}
return twoFaConfig;
}
/**
* Initiates the task to load user-specific two-factor authentication settings asynchronously.
*
* @method loadUserTwoFaSettings
*/
@task *loadUserTwoFaSettings() {
const twoFaSettings = yield this.fetch.get('users/two-fa');
if (twoFaSettings) {
this.isUserTwoFaEnabled = twoFaSettings.enabled;
this.twoFaSettings = twoFaSettings;
}
return twoFaSettings;
}
/**
* Initiates the task to save user-specific two-factor authentication settings for the company asynchronously.
*
* @method saveTwoFactorSettingsForCompany
* @param {Object} twoFaSettings - User-specific two-factor authentication settings.
*/
@task *saveTwoFactorSettingsForCompany(twoFaSettings = {}) {
yield this.fetch
.post('companies/two-fa', { twoFaSettings })
.then(() => {
this.notifications.success('2FA Settings saved for organization successfully.');
})
.catch((error) => {
this.notifications.serverError(error);
});
}
}

View File

@@ -120,21 +120,25 @@ export default class OnboardIndexController extends Controller {
return;
}
// Set user timezone
input.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
this.isLoading = true;
return this.fetch
.post('onboard/create-account', input)
.then((response) => {
if (response.status === 'success') {
this.session.isOnboarding().manuallyAuthenticate(response.token);
.then(({ status, skipVerification, token, session }) => {
if (status === 'success') {
if (skipVerification === true && token) {
// only manually authenticate if skip verification
this.session.isOnboarding().manuallyAuthenticate(token);
if (response.skipVerification === true) {
return this.router.transitionTo('console').then(() => {
this.notifications.success('Welcome to Fleetbase!');
});
}
return this.router.transitionTo('onboard.verify-email', { queryParams: { hello: response.session } });
return this.router.transitionTo('onboard.verify-email', { queryParams: { hello: session } });
}
})
.catch((error) => {

View File

@@ -1,133 +1,7 @@
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import AuthVerificationController from '../auth/verification';
import { action } from '@ember/object';
import { later } from '@ember/runloop';
import { not } from '@ember/object/computed';
export default class OnboardVerifyEmailController extends Controller {
/**
* Inject the `fetch` service
*
* @memberof OnboardIndexController
*/
@service fetch;
/**
* Inject the `notifications` service
*
* @memberof OnboardIndexController
*/
@service notifications;
/**
* Inject the `modalsManager` service
*
* @memberof OnboardIndexController
*/
@service modalsManager;
/**
* Inject the `currentUser` service
*
* @memberof OnboardIndexController
*/
@service currentUser;
/**
* Inject the `router` service
*
* @memberof OnboardIndexController
*/
@service router;
/**
* The session paramerer.
*
* @memberof OnboardVerifyEmailController
*/
@tracked hello;
/**
* The loading state of the verification request.
*
* @memberof OnboardVerifyEmailController
*/
@tracked isLoading = false;
/**
* Validation state tracker.
*
* @memberof OnboardVerifyEmailController
*/
@tracked isReadyToSubmit = false;
/**
* The request timeout to trigger alternative verification options.
*
* @memberof OnboardVerifyEmailController
*/
@tracked waitTimeout = 800 * 60 * 2;
/**
* Determines if Fleetbase is still awaiting verification after a certain time.
*
* @memberof OnboardVerifyEmailController
*/
@tracked stillWaiting = false;
/**
* the input code.
*
* @memberof OnboardVerifyEmailController
*/
@tracked code;
/**
* The query param for the session token.
*
* @memberof OnboardVerifyEmailController
*/
@tracked queryParams = ['hello'];
/**
* The boolean opposite of `isReadyToSubmit`
*
* @memberof OnboardVerifyEmailController
*/
@not('isReadyToSubmit') isNotReadyToSubmit;
/**
* Creates an instance of OnboardVerifyEmailController.
* @memberof OnboardVerifyEmailController
*/
constructor() {
super(...arguments);
later(
this,
() => {
this.stillWaiting = true;
},
this.waitTimeout
);
}
/**
* Validates the input
*
* @param {InputEvent} { target: { value } }
* @memberof OnboardVerifyEmailController
*/
@action validateInput({ target: { value } }) {
if (value.length > 5) {
this.isReadyToSubmit = true;
} else {
this.isReadyToSubmit = false;
}
}
export default class OnboardVerifyEmailController extends AuthVerificationController {
/**
* Submits to verify code.
*
@@ -135,19 +9,24 @@ export default class OnboardVerifyEmailController extends Controller {
* @memberof OnboardVerifyEmailController
*/
@action verifyCode() {
const session = this.hello;
const code = this.code;
const { hello, code } = this;
this.isLoading = true;
return this.fetch
.post('onboard/verify-email', { session, code })
.then((response) => {
if (response.status === 'success') {
.post('onboard/verify-email', { session: hello, code })
.then(({ status, token }) => {
if (status === 'ok') {
this.notifications.success('Email successfully verified!');
this.notifications.info('Welcome to Fleetbase!');
return this.router.transitionTo('console');
if (token) {
this.notifications.info('Welcome to Fleetbase!');
this.session.manuallyAuthenticate(token);
return this.router.transitionTo('console');
}
return this.router.transitionTo('auth.login');
}
})
.catch((error) => {
@@ -157,46 +36,4 @@ export default class OnboardVerifyEmailController extends Controller {
this.isLoading = false;
});
}
/**
* Action to resend verification code by SMS.
*
* @memberof OnboardVerifyEmailController
*/
@action resendBySms() {
this.modalsManager.show('modals/verify-by-sms', {
title: 'Verify Account by Phone',
acceptButtonText: 'Send',
phone: this.currentUser.phone,
confirm: (modal) => {
modal.startLoading();
const phone = modal.getOption('phone');
return this.fetch.post('onboard/send-verification-sms', { phone }).then(() => {
this.notifications.success('Verification code SMS sent!');
});
},
});
}
/**
* Action to resend verification code by email.
*
* @memberof OnboardVerifyEmailController
*/
@action resendEmail() {
this.modalsManager.show('modals/resend-verification-email', {
title: 'Resend Verification Code',
acceptButtonText: 'Send',
email: this.currentUser.email,
confirm: (modal) => {
modal.startLoading();
const email = modal.getOption('email');
return this.fetch.post('onboard/send-verification-email', { email }).then(() => {
this.notifications.success('Verification code email sent!');
});
},
});
}
}

View File

@@ -0,0 +1,7 @@
import { helper } from '@ember/component/helper';
export default helper(function spreadWidgetOptions([params]) {
const { id, options } = params;
const gridOptions = { id, ...options };
return gridOptions;
});

View File

@@ -1,7 +1,12 @@
export function initialize() {
const socketClusterClientScript = document.createElement('script');
socketClusterClientScript.src = '/assets/socketcluster-client.min.js';
document.body.appendChild(socketClusterClientScript);
// Check if the script already exists
// Only insert the script tag if it doesn't already exist
if (!document.querySelector('script[data-socketcluster-client]')) {
const socketClusterClientScript = document.createElement('script');
socketClusterClientScript.setAttribute('data-socketcluster-client', '1');
socketClusterClientScript.src = '/assets/socketcluster-client.min.js';
document.body.appendChild(socketClusterClientScript);
}
}
export default {

View File

@@ -0,0 +1,36 @@
import { faGithub } from '@fortawesome/free-brands-svg-icons';
export function initialize(application) {
const universe = application.lookup('service:universe');
const defaultWidgets = [
{
widgetId: 'fleetbase-blog',
name: 'Fleetbase Blog',
description: 'Lists latest news and events from the Fleetbase official team.',
icon: 'newspaper',
component: 'fleetbase-blog',
grid_options: { w: 8, h: 9, minW: 8, minH: 9 },
options: {
title: 'Fleetbase Blog',
},
},
{
widgetId: 'fleetbase-github-card',
name: 'Github Card',
description: 'Displays current Github stats from the official Fleetbase repo.',
icon: faGithub,
component: 'github-card',
grid_options: { w: 4, h: 8, minW: 4, minH: 8 },
options: {
title: 'Github Card',
},
},
];
universe.registerDefaultDashboardWidgets(defaultWidgets);
universe.registerDashboardWidgets(defaultWidgets);
}
export default {
initialize,
};

View File

@@ -0,0 +1,21 @@
import config from 'ember-get-config';
export function initialize(owner) {
const universe = owner.lookup('service:universe');
if (universe) {
universe.registerOrganizationMenuItem(`v${config.version}`, {
index: 4,
route: null,
icon: 'code-branch',
iconSize: 'xs',
iconClass: 'mr-1.5',
wrapperClass: 'app-version-in-nav',
overwriteWrapperClass: true,
});
}
}
export default {
initialize,
};

View File

@@ -29,6 +29,7 @@ export default class CategoryModel extends Model {
@attr('string') slug;
@attr('string') order;
@attr('raw') translations;
@attr('raw') meta;
/** @dates */
@attr('date') deleted_at;

View File

@@ -0,0 +1,44 @@
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
import { computed } from '@ember/object';
import { format, formatDistanceToNow } from 'date-fns';
export default class CommentModel extends Model {
/** @ids */
@attr('string') company_uuid;
@attr('string') parent_comment_uuid;
@attr('string') subject_uuid;
@attr('string') subject_type;
/** @relationships */
@belongsTo('user') author;
@belongsTo('comment', { inverse: 'replies' }) parent;
@hasMany('comment', { inverse: 'parent' }) replies;
/** @attributes */
@attr('string') content;
@attr('boolean') editable;
@attr('raw') tags;
@attr('raw') meta;
/** @dates */
@attr('date') created_at;
@attr('date') updated_at;
@attr('date') deleted_at;
/** @computed */
@computed('created_at') get createdAgo() {
return formatDistanceToNow(this.created_at);
}
@computed('created_at') get createdAt() {
return format(this.created_at, 'PPP p');
}
@computed('updated_at') get updatedAgo() {
return formatDistanceToNow(this.updated_at);
}
@computed('updated_at') get updatedAt() {
return format(this.updated_at, 'PPP p');
}
}

View File

@@ -13,6 +13,7 @@ export default class Company extends Model {
@attr('string') place_uuid;
/** @relationships */
@belongsTo('user') owner;
@belongsTo('file') logo;
@belongsTo('file') backdrop;
@@ -23,6 +24,7 @@ export default class Company extends Model {
@attr('string') backdrop_url;
@attr('string') description;
@attr('raw') options;
@attr('number') users_count;
@attr('string') type;
@attr('string') currency;
@attr('string') country;

View File

@@ -0,0 +1,54 @@
import Model, { attr } from '@ember-data/model';
import { computed } from '@ember/object';
import { getOwner } from '@ember/application';
import { format, formatDistanceToNow } from 'date-fns';
function isValidFileObjectJson(str) {
return typeof str === 'string' && str.startsWith('{') && str.endsWith('}');
}
export default class CustomFieldValueModel extends Model {
/** @ids */
@attr('string') company_uuid;
@attr('string') custom_field_uuid;
@attr('string') subject_uuid;
@attr('string') subject_type;
/** @attributes */
@attr('string') value;
@attr('string') value_type;
/** @dates */
@attr('date') created_at;
@attr('date') updated_at;
@attr('date') deleted_at;
/** @computed */
@computed('value') get asFile() {
const owner = getOwner(this);
const fetch = owner.lookup(`service:fetch`);
const value = this.value;
if (!isValidFileObjectJson(value)) {
return null;
}
const fileModel = fetch.jsonToModel(value, 'file');
return fileModel;
}
@computed('created_at') get createdAgo() {
return formatDistanceToNow(this.created_at);
}
@computed('created_at') get createdAt() {
return format(this.created_at, 'PPP p');
}
@computed('updated_at') get updatedAgo() {
return formatDistanceToNow(this.updated_at);
}
@computed('updated_at') get updatedAt() {
return format(this.updated_at, 'PPP p');
}
}

View File

@@ -0,0 +1,48 @@
import Model, { attr } from '@ember-data/model';
import { computed } from '@ember/object';
import { format, formatDistanceToNow } from 'date-fns';
export default class CustomFieldModel extends Model {
/** @ids */
@attr('string') company_uuid;
@attr('string') category_uuid;
@attr('string') subject_uuid;
@attr('string') subject_type;
/** @attributes */
@attr('string') name;
@attr('string') description;
@attr('string') help_text;
@attr('string') label;
@attr('string') type;
@attr('string') component;
@attr('string') default_value;
@attr('number') order;
@attr('boolean') required;
@attr('boolean', { defaultValue: true }) editable;
@attr('raw') options;
@attr('raw') validation_rules;
@attr('raw') meta;
/** @dates */
@attr('date') created_at;
@attr('date') updated_at;
@attr('date') deleted_at;
/** @computed */
@computed('created_at') get createdAgo() {
return formatDistanceToNow(this.created_at);
}
@computed('created_at') get createdAt() {
return format(this.created_at, 'PPP p');
}
@computed('updated_at') get updatedAgo() {
return formatDistanceToNow(this.updated_at);
}
@computed('updated_at') get updatedAt() {
return format(this.updated_at, 'PPP p');
}
}

View File

@@ -0,0 +1,58 @@
import Model, { attr, belongsTo } from '@ember-data/model';
import { computed } from '@ember/object';
import { format, formatDistanceToNow } from 'date-fns';
export default class DashboardWidgetModel extends Model {
/** @ids */
@attr('string') dashboard_uuid;
/** @relationships */
@belongsTo('dashboard') dashboard;
/** @attributes */
@attr('string') name;
@attr('string') component;
@attr('object') grid_options;
@attr('object') options;
/** @dates */
@attr('date') created_at;
@attr('date') updated_at;
/** @computed */
@computed('updated_at') get updatedAgo() {
return formatDistanceToNow(this.updated_at);
}
@computed('updated_at') get updatedAt() {
return format(this.updated_at, 'PPP p');
}
@computed('updated_at') get updatedAtShort() {
return format(this.updated_at, 'PP');
}
@computed('created_at') get createdAgo() {
return formatDistanceToNow(this.created_at);
}
@computed('created_at') get createdAt() {
return format(this.created_at, 'PPP p');
}
@computed('created_at') get createdAtShort() {
return format(this.created_at, 'PP');
}
/**
* Update the dashboard widget properties on the server
*
* @param {Object} [properties={}]
* @return {Promise<DashboardWidgetModel>}
* @memberof DashboardWidgetModel
*/
updateProperties(properties = {}) {
this.setProperties(properties);
return this.save();
}
}

View File

@@ -0,0 +1,86 @@
import Model, { attr, hasMany } from '@ember-data/model';
import { computed } from '@ember/object';
import { format, formatDistanceToNow } from 'date-fns';
import { getOwner } from '@ember/application';
export default class DashboardModel extends Model {
/** @ids */
@attr('string') company_uuid;
@attr('string') user_uuid;
/** @relationships */
@hasMany('dashboard-widget', { async: false }) widgets;
/** @attributes */
@attr('string') name;
@attr('boolean') is_default;
/** @dates */
@attr('date') created_at;
@attr('date') updated_at;
/** @computed */
@computed('updated_at') get updatedAgo() {
return formatDistanceToNow(this.updated_at);
}
@computed('updated_at') get updatedAt() {
return format(this.updated_at, 'PPP p');
}
@computed('updated_at') get updatedAtShort() {
return format(this.updated_at, 'PP');
}
@computed('created_at') get createdAgo() {
return formatDistanceToNow(this.created_at);
}
@computed('created_at') get createdAt() {
return format(this.created_at, 'PPP p');
}
@computed('created_at') get createdAtShort() {
return format(this.created_at, 'PP');
}
/** @methods */
addWidget(widget) {
const owner = getOwner(this);
const store = owner.lookup('service:store');
const widgetRecord = store.createRecord('dashboard-widget', { ...widget, dashboard: this });
return new Promise((resolve, reject) => {
widgetRecord
.save()
.then((widgetRecord) => {
this.widgets.pushObject(widgetRecord);
resolve(widgetRecord);
})
.catch((error) => {
store.unloadRecord(widgetRecord);
reject(error);
});
});
}
removeWidget(widget) {
const owner = getOwner(this);
const store = owner.lookup('service:store');
const widgetRecord = store.peekRecord('dashboard-widget', widget);
if (widgetRecord) {
return new Promise((resolve, reject) => {
widgetRecord
.destroyRecord()
.then(() => {
this.widgets.removeObject(widgetRecord);
resolve();
})
.catch((error) => {
reject(error);
});
});
}
}
}

View File

@@ -1,6 +1,5 @@
import Model, { attr } from '@ember-data/model';
import { computed } from '@ember/object';
import { format, formatDistanceToNow } from 'date-fns';
export default class NotificationModel extends Model {

View File

@@ -79,6 +79,11 @@ export default class UserModel extends Model {
@not('isEmailVerified') emailIsNotVerified;
@not('isPhoneVerified') phoneIsNotVerified;
/** @computed */
@computed('meta.two_factor_enabled') get isTwoFactorEnabled() {
return this.meta && this.meta.two_factor_enabled;
}
@computed('types') get typesList() {
const types = Array.from(this.types);
return types.join(', ');

View File

@@ -10,7 +10,9 @@ Router.map(function () {
this.route('auth', function () {
this.route('login', { path: '/' });
this.route('forgot-password');
this.route('reset-password');
this.route('reset-password', { path: '/reset-password/:id' });
this.route('two-fa');
this.route('verification');
});
this.route('onboard', function () {
this.route('verify-email');
@@ -25,9 +27,11 @@ Router.map(function () {
this.route('notifications');
this.route('account', function () {
this.route('virtual', { path: '/:slug/:view' });
this.route('auth');
});
this.route('settings', function () {
this.route('virtual', { path: '/:slug/:view' });
this.route('two-fa');
});
this.route('virtual', { path: '/:slug/:view' });
this.route('admin', function () {
@@ -43,32 +47,12 @@ Router.map(function () {
});
this.route('branding');
this.route('notifications');
this.route('two-fa-settings');
this.route('virtual', { path: '/:slug/:view' });
});
this.mount('@fleetbase/billing-engine', {
as: 'billing',
path: 'billing'
});
this.mount('@fleetbase/dev-engine', {
as: 'developers',
path: 'developers'
});
this.mount('@fleetbase/fleetops-engine', {
as: 'fleet-ops',
path: 'fleet-ops'
});
this.mount('@fleetbase/iam-engine', {
as: 'iam',
path: 'iam'
});
this.mount('@fleetbase/storefront-engine', {
as: 'storefront',
path: 'storefront'
this.route('organizations', function () {
this.route('index', { path: '/' });
this.route('users', { path: '/:company_id' });
});
});
});
this.route('install');

View File

@@ -3,8 +3,23 @@ import { inject as service } from '@ember/service';
export default class AuthResetPasswordRoute extends Route {
@service store;
@service fetch;
@service router;
@service notifications;
@service intl;
model() {
return this.store.findRecord('brand', 1);
async model({ id }) {
return this.fetch.get('auth/validate-verification', { id });
}
async setupController(controller, model) {
super.setupController(...arguments);
if (model.is_valid === false) {
this.notifications.warning(this.intl.t('auth.reset-password.invalid-verification-code'));
return this.router.transitionTo('auth');
}
// set brand to controller
controller.brand = await this.store.findRecord('brand', 1);
}
}

View File

@@ -0,0 +1,114 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class AuthTwoFaRoute extends Route {
/**
* Fetch service for making HTTP requests.
*
* @var {Service}
*/
@service fetch;
/**
* Notifications service for handling notifications.
*
* @var {Service}
*/
@service notifications;
/**
* Router service.
*
* @var {Service}
*/
@service router;
/**
* Session service for managing user sessions.
*
* @var {Service}
*/
@service session;
/**
* Query parameters for the route.
*
* @var {Object}
*/
queryParams = {
token: {
refreshModel: false,
replace: true,
},
clientToken: {
refreshModel: false,
replace: true,
},
};
/**
* Executes before the model is loaded, used for validating 2FA session with the server.
*
* @param {Object} transition - The transition object representing the route transition.
* @return {Promise} A promise that resolves if the 2FA session is valid, and rejects with an error otherwise.
*/
beforeModel(transition) {
// validate 2fa session with server
let { token, clientToken } = transition.to.queryParams;
return this.session.store.restore().then(({ identity }) => {
if (!identity) {
this.notifications.error('2FA failed to initialize.');
return this.router.transitionTo('auth.login');
}
return this.fetch
.post('two-fa/validate', { token, identity, clientToken })
.then(({ clientToken, expired }) => {
// handle when code expired
if (expired === true) {
return this.invalidateTwoFaSession(token, identity);
}
// clear session data after validated 2fa session
this.session.store.persist({
identity,
token,
clientToken,
});
})
.catch((error) => {
this.notifications.serverError(error);
return this.router.transitionTo('auth.login');
});
});
}
/**
* Sets up the controller, including client token and session expiration details.
*
* @param {Object} controller - The controller for the route.
*/
setupController(controller) {
super.setupController(...arguments);
this.session.store.restore().then(({ clientToken, identity }) => {
controller.clientToken = clientToken;
controller.identity = identity;
controller.twoFactorSessionExpiresAfter = controller.getExpirationDateFromClientToken(clientToken);
controller.countdownReady = true;
});
}
invalidateTwoFaSession(token, identity) {
this.notifications.error('2FA authentication session has expired.');
return this.fetch
.post('two-fa/invalidate', {
token,
identity,
})
.then(() => {
return this.router.transitionTo('auth.login');
});
}
}

View File

@@ -0,0 +1,33 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class AuthVerificationRoute extends Route {
@service session;
@service fetch;
@service router;
queryParams = {
token: {
refreshModel: false,
replace: true,
},
};
beforeModel(transition) {
let { token } = transition.to.queryParams;
return this.session.store.restore().then(({ email }) => {
return this.fetch.post('auth/validate-verification-session', { email, token }).then(({ valid }) => {
if (!valid) {
return this.router.transitionTo('auth.login');
}
});
});
}
async setupController(controller) {
super.setupController(...arguments);
let { email } = await this.session.store.restore();
controller.email = email;
}
}

View File

@@ -25,6 +25,13 @@ export default class ConsoleRoute extends Route {
*/
@service session;
/**
* Inject the `intl` service
*
* @var {Service}
*/
@service intl;
/**
* Inject the `currentUser` service
*
@@ -72,6 +79,12 @@ export default class ConsoleRoute extends Route {
@action setupController(controller, model) {
super.setupController(controller, model);
// Get and set user locale
this.fetch.get('users/locale').then(({ locale }) => {
this.intl.setLocale(locale);
});
// Get user organizations
this.fetch.get('auth/organizations').then((organizations) => {
this.currentUser.setOption('organizations', organizations);
controller.organizations = organizations;

View File

@@ -0,0 +1,3 @@
import Route from '@ember/routing/route';
export default class ConsoleAccountAuthRoute extends Route {}

View File

@@ -0,0 +1,19 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class ConsoleAdminOrganizationsRoute extends Route {
@service store;
queryParams = {
page: { refreshModel: true },
query: { refreshModel: true },
sort: { refreshModel: true },
limit: { refreshModel: true },
name: { refreshModel: true },
country: { refreshModel: true },
};
model(params) {
return this.store.query('company', { view: 'admin', ...params });
}
}

View File

@@ -0,0 +1,50 @@
import Route from '@ember/routing/route';
import ArrayProxy from '@ember/array/proxy';
import { inject as service } from '@ember/service';
import { isArray } from '@ember/array';
export default class ConsoleAdminOrganizationsIndexUsersRoute extends Route {
@service fetch;
@service store;
queryParams = {
nestedPage: { refreshModel: true },
nestedLimit: { refreshModel: true },
nestedSort: { refreshModel: true },
nestedQuery: { refreshModel: true },
};
model(params) {
this.companyId = params.public_id;
return this.fetch
.get(`companies/${this.companyId}/users`, {
page: params.nestedPage,
limit: params.nestedLimit,
sort: params.nestedSort,
query: params.nestedQuery,
paginate: 1,
})
.then(this.transformResults.bind(this));
}
transformResults({ users, meta }) {
if (isArray(users)) {
users = users.map((user) => this.fetch.jsonToModel(user, 'user'));
}
return ArrayProxy.create({ content: users, meta });
}
setupController(controller) {
super.setupController(...arguments);
controller.company = this.getCompany();
}
getCompany() {
const companies = this.store.peekAll('company');
return companies.find((company) => {
return this.companyId === company.public_id || this.companyId === company.id;
});
}
}

View File

@@ -0,0 +1,10 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class ConsoleAdminScheduleMonitorRoute extends Route {
@service fetch;
model() {
return this.fetch.get('schedule-monitor/tasks');
}
}

View File

@@ -0,0 +1,14 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class ConsoleAdminScheduleMonitorLogsRoute extends Route {
@service fetch;
model({ id }) {
return this.fetch.get(`schedule-monitor/${id}`);
}
async setupController(controller, model) {
controller.logs = await this.fetch.get(`schedule-monitor/${model.id}/logs`);
}
}

View File

@@ -0,0 +1,3 @@
import Route from '@ember/routing/route';
export default class ConsoleAdminTwoFaSettingsRoute extends Route {}

View File

@@ -0,0 +1,3 @@
import Route from '@ember/routing/route';
export default class ConsoleSettingsAuthRoute extends Route {}

View File

@@ -0,0 +1,3 @@
import Route from '@ember/routing/route';
export default class ConsoleSettingsTwoFaRoute extends Route {}

View File

@@ -1,3 +1,10 @@
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class InviteForUserRoute extends Route {}
export default class InviteForUserRoute extends Route {
@service store;
model() {
return this.store.findRecord('brand', 1);
}
}

View File

@@ -0,0 +1,38 @@
import ApplicationSerializer from '@fleetbase/ember-core/serializers/application';
import { EmbeddedRecordsMixin } from '@ember-data/serializer/rest';
export default class CommentSerializer extends ApplicationSerializer.extend(EmbeddedRecordsMixin) {
/**
* Embedded relationship attributes
*
* @var {Object}
*/
get attrs() {
return {
author: { embedded: 'always' },
parent: { embedded: 'always' },
replies: { embedded: 'always' },
};
}
serializeAttribute(snapshot, json, key) {
if (key === 'editable') {
return;
}
super.serializeAttribute(...arguments);
}
serializeHasMany(snapshot, json, relationship) {
let key = relationship.key;
if (key === 'replies') {
return;
} else {
super.serializeHasMany(...arguments);
}
}
serializeBelongsTo() {
return;
}
}

View File

@@ -0,0 +1,15 @@
import ApplicationSerializer from '@fleetbase/ember-core/serializers/application';
import { EmbeddedRecordsMixin } from '@ember-data/serializer/rest';
export default class CompanySerializer extends ApplicationSerializer.extend(EmbeddedRecordsMixin) {
/**
* Embedded relationship attributes
*
* @var {Object}
*/
get attrs() {
return {
owner: { embedded: 'always' },
};
}
}

View File

@@ -0,0 +1,3 @@
import ApplicationSerializer from '@fleetbase/ember-core/serializers/application';
export default class DashboardWidgetSerializer extends ApplicationSerializer {}

View File

@@ -0,0 +1,18 @@
import ApplicationSerializer from '@fleetbase/ember-core/serializers/application';
import { EmbeddedRecordsMixin } from '@ember-data/serializer/rest';
export default class DashboardSerializer extends ApplicationSerializer.extend(EmbeddedRecordsMixin) {
attrs = {
widgets: { embedded: 'always' },
};
serializeHasMany(snapshot, json, relationship) {
let key = relationship.key;
if (key === 'widgets') {
return;
}
return super.serializeHasMany(...arguments);
}
}

View File

@@ -0,0 +1,4 @@
import ApplicationSerializer from '@fleetbase/ember-core/serializers/application';
import { EmbeddedRecordsMixin } from '@ember-data/serializer/rest';
export default class TwoFaSettingsSerializer extends ApplicationSerializer.extend(EmbeddedRecordsMixin) {}

Some files were not shown because too many files have changed in this diff Show More