@lyxa.ai/core 1.3.113 → 1.3.115
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/libraries/mongo/models/user.model.js +3 -2
- package/dist/libraries/mongo/models/user.model.js.map +1 -1
- package/dist/libraries/socket/adapters/socket-subscription.d.ts +1 -2
- package/dist/libraries/socket/adapters/socket-subscription.js +1 -8
- package/dist/libraries/socket/adapters/socket-subscription.js.map +1 -1
- package/dist/libraries/trpc/middlewares/auth.js +22 -0
- package/dist/libraries/trpc/middlewares/auth.js.map +1 -1
- package/dist/types/README.md +1 -1
- package/dist/types/package.json +1 -1
- package/dist/types/utilities/validation/common-validation.d.ts +12 -12
- package/package.json +1 -1
|
@@ -104,7 +104,7 @@ __decorate([
|
|
|
104
104
|
__metadata("design:type", Boolean)
|
|
105
105
|
], User.prototype, "isSubscribed", void 0);
|
|
106
106
|
__decorate([
|
|
107
|
-
(0, typegoose_1.prop)({ type: String
|
|
107
|
+
(0, typegoose_1.prop)({ type: String }),
|
|
108
108
|
__metadata("design:type", String)
|
|
109
109
|
], User.prototype, "phoneNumber", void 0);
|
|
110
110
|
__decorate([
|
|
@@ -134,6 +134,7 @@ __decorate([
|
|
|
134
134
|
exports.User = User = User_1 = __decorate([
|
|
135
135
|
(0, typegoose_1.modelOptions)({ schemaOptions: { collection: 'users' } }),
|
|
136
136
|
(0, typegoose_1.index)({ location: '2dsphere' }),
|
|
137
|
-
(0, typegoose_1.index)({ createdAt: 1, addresses: 1 })
|
|
137
|
+
(0, typegoose_1.index)({ createdAt: 1, addresses: 1 }),
|
|
138
|
+
(0, typegoose_1.index)({ phoneNumber: 1 }, { unique: true, partialFilterExpression: { deletedAt: null, phoneNumber: { $exists: true, $ne: null } } })
|
|
138
139
|
], User);
|
|
139
140
|
//# sourceMappingURL=user.model.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user.model.js","sourceRoot":"/","sources":["libraries/mongo/models/user.model.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,oDAAuF;AACvF,4EAAqE;AACrE,uDAA6C;AAC7C,0DAAqD;AACrD,iDAAwC;AACxC,6DAAoD;AACpD,kDAAuD;AACvD,kEAAwD;AACxD,oEAA0D;AAC1D,0DAAiD;
|
|
1
|
+
{"version":3,"file":"user.model.js","sourceRoot":"/","sources":["libraries/mongo/models/user.model.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,oDAAuF;AACvF,4EAAqE;AACrE,uDAA6C;AAC7C,0DAAqD;AACrD,iDAAwC;AACxC,6DAAoD;AACpD,kDAAuD;AACvD,kEAAwD;AACxD,oEAA0D;AAC1D,0DAAiD;AAS1C,IAAM,IAAI,YAAV,MAAM,IAAK,SAAQ,2BAAU;IAE5B,QAAQ,CAAiB;IAGzB,QAAQ,CAAU;IAGlB,SAAS,CAAiB;IAG1B,QAAQ,CAAe;IAGvB,cAAc,CAAU;IAGxB,eAAe,CAAQ;IAGvB,OAAO,CAAiB;IAGxB,yBAAyB,CAAU;IAGnC,kBAAkB,CAAU;IAG5B,iCAAiC,CAAU;IAG3C,qBAAqB,CAAW;IAGhC,YAAY,CAAe;IAG3B,YAAY,CAAqB;IAGjC,YAAY,CAAW;IAGvB,WAAW,CAAU;IAGrB,YAAY,CAAa;IAGzB,eAAe,CAAW;IAO1B,YAAY,CAAgB;IAG5B,SAAS,CAAY;IAGrB,MAAM,CAAU;IAEhB,MAAM,CAAC,KAAK,CAAC,YAAY,CAE/B,MAAc,EACd,IAAI,GAAG,CAAC,EACR,OAAO,GAAG,CAAC;QAEX,OAAO,IAAI,CAAC,iBAAiB,CAC5B,MAAM,EACN,EAAE,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,cAAc,EAAE,IAAI,GAAG,OAAO,EAAE,EAAE,EAC5F,EAAE,GAAG,EAAE,IAAI,EAAE,CACb,CAAC;IACH,CAAC;CACD,CAAA;AA7EY,oBA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AAI,CA6EhB","sourcesContent":["import { index, modelOptions, prop, Ref, ReturnModelType } from '@typegoose/typegoose';\nimport { TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';\nimport { CoreUser } from './core-user.model';\nimport { UserAddress } from './shared/address.model';\nimport { Coupon } from './coupon.model';\nimport { Subscription } from './subscription.model';\nimport { OnlineStatus } from '../../../utilities/enum';\nimport { OTPFields } from './embedded/otp-fields.model';\nimport { GeoLocation } from './shared/geo-location.model';\nimport { Wallet } from './embedded/wallet.model';\n\n@modelOptions({ schemaOptions: { collection: 'users' } })\n@index({ location: '2dsphere' })\n@index({ createdAt: 1, addresses: 1 })\n@index(\n\t{ phoneNumber: 1 },\n\t{ unique: true, partialFilterExpression: { deletedAt: null, phoneNumber: { $exists: true, $ne: null } } }\n)\nexport class User extends TimeStamps {\n\t@prop({ required: true, ref: () => CoreUser })\n\tpublic coreUser!: Ref<CoreUser>;\n\n\t@prop({ type: () => String })\n\tpublic deviceId?: string;\n\n\t@prop({ type: () => [UserAddress], default: [] })\n\tpublic addresses?: UserAddress[];\n\n\t@prop({ type: GeoLocation }) // Last order location for finding user zone\n\tpublic location?: GeoLocation;\n\n\t@prop({ type: Number, default: 0 })\n\tpublic orderCompleted?: number;\n\n\t@prop({ type: Date })\n\tpublic repeatedOrderAt?: Date;\n\n\t@prop({ ref: () => Coupon })\n\tpublic coupons?: Ref<Coupon>[];\n\n\t@prop({ type: String })\n\tpublic newUserCouponDiscountType?: string;\n\n\t@prop({ type: Number })\n\tpublic newUserCouponValue?: number;\n\n\t@prop({ type: Number })\n\tpublic newUserCouponMaximumDiscountLimit?: number;\n\n\t@prop({ type: Boolean, default: false })\n\tpublic isNewUserCouponShowed?: boolean;\n\n\t@prop({ ref: () => Coupon })\n\tpublic referralCode?: Ref<Coupon>;\n\n\t@prop({ type: String, ref: () => Subscription })\n\tpublic subscription?: Ref<Subscription>;\n\n\t@prop({ type: Boolean, default: false })\n\tpublic isSubscribed?: boolean;\n\n\t@prop({ type: String })\n\tpublic phoneNumber?: string;\n\n\t@prop({ type: () => OTPFields })\n\tpublic phoneOtpInfo?: OTPFields;\n\n\t@prop({ type: Boolean, default: false })\n\tpublic isPhoneVerified?: boolean;\n\n\t@prop({\n\t\ttype: String,\n\t\tenum: OnlineStatus,\n\t\tdefault: OnlineStatus.OFFLINE,\n\t})\n\tpublic onlineStatus?: OnlineStatus;\n\n\t@prop({ type: () => [String], default: [] })\n\tpublic fcmTokens?: string[];\n\n\t@prop({ type: Wallet })\n\tpublic wallet?: Wallet;\n\n\tpublic static async updateWallet(\n\t\tthis: ReturnModelType<typeof User>,\n\t\tuserId: string,\n\t\tmain = 0,\n\t\treserve = 0\n\t) {\n\t\treturn this.findByIdAndUpdate(\n\t\t\tuserId,\n\t\t\t{ $inc: { 'wallet.main': main, 'wallet.reserve': reserve, 'wallet.total': main + reserve } },\n\t\t\t{ new: true }\n\t\t);\n\t}\n}\n"]}
|
|
@@ -3,7 +3,6 @@ import { InputFor, OutputFor } from '../core';
|
|
|
3
3
|
import { TokenType } from '../../auth';
|
|
4
4
|
import { ProcedureResolverOptions } from '@trpc/server/unstable-core-do-not-import';
|
|
5
5
|
import { EntityContext, LyxaHTTPContext } from '../../trpc/context';
|
|
6
|
-
import mongoose from 'mongoose';
|
|
7
6
|
type optsType<TEventType extends SocketEventType, TInput extends InputFor<TEventType>> = ProcedureResolverOptions<object, LyxaHTTPContext, {
|
|
8
7
|
res: import('http').ServerResponse<import('http').IncomingMessage>;
|
|
9
8
|
tokenType: TokenType | undefined;
|
|
@@ -13,6 +12,6 @@ type optsType<TEventType extends SocketEventType, TInput extends InputFor<TEvent
|
|
|
13
12
|
usedRefreshToken: boolean | undefined;
|
|
14
13
|
tokenRenewed: boolean | undefined;
|
|
15
14
|
}, TInput>;
|
|
16
|
-
export declare function getEntityId(entity: EntityContext): string
|
|
15
|
+
export declare function getEntityId(entity: EntityContext): string;
|
|
17
16
|
export declare function createSocketSubscriptionAdapter<TEventType extends SocketEventType, TInput extends InputFor<TEventType>>(eventType: TEventType): (opts: optsType<TEventType, TInput>) => AsyncGenerator<Awaited<OutputFor<TEventType>>, void, unknown>;
|
|
18
17
|
export {};
|
|
@@ -5,18 +5,11 @@ exports.createSocketSubscriptionAdapter = createSocketSubscriptionAdapter;
|
|
|
5
5
|
const core_1 = require("../core");
|
|
6
6
|
const crypto_1 = require("crypto");
|
|
7
7
|
const instance_utils_1 = require("../../../utilities/instance.utils");
|
|
8
|
-
const auth_1 = require("../../auth");
|
|
9
8
|
const events_1 = require("events");
|
|
10
9
|
const index_1 = require("../../../index");
|
|
11
10
|
const connections_1 = require("../connections");
|
|
12
11
|
function getEntityId(entity) {
|
|
13
|
-
|
|
14
|
-
case auth_1.AuthEntityType.SELLER:
|
|
15
|
-
const shops = entity.parameters.shops;
|
|
16
|
-
return shops[0];
|
|
17
|
-
default:
|
|
18
|
-
return entity.id;
|
|
19
|
-
}
|
|
12
|
+
return entity.id;
|
|
20
13
|
}
|
|
21
14
|
async function* _createSocketSubscription(eventType, opts) {
|
|
22
15
|
const { ctx } = opts;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket-subscription.js","sourceRoot":"/","sources":["libraries/socket/adapters/socket-subscription.ts"],"names":[],"mappings":";;AA4CA,
|
|
1
|
+
{"version":3,"file":"socket-subscription.js","sourceRoot":"/","sources":["libraries/socket/adapters/socket-subscription.ts"],"names":[],"mappings":";;AA4CA,kCAUC;AA2CD,0EAKC;AArGD,kCAA0F;AAC1F,mCAAoC;AACpC,sEAAkE;AAIlE,mCAA4B;AAC5B,0CAA8C;AAE9C,gDAIwB;AA8BxB,SAAgB,WAAW,CAAC,MAAqB;IAShD,OAAO,MAAM,CAAC,EAAE,CAAC;AAClB,CAAC;AAED,KAAK,SAAS,CAAC,CAAC,yBAAyB,CAGvC,SAAqB,EAAE,IAAkC;IAC1D,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACrB,MAAM,MAAM,GAAG,IAAA,oBAAY,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,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,kCAAkC,CAAC,CAAC;IAClF,CAAC,CAAC,CAAC;IAIH,IAAI,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,IAAA,WAAE,EAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QAC9E,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,kCAAkC,CAAC,CAAC;QACvF,MAAM,IAAW,CAAC;IACnB,CAAC;AACF,CAAC;AAED,SAAgB,+BAA+B,CAG7C,SAAqB;IACtB,OAAO,CAAC,IAAkC,EAAE,EAAE,CAAC,yBAAyB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import { SocketEventType } from '../../../utilities/enum';\nimport { EventFactory, InputFor, LocalEventEmitter, LocalSubs, OutputFor } from '../core';\nimport { randomUUID } from 'crypto';\nimport { getInstanceId } from '../../../utilities/instance.utils';\nimport { AuthEntityType, TokenType } from '../../auth';\nimport { ProcedureResolverOptions } from '@trpc/server/unstable-core-do-not-import';\nimport { EntityContext, LyxaHTTPContext } from '../../trpc/context';\nimport { on } from 'events';\nimport { getLibraries } from '../../../index';\nimport mongoose from 'mongoose';\nimport {\n\tconnectEntityToSocketEvent,\n\tdisconnectEntityFromSocketEvent,\n\tEntitySubscription,\n} from '../connections';\n\ntype optsType<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n> = ProcedureResolverOptions<\n\tobject,\n\tLyxaHTTPContext,\n\t{\n\t\tres: import('http').ServerResponse<import('http').IncomingMessage>;\n\t\ttokenType: TokenType | undefined;\n\t\tentity: EntityContext | undefined;\n\t\treq: import('http').IncomingMessage;\n\t\trequestId: string | undefined;\n\t\tusedRefreshToken: boolean | undefined;\n\t\ttokenRenewed: boolean | undefined;\n\t},\n\tTInput\n>;\n\ninterface _SubscriptionContext {\n\tentity?: { id: string; type: AuthEntityType };\n\tsignal?: AbortSignal;\n}\n\ninterface _SubscriptionOpts<TEventType extends SocketEventType, TInput extends InputFor<TEventType>> {\n\tctx: _SubscriptionContext;\n\tinput: TInput;\n}\n\nexport function getEntityId(entity: EntityContext ) {\n\t// switch (entity.type) {\n\t// \tcase AuthEntityType.SELLER:\n\t// \t\tconst shops = entity.parameters.shops as mongoose.Types.ObjectId[];\n\t// \t\treturn shops[0];\n\t// \tdefault:\n\t// \t\treturn entity.id;\n\t// }\n\n\treturn entity.id;\n}\n\nasync function* _createSocketSubscription<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType, opts: optsType<TEventType, TInput>) {\n\tconst { ctx } = opts;\n\tconst logger = getLibraries().getLogger().logger;\n\n\t// --- USE getEntityId ---\n\tif (!ctx.entity) throw new Error('Entity is required for socket subscription');\n\tconst entityId = getEntityId(ctx.entity);\n\n\tlogger.debug(`Entity ID: ${entityId}`);\n\tconst entity: EntitySubscription = { id: entityId.toString(), type: ctx.entity.type };\n\n\tconst eventKey = EventFactory.getSubscriptionKey(eventType, opts.input);\n\tconsole.log('Event Key:', eventKey);\n\tconst socketId = randomUUID();\n\tconst socketInfo = { socketId, eventKey, instanceId: getInstanceId() };\n\n\tconst localEE = new LocalEventEmitter(socketId);\n\n\t// --- CONNECT ---\n\tawait connectEntityToSocketEvent(entity, socketInfo);\n\tLocalSubs.bind(entity, eventKey, localEE);\n\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription connected');\n\n\t// --- DISCONNECT ---\n\topts.signal?.addEventListener('abort', () => {\n\t\tLocalSubs.unbind(entity, eventKey, localEE);\n\t\tdisconnectEntityFromSocketEvent(entity, socketInfo);\n\t\tlogger.debug({ entity, socketId, eventKey }, 'Socket subscription disconnected');\n\t});\n\n\t// --- STREAM EVENTS ---\n\ttype Out = OutputFor<TEventType>;\n\tfor await (const [data] of on(localEE.ee, eventKey, { signal: opts.signal })) {\n\t\tlogger.debug({ entity, socketId, eventKey, data }, 'Socket subscription sending data');\n\t\tyield data as Out;\n\t}\n}\n\nexport function createSocketSubscriptionAdapter<\n\tTEventType extends SocketEventType,\n\tTInput extends InputFor<TEventType>,\n>(eventType: TEventType) {\n\treturn (opts: optsType<TEventType, TInput>) => _createSocketSubscription(eventType, opts);\n}\n\n/**\n * @Example\n * const socketRouterTwo = createTRPCRouter({\n * \tonMessage: createAuthenticatedProcedure({ entityTypes: [AuthEntityType.CRM] })\n * \t\t.input(ChatroomMessageSendSocketInputSchema)\n * \t\t.output(zAsyncIterable({ yield: ChatroomMessageSendOutputSchema }))\n * \t\t.subscription(createSocketSubscriptionAdapter(SocketEventType.CHATROOM_MESSAGE_SEND)),\n * });\n */\n"]}
|
|
@@ -40,6 +40,28 @@ function createAuthenticatedProcedure(options) {
|
|
|
40
40
|
if (admin.status !== enum_1.Status.ACTIVE)
|
|
41
41
|
(0, error_common_1.unauthorizedError)('Admin is not active');
|
|
42
42
|
}
|
|
43
|
+
if (entity?.type == auth_1.AuthEntityType.SELLER) {
|
|
44
|
+
const shopAccessControlModel = await models_1.ShopAccessControlModel.findOne({ _id: entity.id });
|
|
45
|
+
if (!shopAccessControlModel)
|
|
46
|
+
throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });
|
|
47
|
+
if (['parent', 'parent_manager', 'parent_order_manager'].includes(shopAccessControlModel.role)) {
|
|
48
|
+
const parent = await models_1.ParentModel.findOne({ _id: entity.parent });
|
|
49
|
+
if (!parent)
|
|
50
|
+
throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });
|
|
51
|
+
if (parent.status !== enum_1.Status.ACTIVE)
|
|
52
|
+
(0, error_common_1.unauthorizedError)('Seller is not active');
|
|
53
|
+
}
|
|
54
|
+
const shops = shopAccessControlModel.shops ?? [];
|
|
55
|
+
if (shops.length > 0 &&
|
|
56
|
+
['shop', 'shop_manager', 'shop_order_manager'].includes(shopAccessControlModel.role)) {
|
|
57
|
+
const shopId = shops[0];
|
|
58
|
+
const shop = await models_1.ShopModel.findOne({ _id: shopId });
|
|
59
|
+
if (!shop)
|
|
60
|
+
throw new server_1.TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });
|
|
61
|
+
if (shop.status !== enum_1.Status.ACTIVE)
|
|
62
|
+
(0, error_common_1.unauthorizedError)('Seller is not active');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
43
65
|
if (entity?.type == auth_1.AuthEntityType.DELIVERY_BOY) {
|
|
44
66
|
const rider = await models_1.RiderModel.findOne({ _id: entity.id });
|
|
45
67
|
if (!rider)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sourceRoot":"/","sources":["libraries/trpc/middlewares/auth.ts"],"names":[],"mappings":";;AAiBA,oEAgGC;AAjHD,yCAAyC;AACzC,oCAA2C;AAC3C,qCAA+F;AAC/F,+CAA8E;AAC9E,kDAAiD;AACjD,kEAAoE;AAYpE,SAAgB,4BAA4B,CAAC,OAAoB;IAChE,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,IAAI,EAAE,WAAW,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAE9E,OAAO,uBAAe,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE;QAClD,MAAM,UAAU,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;QACpD,MAAM,kBAAkB,GAAG,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAE9D,IAAI,CAAC,UAAU,EAAE,CAAC;YACjB,MAAM,IAAI,kBAAS,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,yBAAyB,EAAE,CAAC,CAAC;QACnF,CAAC;QAED,MAAM,WAAW,GAAG,UAAU,CAAC,OA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a,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,gCAAgC,CAAC,CAAC,CAAC,uBAAuB,CAAC;YAEtG,IAAA,gCAAiB,EAAC,YAAY,CAAC,CAAC;QACjC,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,aAAa,CAAC,MAAO,CAAC,IAAI,CAAC;YAAE,IAAA,gCAAiB,EAAC,0BAA0B,CAAC,CAAC;QAErG,GAAG,CAAC,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC;QAClC,GAAG,CAAC,SAAS,GAAG,gBAAS,CAAC,OAAO,CAAC;QAClC,GAAG,CAAC,gBAAgB,GAAG,IAAI,CAAC;QAE5B,GAAG,CAAC,YAAY,GAAG,aAAa,CAAC,WAAW,KAAK,SAAS,CAAC;QAE3D,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE,CAAC;YAC5C,IAAI,aAAa,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;gBACzC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,oBAAoB,EAAE,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;YAC9E,CAAC;YAED,IAAI,aAAa,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;gBAC1C,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,qBAAqB,EAAE,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAChF,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACtB,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { TRPCError } from '@trpc/server';\nimport { publicProcedure } from '../index';\nimport { AuthEntityType, handleTokenRenewal, TokenType, verifyAccessToken, } from '../../auth';\nimport { AdminModel, getCoreUserModel, RiderModel } from '../../mongo/models';\nimport { Status } from '../../../utilities/enum';\nimport { unauthorizedError } from '../../../utilities/error-common';\n\ninterface AuthOptions {\n\tentityTypes: AuthEntityType[];\n\tallowRefreshToken?: boolean;\n\tautoRefresh?: boolean;\n}\n\n/**\n * A factory that creates an authenticated procedure, optionally allowing\n * refresh tokens and auto-refreshing expired access tokens.\n */\nexport function createAuthenticatedProcedure(options: AuthOptions) {\n\tconst { entityTypes, allowRefreshToken = true, autoRefresh = true } = options;\n\n\treturn publicProcedure.use(async ({ ctx, next }) => {\n\t\tconst authHeader = ctx.req.headers['authorization'];\n\t\tconst refreshTokenHeader = ctx.req.headers['x-refresh-token'];\n\n\t\tif (!authHeader) {\n\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'No authorization header' });\n\t\t}\n\n\t\tconst accessToken = authHeader.replace(/^Bearer\\s+/, '');\n\t\tlet refreshToken = '';\n\n\t\tif (refreshTokenHeader) {\n\t\t\trefreshToken =\n\t\t\t\ttypeof refreshTokenHeader === 'string'\n\t\t\t\t\t? refreshTokenHeader.replace(/^Bearer\\s+/, '')\n\t\t\t\t\t: refreshTokenHeader[0].replace(/^Bearer\\s+/, '');\n\t\t}\n\n\t\tif (!accessToken) unauthorizedError('Missing access token');\n\n\t\tlet entity = await verifyAccessToken(entityTypes, accessToken);\n\n\t\tif (entity?.type == AuthEntityType.USER) {\n\t\t\tconst user = await getCoreUserModel().findOne({ _id: entity.parameters.coreUserId });\n\n\t\t\tif (!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'User not found' });\n\t\t\tif (user.status !== Status.ACTIVE) unauthorizedError('User is not active');\n\t\t}\n\n\t\tif (entity?.type == AuthEntityType.CRM) {\n\t\t\tconst admin = await AdminModel.findOne({ _id: entity.parameters.adminId });\n\n\t\t\tif (!admin) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\t\t\tif (admin.status !== Status.ACTIVE) unauthorizedError('Admin is not active');\n\t\t}\n\n\t\t// For rider\n\t\tif(entity?.type == AuthEntityType.DELIVERY_BOY) {\n\t\t\tconst rider = await RiderModel.findOne({ _id: entity.id });\n\n\t\t\t// Check the rider exists or not\n\t\t\tif (!rider) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\n\t\t\t// Check the rider isLogin true or false\n\t\t\tif (rider.isLogin) {\n\t\t\t\tif (rider.lastLoginDeviceId !== entity.parameters.deviceId) {\n\t\t\t\t\tunauthorizedError('You already logged in another device');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunauthorizedError('You have been logged out, Please login in again');\n\t\t\t}\n\t\t}\n\n\t\tif (entity) {\n\t\t\tctx.entity = entity;\n\t\t\tctx.tokenType = TokenType.ACCESS;\n\t\t\tctx.usedRefreshToken = false;\n\t\t\tctx.tokenRenewed = false;\n\n\t\t\treturn next({ ctx });\n\t\t}\n\n\t\tif (!allowRefreshToken || !refreshToken) unauthorizedError('Invalid access token');\n\n\t\tconst renewalResult = await handleTokenRenewal(refreshToken);\n\n\t\tif (!renewalResult.success) {\n\t\t\tconst errorMessage =\n\t\t\t\trenewalResult.tokenStatus === 'revoked' ? 'Refresh token has been revoked' : 'Invalid refresh token';\n\n\t\t\tunauthorizedError(errorMessage);\n\t\t}\n\n\t\tif (!entityTypes.includes(renewalResult.entity!.type)) unauthorizedError('Unauthorized entity type');\n\n\t\tctx.entity = renewalResult.entity;\n\t\tctx.tokenType = TokenType.REFRESH;\n\t\tctx.usedRefreshToken = true;\n\n\t\tctx.tokenRenewed = renewalResult.tokenStatus === 'expired';\n\n\t\tif (autoRefresh && renewalResult.newTokens) {\n\t\t\tif (renewalResult.newTokens.accessToken) {\n\t\t\t\tctx.res.setHeader('X-New-Access-Token', renewalResult.newTokens.accessToken);\n\t\t\t}\n\n\t\t\tif (renewalResult.newTokens.refreshToken) {\n\t\t\t\tctx.res.setHeader('X-New-Refresh-Token', renewalResult.newTokens.refreshToken);\n\t\t\t}\n\t\t}\n\n\t\treturn next({ ctx });\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"/","sources":["libraries/trpc/middlewares/auth.ts"],"names":[],"mappings":";;AAwBA,oEA6HC;AArJD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AgB,GAAG,IAAI,CAAC;QAE5B,GAAG,CAAC,YAAY,GAAG,aAAa,CAAC,WAAW,KAAK,SAAS,CAAC;QAE3D,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE,CAAC;YAC5C,IAAI,aAAa,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;gBACzC,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,oBAAoB,EAAE,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;YAC9E,CAAC;YAED,IAAI,aAAa,CAAC,SAAS,CAAC,YAAY,EAAE,CAAC;gBAC1C,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,qBAAqB,EAAE,aAAa,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;YAChF,CAAC;QACF,CAAC;QAED,OAAO,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACtB,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { TRPCError } from '@trpc/server';\nimport { publicProcedure } from '../index';\nimport { AuthEntityType, handleTokenRenewal, TokenType, verifyAccessToken, } from '../../auth';\nimport {\n\tAdminModel,\n\tgetCoreUserModel,\n\tParentModel,\n\tRiderModel,\n\tShopAccessControlModel,\n\tShopModel,\n} from '../../mongo/models';\nimport { Status } from '../../../utilities/enum';\nimport { unauthorizedError } from '../../../utilities/error-common';\n\ninterface AuthOptions {\n\tentityTypes: AuthEntityType[];\n\tallowRefreshToken?: boolean;\n\tautoRefresh?: boolean;\n}\n\n/**\n * A factory that creates an authenticated procedure, optionally allowing\n * refresh tokens and auto-refreshing expired access tokens.\n */\nexport function createAuthenticatedProcedure(options: AuthOptions) {\n\tconst { entityTypes, allowRefreshToken = true, autoRefresh = true } = options;\n\n\treturn publicProcedure.use(async ({ ctx, next }) => {\n\t\tconst authHeader = ctx.req.headers['authorization'];\n\t\tconst refreshTokenHeader = ctx.req.headers['x-refresh-token'];\n\n\t\tif (!authHeader) {\n\t\t\tthrow new TRPCError({ code: 'UNAUTHORIZED', message: 'No authorization header' });\n\t\t}\n\n\t\tconst accessToken = authHeader.replace(/^Bearer\\s+/, '');\n\t\tlet refreshToken = '';\n\n\t\tif (refreshTokenHeader) {\n\t\t\trefreshToken =\n\t\t\t\ttypeof refreshTokenHeader === 'string'\n\t\t\t\t\t? refreshTokenHeader.replace(/^Bearer\\s+/, '')\n\t\t\t\t\t: refreshTokenHeader[0].replace(/^Bearer\\s+/, '');\n\t\t}\n\n\t\tif (!accessToken) unauthorizedError('Missing access token');\n\n\t\tlet entity = await verifyAccessToken(entityTypes, accessToken);\n\n\t\tif (entity?.type == AuthEntityType.USER) {\n\t\t\tconst user = await getCoreUserModel().findOne({ _id: entity.parameters.coreUserId });\n\n\t\t\tif (!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'User not found' });\n\t\t\tif (user.status !== Status.ACTIVE) unauthorizedError('User is not active');\n\t\t}\n\n\t\tif (entity?.type == AuthEntityType.CRM) {\n\t\t\tconst admin = await AdminModel.findOne({ _id: entity.parameters.adminId });\n\n\t\t\tif (!admin) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\t\t\tif (admin.status !== Status.ACTIVE) unauthorizedError('Admin is not active');\n\t\t}\n\n\t\t// Seller\n\t\tif (entity?.type == AuthEntityType.SELLER) {\n\t\t\tconst shopAccessControlModel = await ShopAccessControlModel.findOne({ _id: entity.id });\n\n\t\t\tif (!shopAccessControlModel) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });\n\n\t\t\t// For Parent\n\t\t\tif (['parent', 'parent_manager', 'parent_order_manager'].includes(shopAccessControlModel.role)) {\n\t\t\t\tconst parent = await ParentModel.findOne({ _id: entity.parent });\n\n\t\t\t\tif (!parent) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });\n\t\t\t\tif (parent.status !== Status.ACTIVE) unauthorizedError('Seller is not active');\n\t\t\t}\n\n\t\t\t// For Shop\n\t\t\tconst shops = shopAccessControlModel.shops ?? [];\n\n\t\t\tif (\n\t\t\t\tshops.length > 0 &&\n\t\t\t\t['shop', 'shop_manager', 'shop_order_manager'].includes(shopAccessControlModel.role)\n\t\t\t) {\n\t\t\t\tconst shopId = shops[0];\n\t\t\t\tconst shop = await ShopModel.findOne({ _id: shopId });\n\n\t\t\t\tif (!shop) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Seller not found' });\n\t\t\t\tif (shop.status !== Status.ACTIVE) unauthorizedError('Seller is not active');\n\t\t\t}\n\t\t}\n\n\t\t// For rider\n\t\tif (entity?.type == AuthEntityType.DELIVERY_BOY) {\n\t\t\tconst rider = await RiderModel.findOne({ _id: entity.id });\n\n\t\t\t// Check the rider exists or not\n\t\t\tif (!rider) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Admin not found' });\n\n\t\t\t// Check the rider isLogin true or false\n\t\t\tif (rider.isLogin) {\n\t\t\t\tif (rider.lastLoginDeviceId !== entity.parameters.deviceId) {\n\t\t\t\t\tunauthorizedError('You already logged in another device');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunauthorizedError('You have been logged out, Please login in again');\n\t\t\t}\n\t\t}\n\n\t\tif (entity) {\n\t\t\tctx.entity = entity;\n\t\t\tctx.tokenType = TokenType.ACCESS;\n\t\t\tctx.usedRefreshToken = false;\n\t\t\tctx.tokenRenewed = false;\n\n\t\t\treturn next({ ctx });\n\t\t}\n\n\t\tif (!allowRefreshToken || !refreshToken) unauthorizedError('Invalid access token');\n\n\t\tconst renewalResult = await handleTokenRenewal(refreshToken);\n\n\t\tif (!renewalResult.success) {\n\t\t\tconst errorMessage =\n\t\t\t\trenewalResult.tokenStatus === 'revoked' ? 'Refresh token has been revoked' : 'Invalid refresh token';\n\n\t\t\tunauthorizedError(errorMessage);\n\t\t}\n\n\t\tif (!entityTypes.includes(renewalResult.entity!.type)) unauthorizedError('Unauthorized entity type');\n\n\t\tctx.entity = renewalResult.entity;\n\t\tctx.tokenType = TokenType.REFRESH;\n\t\tctx.usedRefreshToken = true;\n\n\t\tctx.tokenRenewed = renewalResult.tokenStatus === 'expired';\n\n\t\tif (autoRefresh && renewalResult.newTokens) {\n\t\t\tif (renewalResult.newTokens.accessToken) {\n\t\t\t\tctx.res.setHeader('X-New-Access-Token', renewalResult.newTokens.accessToken);\n\t\t\t}\n\n\t\t\tif (renewalResult.newTokens.refreshToken) {\n\t\t\t\tctx.res.setHeader('X-New-Refresh-Token', renewalResult.newTokens.refreshToken);\n\t\t\t}\n\t\t}\n\n\t\treturn next({ ctx });\n\t});\n}\n"]}
|
package/dist/types/README.md
CHANGED
package/dist/types/package.json
CHANGED
|
@@ -26,8 +26,8 @@ export declare const FilterSchema: z.ZodOptional<z.ZodObject<{
|
|
|
26
26
|
searchFields?: string[] | undefined;
|
|
27
27
|
} | undefined;
|
|
28
28
|
sort?: Record<string, 1 | -1> | undefined;
|
|
29
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
30
29
|
populate?: any;
|
|
30
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
31
31
|
query?: Record<string, any> | undefined;
|
|
32
32
|
}, {
|
|
33
33
|
search?: {
|
|
@@ -36,8 +36,8 @@ export declare const FilterSchema: z.ZodOptional<z.ZodObject<{
|
|
|
36
36
|
} | undefined;
|
|
37
37
|
sort?: Record<string, 1 | -1> | undefined;
|
|
38
38
|
size?: number | undefined;
|
|
39
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
40
39
|
populate?: any;
|
|
40
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
41
41
|
query?: Record<string, any> | undefined;
|
|
42
42
|
page?: number | undefined;
|
|
43
43
|
}>>;
|
|
@@ -733,12 +733,12 @@ export declare const GetByIdInputSchema: z.ZodObject<{
|
|
|
733
733
|
populate: z.ZodOptional<z.ZodUnion<[z.ZodType<any, z.ZodTypeDef, any>, z.ZodArray<z.ZodType<any, z.ZodTypeDef, any>, "many">]>>;
|
|
734
734
|
}, "strip", z.ZodTypeAny, {
|
|
735
735
|
_id: import("mongoose").Types.ObjectId;
|
|
736
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
737
736
|
populate?: any;
|
|
737
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
738
738
|
}, {
|
|
739
739
|
_id: string | import("mongoose").Types.ObjectId;
|
|
740
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
741
740
|
populate?: any;
|
|
741
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
742
742
|
}>;
|
|
743
743
|
export type GetByIdInputDTO = DTO<typeof GetByIdInputSchema>;
|
|
744
744
|
export declare const GetProductByIdInputSchema: z.ZodObject<{
|
|
@@ -751,12 +751,12 @@ export declare const GetProductByIdInputSchema: z.ZodObject<{
|
|
|
751
751
|
_id: import("mongoose").Types.ObjectId;
|
|
752
752
|
withAttributeHiddenItems: boolean;
|
|
753
753
|
withAddonsHiddenItems: boolean;
|
|
754
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
755
754
|
populate?: any;
|
|
755
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
756
756
|
}, {
|
|
757
757
|
_id: string | import("mongoose").Types.ObjectId;
|
|
758
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
759
758
|
populate?: any;
|
|
759
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
760
760
|
withAttributeHiddenItems?: boolean | undefined;
|
|
761
761
|
withAddonsHiddenItems?: boolean | undefined;
|
|
762
762
|
}>;
|
|
@@ -768,13 +768,13 @@ export declare const GetOrderByIdInputSchema: z.ZodObject<{
|
|
|
768
768
|
userOrderCompletionScope: z.ZodOptional<z.ZodNativeEnum<typeof UserOrderCompletionScope>>;
|
|
769
769
|
}, "strip", z.ZodTypeAny, {
|
|
770
770
|
_id: import("mongoose").Types.ObjectId;
|
|
771
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
772
771
|
populate?: any;
|
|
772
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
773
773
|
userOrderCompletionScope?: UserOrderCompletionScope | undefined;
|
|
774
774
|
}, {
|
|
775
775
|
_id: string | import("mongoose").Types.ObjectId;
|
|
776
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
777
776
|
populate?: any;
|
|
777
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
778
778
|
userOrderCompletionScope?: UserOrderCompletionScope | undefined;
|
|
779
779
|
}>;
|
|
780
780
|
export type GetOrderByIdInputDTO = DTO<typeof GetOrderByIdInputSchema>;
|
|
@@ -782,11 +782,11 @@ export declare const GetByTokenInputSchema: z.ZodOptional<z.ZodObject<{
|
|
|
782
782
|
select: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>]>>>;
|
|
783
783
|
populate: z.ZodOptional<z.ZodUnion<[z.ZodType<any, z.ZodTypeDef, any>, z.ZodArray<z.ZodType<any, z.ZodTypeDef, any>, "many">]>>;
|
|
784
784
|
}, "strip", z.ZodTypeAny, {
|
|
785
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
786
785
|
populate?: any;
|
|
787
|
-
}, {
|
|
788
786
|
select?: Record<string, 0 | 1> | undefined;
|
|
787
|
+
}, {
|
|
789
788
|
populate?: any;
|
|
789
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
790
790
|
}>>;
|
|
791
791
|
export type GetByTokenInputDTO = DTO<typeof GetByTokenInputSchema>;
|
|
792
792
|
export declare const GetOneQuerySchema: z.ZodObject<{
|
|
@@ -794,12 +794,12 @@ export declare const GetOneQuerySchema: z.ZodObject<{
|
|
|
794
794
|
select: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodLiteral<0>, z.ZodLiteral<1>]>>>;
|
|
795
795
|
populate: z.ZodOptional<z.ZodUnion<[z.ZodType<any, z.ZodTypeDef, any>, z.ZodArray<z.ZodType<any, z.ZodTypeDef, any>, "many">]>>;
|
|
796
796
|
}, "strip", z.ZodTypeAny, {
|
|
797
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
798
797
|
populate?: any;
|
|
798
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
799
799
|
query?: Record<string, any> | undefined;
|
|
800
800
|
}, {
|
|
801
|
-
select?: Record<string, 0 | 1> | undefined;
|
|
802
801
|
populate?: any;
|
|
802
|
+
select?: Record<string, 0 | 1> | undefined;
|
|
803
803
|
query?: Record<string, any> | undefined;
|
|
804
804
|
}>;
|
|
805
805
|
export type GetOneQueryDTO = DTO<typeof GetOneQuerySchema>;
|