90dc-core 1.10.2 → 1.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/models/UserInterfaces.d.ts +1 -0
- package/dist/lib/models/UserInterfaces.d.ts.map +1 -1
- package/dist/lib/models/UserInterfaces.js.map +1 -1
- package/dist/lib/utils/AuthenticationUtil.d.ts +0 -13
- package/dist/lib/utils/AuthenticationUtil.d.ts.map +1 -1
- package/dist/lib/utils/AuthenticationUtil.js +3 -14
- package/dist/lib/utils/AuthenticationUtil.js.map +1 -1
- package/dist/lib/utils/NotificationClient.d.ts +247 -0
- package/dist/lib/utils/NotificationClient.d.ts.map +1 -0
- package/dist/lib/utils/NotificationClient.js +349 -0
- package/dist/lib/utils/NotificationClient.js.map +1 -0
- package/dist/lib/utils/NotificationsUtil.d.ts +4 -13
- package/dist/lib/utils/NotificationsUtil.d.ts.map +1 -1
- package/dist/lib/utils/NotificationsUtil.js +23 -13
- package/dist/lib/utils/NotificationsUtil.js.map +1 -1
- package/package.json +2 -1
- package/src/index.ts +2 -0
- package/src/lib/models/UserInterfaces.ts +1 -0
- package/src/lib/utils/AuthenticationUtil.ts +145 -158
- package/src/lib/utils/NotificationClient.ts +513 -0
- package/src/lib/utils/NotificationsUtil.ts +26 -16
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from "./lib/models/ProgramInterfaces";
|
|
|
2
2
|
export * from "./lib/models/ExerciseInterfaces";
|
|
3
3
|
export * from "./lib/models/WorkoutInterfaces";
|
|
4
4
|
export * from "./lib/models/UserInterfaces";
|
|
5
|
+
export * from "./lib/models/NotificationInterfaces";
|
|
5
6
|
export * from "./lib/dbmodels/UsersFriends";
|
|
6
7
|
export * from "./lib/dbmodels/PersistedUser";
|
|
7
8
|
export * from "./lib/dbmodels/UserBadges";
|
|
@@ -21,4 +22,5 @@ export * from "./lib/dbmodels/nonconsprogram/UserNonConsumableProgram";
|
|
|
21
22
|
export * from "./lib/utils/Logger";
|
|
22
23
|
export { AuthenticationUtil } from "./lib/utils/AuthenticationUtil";
|
|
23
24
|
export { NotificationsUtil } from "./lib/utils/NotificationsUtil";
|
|
25
|
+
export { NotificationClient } from "./lib/utils/NotificationClient";
|
|
24
26
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,gCAAgC,CAAC;AAC/C,cAAc,iCAAiC,CAAC;AAChD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,gCAAgC,CAAC;AAC/C,cAAc,iCAAiC,CAAC;AAChD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AAGpD,cAAc,6BAA6B,CAAA;AAC3C,cAAc,8BAA8B,CAAA;AAC5C,cAAc,2BAA2B,CAAA;AACzC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,sBAAsB,CAAA;AACpC,cAAc,gCAAgC,CAAA;AAC9C,cAAc,gCAAgC,CAAA;AAC9C,cAAc,iCAAiC,CAAA;AAC/C,cAAc,iCAAiC,CAAA;AAC/C,cAAc,6BAA6B,CAAA;AAC3C,cAAc,gCAAgC,CAAA;AAC9C,cAAc,oDAAoD,CAAA;AAClE,cAAc,wEAAwE,CAAA;AACtF,cAAc,2DAA2D,CAAA;AACzE,cAAc,8DAA8D,CAAA;AAC5E,cAAc,wDAAwD,CAAA;AAItE,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAC,kBAAkB,EAAC,MAAM,gCAAgC,CAAA;AACjE,OAAO,EAAC,iBAAiB,EAAC,MAAM,+BAA+B,CAAA;AAC/D,OAAO,EAAC,kBAAkB,EAAC,MAAM,gCAAgC,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@ export * from "./lib/models/ProgramInterfaces";
|
|
|
3
3
|
export * from "./lib/models/ExerciseInterfaces";
|
|
4
4
|
export * from "./lib/models/WorkoutInterfaces";
|
|
5
5
|
export * from "./lib/models/UserInterfaces";
|
|
6
|
+
export * from "./lib/models/NotificationInterfaces";
|
|
6
7
|
//DB Models
|
|
7
8
|
export * from "./lib/dbmodels/UsersFriends";
|
|
8
9
|
export * from "./lib/dbmodels/PersistedUser";
|
|
@@ -24,5 +25,6 @@ export * from "./lib/dbmodels/nonconsprogram/UserNonConsumableProgram";
|
|
|
24
25
|
export * from "./lib/utils/Logger";
|
|
25
26
|
export { AuthenticationUtil } from "./lib/utils/AuthenticationUtil";
|
|
26
27
|
export { NotificationsUtil } from "./lib/utils/NotificationsUtil";
|
|
28
|
+
export { NotificationClient } from "./lib/utils/NotificationClient";
|
|
27
29
|
|
|
28
30
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["//Interfaces\nexport * from \"./lib/models/ProgramInterfaces\";\nexport * from \"./lib/models/ExerciseInterfaces\";\nexport * from \"./lib/models/WorkoutInterfaces\";\nexport * from \"./lib/models/UserInterfaces\";\n\n//DB Models\nexport * from \"./lib/dbmodels/UsersFriends\"\nexport * from \"./lib/dbmodels/PersistedUser\"\nexport * from \"./lib/dbmodels/UserBadges\"\nexport * from \"./lib/dbmodels/UserStreaks\"\nexport * from \"./lib/dbmodels/Badge\"\nexport * from \"./lib/dbmodels/program/Program\"\nexport * from \"./lib/dbmodels/program/Workout\"\nexport * from \"./lib/dbmodels/program/Exercise\"\nexport * from \"./lib/dbmodels/program/Superset\"\nexport * from \"./lib/dbmodels/Subscription\"\nexport * from \"./lib/dbmodels/SubscriptionLog\"\nexport * from \"./lib/dbmodels/nonconsprogram/NonConsumableProgram\"\nexport * from \"./lib/dbmodels/nonconsprogram/TranslatedNonConsumableProgramWebContent\"\nexport * from \"./lib/dbmodels/nonconsprogram/TranslatedConsumableProgram\"\nexport * from \"./lib/dbmodels/nonconsprogram/NonConsumableProgramWebContent\"\nexport * from \"./lib/dbmodels/nonconsprogram/UserNonConsumableProgram\"\n\n\n//Utils\nexport * from \"./lib/utils/Logger\"\nexport {AuthenticationUtil} from \"./lib/utils/AuthenticationUtil\"\nexport {NotificationsUtil} from \"./lib/utils/NotificationsUtil\"\n"],"names":["AuthenticationUtil","NotificationsUtil"],"mappings":"AAAA,YAAY;AACZ,cAAc,iCAAiC;AAC/C,cAAc,kCAAkC;AAChD,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["//Interfaces\nexport * from \"./lib/models/ProgramInterfaces\";\nexport * from \"./lib/models/ExerciseInterfaces\";\nexport * from \"./lib/models/WorkoutInterfaces\";\nexport * from \"./lib/models/UserInterfaces\";\nexport * from \"./lib/models/NotificationInterfaces\";\n\n//DB Models\nexport * from \"./lib/dbmodels/UsersFriends\"\nexport * from \"./lib/dbmodels/PersistedUser\"\nexport * from \"./lib/dbmodels/UserBadges\"\nexport * from \"./lib/dbmodels/UserStreaks\"\nexport * from \"./lib/dbmodels/Badge\"\nexport * from \"./lib/dbmodels/program/Program\"\nexport * from \"./lib/dbmodels/program/Workout\"\nexport * from \"./lib/dbmodels/program/Exercise\"\nexport * from \"./lib/dbmodels/program/Superset\"\nexport * from \"./lib/dbmodels/Subscription\"\nexport * from \"./lib/dbmodels/SubscriptionLog\"\nexport * from \"./lib/dbmodels/nonconsprogram/NonConsumableProgram\"\nexport * from \"./lib/dbmodels/nonconsprogram/TranslatedNonConsumableProgramWebContent\"\nexport * from \"./lib/dbmodels/nonconsprogram/TranslatedConsumableProgram\"\nexport * from \"./lib/dbmodels/nonconsprogram/NonConsumableProgramWebContent\"\nexport * from \"./lib/dbmodels/nonconsprogram/UserNonConsumableProgram\"\n\n\n//Utils\nexport * from \"./lib/utils/Logger\"\nexport {AuthenticationUtil} from \"./lib/utils/AuthenticationUtil\"\nexport {NotificationsUtil} from \"./lib/utils/NotificationsUtil\"\nexport {NotificationClient} from \"./lib/utils/NotificationClient\"\n"],"names":["AuthenticationUtil","NotificationsUtil","NotificationClient"],"mappings":"AAAA,YAAY;AACZ,cAAc,iCAAiC;AAC/C,cAAc,kCAAkC;AAChD,cAAc,iCAAiC;AAC/C,cAAc,8BAA8B;AAC5C,cAAc,sCAAsC;AAEpD,WAAW;AACX,cAAc,8BAA6B;AAC3C,cAAc,+BAA8B;AAC5C,cAAc,4BAA2B;AACzC,cAAc,6BAA4B;AAC1C,cAAc,uBAAsB;AACpC,cAAc,iCAAgC;AAC9C,cAAc,iCAAgC;AAC9C,cAAc,kCAAiC;AAC/C,cAAc,kCAAiC;AAC/C,cAAc,8BAA6B;AAC3C,cAAc,iCAAgC;AAC9C,cAAc,qDAAoD;AAClE,cAAc,yEAAwE;AACtF,cAAc,4DAA2D;AACzE,cAAc,+DAA8D;AAC5E,cAAc,yDAAwD;AAGtE,OAAO;AACP,cAAc,qBAAoB;AAClC,SAAQA,kBAAkB,QAAO,iCAAgC;AACjE,SAAQC,iBAAiB,QAAO,gCAA+B;AAC/D,SAAQC,kBAAkB,QAAO,iCAAgC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserInterfaces.d.ts","sourceRoot":"","sources":["../../../src/lib/models/UserInterfaces.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAEpC,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,M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AAC;CACf;AAED,MAAM,WAAW,yBAAyB;IACxC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/models/UserInterfaces.ts"],"sourcesContent":["import type jwt from \"jsonwebtoken\";\n\nexport interface UserTypes {\n userUuid: string;\n email: string;\n firstName: string;\n lastName: string;\n avatar: string;\n role: string;\n}\n\nexport interface VerificationStatus {\n status: string;\n}\n\nexport interface TransactionsResponse {\n revision: string;\n bundleId: string;\n environment: string;\n hasMore: boolean;\n signedTransactions: string[];\n errorCode?: number;\n}\n\nexport interface UserInfoModel {\n userUuid: string;\n height: string;\n weight: string;\n}\n\nexport interface SingleTransactionResponse {\n revision: string;\n bundleId: string;\n environment: string;\n hasMore: boolean;\n signedTransactionInfo: string;\n errorCode?: number;\n}\n\nexport interface SubscriptionStatus {\n originalTransactionId: string;\n status: number;\n signedTransactionInfo: string;\n signedRenewalInfo: string;\n}\n\nexport interface SubscriptionStatusResponse {\n environment: string;\n bundleId: string;\n data: [\n {\n subscriptionGroupIdentifier: string;\n lastTransactions: SubscriptionStatus[];\n }\n ];\n errorCode?: number;\n}\n\nexport interface SubscriptionStatusResponseError {\n errorCode: number;\n errorMessage: string;\n}\n\nexport interface SubscriptionStatusResult {\n originalTransactionId: string;\n status: number;\n signedTransactionInfo: string | jwt.JwtPayload | null;\n signedRenewalInfo: string | jwt.JwtPayload | null;\n}\n\nexport interface SignedTransactions {\n transactionId: string;\n originalTransactionId: string;\n webOrderLineItemId: string;\n bundleId: string;\n productId: string;\n subscriptionGroupIdentifier: string;\n purchaseDate: number;\n originalPurchaseDate: number;\n expiresDate: number;\n quantity: number;\n type: string;\n inAppOwnershipType: string;\n signedDate: number;\n environment: string;\n transactionReason: string;\n storefront: string;\n storefrontId: string;\n}\n\nexport interface Credentials {\n refresh_token?: string | null,\n expiry_date?: number | null,\n access_token?: string | null,\n token_type?: string | null ,\n id_token?: string | null,\n scope?: string\n}\n\n\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\nexport interface UserPhotoRequest {\n base64: string;\n}\n\nexport interface ProgressPhoto {\n date: Date;\n progressPhoto: string;\n userUuid: string;\n}\n\nexport interface ForgotPassword {\n uuid: string;\n userUuid: string;\n token: string;\n date: Date;\n}\n\nexport interface RefreshPayload {\n userUuid: string;\n}\n\nexport interface TokenRequest {\n token: string;\n}\n\nexport interface RefreshRequest {\n refreshToken: string;\n}\n\nexport interface UuidRequest {\n userUuid: string;\n}\n\nexport interface EmailRequest {\n email: string;\n}\n\nexport interface TitleRequest {\n title: string;\n}\n\nexport interface UserPhoto {\n base64: string;\n title: string;\n}\n\nexport default interface AuthenticationToken {\n type: string;\n contents: string;\n}\n\nexport interface RestorePasswordRequest {\n email: string;\n}\n\nexport interface BeforeSubscriptionOptions {\n firstName: string;\n lastName: string;\n sex: string;\n goal: string;\n weightGoal: string;\n level: string;\n type: string;\n days: number;\n}\n\nexport interface AfterSubscriptionOptions {\n dateOfBirth: string;\n metricSystem: string;\n height: string;\n weight: string;\n}\n"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/models/UserInterfaces.ts"],"sourcesContent":["import type jwt from \"jsonwebtoken\";\n\nexport interface UserTypes {\n userUuid: string;\n email: string;\n firstName: string;\n lastName: string;\n avatar: string;\n role: string;\n isSubscriptionActive: boolean;\n}\n\nexport interface VerificationStatus {\n status: string;\n}\n\nexport interface TransactionsResponse {\n revision: string;\n bundleId: string;\n environment: string;\n hasMore: boolean;\n signedTransactions: string[];\n errorCode?: number;\n}\n\nexport interface UserInfoModel {\n userUuid: string;\n height: string;\n weight: string;\n}\n\nexport interface SingleTransactionResponse {\n revision: string;\n bundleId: string;\n environment: string;\n hasMore: boolean;\n signedTransactionInfo: string;\n errorCode?: number;\n}\n\nexport interface SubscriptionStatus {\n originalTransactionId: string;\n status: number;\n signedTransactionInfo: string;\n signedRenewalInfo: string;\n}\n\nexport interface SubscriptionStatusResponse {\n environment: string;\n bundleId: string;\n data: [\n {\n subscriptionGroupIdentifier: string;\n lastTransactions: SubscriptionStatus[];\n }\n ];\n errorCode?: number;\n}\n\nexport interface SubscriptionStatusResponseError {\n errorCode: number;\n errorMessage: string;\n}\n\nexport interface SubscriptionStatusResult {\n originalTransactionId: string;\n status: number;\n signedTransactionInfo: string | jwt.JwtPayload | null;\n signedRenewalInfo: string | jwt.JwtPayload | null;\n}\n\nexport interface SignedTransactions {\n transactionId: string;\n originalTransactionId: string;\n webOrderLineItemId: string;\n bundleId: string;\n productId: string;\n subscriptionGroupIdentifier: string;\n purchaseDate: number;\n originalPurchaseDate: number;\n expiresDate: number;\n quantity: number;\n type: string;\n inAppOwnershipType: string;\n signedDate: number;\n environment: string;\n transactionReason: string;\n storefront: string;\n storefrontId: string;\n}\n\nexport interface Credentials {\n refresh_token?: string | null,\n expiry_date?: number | null,\n access_token?: string | null,\n token_type?: string | null ,\n id_token?: string | null,\n scope?: string\n}\n\n\nexport interface LoginRequest {\n email: string;\n password: string;\n}\n\nexport interface UserPhotoRequest {\n base64: string;\n}\n\nexport interface ProgressPhoto {\n date: Date;\n progressPhoto: string;\n userUuid: string;\n}\n\nexport interface ForgotPassword {\n uuid: string;\n userUuid: string;\n token: string;\n date: Date;\n}\n\nexport interface RefreshPayload {\n userUuid: string;\n}\n\nexport interface TokenRequest {\n token: string;\n}\n\nexport interface RefreshRequest {\n refreshToken: string;\n}\n\nexport interface UuidRequest {\n userUuid: string;\n}\n\nexport interface EmailRequest {\n email: string;\n}\n\nexport interface TitleRequest {\n title: string;\n}\n\nexport interface UserPhoto {\n base64: string;\n title: string;\n}\n\nexport default interface AuthenticationToken {\n type: string;\n contents: string;\n}\n\nexport interface RestorePasswordRequest {\n email: string;\n}\n\nexport interface BeforeSubscriptionOptions {\n firstName: string;\n lastName: string;\n sex: string;\n goal: string;\n weightGoal: string;\n level: string;\n type: string;\n days: number;\n}\n\nexport interface AfterSubscriptionOptions {\n dateOfBirth: string;\n metricSystem: string;\n height: string;\n weight: string;\n}\n"],"names":[],"mappings":"AAAA,WAiLC"}
|
|
@@ -2,23 +2,10 @@ import jwt from "jsonwebtoken";
|
|
|
2
2
|
import type { LoginTicket } from "google-auth-library";
|
|
3
3
|
import { PersistedUser } from "../dbmodels/PersistedUser";
|
|
4
4
|
import type { Credentials as CredentialsType, SignedTransactions, SubscriptionStatusResult, UserTypes, VerificationStatus } from "../models/UserInterfaces";
|
|
5
|
-
/**
|
|
6
|
-
* Comprehensive Authentication Utility
|
|
7
|
-
* Handles JWT tokens, OAuth (Google, Apple, Facebook), and subscription verification (Apple, Google, Mollie)
|
|
8
|
-
*
|
|
9
|
-
* @class AuthenticationUtil
|
|
10
|
-
* @version 2.0.0 - Consolidated from auth-service and core
|
|
11
|
-
*/
|
|
12
5
|
export declare class AuthenticationUtil {
|
|
13
6
|
static readonly ACCESS_SECRET: string;
|
|
14
7
|
static readonly REFRESH_SECRET: string;
|
|
15
|
-
/**
|
|
16
|
-
* Fetch user from database using JWT token
|
|
17
|
-
*/
|
|
18
8
|
static fetchUserWithTokenInfo(token: string): Promise<PersistedUser | null>;
|
|
19
|
-
/**
|
|
20
|
-
* Verify JWT token and fetch user from database
|
|
21
|
-
*/
|
|
22
9
|
static verifyTokenAndFetchUser(token: string): Promise<PersistedUser | null | false>;
|
|
23
10
|
/**
|
|
24
11
|
* Sign access token
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationUtil.d.ts","sourceRoot":"","sources":["../../../src/lib/utils/AuthenticationUtil.ts"],"names":[],"mappings":"AACA,OAAO,GAAiC,MAAM,cAAc,CAAC;AAK7D,OAAO,KAAK,EAEV,WAAW,EAGZ,MAAM,qBAAqB,CAAC;AAI7B,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EACV,WAAW,IAAI,eAAe,EAC9B,kBAAkB,EAIlB,wBAAwB,EAExB,SAAS,EACT,kBAAkB,EAEnB,MAAM,0BAA0B,CAAC;AAclC
|
|
1
|
+
{"version":3,"file":"AuthenticationUtil.d.ts","sourceRoot":"","sources":["../../../src/lib/utils/AuthenticationUtil.ts"],"names":[],"mappings":"AACA,OAAO,GAAiC,MAAM,cAAc,CAAC;AAK7D,OAAO,KAAK,EAEV,WAAW,EAGZ,MAAM,qBAAqB,CAAC;AAI7B,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,KAAK,EACV,WAAW,IAAI,eAAe,EAC9B,kBAAkB,EAIlB,wBAAwB,EAExB,SAAS,EACT,kBAAkB,EAEnB,MAAM,0BAA0B,CAAC;AAclC,qBAAa,kBAAkB;IAC7B,gBAAuB,aAAa,SAA6C;IACjF,gBAAuB,cAAc,SAA8C;WAI/D,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC;WAQ1E,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,GAAG,KAAK,CAAC;IAmC3F;;OAEG;WACW,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM;IAMtD;;OAEG;WACW,gBAAgB,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM;IAIvD;;OAEG;WACW,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,KAAK,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E;;OAEG;WACiB,wBAAwB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAyBtF;;OAEG;WACiB,uBAAuB,CACvC,aAAa,EAAE,MAAM,EACrB,YAAY,EAAE,MAAM,GACrB,OAAO,CAAC,GAAG,CAAC;IAoBf;;OAEG;WACiB,qBAAqB,IAAI,OAAO,CAAC,eAAe,CAAC;IAYrE;;OAEG;WACiB,+BAA+B,CAAC,KAAK,EAAE,MAAM;IAiCjE;;OAEG;WACiB,4BAA4B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAwBlF"}
|
|
@@ -17,28 +17,17 @@ var TokenExpiration;
|
|
|
17
17
|
const appleJwksClient = jwksClient({
|
|
18
18
|
jwksUri: "https://appleid.apple.com/auth/keys"
|
|
19
19
|
});
|
|
20
|
-
|
|
21
|
-
* Comprehensive Authentication Utility
|
|
22
|
-
* Handles JWT tokens, OAuth (Google, Apple, Facebook), and subscription verification (Apple, Google, Mollie)
|
|
23
|
-
*
|
|
24
|
-
* @class AuthenticationUtil
|
|
25
|
-
* @version 2.0.0 - Consolidated from auth-service and core
|
|
26
|
-
*/ export class AuthenticationUtil {
|
|
27
|
-
// JWT Secrets
|
|
20
|
+
export class AuthenticationUtil {
|
|
28
21
|
static ACCESS_SECRET = process.env.ACCESS_TOKEN_SECRET;
|
|
29
22
|
static REFRESH_SECRET = process.env.REFRESH_TOKEN_SECRET;
|
|
30
|
-
|
|
31
|
-
* Fetch user from database using JWT token
|
|
32
|
-
*/ static async fetchUserWithTokenInfo(token) {
|
|
23
|
+
static async fetchUserWithTokenInfo(token) {
|
|
33
24
|
const userInToken = await AuthenticationUtil.verifyTokenAndFetchUser(token);
|
|
34
25
|
if (!userInToken || !userInToken.userUuid) {
|
|
35
26
|
return null;
|
|
36
27
|
}
|
|
37
28
|
return userInToken;
|
|
38
29
|
}
|
|
39
|
-
|
|
40
|
-
* Verify JWT token and fetch user from database
|
|
41
|
-
*/ static verifyTokenAndFetchUser(token) {
|
|
30
|
+
static verifyTokenAndFetchUser(token) {
|
|
42
31
|
return new Promise((resolve, reject)=>{
|
|
43
32
|
jwt.verify(token, this.ACCESS_SECRET, (err, decoded)=>{
|
|
44
33
|
if (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/lib/utils/AuthenticationUtil.ts"],"sourcesContent":["import * as dotenv from \"dotenv\";\nimport jwt, { JwtPayload, VerifyErrors } from \"jsonwebtoken\";\nimport axios, { AxiosResponse, isAxiosError } from \"axios\";\nimport fs from \"fs\";\nimport { google, androidpublisher_v3 } from \"googleapis\";\nimport * as bcrypt from \"bcryptjs\";\nimport type {\n Credentials,\n LoginTicket,\n OAuth2Client,\n TokenPayload,\n} from \"google-auth-library\";\nimport { OAuth2Client as OAuth2ClientImpl } from \"google-auth-library\";\nimport jwksClient, { SigningKey } from \"jwks-rsa\";\nimport Schema$SubscriptionPurchaseV2 = androidpublisher_v3.Schema$SubscriptionPurchaseV2;\nimport { PersistedUser } from \"../dbmodels/PersistedUser\";\nimport type {\n Credentials as CredentialsType,\n SignedTransactions,\n SingleTransactionResponse,\n SubscriptionStatusResponse,\n SubscriptionStatusResponseError,\n SubscriptionStatusResult,\n TransactionsResponse,\n UserTypes,\n VerificationStatus,\n LoginRequest,\n} from \"../models/UserInterfaces\";\nimport { AppleTransactionError } from \"../Errors/Errors\";\n\ndotenv.config();\n\nenum TokenExpiration {\n ACCESS = 60 * 60,\n REFRESH = 356 * 24 * 60 * 60,\n}\n\nconst appleJwksClient = jwksClient({\n jwksUri: \"https://appleid.apple.com/auth/keys\",\n});\n\n/**\n * Comprehensive Authentication Utility\n * Handles JWT tokens, OAuth (Google, Apple, Facebook), and subscription verification (Apple, Google, Mollie)\n *\n * @class AuthenticationUtil\n * @version 2.0.0 - Consolidated from auth-service and core\n */\nexport class AuthenticationUtil {\n // JWT Secrets\n public static readonly ACCESS_SECRET = process.env.ACCESS_TOKEN_SECRET as string;\n public static readonly REFRESH_SECRET = process.env.REFRESH_TOKEN_SECRET as string;\n\n\n /**\n * Fetch user from database using JWT token\n */\n public static async fetchUserWithTokenInfo(token: string): Promise<PersistedUser | null> {\n const userInToken = await AuthenticationUtil.verifyTokenAndFetchUser(token);\n if (!userInToken || !userInToken.userUuid) {\n return null;\n }\n return userInToken;\n }\n\n /**\n * Verify JWT token and fetch user from database\n */\n public static verifyTokenAndFetchUser(token: string): Promise<PersistedUser | null | false> {\n return new Promise<PersistedUser | null | false>((resolve, reject) => {\n jwt.verify(\n token,\n this.ACCESS_SECRET,\n (err: VerifyErrors | null, decoded: JwtPayload | string | undefined) => {\n if (err) {\n reject(err);\n return;\n }\n\n if (decoded === undefined) {\n resolve(null);\n return;\n }\n\n const user: UserTypes = <UserTypes>decoded;\n\n if (!user.userUuid) {\n resolve(false);\n return;\n }\n\n PersistedUser.findByPk(user.userUuid)\n .then((persistedUser: PersistedUser | null) => {\n resolve(persistedUser);\n })\n .catch((e: Error) => {\n reject(e);\n });\n }\n );\n });\n }\n\n /**\n * Sign access token\n */\n public static signAccessToken(user: UserTypes): string {\n return jwt.sign(user, this.ACCESS_SECRET, {\n expiresIn: TokenExpiration.ACCESS,\n });\n }\n\n /**\n * Sign refresh token\n */\n public static signRefreshToken(user: UserTypes): string {\n return jwt.sign(user, this.REFRESH_SECRET);\n }\n\n /**\n * Verify refresh token and return new access token\n */\n public static verifyRefreshToken(refreshToken: string): Promise<string | null | false> {\n return new Promise<string | null | false>((resolve, reject) => {\n jwt.verify(\n refreshToken,\n this.REFRESH_SECRET,\n async (err: VerifyErrors | null, user: JwtPayload | string | undefined) => {\n if (err) {\n reject(err);\n return;\n }\n\n if (user === undefined) {\n resolve(null);\n return;\n }\n\n const userTypes = <UserTypes>user;\n const newAccessToken = this.signAccessToken(userTypes);\n resolve(newAccessToken);\n }\n );\n });\n }\n\n // ==================== Password Management ====================\n\n /**\n * Hash password using bcrypt\n */\n public static async hashPassword(password: string): Promise<string> {\n return bcrypt.hash(password, 10);\n }\n\n /**\n * Compare password with hash\n */\n public static async comparePassword(plainPassword: string, hash: string): Promise<boolean> {\n return bcrypt.compare(plainPassword, hash);\n }\n\n // ==================== User Registration & Login ====================\n\n /**\n * Check if user is already registered\n */\n public static async checkIfUserAlreadyRegistered(email: string | undefined): Promise<boolean> {\n if (!email) return false;\n const user = await PersistedUser.findOne({ where: { email } });\n return user !== null;\n }\n\n /**\n * Login user with email and password\n */\n public static async login(email: string, password: string): Promise<PersistedUser | null> {\n const users = await PersistedUser.findAll({ where: { email } });\n\n if (!users || users.length === 0) {\n return null;\n }\n\n for (const user of users) {\n const passwordsMatch = await this.comparePassword(password, user.password);\n if (passwordsMatch) {\n return user;\n }\n }\n\n return null;\n }\n\n // ==================== Google OAuth ====================\n\n /**\n * Verify Google OAuth token\n */\n public static async verifyGoogleToken(\n idToken: string,\n audience: string\n ): Promise<LoginTicket | null> {\n const client = new OAuth2ClientImpl(audience);\n try {\n return await client.verifyIdToken({ idToken, audience });\n } catch (error) {\n console.error(\"Google Token Verification Error:\", error);\n return null;\n }\n }\n\n /**\n * Get Google OAuth client ID based on platform\n */\n public static getGoogleClientId(platform: string): string | undefined {\n switch (platform) {\n case \"android\":\n return process.env.ANDROID_GOOGLE_CLIENT_ID;\n case \"ios\":\n return process.env.IOS_GOOGLE_CLIENT_ID;\n case \"web\":\n return process.env.WEB_GOOGLE_CLIENT_ID;\n default:\n return undefined;\n }\n }\n\n // ==================== Apple OAuth & Subscriptions ====================\n\n /**\n * Generate Apple JWT for App Store Connect API\n */\n public static generateAppleJWT(): string {\n const privateKey: string = fs.readFileSync(\n process.env.APPLE_SUBSCRIPTION_KEY_PATH as string,\n \"utf-8\"\n );\n\n const header = {\n alg: \"ES256\",\n kid: process.env.APPLE_KID as string,\n typ: \"JWT\",\n };\n\n const payload = {\n iss: process.env.APPLE_ISSUER as string,\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + 3600,\n aud: \"appstoreconnect-v1\",\n bid: process.env.APPLE_BUNDLE_ID as string,\n };\n\n return jwt.sign(payload, privateKey, { header });\n }\n\n /**\n * Verify Apple JWT for Sign in with Apple\n */\n public static verifyAppleJwt(userData: string, key: string) {\n try {\n return jwt.verify(userData, key);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n /**\n * Get Apple Sign In public key\n */\n public static async getAppleSignInKey(kid: string): Promise<string | undefined> {\n try {\n const key: SigningKey = await appleJwksClient.getSigningKey(kid);\n return key.getPublicKey();\n } catch (e) {\n console.error(e);\n return undefined;\n }\n }\n\n /**\n * Verify Apple receipt (legacy)\n */\n public static async verifyAppleReceipt(data: string): Promise<VerificationStatus> {\n const response: AxiosResponse = await axios.post(\n \"https://buy.itunes.apple.com/verifyReceipt\",\n {\n \"receipt-data\": data,\n password: process.env.APPLE_SHARED_SECRET as string,\n \"exclude-old-transactions\": true,\n }\n );\n\n return response.data as VerificationStatus;\n }\n\n /**\n * Get Apple transaction history\n */\n public static async getAppleTransactions(\n originalTransactionId: string\n ): Promise<SignedTransactions[]> {\n const result: SignedTransactions[] = [];\n\n try {\n const response: AxiosResponse<TransactionsResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/history/${originalTransactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const token of response.data.signedTransactions) {\n result.push(jwt.decode(token) as SignedTransactions);\n }\n\n return result;\n } catch (error) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox environment\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<TransactionsResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/history/${originalTransactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const token of response.data.signedTransactions) {\n result.push(jwt.decode(token) as SignedTransactions);\n }\n\n return result;\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Get Apple subscription status\n */\n public static async getAppleSubscriptionsStatuses(\n transactionId: string\n ): Promise<SubscriptionStatusResult[]> {\n const result: SubscriptionStatusResult[] = [];\n\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.data[0].lastTransactions) {\n result.push({\n originalTransactionId: transaction.originalTransactionId,\n status: transaction.status,\n signedTransactionInfo: jwt.decode(transaction.signedTransactionInfo),\n signedRenewalInfo: jwt.decode(transaction.signedRenewalInfo),\n });\n }\n\n return result;\n } catch (error: unknown) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.data[0].lastTransactions) {\n result.push({\n originalTransactionId: transaction.originalTransactionId,\n status: transaction.status,\n signedTransactionInfo: jwt.decode(transaction.signedTransactionInfo),\n signedRenewalInfo: jwt.decode(transaction.signedRenewalInfo),\n });\n }\n\n return result;\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Check if Apple subscription is active\n */\n public static async isAppleSubscriptionActive(transactionId: string): Promise<boolean> {\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (\n response.data.data[0].lastTransactions[0].status === 0 ||\n response.data.data[0].lastTransactions[0].status === 2\n );\n } catch (e) {\n if (\n axios.isAxiosError(e) &&\n e.response &&\n (e.response.data as SubscriptionStatusResponseError)[\"errorMessage\"] ===\n \"Invalid transaction id.\"\n ) {\n return false;\n }\n return false;\n }\n }\n\n /**\n * Get single Apple transaction info\n */\n public static async getSingleAppleTransactionsInfo(transactionId: string) {\n try {\n const response: AxiosResponse<SingleTransactionResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/transactions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return { signedTransactionInfo: jwt.decode(response.data.signedTransactionInfo) };\n } catch (error) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<SingleTransactionResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/transactions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return { signedTransactionInfo: jwt.decode(response.data.signedTransactionInfo) };\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Check if user bought a program (non-consumable)\n */\n public static async checkIfUserBoughtProgram(transactionId: string): Promise<string[]> {\n try {\n const productIds: string[] = [];\n const url = process.env.PURCHASE_HISTORY_URL || \"https://api.storekit.itunes.apple.com\";\n const response: AxiosResponse = await axios.get(\n `${url}/inApps/v2/history/${transactionId}?productType=NON_CONSUMABLE`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.signedTransactions) {\n productIds.push((jwt.decode(transaction) as { productId: string }).productId);\n }\n\n return productIds;\n } catch (e) {\n console.error((e as Error).message);\n return [];\n }\n }\n\n /**\n * Extend Apple subscription\n */\n public static async extendAppleSubscription(\n transactionId: string,\n extendByDays: number\n ): Promise<any> {\n const response: AxiosResponse = await axios.put(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/extend/${transactionId}`,\n {\n extendByDays,\n extendReasonCode: 1,\n requestIdentifier: require(\"crypto\").randomUUID(),\n },\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n },\n }\n );\n\n return response.data;\n }\n\n // ==================== Android (Google Play) Subscriptions ====================\n\n /**\n * Get Android access token for Google Play API\n */\n public static async getAndroidAccessToken(): Promise<CredentialsType> {\n const keyPath = process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH as string;\n\n const jwtClient = new google.auth.JWT({\n keyFile: keyPath,\n scopes: [\"https://www.googleapis.com/auth/androidpublisher\"],\n });\n\n const authResponse: CredentialsType = await jwtClient.authorize();\n return authResponse;\n }\n\n /**\n * Get Android subscription status\n */\n public static async getAndroidSubscriptionsStatuses(token: string) {\n try {\n const credentials = await this.getAndroidAccessToken();\n\n const response: AxiosResponse = await axios.get(\n `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${process.env.ANDROID_PACKAGE_NAME || \"nl.browney.nintydayschallenge\"}/purchases/subscriptionsv2/tokens/${token}`,\n {\n headers: {\n Authorization: `Bearer ${credentials.access_token as string}`,\n },\n }\n );\n\n return response.data;\n } catch (error) {\n if (isAxiosError(error) && error.response && error.response.status === 410) {\n // Subscription expired\n return {\n lineItems: [\n {\n expiryTime: new Date(Date.now() - 86400000).toISOString(), // Yesterday\n },\n ],\n };\n } else {\n if (isAxiosError(error)) {\n console.error(\"Android subscription error:\", error.message);\n return false;\n }\n }\n }\n }\n\n /**\n * Check if Android subscription is active\n */\n public static async isAndroidSubscriptionsActive(token: string): Promise<boolean> {\n try {\n const credentials = await this.getAndroidAccessToken();\n\n const response: AxiosResponse = await axios.get(\n `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${process.env.ANDROID_PACKAGE_NAME || \"nl.browney.nintydayschallenge\"}/purchases/subscriptionsv2/tokens/${token}`,\n {\n headers: {\n Authorization: `Bearer ${credentials.access_token as string}`,\n },\n }\n );\n\n return (\n (response.data as { subscriptionState: string }).subscriptionState ===\n \"SUBSCRIPTION_STATE_ACTIVE\"\n );\n } catch (error) {\n if (isAxiosError(error)) {\n console.error(\"An error occurred:\", error.message);\n }\n return false;\n }\n }\n}\n"],"names":["dotenv","jwt","axios","isAxiosError","fs","google","bcrypt","OAuth2Client","OAuth2ClientImpl","jwksClient","PersistedUser","AppleTransactionError","config","TokenExpiration","ACCESS","REFRESH","appleJwksClient","jwksUri","AuthenticationUtil","ACCESS_SECRET","process","env","ACCESS_TOKEN_SECRET","REFRESH_SECRET","REFRESH_TOKEN_SECRET","fetchUserWithTokenInfo","token","userInToken","verifyTokenAndFetchUser","userUuid","Promise","resolve","reject","verify","err","decoded","undefined","user","findByPk","then","persistedUser","catch","e","signAccessToken","sign","expiresIn","signRefreshToken","verifyRefreshToken","refreshToken","userTypes","newAccessToken","hashPassword","password","hash","comparePassword","plainPassword","compare","checkIfUserAlreadyRegistered","email","findOne","where","login","users","findAll","length","passwordsMatch","verifyGoogleToken","idToken","audience","client","verifyIdToken","error","console","getGoogleClientId","platform","ANDROID_GOOGLE_CLIENT_ID","IOS_GOOGLE_CLIENT_ID","WEB_GOOGLE_CLIENT_ID","generateAppleJWT","privateKey","readFileSync","APPLE_SUBSCRIPTION_KEY_PATH","header","alg","kid","APPLE_KID","typ","payload","iss","APPLE_ISSUER","iat","Math","floor","Date","now","exp","aud","bid","APPLE_BUNDLE_ID","verifyAppleJwt","userData","key","getAppleSignInKey","getSigningKey","getPublicKey","verifyAppleReceipt","data","response","post","APPLE_SHARED_SECRET","getAppleTransactions","originalTransactionId","result","get","headers","Authorization","signedTransactions","push","decode","status","errorCode","getAppleSubscriptionsStatuses","transactionId","transaction","lastTransactions","signedTransactionInfo","signedRenewalInfo","isAppleSubscriptionActive","getSingleAppleTransactionsInfo","checkIfUserBoughtProgram","productIds","url","PURCHASE_HISTORY_URL","productId","message","extendAppleSubscription","extendByDays","put","extendReasonCode","requestIdentifier","require","randomUUID","getAndroidAccessToken","keyPath","GOOGLE_SERVICE_ACCOUNT_KEY_PATH","jwtClient","auth","JWT","keyFile","scopes","authResponse","authorize","getAndroidSubscriptionsStatuses","credentials","ANDROID_PACKAGE_NAME","access_token","lineItems","expiryTime","toISOString","isAndroidSubscriptionsActive","subscriptionState"],"mappings":"AAAA,YAAYA,YAAY,SAAS;AACjC,OAAOC,SAAuC,eAAe;AAC7D,OAAOC,SAAwBC,YAAY,QAAQ,QAAQ;AAC3D,OAAOC,QAAQ,KAAK;AACpB,SAASC,MAAM,QAA6B,aAAa;AACzD,YAAYC,YAAY,WAAW;AAOnC,SAASC,gBAAgBC,gBAAgB,QAAQ,sBAAsB;AACvE,OAAOC,gBAAgC,WAAW;AAElD,SAASC,aAAa,QAAQ,4BAA4B;AAa1D,SAASC,qBAAqB,QAAQ,mBAAmB;AAEzDX,OAAOY,MAAM;IAEb;UAAKC,eAAe;IAAfA,gBAAAA,gBACHC,YAAAA,QAAAA;IADGD,gBAAAA,gBAEHE,aAAAA,YAAAA;GAF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EAAyE,EAAE7F,QAAQC,GAAG,CAACqI,oBAAoB,IAAI,gCAAgC,kCAAkC,EAAEhI,MAAM,CAAC,EAC3L;gBACEwF,SAAS;oBACPC,eAAe,CAAC,OAAO,EAAEsC,YAAYE,YAAY,CAAW,CAAC;gBAC/D;YACF;YAGF,OACE,AAAChD,SAASD,IAAI,CAAmCsD,iBAAiB,KAClE;QAEJ,EAAE,OAAOzF,OAAO;YACd,IAAIpE,aAAaoE,QAAQ;gBACvBC,QAAQD,KAAK,CAAC,sBAAsBA,MAAM+D,OAAO;YACnD,CAAC;YACD,OAAO,KAAK;QACd;IACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/utils/AuthenticationUtil.ts"],"sourcesContent":["import * as dotenv from \"dotenv\";\nimport jwt, { JwtPayload, VerifyErrors } from \"jsonwebtoken\";\nimport axios, { AxiosResponse, isAxiosError } from \"axios\";\nimport fs from \"fs\";\nimport { google, androidpublisher_v3 } from \"googleapis\";\nimport * as bcrypt from \"bcryptjs\";\nimport type {\n Credentials,\n LoginTicket,\n OAuth2Client,\n TokenPayload,\n} from \"google-auth-library\";\nimport { OAuth2Client as OAuth2ClientImpl } from \"google-auth-library\";\nimport jwksClient, { SigningKey } from \"jwks-rsa\";\nimport Schema$SubscriptionPurchaseV2 = androidpublisher_v3.Schema$SubscriptionPurchaseV2;\nimport { PersistedUser } from \"../dbmodels/PersistedUser\";\nimport type {\n Credentials as CredentialsType,\n SignedTransactions,\n SingleTransactionResponse,\n SubscriptionStatusResponse,\n SubscriptionStatusResponseError,\n SubscriptionStatusResult,\n TransactionsResponse,\n UserTypes,\n VerificationStatus,\n LoginRequest,\n} from \"../models/UserInterfaces\";\nimport { AppleTransactionError } from \"../Errors/Errors\";\n\ndotenv.config();\n\nenum TokenExpiration {\n ACCESS = 60 * 60,\n REFRESH = 356 * 24 * 60 * 60,\n}\n\nconst appleJwksClient = jwksClient({\n jwksUri: \"https://appleid.apple.com/auth/keys\",\n});\n\nexport class AuthenticationUtil {\n public static readonly ACCESS_SECRET = process.env.ACCESS_TOKEN_SECRET as string;\n public static readonly REFRESH_SECRET = process.env.REFRESH_TOKEN_SECRET as string;\n\n\n\n public static async fetchUserWithTokenInfo(token: string): Promise<PersistedUser | null> {\n const userInToken = await AuthenticationUtil.verifyTokenAndFetchUser(token);\n if (!userInToken || !userInToken.userUuid) {\n return null;\n }\n return userInToken;\n }\n\n public static verifyTokenAndFetchUser(token: string): Promise<PersistedUser | null | false> {\n return new Promise<PersistedUser | null | false>((resolve, reject) => {\n jwt.verify(\n token,\n this.ACCESS_SECRET,\n (err: VerifyErrors | null, decoded: JwtPayload | string | undefined) => {\n if (err) {\n reject(err);\n return;\n }\n\n if (decoded === undefined) {\n resolve(null);\n return;\n }\n\n const user: UserTypes = <UserTypes>decoded;\n\n if (!user.userUuid) {\n resolve(false);\n return;\n }\n\n PersistedUser.findByPk(user.userUuid)\n .then((persistedUser: PersistedUser | null) => {\n resolve(persistedUser);\n })\n .catch((e: Error) => {\n reject(e);\n });\n }\n );\n });\n }\n\n /**\n * Sign access token\n */\n public static signAccessToken(user: UserTypes): string {\n return jwt.sign(user, this.ACCESS_SECRET, {\n expiresIn: TokenExpiration.ACCESS,\n });\n }\n\n /**\n * Sign refresh token\n */\n public static signRefreshToken(user: UserTypes): string {\n return jwt.sign(user, this.REFRESH_SECRET);\n }\n\n /**\n * Verify refresh token and return new access token\n */\n public static verifyRefreshToken(refreshToken: string): Promise<string | null | false> {\n return new Promise<string | null | false>((resolve, reject) => {\n jwt.verify(\n refreshToken,\n this.REFRESH_SECRET,\n async (err: VerifyErrors | null, user: JwtPayload | string | undefined) => {\n if (err) {\n reject(err);\n return;\n }\n\n if (user === undefined) {\n resolve(null);\n return;\n }\n\n const userTypes = <UserTypes>user;\n const newAccessToken = this.signAccessToken(userTypes);\n resolve(newAccessToken);\n }\n );\n });\n }\n\n // ==================== Password Management ====================\n\n /**\n * Hash password using bcrypt\n */\n public static async hashPassword(password: string): Promise<string> {\n return bcrypt.hash(password, 10);\n }\n\n /**\n * Compare password with hash\n */\n public static async comparePassword(plainPassword: string, hash: string): Promise<boolean> {\n return bcrypt.compare(plainPassword, hash);\n }\n\n // ==================== User Registration & Login ====================\n\n /**\n * Check if user is already registered\n */\n public static async checkIfUserAlreadyRegistered(email: string | undefined): Promise<boolean> {\n if (!email) return false;\n const user = await PersistedUser.findOne({ where: { email } });\n return user !== null;\n }\n\n /**\n * Login user with email and password\n */\n public static async login(email: string, password: string): Promise<PersistedUser | null> {\n const users = await PersistedUser.findAll({ where: { email } });\n\n if (!users || users.length === 0) {\n return null;\n }\n\n for (const user of users) {\n const passwordsMatch = await this.comparePassword(password, user.password);\n if (passwordsMatch) {\n return user;\n }\n }\n\n return null;\n }\n\n // ==================== Google OAuth ====================\n\n /**\n * Verify Google OAuth token\n */\n public static async verifyGoogleToken(\n idToken: string,\n audience: string\n ): Promise<LoginTicket | null> {\n const client = new OAuth2ClientImpl(audience);\n try {\n return await client.verifyIdToken({ idToken, audience });\n } catch (error) {\n console.error(\"Google Token Verification Error:\", error);\n return null;\n }\n }\n\n /**\n * Get Google OAuth client ID based on platform\n */\n public static getGoogleClientId(platform: string): string | undefined {\n switch (platform) {\n case \"android\":\n return process.env.ANDROID_GOOGLE_CLIENT_ID;\n case \"ios\":\n return process.env.IOS_GOOGLE_CLIENT_ID;\n case \"web\":\n return process.env.WEB_GOOGLE_CLIENT_ID;\n default:\n return undefined;\n }\n }\n\n // ==================== Apple OAuth & Subscriptions ====================\n\n /**\n * Generate Apple JWT for App Store Connect API\n */\n public static generateAppleJWT(): string {\n const privateKey: string = fs.readFileSync(\n process.env.APPLE_SUBSCRIPTION_KEY_PATH as string,\n \"utf-8\"\n );\n\n const header = {\n alg: \"ES256\",\n kid: process.env.APPLE_KID as string,\n typ: \"JWT\",\n };\n\n const payload = {\n iss: process.env.APPLE_ISSUER as string,\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + 3600,\n aud: \"appstoreconnect-v1\",\n bid: process.env.APPLE_BUNDLE_ID as string,\n };\n\n return jwt.sign(payload, privateKey, { header });\n }\n\n /**\n * Verify Apple JWT for Sign in with Apple\n */\n public static verifyAppleJwt(userData: string, key: string) {\n try {\n return jwt.verify(userData, key);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n /**\n * Get Apple Sign In public key\n */\n public static async getAppleSignInKey(kid: string): Promise<string | undefined> {\n try {\n const key: SigningKey = await appleJwksClient.getSigningKey(kid);\n return key.getPublicKey();\n } catch (e) {\n console.error(e);\n return undefined;\n }\n }\n\n /**\n * Verify Apple receipt (legacy)\n */\n public static async verifyAppleReceipt(data: string): Promise<VerificationStatus> {\n const response: AxiosResponse = await axios.post(\n \"https://buy.itunes.apple.com/verifyReceipt\",\n {\n \"receipt-data\": data,\n password: process.env.APPLE_SHARED_SECRET as string,\n \"exclude-old-transactions\": true,\n }\n );\n\n return response.data as VerificationStatus;\n }\n\n /**\n * Get Apple transaction history\n */\n public static async getAppleTransactions(\n originalTransactionId: string\n ): Promise<SignedTransactions[]> {\n const result: SignedTransactions[] = [];\n\n try {\n const response: AxiosResponse<TransactionsResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/history/${originalTransactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const token of response.data.signedTransactions) {\n result.push(jwt.decode(token) as SignedTransactions);\n }\n\n return result;\n } catch (error) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox environment\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<TransactionsResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/history/${originalTransactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const token of response.data.signedTransactions) {\n result.push(jwt.decode(token) as SignedTransactions);\n }\n\n return result;\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Get Apple subscription status\n */\n public static async getAppleSubscriptionsStatuses(\n transactionId: string\n ): Promise<SubscriptionStatusResult[]> {\n const result: SubscriptionStatusResult[] = [];\n\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.data[0].lastTransactions) {\n result.push({\n originalTransactionId: transaction.originalTransactionId,\n status: transaction.status,\n signedTransactionInfo: jwt.decode(transaction.signedTransactionInfo),\n signedRenewalInfo: jwt.decode(transaction.signedRenewalInfo),\n });\n }\n\n return result;\n } catch (error: unknown) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.data[0].lastTransactions) {\n result.push({\n originalTransactionId: transaction.originalTransactionId,\n status: transaction.status,\n signedTransactionInfo: jwt.decode(transaction.signedTransactionInfo),\n signedRenewalInfo: jwt.decode(transaction.signedRenewalInfo),\n });\n }\n\n return result;\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Check if Apple subscription is active\n */\n public static async isAppleSubscriptionActive(transactionId: string): Promise<boolean> {\n try {\n const response: AxiosResponse<SubscriptionStatusResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return (\n response.data.data[0].lastTransactions[0].status === 0 ||\n response.data.data[0].lastTransactions[0].status === 2\n );\n } catch (e) {\n if (\n axios.isAxiosError(e) &&\n e.response &&\n (e.response.data as SubscriptionStatusResponseError)[\"errorMessage\"] ===\n \"Invalid transaction id.\"\n ) {\n return false;\n }\n return false;\n }\n }\n\n /**\n * Get single Apple transaction info\n */\n public static async getSingleAppleTransactionsInfo(transactionId: string) {\n try {\n const response: AxiosResponse<SingleTransactionResponse> = await axios.get(\n `https://api.storekit.itunes.apple.com/inApps/v1/transactions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return { signedTransactionInfo: jwt.decode(response.data.signedTransactionInfo) };\n } catch (error) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n\n // Try sandbox\n if (\n isAxiosError(error) &&\n (error.response?.data.errorCode === 4040010 || error.response?.status === 401)\n ) {\n try {\n const response: AxiosResponse<SingleTransactionResponse> = await axios.get(\n `https://api.storekit-sandbox.itunes.apple.com/inApps/v1/transactions/${transactionId}`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n return { signedTransactionInfo: jwt.decode(response.data.signedTransactionInfo) };\n } catch (e) {\n if (isAxiosError(error) && error.response?.status === 400) {\n throw new AppleTransactionError(\"Invalid transaction id.\");\n }\n }\n throw new AppleTransactionError(\"Transaction was not found in both environments.\");\n }\n throw error;\n }\n }\n\n /**\n * Check if user bought a program (non-consumable)\n */\n public static async checkIfUserBoughtProgram(transactionId: string): Promise<string[]> {\n try {\n const productIds: string[] = [];\n const url = process.env.PURCHASE_HISTORY_URL || \"https://api.storekit.itunes.apple.com\";\n const response: AxiosResponse = await axios.get(\n `${url}/inApps/v2/history/${transactionId}?productType=NON_CONSUMABLE`,\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n \"Content-Type\": \"application/json\",\n },\n }\n );\n\n for (const transaction of response.data.signedTransactions) {\n productIds.push((jwt.decode(transaction) as { productId: string }).productId);\n }\n\n return productIds;\n } catch (e) {\n console.error((e as Error).message);\n return [];\n }\n }\n\n /**\n * Extend Apple subscription\n */\n public static async extendAppleSubscription(\n transactionId: string,\n extendByDays: number\n ): Promise<any> {\n const response: AxiosResponse = await axios.put(\n `https://api.storekit.itunes.apple.com/inApps/v1/subscriptions/extend/${transactionId}`,\n {\n extendByDays,\n extendReasonCode: 1,\n requestIdentifier: require(\"crypto\").randomUUID(),\n },\n {\n headers: {\n Authorization: `Bearer ${this.generateAppleJWT()}`,\n },\n }\n );\n\n return response.data;\n }\n\n // ==================== Android (Google Play) Subscriptions ====================\n\n /**\n * Get Android access token for Google Play API\n */\n public static async getAndroidAccessToken(): Promise<CredentialsType> {\n const keyPath = process.env.GOOGLE_SERVICE_ACCOUNT_KEY_PATH as string;\n\n const jwtClient = new google.auth.JWT({\n keyFile: keyPath,\n scopes: [\"https://www.googleapis.com/auth/androidpublisher\"],\n });\n\n const authResponse: CredentialsType = await jwtClient.authorize();\n return authResponse;\n }\n\n /**\n * Get Android subscription status\n */\n public static async getAndroidSubscriptionsStatuses(token: string) {\n try {\n const credentials = await this.getAndroidAccessToken();\n\n const response: AxiosResponse = await axios.get(\n `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${process.env.ANDROID_PACKAGE_NAME || \"nl.browney.nintydayschallenge\"}/purchases/subscriptionsv2/tokens/${token}`,\n {\n headers: {\n Authorization: `Bearer ${credentials.access_token as string}`,\n },\n }\n );\n\n return response.data;\n } catch (error) {\n if (isAxiosError(error) && error.response && error.response.status === 410) {\n // Subscription expired\n return {\n lineItems: [\n {\n expiryTime: new Date(Date.now() - 86400000).toISOString(), // Yesterday\n },\n ],\n };\n } else {\n if (isAxiosError(error)) {\n console.error(\"Android subscription error:\", error.message);\n return false;\n }\n }\n }\n }\n\n /**\n * Check if Android subscription is active\n */\n public static async isAndroidSubscriptionsActive(token: string): Promise<boolean> {\n try {\n const credentials = await this.getAndroidAccessToken();\n\n const response: AxiosResponse = await axios.get(\n `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${process.env.ANDROID_PACKAGE_NAME || \"nl.browney.nintydayschallenge\"}/purchases/subscriptionsv2/tokens/${token}`,\n {\n headers: {\n Authorization: `Bearer ${credentials.access_token as string}`,\n },\n }\n );\n\n return (\n (response.data as { subscriptionState: string }).subscriptionState ===\n \"SUBSCRIPTION_STATE_ACTIVE\"\n );\n } catch (error) {\n if (isAxiosError(error)) {\n console.error(\"An error occurred:\", error.message);\n }\n return false;\n }\n }\n}\n"],"names":["dotenv","jwt","axios","isAxiosError","fs","google","bcrypt","OAuth2Client","OAuth2ClientImpl","jwksClient","PersistedUser","AppleTransactionError","config","TokenExpiration","ACCESS","REFRESH","appleJwksClient","jwksUri","AuthenticationUtil","ACCESS_SECRET","process","env","ACCESS_TOKEN_SECRET","REFRESH_SECRET","REFRESH_TOKEN_SECRET","fetchUserWithTokenInfo","token","userInToken","verifyTokenAndFetchUser","userUuid","Promise","resolve","reject","verify","err","decoded","undefined","user","findByPk","then","persistedUser","catch","e","signAccessToken","sign","expiresIn","signRefreshToken","verifyRefreshToken","refreshToken","userTypes","newAccessToken","hashPassword","password","hash","comparePassword","plainPassword","compare","checkIfUserAlreadyRegistered","email","findOne","where","login","users","findAll","length","passwordsMatch","verifyGoogleToken","idToken","audience","client","verifyIdToken","error","console","getGoogleClientId","platform","ANDROID_GOOGLE_CLIENT_ID","IOS_GOOGLE_CLIENT_ID","WEB_GOOGLE_CLIENT_ID","generateAppleJWT","privateKey","readFileSync","APPLE_SUBSCRIPTION_KEY_PATH","header","alg","kid","APPLE_KID","typ","payload","iss","APPLE_ISSUER","iat","Math","floor","Date","now","exp","aud","bid","APPLE_BUNDLE_ID","verifyAppleJwt","userData","key","getAppleSignInKey","getSigningKey","getPublicKey","verifyAppleReceipt","data","response","post","APPLE_SHARED_SECRET","getAppleTransactions","originalTransactionId","result","get","headers","Authorization","signedTransactions","push","decode","status","errorCode","getAppleSubscriptionsStatuses","transactionId","transaction","lastTransactions","signedTransactionInfo","signedRenewalInfo","isAppleSubscriptionActive","getSingleAppleTransactionsInfo","checkIfUserBoughtProgram","productIds","url","PURCHASE_HISTORY_URL","productId","message","extendAppleSubscription","extendByDays","put","extendReasonCode","requestIdentifier","require","randomUUID","getAndroidAccessToken","keyPath","GOOGLE_SERVICE_ACCOUNT_KEY_PATH","jwtClient","auth","JWT","keyFile","scopes","authResponse","authorize","getAndroidSubscriptionsStatuses","credentials","ANDROID_PACKAGE_NAME","access_token","lineItems","expiryTime","toISOString","isAndroidSubscriptionsActive","subscriptionState"],"mappings":"AAAA,YAAYA,YAAY,SAAS;AACjC,OAAOC,SAAuC,eAAe;AAC7D,OAAOC,SAAwBC,YAAY,QAAQ,QAAQ;AAC3D,OAAOC,QAAQ,KAAK;AACpB,SAASC,MAAM,QAA6B,aAAa;AACzD,YAAYC,YAAY,WAAW;AAOnC,SAASC,gBAAgBC,gBAAgB,QAAQ,sBAAsB;AACvE,OAAOC,gBAAgC,WAAW;AAElD,SAASC,aAAa,QAAQ,4BAA4B;AAa1D,SAASC,qBAAqB,QAAQ,mBAAmB;AAEzDX,OAAOY,MAAM;IAEb;UAAKC,eAAe;IAAfA,gBAAAA,gBACHC,YAAAA,QAAAA;IADGD,gBAAAA,gBAEHE,aAAAA,YAAAA;G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,oBAAoB,IAAI,gCAAgC,kCAAkC,EAAEhI,MAAM,CAAC,EAC3L;gBACEwF,SAAS;oBACPC,eAAe,CAAC,OAAO,EAAEsC,YAAYE,YAAY,CAAW,CAAC;gBAC/D;YACF;YAGJ,OACI,AAAChD,SAASD,IAAI,CAAmCsD,iBAAiB,KAClE;QAEN,EAAE,OAAOzF,OAAO;YACd,IAAIpE,aAAaoE,QAAQ;gBACvBC,QAAQD,KAAK,CAAC,sBAAsBA,MAAM+D,OAAO;YACnD,CAAC;YACD,OAAO,KAAK;QACd;IACF;AACF,CAAC"}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import type { NotificationPayload, EmailReminderPayload, GroupNotificationRequest, NotificationRequest, CreateNotificationRequest, NotificationTranslationRequest } from "../models/NotificationInterfaces";
|
|
2
|
+
/**
|
|
3
|
+
* Configuration for the notification client
|
|
4
|
+
*/
|
|
5
|
+
export interface NotificationClientConfig {
|
|
6
|
+
baseURL: string;
|
|
7
|
+
timeout?: number;
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Abandoned cart notification payload
|
|
12
|
+
*/
|
|
13
|
+
export interface AbandonedCartPayload {
|
|
14
|
+
email: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Password restoration types
|
|
18
|
+
*/
|
|
19
|
+
export type PasswordRestorationType = "change" | "reset" | "platform-reset";
|
|
20
|
+
/**
|
|
21
|
+
* Password restoration request
|
|
22
|
+
*/
|
|
23
|
+
export interface PasswordRestorationRequest {
|
|
24
|
+
email: string;
|
|
25
|
+
type: PasswordRestorationType;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Email confirmation request
|
|
29
|
+
*/
|
|
30
|
+
export interface EmailConfirmationRequest {
|
|
31
|
+
type: "main" | "utility";
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Shopify email request
|
|
35
|
+
*/
|
|
36
|
+
export interface ShopifyEmailRequest {
|
|
37
|
+
email: string;
|
|
38
|
+
name: string;
|
|
39
|
+
orderNumber: string;
|
|
40
|
+
items: Array<{
|
|
41
|
+
name: string;
|
|
42
|
+
quantity: number;
|
|
43
|
+
price: number;
|
|
44
|
+
}>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Challenge friend email request
|
|
48
|
+
*/
|
|
49
|
+
export interface ChallengeFriendRequest {
|
|
50
|
+
friendsEmail: string;
|
|
51
|
+
name: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* NotificationClient
|
|
55
|
+
*
|
|
56
|
+
* Provides methods to interact with the notification service via HTTP API.
|
|
57
|
+
* This allows services to send notifications without direct database access
|
|
58
|
+
* or code duplication.
|
|
59
|
+
*/
|
|
60
|
+
export declare class NotificationClient {
|
|
61
|
+
private client;
|
|
62
|
+
/**
|
|
63
|
+
* Create a new notification client
|
|
64
|
+
*
|
|
65
|
+
* @param config - Client configuration with base URL and optional settings
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* const notificationClient = new NotificationClient({
|
|
70
|
+
* baseURL: 'http://localhost:3037',
|
|
71
|
+
* timeout: 5000
|
|
72
|
+
* });
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
constructor(config: NotificationClientConfig);
|
|
76
|
+
/**
|
|
77
|
+
* Schedule a push notification for a specific user
|
|
78
|
+
*
|
|
79
|
+
* @param payload - Notification details including user UUID and notification type
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* await client.scheduleNotification({
|
|
84
|
+
* userUuid: '123e4567-e89b-12d3-a456-426614174000',
|
|
85
|
+
* name: 'workout_reminder'
|
|
86
|
+
* });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
scheduleNotification(payload: NotificationPayload): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Send immediate notification to a specific user
|
|
92
|
+
*
|
|
93
|
+
* @param userUuid - User UUID
|
|
94
|
+
* @param notification - Notification content
|
|
95
|
+
* @returns Message ID from Firebase
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```typescript
|
|
99
|
+
* const messageId = await client.sendToUser('user-uuid', {
|
|
100
|
+
* title: 'Workout Reminder',
|
|
101
|
+
* body: 'Time for your daily workout!',
|
|
102
|
+
* redirectPath: '/workout'
|
|
103
|
+
* });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
sendToUser(userUuid: string, notification: NotificationRequest): Promise<string>;
|
|
107
|
+
/**
|
|
108
|
+
* Send notification to multiple users in batch
|
|
109
|
+
*
|
|
110
|
+
* @param userUuids - Array of user UUIDs
|
|
111
|
+
* @param notification - Notification content
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```typescript
|
|
115
|
+
* await client.sendToUsers(['uuid1', 'uuid2'], {
|
|
116
|
+
* title: 'New Feature',
|
|
117
|
+
* body: 'Check out what's new!'
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
sendToUsers(userUuids: string[], notification: NotificationRequest): Promise<void>;
|
|
122
|
+
/**
|
|
123
|
+
* Send notification to all users
|
|
124
|
+
*
|
|
125
|
+
* @param notification - Notification content
|
|
126
|
+
* @returns Total number of users notified
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* const totalSent = await client.sendToAllUsers({
|
|
131
|
+
* title: 'System Update',
|
|
132
|
+
* body: 'App will be updated soon'
|
|
133
|
+
* });
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
sendToAllUsers(notification: NotificationRequest): Promise<number>;
|
|
137
|
+
/**
|
|
138
|
+
* Send a push notification to a specific group of users
|
|
139
|
+
*
|
|
140
|
+
* @param request - Group notification request with target group and message
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```typescript
|
|
144
|
+
* await client.sendGroupNotification({
|
|
145
|
+
* group: NotificationGroups.PREMIUM,
|
|
146
|
+
* notification: {
|
|
147
|
+
* title: 'New Feature!',
|
|
148
|
+
* body: 'Check out our new workout plans'
|
|
149
|
+
* }
|
|
150
|
+
* });
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
sendGroupNotification(request: GroupNotificationRequest): Promise<void>;
|
|
154
|
+
/**
|
|
155
|
+
* Schedule an email checkout reminder
|
|
156
|
+
*
|
|
157
|
+
* @param payload - Email reminder details
|
|
158
|
+
*/
|
|
159
|
+
scheduleEmailReminder(payload: EmailReminderPayload): Promise<void>;
|
|
160
|
+
/**
|
|
161
|
+
* Send abandoned cart notification
|
|
162
|
+
*
|
|
163
|
+
* @param payload - Abandoned cart details with user email
|
|
164
|
+
*/
|
|
165
|
+
sendAbandonedCart(payload: AbandonedCartPayload): Promise<void>;
|
|
166
|
+
/**
|
|
167
|
+
* Send password restoration email
|
|
168
|
+
*
|
|
169
|
+
* @param request - Password restoration request
|
|
170
|
+
*/
|
|
171
|
+
sendPasswordRestoration(request: PasswordRestorationRequest): Promise<void>;
|
|
172
|
+
/**
|
|
173
|
+
* Send email confirmation
|
|
174
|
+
*
|
|
175
|
+
* @param request - Email confirmation request
|
|
176
|
+
* @param authToken - User authentication token (required)
|
|
177
|
+
*/
|
|
178
|
+
sendEmailConfirmation(request: EmailConfirmationRequest, authToken: string): Promise<void>;
|
|
179
|
+
/**
|
|
180
|
+
* Send Shopify email
|
|
181
|
+
*
|
|
182
|
+
* @param request - Shopify email details
|
|
183
|
+
*/
|
|
184
|
+
sendShopifyEmail(request: ShopifyEmailRequest): Promise<void>;
|
|
185
|
+
/**
|
|
186
|
+
* Send challenge friend invitation email
|
|
187
|
+
*
|
|
188
|
+
* @param request - Challenge friend request
|
|
189
|
+
*/
|
|
190
|
+
sendChallengeFriendEmail(request: ChallengeFriendRequest): Promise<void>;
|
|
191
|
+
/**
|
|
192
|
+
* Send account deletion email
|
|
193
|
+
*
|
|
194
|
+
* @param authToken - User authentication token (required)
|
|
195
|
+
*/
|
|
196
|
+
sendDeleteAccountEmail(authToken: string): Promise<void>;
|
|
197
|
+
/**
|
|
198
|
+
* Send export finished email
|
|
199
|
+
*
|
|
200
|
+
* @param authToken - User authentication token (required)
|
|
201
|
+
*/
|
|
202
|
+
sendExportFinishedEmail(authToken: string): Promise<void>;
|
|
203
|
+
/**
|
|
204
|
+
* Create a new notification template
|
|
205
|
+
*
|
|
206
|
+
* @param request - Notification template details
|
|
207
|
+
* @returns The created notification UUID
|
|
208
|
+
*/
|
|
209
|
+
createNotification(request: CreateNotificationRequest): Promise<string>;
|
|
210
|
+
/**
|
|
211
|
+
* Create a notification translation
|
|
212
|
+
*
|
|
213
|
+
* @param request - Translation details
|
|
214
|
+
*/
|
|
215
|
+
createNotificationTranslation(request: NotificationTranslationRequest): Promise<void>;
|
|
216
|
+
/**
|
|
217
|
+
* Update a notification template
|
|
218
|
+
*
|
|
219
|
+
* @param request - Updated notification details
|
|
220
|
+
*/
|
|
221
|
+
updateNotification(request: NotificationTranslationRequest): Promise<void>;
|
|
222
|
+
/**
|
|
223
|
+
* Update a notification translation
|
|
224
|
+
*
|
|
225
|
+
* @param request - Updated translation details
|
|
226
|
+
*/
|
|
227
|
+
updateNotificationTranslation(request: NotificationTranslationRequest): Promise<void>;
|
|
228
|
+
/**
|
|
229
|
+
* Get all notifications, optionally filtered by language
|
|
230
|
+
*
|
|
231
|
+
* @param language - Optional language code to filter translations
|
|
232
|
+
* @returns Array of notifications with translations
|
|
233
|
+
*/
|
|
234
|
+
getNotifications(language?: string): Promise<any[]>;
|
|
235
|
+
/**
|
|
236
|
+
* Delete a notification or translation
|
|
237
|
+
*
|
|
238
|
+
* @param uuid - Notification UUID
|
|
239
|
+
* @param language - Optional language code to delete only translation
|
|
240
|
+
*/
|
|
241
|
+
deleteNotification(uuid: string, language?: string): Promise<void>;
|
|
242
|
+
/**
|
|
243
|
+
* Handle and format errors from notification service
|
|
244
|
+
*/
|
|
245
|
+
private handleError;
|
|
246
|
+
}
|
|
247
|
+
//# sourceMappingURL=NotificationClient.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NotificationClient.d.ts","sourceRoot":"","sources":["../../../src/lib/utils/NotificationClient.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,mBAAmB,EACnB,yBAAyB,EACzB,8BAA8B,EAC/B,MAAM,kCAAkC,CAAC;AAE1C;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,QAAQ,GAAG,OAAO,GAAG,gBAAgB,CAAC;AAE5E;;GAEG;AACH,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,uBAAuB,CAAC;CAC/B;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,KAAK,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,MAAM,CAAC;QACjB,KAAK,EAAE,MAAM,CAAC;KACf,CAAC,CAAC;CACJ;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;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