@upsnap/strapi 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -30,7 +30,7 @@ const service = ({ strapi }) => ({
30
30
  const settings2 = await this.settingsStore.get();
31
31
  return settings2?.token || null;
32
32
  },
33
- async makeBackendRequest(endpoint, options, forValidation = false) {
33
+ async makeBackendRequest(endpoint, options, forValidation = false, sessionToken = "") {
34
34
  const token = await this.getToken();
35
35
  if (!token && !forValidation) {
36
36
  return { error: "No token found in settings" };
@@ -38,12 +38,27 @@ const service = ({ strapi }) => ({
38
38
  const response = await fetch(`${BACKEND_URL}${endpoint}`, {
39
39
  ...options,
40
40
  headers: {
41
- Authorization: `Bearer ${token}`,
41
+ Authorization: `Bearer ${sessionToken || token}`,
42
42
  "Content-Type": "application/json",
43
43
  ...options.headers || {}
44
44
  }
45
45
  });
46
- return response.json();
46
+ const contentType = response.headers.get("content-type") || "";
47
+ if (contentType.includes("application/json")) {
48
+ return await response.json();
49
+ }
50
+ if (contentType.includes("text/csv")) {
51
+ return {
52
+ type: "csv",
53
+ data: await response.text(),
54
+ headers: response.headers
55
+ };
56
+ }
57
+ return {
58
+ type: "blob",
59
+ data: await response.arrayBuffer(),
60
+ headers: response.headers
61
+ };
47
62
  }
48
63
  });
49
64
  const settings = ({ strapi }) => ({
@@ -55,14 +70,16 @@ const settings = ({ strapi }) => ({
55
70
  };
56
71
  },
57
72
  async set(ctx) {
58
- const { token } = ctx.request.body;
59
- const isValidData = await service({ strapi }).makeBackendRequest("/tokens/validate", {
60
- method: "POST",
61
- body: JSON.stringify({ token })
62
- }, true);
63
- if (!isValidData?.data?.valid) {
64
- ctx.body = { ok: false, error: "Invalid token" };
65
- return;
73
+ const { token, logOut } = ctx.request.body;
74
+ if (!logOut) {
75
+ const isValidData = await service({ strapi }).makeBackendRequest("/tokens/validate", {
76
+ method: "POST",
77
+ body: JSON.stringify({ token })
78
+ }, true);
79
+ if (!isValidData?.data?.valid) {
80
+ ctx.body = { ok: false, error: "Invalid token" };
81
+ return;
82
+ }
66
83
  }
67
84
  const store = service({ strapi }).settingsStore;
68
85
  const current = await store.get() || {};
@@ -593,6 +610,81 @@ const monitor = ({ strapi }) => ({
593
610
  body: JSON.stringify({ ids: monitorIds, action: "delete" })
594
611
  });
595
612
  ctx.body = { monitorsData };
613
+ },
614
+ async getAllIncidents(ctx) {
615
+ const { ...params } = ctx.request.body;
616
+ const {
617
+ monitorId,
618
+ timeRange,
619
+ page,
620
+ pageSize,
621
+ checkType,
622
+ region,
623
+ search,
624
+ sortBy,
625
+ sortOrder
626
+ } = params;
627
+ if (!monitorId) {
628
+ ctx.status = 400;
629
+ ctx.body = { error: "monitorId is required" };
630
+ return;
631
+ }
632
+ const queryParams = new URLSearchParams();
633
+ queryParams.set("monitorId", monitorId);
634
+ if (timeRange) queryParams.set("time_range", timeRange);
635
+ if (page !== void 0) queryParams.set("page", page.toString());
636
+ if (pageSize !== void 0)
637
+ queryParams.set("page_size", pageSize.toString());
638
+ if (checkType) queryParams.set("check_type", checkType);
639
+ if (region) queryParams.set("region", region);
640
+ if (search) queryParams.set("search", search);
641
+ if (sortBy) queryParams.set("sort_by", sortBy);
642
+ if (sortOrder) queryParams.set("sort_order", sortOrder);
643
+ const incidentsData = await service({ strapi }).makeBackendRequest(
644
+ `/user/monitors/incidents?${queryParams.toString()}`,
645
+ {
646
+ method: "GET"
647
+ }
648
+ );
649
+ ctx.body = { incidentsData };
650
+ },
651
+ async exportIncidents(ctx) {
652
+ try {
653
+ const { monitorId, region, type, start_time, end_time, search, file_type } = ctx.request.body;
654
+ if (!monitorId) {
655
+ ctx.status = 400;
656
+ ctx.body = { error: "monitorId is required" };
657
+ return;
658
+ }
659
+ const queryParams = new URLSearchParams();
660
+ if (type) queryParams.set("type", type);
661
+ if (start_time) queryParams.set("start_time", start_time);
662
+ if (end_time) queryParams.set("end_time", end_time);
663
+ if (search) queryParams.set("search", search);
664
+ if (file_type) queryParams.set("file_type", file_type);
665
+ if (region) queryParams.set("region", region);
666
+ const response = await service({ strapi }).makeBackendRequest(
667
+ `/user/monitors/${monitorId}/incidents/export?${queryParams.toString()}`,
668
+ { method: "GET" }
669
+ );
670
+ if (!response?.type) {
671
+ ctx.body = response;
672
+ return;
673
+ }
674
+ const contentType = response.headers.get("content-type") || "application/octet-stream";
675
+ const disposition = response.headers.get("content-disposition") || `attachment; filename=incidents.${file_type === "excel" ? "xlsx" : file_type || "csv"}`;
676
+ ctx.set("Content-Type", contentType);
677
+ ctx.set("Content-Disposition", disposition);
678
+ if (response.type === "csv") {
679
+ ctx.body = response.data;
680
+ } else {
681
+ ctx.body = Buffer.from(response.data);
682
+ }
683
+ } catch (error) {
684
+ console.error("Error exporting incidents: ", error);
685
+ ctx.status = 500;
686
+ ctx.body = { error: "Failed to export incidents" };
687
+ }
596
688
  }
597
689
  });
598
690
  const statusPage = ({ strapi }) => ({
@@ -660,12 +752,212 @@ const regions = ({ strapi }) => ({
660
752
  ctx.body = { regionsData };
661
753
  }
662
754
  });
755
+ const userDetailsService = ({ strapi }) => ({
756
+ async createUserApiToken(sessionToken) {
757
+ const apiTokens = await service({ strapi }).makeBackendRequest(
758
+ `/tokens/generate`,
759
+ {
760
+ method: "POST",
761
+ body: JSON.stringify({
762
+ name: "For Strapi",
763
+ description: "Token for strapi plugin",
764
+ expires: 0
765
+ })
766
+ },
767
+ true,
768
+ sessionToken
769
+ );
770
+ if (apiTokens?.data?.token_hash) {
771
+ const token = apiTokens?.data?.token_hash;
772
+ return token;
773
+ }
774
+ return null;
775
+ },
776
+ async getUserApiToken(sessionToken) {
777
+ const apiTokens = await service({ strapi }).makeBackendRequest(
778
+ `/tokens`,
779
+ {
780
+ method: "GET"
781
+ },
782
+ true,
783
+ sessionToken
784
+ );
785
+ const tokens = apiTokens?.data?.tokens || [];
786
+ let apiToken = "";
787
+ if (apiTokens?.status === "success" && tokens.length === 0) {
788
+ apiToken = await this.createUserApiToken(sessionToken);
789
+ } else if (tokens.length > 0) {
790
+ apiToken = tokens?.[0]?.token_hash;
791
+ }
792
+ return apiToken;
793
+ },
794
+ async createInitialMonitor(site_url, apiToken) {
795
+ try {
796
+ const payload = {
797
+ name: "Default Monitor",
798
+ service_type: "website",
799
+ is_enabled: true,
800
+ channel_ids: [],
801
+ tag_ids: [],
802
+ regions: [
803
+ {
804
+ id: "default",
805
+ is_primary: true,
806
+ name: "Default (Server Region)"
807
+ }
808
+ ],
809
+ config: {
810
+ meta: {
811
+ follow_redirects: true,
812
+ timeout: 5,
813
+ url: site_url
814
+ },
815
+ services: {
816
+ broken_links: {
817
+ enabled: true,
818
+ monitor_interval: 86400
819
+ },
820
+ domain: {
821
+ enabled: true,
822
+ monitor_interval: 86400,
823
+ notify_days_before_expiry: 7
824
+ },
825
+ lighthouse: {
826
+ enabled: true,
827
+ strategy: "desktop",
828
+ monitor_interval: 604800
829
+ },
830
+ mixed_content: {
831
+ enabled: true,
832
+ monitor_interval: 86400
833
+ },
834
+ ssl: {
835
+ enabled: true,
836
+ monitor_interval: 86400,
837
+ notify_days_before_expiry: 7
838
+ },
839
+ uptime: {
840
+ enabled: true,
841
+ monitor_interval: 300
842
+ }
843
+ }
844
+ }
845
+ };
846
+ const monitorsData = await service({ strapi }).makeBackendRequest(`/user/monitors`, {
847
+ method: "POST",
848
+ body: JSON.stringify(payload)
849
+ }, true, apiToken);
850
+ if (monitorsData?.status === "success") {
851
+ const monitorId = monitorsData?.data?.monitor?.id;
852
+ return monitorId;
853
+ }
854
+ return null;
855
+ } catch (err) {
856
+ console.log("Error creating initial monitor ", err);
857
+ return null;
858
+ }
859
+ }
860
+ });
663
861
  const userDetails = ({ strapi }) => ({
664
862
  async getUserDetails(ctx) {
665
863
  const userDetailsData = await service({ strapi }).makeBackendRequest(`/user/details`, {
666
864
  method: "GET"
667
865
  });
668
866
  ctx.body = { userDetailsData };
867
+ },
868
+ async signUp(ctx) {
869
+ try {
870
+ const { email, password, source, site_url, fullName } = ctx.request.body;
871
+ const registerData = await service({ strapi }).makeBackendRequest(
872
+ `/user/register`,
873
+ {
874
+ method: "POST",
875
+ body: JSON.stringify({
876
+ email,
877
+ password,
878
+ source,
879
+ full_name: fullName
880
+ })
881
+ },
882
+ true
883
+ );
884
+ if (registerData?.data?.token) {
885
+ const apiToken = await userDetailsService({ strapi }).getUserApiToken(registerData?.data?.token);
886
+ const monitorId = await userDetailsService({ strapi }).createInitialMonitor(site_url, apiToken);
887
+ if (!apiToken || !monitorId) {
888
+ ctx.body = { ok: false, message: "Error creating API token or Monitor" };
889
+ return;
890
+ }
891
+ const store = service({ strapi }).settingsStore;
892
+ const current = await store.get() || {};
893
+ await store.set({
894
+ value: {
895
+ ...current,
896
+ token: apiToken,
897
+ primaryMonitorId: monitorId
898
+ }
899
+ });
900
+ return ctx.body = { ok: true, message: registerData?.data?.message };
901
+ }
902
+ ctx.body = { ok: false };
903
+ } catch (err) {
904
+ console.log("Error signing up ", err);
905
+ ctx.body = { ok: false };
906
+ }
907
+ },
908
+ async signIn(ctx) {
909
+ try {
910
+ const { email, password } = ctx.request.body;
911
+ const loginData = await service({ strapi }).makeBackendRequest(
912
+ `/user/login`,
913
+ {
914
+ method: "POST",
915
+ body: JSON.stringify({
916
+ email,
917
+ password
918
+ })
919
+ },
920
+ true
921
+ );
922
+ if (loginData?.data?.token) {
923
+ const apiToken = await userDetailsService({ strapi }).getUserApiToken(loginData?.data?.token);
924
+ const store = service({ strapi }).settingsStore;
925
+ const current = await store.get() || {};
926
+ await store.set({
927
+ value: {
928
+ ...current,
929
+ token: apiToken
930
+ }
931
+ });
932
+ return ctx.body = { ok: true };
933
+ }
934
+ ctx.body = { ok: false, message: loginData?.message };
935
+ } catch (err) {
936
+ console.log("Error signing in ", err);
937
+ ctx.body = { ok: false };
938
+ }
939
+ },
940
+ async forgotPassword(ctx) {
941
+ try {
942
+ const { email } = ctx.request.body;
943
+ const forgotPasswordData = await service({ strapi }).makeBackendRequest(
944
+ `/user/forgot-password`,
945
+ {
946
+ method: "POST",
947
+ body: JSON.stringify({
948
+ email
949
+ })
950
+ },
951
+ true
952
+ );
953
+ if (forgotPasswordData?.status === "success") {
954
+ return ctx.body = { ok: true, message: forgotPasswordData?.data?.message };
955
+ }
956
+ ctx.body = { ok: false };
957
+ } catch (err) {
958
+ console.log("Error for forgot password ", err);
959
+ ctx.body = { ok: false };
960
+ }
669
961
  }
670
962
  });
671
963
  const notificationChannels = ({ strapi }) => ({
@@ -1066,12 +1358,58 @@ const routes = {
1066
1358
  policies: [],
1067
1359
  auth: false
1068
1360
  }
1361
+ },
1362
+ {
1363
+ method: "POST",
1364
+ path: "/signup",
1365
+ handler: "userDetails.signUp",
1366
+ config: {
1367
+ policies: [],
1368
+ auth: false
1369
+ }
1370
+ },
1371
+ {
1372
+ method: "POST",
1373
+ path: "/login",
1374
+ handler: "userDetails.signIn",
1375
+ config: {
1376
+ policies: [],
1377
+ auth: false
1378
+ }
1379
+ },
1380
+ {
1381
+ method: "POST",
1382
+ path: "/forgot-password",
1383
+ handler: "userDetails.forgotPassword",
1384
+ config: {
1385
+ policies: [],
1386
+ auth: false
1387
+ }
1388
+ },
1389
+ {
1390
+ method: "POST",
1391
+ path: "/monitor/all-incidents",
1392
+ handler: "monitor.getAllIncidents",
1393
+ config: {
1394
+ policies: [],
1395
+ auth: false
1396
+ }
1397
+ },
1398
+ {
1399
+ method: "POST",
1400
+ path: "/monitor/incidents/export",
1401
+ handler: "monitor.exportIncidents",
1402
+ config: {
1403
+ policies: [],
1404
+ auth: false
1405
+ }
1069
1406
  }
1070
1407
  ]
1071
1408
  }
1072
1409
  };
1073
1410
  const services = {
1074
- service
1411
+ service,
1412
+ userDetailsService
1075
1413
  };
1076
1414
  const index = {
1077
1415
  register,
@@ -47,6 +47,8 @@ declare const _default: {
47
47
  updateMonitor(ctx: any): Promise<void>;
48
48
  deleteMonitor(ctx: any): Promise<void>;
49
49
  deleteMonitors(ctx: any): Promise<void>;
50
+ getAllIncidents(ctx: any): Promise<void>;
51
+ exportIncidents(ctx: any): Promise<void>;
50
52
  };
51
53
  statusPage: ({ strapi }: {
52
54
  strapi: import('@strapi/types/dist/core').Strapi;
@@ -67,6 +69,17 @@ declare const _default: {
67
69
  strapi: import('@strapi/types/dist/core').Strapi;
68
70
  }) => {
69
71
  getUserDetails(ctx: any): Promise<void>;
72
+ signUp(ctx: any): Promise<{
73
+ ok: boolean;
74
+ message: any;
75
+ }>;
76
+ signIn(ctx: any): Promise<{
77
+ ok: boolean;
78
+ }>;
79
+ forgotPassword(ctx: any): Promise<{
80
+ ok: boolean;
81
+ message: any;
82
+ }>;
70
83
  };
71
84
  notificationChannels: ({ strapi }: {
72
85
  strapi: import('@strapi/types/dist/core').Strapi;
@@ -123,7 +136,14 @@ declare const _default: {
123
136
  }>): Promise<void>;
124
137
  };
125
138
  getToken(): Promise<string>;
126
- makeBackendRequest(endpoint: string, options: RequestInit, forValidation?: boolean): Promise<unknown>;
139
+ makeBackendRequest(endpoint: string, options: RequestInit, forValidation?: boolean, sessionToken?: string): Promise<unknown>;
140
+ };
141
+ userDetailsService: ({ strapi }: {
142
+ strapi: import('@strapi/types/dist/core').Strapi;
143
+ }) => {
144
+ createUserApiToken(sessionToken: string): Promise<any>;
145
+ getUserApiToken(sessionToken: string): Promise<string>;
146
+ createInitialMonitor(site_url: string, apiToken: string): Promise<any>;
127
147
  };
128
148
  };
129
149
  contentTypes: {};
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.7",
2
+ "version": "1.0.9",
3
3
  "repository": {
4
4
  "type": "git",
5
5
  "url": "https://github.com/Appfoster/upsnap-strapi"