equipped 4.0.0-alpha-10
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/CHANGELOG.md +64 -0
- package/lib/bull/index.d.ts +37 -0
- package/lib/bull/index.js +93 -0
- package/lib/cache/cache.d.ts +7 -0
- package/lib/cache/cache.js +6 -0
- package/lib/cache/types/redis-cache.d.ts +11 -0
- package/lib/cache/types/redis-cache.js +40 -0
- package/lib/emails/index.d.ts +14 -0
- package/lib/emails/index.js +13 -0
- package/lib/enums/index.d.ts +19 -0
- package/lib/enums/index.js +29 -0
- package/lib/enums/types.d.ts +36 -0
- package/lib/enums/types.js +22 -0
- package/lib/errors/customError.d.ts +14 -0
- package/lib/errors/customError.js +12 -0
- package/lib/errors/index.d.ts +10 -0
- package/lib/errors/index.js +26 -0
- package/lib/errors/types/accessTokenExpired.d.ts +5 -0
- package/lib/errors/types/accessTokenExpired.js +12 -0
- package/lib/errors/types/accountNotVerifiedError.d.ts +5 -0
- package/lib/errors/types/accountNotVerifiedError.js +12 -0
- package/lib/errors/types/badRequestError.d.ts +5 -0
- package/lib/errors/types/badRequestError.js +12 -0
- package/lib/errors/types/invalidToken.d.ts +5 -0
- package/lib/errors/types/invalidToken.js +12 -0
- package/lib/errors/types/notAuthenticatedError.d.ts +5 -0
- package/lib/errors/types/notAuthenticatedError.js +12 -0
- package/lib/errors/types/notAuthorizedError.d.ts +5 -0
- package/lib/errors/types/notAuthorizedError.js +12 -0
- package/lib/errors/types/notFoundError.d.ts +5 -0
- package/lib/errors/types/notFoundError.js +12 -0
- package/lib/errors/types/refreshTokenMisusedError.d.ts +5 -0
- package/lib/errors/types/refreshTokenMisusedError.js +12 -0
- package/lib/errors/types/validationError.d.ts +10 -0
- package/lib/errors/types/validationError.js +12 -0
- package/lib/events/events.d.ts +17 -0
- package/lib/events/events.js +26 -0
- package/lib/events/rabbit.d.ts +4 -0
- package/lib/events/rabbit.js +44 -0
- package/lib/exit.d.ts +1 -0
- package/lib/exit.js +25 -0
- package/lib/express/app.d.ts +16 -0
- package/lib/express/app.js +127 -0
- package/lib/express/controllers/index.d.ts +13 -0
- package/lib/express/controllers/index.js +76 -0
- package/lib/express/controllers/request.d.ts +31 -0
- package/lib/express/controllers/request.js +48 -0
- package/lib/express/index.d.ts +5 -0
- package/lib/express/index.js +20 -0
- package/lib/express/middlewares/errorHandler.d.ts +1 -0
- package/lib/express/middlewares/errorHandler.js +22 -0
- package/lib/express/middlewares/index.d.ts +4 -0
- package/lib/express/middlewares/index.js +20 -0
- package/lib/express/middlewares/notFoundHandler.d.ts +1 -0
- package/lib/express/middlewares/notFoundHandler.js +8 -0
- package/lib/express/middlewares/parseAuthUser.d.ts +1 -0
- package/lib/express/middlewares/parseAuthUser.js +15 -0
- package/lib/express/middlewares/requireAuthUser.d.ts +2 -0
- package/lib/express/middlewares/requireAuthUser.js +11 -0
- package/lib/express/middlewares/requireRefreshUser.d.ts +2 -0
- package/lib/express/middlewares/requireRefreshUser.js +14 -0
- package/lib/express/statusCodes.d.ts +16 -0
- package/lib/express/statusCodes.js +17 -0
- package/lib/index.d.ts +18 -0
- package/lib/index.js +45 -0
- package/lib/instance.d.ts +43 -0
- package/lib/instance.js +115 -0
- package/lib/listeners/emitter.d.ts +20 -0
- package/lib/listeners/emitter.js +132 -0
- package/lib/listeners/index.d.ts +1 -0
- package/lib/listeners/index.js +17 -0
- package/lib/logger/index.d.ts +16 -0
- package/lib/logger/index.js +25 -0
- package/lib/mongoose/changeStreams.d.ts +25 -0
- package/lib/mongoose/changeStreams.js +93 -0
- package/lib/mongoose/index.d.ts +4 -0
- package/lib/mongoose/index.js +24 -0
- package/lib/mongoose/query.d.ts +60 -0
- package/lib/mongoose/query.js +97 -0
- package/lib/storage/index.d.ts +18 -0
- package/lib/storage/index.js +2 -0
- package/lib/structure/baseEntity.d.ts +5 -0
- package/lib/structure/baseEntity.js +21 -0
- package/lib/structure/baseMapper.d.ts +4 -0
- package/lib/structure/baseMapper.js +6 -0
- package/lib/structure/index.d.ts +2 -0
- package/lib/structure/index.js +18 -0
- package/lib/utils/auth.d.ts +28 -0
- package/lib/utils/auth.js +65 -0
- package/lib/utils/authUser.d.ts +10 -0
- package/lib/utils/authUser.js +2 -0
- package/lib/utils/media.d.ts +2 -0
- package/lib/utils/media.js +14 -0
- package/lib/utils/tokens.d.ts +15 -0
- package/lib/utils/tokens.js +78 -0
- package/lib/utils/utils.d.ts +4 -0
- package/lib/utils/utils.js +16 -0
- package/lib/validations/index.d.ts +146 -0
- package/lib/validations/index.js +103 -0
- package/package.json +80 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseQueryParams = exports.Conditions = exports.QueryKeys = void 0;
|
|
4
|
+
const instance_1 = require("../instance");
|
|
5
|
+
var QueryKeys;
|
|
6
|
+
(function (QueryKeys) {
|
|
7
|
+
QueryKeys["and"] = "and";
|
|
8
|
+
QueryKeys["or"] = "or";
|
|
9
|
+
})(QueryKeys = exports.QueryKeys || (exports.QueryKeys = {}));
|
|
10
|
+
var Conditions;
|
|
11
|
+
(function (Conditions) {
|
|
12
|
+
Conditions["lt"] = "lt";
|
|
13
|
+
Conditions["lte"] = "lte";
|
|
14
|
+
Conditions["gt"] = "gt";
|
|
15
|
+
Conditions["gte"] = "gte";
|
|
16
|
+
Conditions["eq"] = "eq";
|
|
17
|
+
Conditions["ne"] = "ne";
|
|
18
|
+
Conditions["in"] = "in";
|
|
19
|
+
Conditions["nin"] = "nin";
|
|
20
|
+
Conditions["exists"] = "exists";
|
|
21
|
+
})(Conditions = exports.Conditions || (exports.Conditions = {}));
|
|
22
|
+
const parseQueryParams = async (collection, params) => {
|
|
23
|
+
const query = [];
|
|
24
|
+
const whereType = Object.values(QueryKeys).indexOf(params.whereType) !== -1 ? params.whereType : QueryKeys.and;
|
|
25
|
+
const authType = Object.values(QueryKeys).indexOf(params.authType) !== -1 ? params.authType : QueryKeys.and;
|
|
26
|
+
const where = buildWhereQuery(params.where ?? [], whereType);
|
|
27
|
+
if (where)
|
|
28
|
+
query.push(where);
|
|
29
|
+
const auth = buildWhereQuery(params.auth ?? [], authType);
|
|
30
|
+
if (auth)
|
|
31
|
+
query.push(auth);
|
|
32
|
+
if (params.search && params.search.fields.length > 0) {
|
|
33
|
+
const search = params.search.fields.map((field) => ({
|
|
34
|
+
[field]: {
|
|
35
|
+
$regex: new RegExp(params.search.value, 'i')
|
|
36
|
+
}
|
|
37
|
+
}));
|
|
38
|
+
query.push({ $or: search });
|
|
39
|
+
}
|
|
40
|
+
const totalClause = {};
|
|
41
|
+
if (query.length > 0)
|
|
42
|
+
totalClause['$and'] = query;
|
|
43
|
+
const sort = params.sort?.map((p) => [p.field, p.desc ? 'desc' : 'asc']) ?? [];
|
|
44
|
+
const all = params.all ?? false;
|
|
45
|
+
const settings = instance_1.Instance.get().settings;
|
|
46
|
+
const limit = Number(params.limit) <= settings.paginationDefaultLimit ? Number(params.limit) : settings.paginationDefaultLimit;
|
|
47
|
+
let page = Number.isNaN(Number(params.page)) ? 0 : Number(params.page);
|
|
48
|
+
page = page < 1 ? 1 : page;
|
|
49
|
+
const total = await collection.countDocuments(totalClause).exec();
|
|
50
|
+
let builtQuery = collection.find(totalClause);
|
|
51
|
+
if (sort.length)
|
|
52
|
+
builtQuery = builtQuery.sort(Object.fromEntries(sort));
|
|
53
|
+
if (!all && limit) {
|
|
54
|
+
builtQuery = builtQuery.limit(limit);
|
|
55
|
+
if (page)
|
|
56
|
+
builtQuery = builtQuery.skip((page - 1) * limit);
|
|
57
|
+
}
|
|
58
|
+
const results = await builtQuery.exec();
|
|
59
|
+
const start = 1;
|
|
60
|
+
const last = Math.ceil(total / limit) || 1;
|
|
61
|
+
const next = page >= last ? null : page + 1;
|
|
62
|
+
const previous = page <= start ? null : page - 1;
|
|
63
|
+
return {
|
|
64
|
+
pages: {
|
|
65
|
+
start, last, next, previous, current: page
|
|
66
|
+
},
|
|
67
|
+
docs: {
|
|
68
|
+
limit, total, count: results.length
|
|
69
|
+
},
|
|
70
|
+
results: results.map((r) => r.toJSON())
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
exports.parseQueryParams = parseQueryParams;
|
|
74
|
+
const buildWhereQuery = (params, key = QueryKeys.and) => {
|
|
75
|
+
const where = params.map((param) => {
|
|
76
|
+
if (Object.values(QueryKeys).includes(param.condition))
|
|
77
|
+
return buildWhereQuery(param.value, param.condition);
|
|
78
|
+
const { field } = param;
|
|
79
|
+
const checkedField = field === 'id' ? '_id' : (field ?? '');
|
|
80
|
+
const checkedValue = param.value === undefined ? '' : param.value;
|
|
81
|
+
const checkedCondition = Object.keys(Conditions).indexOf(param.condition) > -1 ? param.condition : Conditions.eq;
|
|
82
|
+
return ({
|
|
83
|
+
field: checkedField,
|
|
84
|
+
value: checkedValue,
|
|
85
|
+
condition: checkedCondition,
|
|
86
|
+
isWhere: true
|
|
87
|
+
});
|
|
88
|
+
}).filter((c) => c).map((c) => {
|
|
89
|
+
if (c.isWhere)
|
|
90
|
+
return {
|
|
91
|
+
[`${c.field}`]: { [`$${c.condition}`]: c.value }
|
|
92
|
+
};
|
|
93
|
+
else
|
|
94
|
+
return c;
|
|
95
|
+
});
|
|
96
|
+
return where.length > 0 ? { [`$${key}`]: where } : null;
|
|
97
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
export interface StorageFile {
|
|
3
|
+
name: string;
|
|
4
|
+
type: string;
|
|
5
|
+
size: number;
|
|
6
|
+
isTruncated: boolean;
|
|
7
|
+
data: Buffer;
|
|
8
|
+
duration: number;
|
|
9
|
+
}
|
|
10
|
+
export interface MediaOutput {
|
|
11
|
+
name: string;
|
|
12
|
+
type: string;
|
|
13
|
+
size: number;
|
|
14
|
+
path: string;
|
|
15
|
+
timestamp: number;
|
|
16
|
+
link: string;
|
|
17
|
+
duration: number;
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BaseEntity = void 0;
|
|
4
|
+
const utils_1 = require("../utils/utils");
|
|
5
|
+
class BaseEntity {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.hash = utils_1.Random.string();
|
|
8
|
+
}
|
|
9
|
+
toJSON() {
|
|
10
|
+
const json = Object.assign({}, this);
|
|
11
|
+
const proto = Object.getPrototypeOf(this);
|
|
12
|
+
Object.getOwnPropertyNames(proto)
|
|
13
|
+
.filter((k) => k !== 'constructor')
|
|
14
|
+
.forEach((key) => {
|
|
15
|
+
const value = this[key];
|
|
16
|
+
json[key] = value?.toJSON?.() ?? value;
|
|
17
|
+
});
|
|
18
|
+
return json;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.BaseEntity = BaseEntity;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./baseEntity"), exports);
|
|
18
|
+
__exportStar(require("./baseMapper"), exports);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const signinWithGoogle: (idToken: string) => Promise<{
|
|
2
|
+
email: string;
|
|
3
|
+
email_verified: 'true' | 'false';
|
|
4
|
+
first_name: string;
|
|
5
|
+
last_name: string;
|
|
6
|
+
picture: string;
|
|
7
|
+
sub: string;
|
|
8
|
+
} & Record<string, any>>;
|
|
9
|
+
export declare const signinWithApple: (idToken: string) => Promise<{
|
|
10
|
+
email?: string | undefined;
|
|
11
|
+
sub: string;
|
|
12
|
+
email_verified?: "false" | "true" | undefined;
|
|
13
|
+
is_private_email?: "false" | "true" | undefined;
|
|
14
|
+
} & Record<string, any>>;
|
|
15
|
+
export declare const signinWithFacebook: (accessToken: string, fields?: string[]) => Promise<{
|
|
16
|
+
id: string;
|
|
17
|
+
email: string;
|
|
18
|
+
email_verified: 'true' | 'false';
|
|
19
|
+
name: string;
|
|
20
|
+
picture: {
|
|
21
|
+
data: {
|
|
22
|
+
height: number;
|
|
23
|
+
is_silhouette: boolean;
|
|
24
|
+
url: string;
|
|
25
|
+
width: number;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
} & Record<string, any>>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.signinWithFacebook = exports.signinWithApple = exports.signinWithGoogle = void 0;
|
|
7
|
+
const axios_1 = __importDefault(require("axios"));
|
|
8
|
+
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
9
|
+
const jwks_rsa_1 = __importDefault(require("jwks-rsa"));
|
|
10
|
+
const signinWithGoogle = async (idToken) => {
|
|
11
|
+
const authUrl = `https://oauth2.googleapis.com/tokeninfo?id_token=${idToken}`;
|
|
12
|
+
const { data } = await axios_1.default.get(authUrl).catch((err) => {
|
|
13
|
+
const message = err?.response?.data?.error;
|
|
14
|
+
throw new Error(message ? 'Invalid id token' : 'Something unexpected happened');
|
|
15
|
+
});
|
|
16
|
+
data.first_name = data.given_name;
|
|
17
|
+
data.last_name = data.family_name;
|
|
18
|
+
return data;
|
|
19
|
+
};
|
|
20
|
+
exports.signinWithGoogle = signinWithGoogle;
|
|
21
|
+
const signinWithApple = async (idToken) => {
|
|
22
|
+
try {
|
|
23
|
+
const APPLE_BASE = 'https://appleid.apple.com';
|
|
24
|
+
const json = jsonwebtoken_1.default.decode(idToken, { complete: true });
|
|
25
|
+
if (!json?.header)
|
|
26
|
+
throw new Error('');
|
|
27
|
+
const { kid, alg } = json.header;
|
|
28
|
+
const publicKey = await (0, jwks_rsa_1.default)({ jwksUri: `${APPLE_BASE}/auth/keys`, cache: true })
|
|
29
|
+
.getSigningKey(kid).then((key) => key.getPublicKey()).catch(() => null);
|
|
30
|
+
if (!publicKey)
|
|
31
|
+
throw new Error('');
|
|
32
|
+
const data = jsonwebtoken_1.default.verify(idToken, publicKey, { algorithms: [alg] });
|
|
33
|
+
if (!data)
|
|
34
|
+
throw new Error('');
|
|
35
|
+
if (data.iss !== APPLE_BASE)
|
|
36
|
+
throw new Error('');
|
|
37
|
+
if (data.exp * 1000 < Date.now())
|
|
38
|
+
throw new Error('expired idToken');
|
|
39
|
+
return data;
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
throw new Error(err.message || 'Invalid idToken');
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
exports.signinWithApple = signinWithApple;
|
|
46
|
+
const signinWithFacebook = async (accessToken, fields = []) => {
|
|
47
|
+
fields = [...new Set([...fields, 'name', 'picture', 'email'])];
|
|
48
|
+
const { data } = await axios_1.default.request({
|
|
49
|
+
method: 'get',
|
|
50
|
+
url: 'https://graph.facebook.com/v15.0/me',
|
|
51
|
+
params: {
|
|
52
|
+
fields: fields.join(','),
|
|
53
|
+
access_token: accessToken
|
|
54
|
+
}
|
|
55
|
+
}).catch((err) => {
|
|
56
|
+
const message = err?.response?.data?.error?.message;
|
|
57
|
+
throw new Error(message ? 'Invalid access token' : 'Something unexpected happened');
|
|
58
|
+
});
|
|
59
|
+
const isValidData = fields.every((key) => key in data);
|
|
60
|
+
if (!isValidData)
|
|
61
|
+
throw new Error('Incomplete scope for access token');
|
|
62
|
+
data.email_verified = 'true';
|
|
63
|
+
return data;
|
|
64
|
+
};
|
|
65
|
+
exports.signinWithFacebook = signinWithFacebook;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMediaDuration = void 0;
|
|
4
|
+
const music_metadata_1 = require("music-metadata");
|
|
5
|
+
const getMediaDuration = async (buffer) => {
|
|
6
|
+
try {
|
|
7
|
+
const meta = await (0, music_metadata_1.parseBuffer)(buffer);
|
|
8
|
+
return meta.format.duration ?? 0;
|
|
9
|
+
}
|
|
10
|
+
catch (e) {
|
|
11
|
+
return 0;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
exports.getMediaDuration = getMediaDuration;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AuthUser, RefreshUser } from './authUser';
|
|
2
|
+
export declare const makeAccessToken: (payload: AuthUser) => Promise<string>;
|
|
3
|
+
export declare const makeRefreshToken: (payload: RefreshUser) => Promise<string>;
|
|
4
|
+
export declare const verifyAccessToken: (token: string) => Promise<AuthUser>;
|
|
5
|
+
export declare const verifyRefreshToken: (token: string) => Promise<RefreshUser>;
|
|
6
|
+
export declare const getCachedAccessToken: (userId: string) => Promise<string | null>;
|
|
7
|
+
export declare const getCachedRefreshToken: (userId: string) => Promise<string | null>;
|
|
8
|
+
export declare const deleteCachedAccessToken: (userId: string) => Promise<void>;
|
|
9
|
+
export declare const deleteCachedRefreshToken: (userId: string) => Promise<void>;
|
|
10
|
+
type Tokens = {
|
|
11
|
+
accessToken: string;
|
|
12
|
+
refreshToken: string;
|
|
13
|
+
};
|
|
14
|
+
export declare const exchangeOldForNewTokens: ({ accessToken, refreshToken }: Tokens, makeTokens: (id: string) => Promise<Tokens>) => Promise<Tokens>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.exchangeOldForNewTokens = exports.deleteCachedRefreshToken = exports.deleteCachedAccessToken = exports.getCachedRefreshToken = exports.getCachedAccessToken = exports.verifyRefreshToken = exports.verifyAccessToken = exports.makeRefreshToken = exports.makeAccessToken = void 0;
|
|
7
|
+
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
8
|
+
const errors_1 = require("../errors");
|
|
9
|
+
const express_1 = require("../express");
|
|
10
|
+
const instance_1 = require("../instance");
|
|
11
|
+
const getAccessTokenKey = (userId) => `${userId}-access-token`;
|
|
12
|
+
const getRefreshTokenKey = (userId) => `${userId}-refresh-token`;
|
|
13
|
+
const makeAccessToken = async (payload) => {
|
|
14
|
+
const token = jsonwebtoken_1.default.sign(payload, instance_1.Instance.get().settings.accessTokenKey, { expiresIn: instance_1.Instance.get().settings.accessTokenTTL });
|
|
15
|
+
await instance_1.Instance.get().cache.set(getAccessTokenKey(payload.id), token, instance_1.Instance.get().settings.accessTokenTTL);
|
|
16
|
+
return token;
|
|
17
|
+
};
|
|
18
|
+
exports.makeAccessToken = makeAccessToken;
|
|
19
|
+
const makeRefreshToken = async (payload) => {
|
|
20
|
+
const token = jsonwebtoken_1.default.sign(payload, instance_1.Instance.get().settings.refreshTokenKey, { expiresIn: instance_1.Instance.get().settings.refreshTokenTTL });
|
|
21
|
+
await instance_1.Instance.get().cache.set(getRefreshTokenKey(payload.id), token, instance_1.Instance.get().settings.refreshTokenTTL);
|
|
22
|
+
return token;
|
|
23
|
+
};
|
|
24
|
+
exports.makeRefreshToken = makeRefreshToken;
|
|
25
|
+
const verifyAccessToken = async (token) => {
|
|
26
|
+
try {
|
|
27
|
+
const user = jsonwebtoken_1.default.verify(token, instance_1.Instance.get().settings.accessTokenKey);
|
|
28
|
+
if (!user)
|
|
29
|
+
throw new errors_1.NotAuthenticatedError();
|
|
30
|
+
const cachedToken = await (0, exports.getCachedAccessToken)(user.id);
|
|
31
|
+
if (token && token !== cachedToken)
|
|
32
|
+
throw new errors_1.AccessTokenExpired();
|
|
33
|
+
return user;
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
if (err instanceof errors_1.AccessTokenExpired)
|
|
37
|
+
throw err;
|
|
38
|
+
if (err instanceof jsonwebtoken_1.default.TokenExpiredError)
|
|
39
|
+
throw new errors_1.AccessTokenExpired();
|
|
40
|
+
else
|
|
41
|
+
throw new errors_1.NotAuthenticatedError();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
exports.verifyAccessToken = verifyAccessToken;
|
|
45
|
+
const verifyRefreshToken = async (token) => {
|
|
46
|
+
try {
|
|
47
|
+
const user = jsonwebtoken_1.default.verify(token, instance_1.Instance.get().settings.refreshTokenKey);
|
|
48
|
+
if (!user)
|
|
49
|
+
throw new errors_1.NotAuthenticatedError();
|
|
50
|
+
return user;
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
throw new errors_1.NotAuthenticatedError();
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
exports.verifyRefreshToken = verifyRefreshToken;
|
|
57
|
+
const getCachedAccessToken = async (userId) => instance_1.Instance.get().cache.get(getAccessTokenKey(userId));
|
|
58
|
+
exports.getCachedAccessToken = getCachedAccessToken;
|
|
59
|
+
const getCachedRefreshToken = async (userId) => instance_1.Instance.get().cache.get(getRefreshTokenKey(userId));
|
|
60
|
+
exports.getCachedRefreshToken = getCachedRefreshToken;
|
|
61
|
+
const deleteCachedAccessToken = async (userId) => instance_1.Instance.get().cache.delete(getAccessTokenKey(userId));
|
|
62
|
+
exports.deleteCachedAccessToken = deleteCachedAccessToken;
|
|
63
|
+
const deleteCachedRefreshToken = async (userId) => instance_1.Instance.get().cache.delete(getRefreshTokenKey(userId));
|
|
64
|
+
exports.deleteCachedRefreshToken = deleteCachedRefreshToken;
|
|
65
|
+
const exchangeOldForNewTokens = async ({ accessToken, refreshToken }, makeTokens) => {
|
|
66
|
+
const authUser = await (0, exports.verifyAccessToken)(accessToken).catch((err) => {
|
|
67
|
+
const error = err;
|
|
68
|
+
if (error.statusCode === express_1.StatusCodes.AccessTokenExpired)
|
|
69
|
+
return null;
|
|
70
|
+
else
|
|
71
|
+
throw err;
|
|
72
|
+
});
|
|
73
|
+
if (authUser)
|
|
74
|
+
return await makeTokens(authUser.id);
|
|
75
|
+
const refreshUser = await (0, exports.verifyRefreshToken)(refreshToken);
|
|
76
|
+
return await makeTokens(refreshUser.id);
|
|
77
|
+
};
|
|
78
|
+
exports.exchangeOldForNewTokens = exchangeOldForNewTokens;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.Random = void 0;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
class Random {
|
|
9
|
+
static string(length = 20) {
|
|
10
|
+
return crypto_1.default.randomBytes(length).toString('hex').slice(0, length);
|
|
11
|
+
}
|
|
12
|
+
static number(min = 0, max = 2 ** 48 - 1) {
|
|
13
|
+
return crypto_1.default.randomInt(min, max);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.Random = Random;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import * as Validate from 'valleyed';
|
|
2
|
+
import { VCore } from 'valleyed/lib/api/core';
|
|
3
|
+
import { StorageFile } from '../storage';
|
|
4
|
+
type Phone = {
|
|
5
|
+
code: string;
|
|
6
|
+
number: string;
|
|
7
|
+
};
|
|
8
|
+
export declare const Schema: {
|
|
9
|
+
or: <T extends VCore<any, any>[]>(options: T, err?: string | undefined) => import("valleyed/lib/api/junctions").VOr<T>;
|
|
10
|
+
and: <I, O>(options: VCore<I, O>[], err?: string | undefined) => import("valleyed/lib/api/junctions").VAnd<I, O>;
|
|
11
|
+
string: (err?: string | undefined) => import("valleyed/lib/api/strings").VString;
|
|
12
|
+
number: (err?: string | undefined) => import("valleyed/lib/api/numbers").VNumber;
|
|
13
|
+
boolean: (err?: string | undefined) => import("valleyed/lib/api/booleans").VBoolean;
|
|
14
|
+
time: <T_1 extends Validate.Timeable = Validate.Timeable>(err?: string | undefined) => import("valleyed/lib/api/times").VTime<T_1>;
|
|
15
|
+
file: (err?: string | undefined) => import("valleyed/lib/api/files").VFile;
|
|
16
|
+
array: <I_1, O_1>(comparer: VCore<I_1, O_1>, err?: string | undefined) => import("valleyed/lib/api/arrays").VArray<I_1, O_1>;
|
|
17
|
+
tuple: <T_2 extends readonly VCore<any, any>[]>(schema: readonly [...T_2], err?: string | undefined) => import("valleyed/lib/api/tuples").VTuple<T_2>;
|
|
18
|
+
object: <T_3 extends Record<string, VCore<any, any>>>(schema: T_3, trim?: boolean | undefined, err?: string | undefined) => import("valleyed/lib/api/objects").VObject<T_3>;
|
|
19
|
+
record: <VI, VO>(vCom: VCore<VI, VO>, err?: string | undefined) => import("valleyed/lib/api/records").VRecord<VI, VO>;
|
|
20
|
+
map: <KI, VI_1, KO, VO_1>(kCom: VCore<KI, KO>, vCom: VCore<VI_1, VO_1>, err?: string | undefined) => import("valleyed/lib/api/records").VMap<KI, VI_1, KO, VO_1>;
|
|
21
|
+
null: (err?: string | undefined) => VCore<null, null>;
|
|
22
|
+
undefined: (err?: string | undefined) => VCore<undefined, undefined>;
|
|
23
|
+
instanceof: <T_4>(classDef: new () => T_4, err?: string | undefined) => VCore<T_4, T_4>;
|
|
24
|
+
any: <T_5 = any>() => VCore<T_5, T_5>;
|
|
25
|
+
force: {
|
|
26
|
+
string: (err?: string | undefined) => import("valleyed/lib/api/strings").VString;
|
|
27
|
+
number: (err?: string | undefined) => import("valleyed/lib/api/numbers").VNumber;
|
|
28
|
+
boolean: (err?: string | undefined) => import("valleyed/lib/api/booleans").VBoolean;
|
|
29
|
+
time: (err?: string | undefined) => import("valleyed/lib/api/times").VTime<Date>;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
export declare const Validation: {
|
|
33
|
+
isNotTruncated: (error?: string) => Validate.Rule<StorageFile>;
|
|
34
|
+
isValidPhone: (error?: string) => Validate.Rule<Phone>;
|
|
35
|
+
Validator: typeof Validate.Validator;
|
|
36
|
+
v: {
|
|
37
|
+
or: <T extends VCore<any, any>[]>(options: T, err?: string | undefined) => import("valleyed/lib/api/junctions").VOr<T>;
|
|
38
|
+
and: <I, O>(options: VCore<I, O>[], err?: string | undefined) => import("valleyed/lib/api/junctions").VAnd<I, O>;
|
|
39
|
+
string: (err?: string | undefined) => import("valleyed/lib/api/strings").VString;
|
|
40
|
+
number: (err?: string | undefined) => import("valleyed/lib/api/numbers").VNumber;
|
|
41
|
+
boolean: (err?: string | undefined) => import("valleyed/lib/api/booleans").VBoolean;
|
|
42
|
+
time: <T_1 extends Validate.Timeable = Validate.Timeable>(err?: string | undefined) => import("valleyed/lib/api/times").VTime<T_1>;
|
|
43
|
+
file: (err?: string | undefined) => import("valleyed/lib/api/files").VFile;
|
|
44
|
+
array: <I_1, O_1>(comparer: VCore<I_1, O_1>, err?: string | undefined) => import("valleyed/lib/api/arrays").VArray<I_1, O_1>;
|
|
45
|
+
tuple: <T_2 extends readonly VCore<any, any>[]>(schema: readonly [...T_2], err?: string | undefined) => import("valleyed/lib/api/tuples").VTuple<T_2>;
|
|
46
|
+
object: <T_3 extends Record<string, VCore<any, any>>>(schema: T_3, trim?: boolean | undefined, err?: string | undefined) => import("valleyed/lib/api/objects").VObject<T_3>;
|
|
47
|
+
record: <VI, VO>(vCom: VCore<VI, VO>, err?: string | undefined) => import("valleyed/lib/api/records").VRecord<VI, VO>;
|
|
48
|
+
map: <KI, VI_1, KO, VO_1>(kCom: VCore<KI, KO>, vCom: VCore<VI_1, VO_1>, err?: string | undefined) => import("valleyed/lib/api/records").VMap<KI, VI_1, KO, VO_1>;
|
|
49
|
+
null: (err?: string | undefined) => VCore<null, null>;
|
|
50
|
+
undefined: (err?: string | undefined) => VCore<undefined, undefined>;
|
|
51
|
+
instanceof: <T_4>(classDef: new () => T_4, err?: string | undefined) => VCore<T_4, T_4>;
|
|
52
|
+
any: <T_5 = any>() => VCore<T_5, T_5>;
|
|
53
|
+
force: {
|
|
54
|
+
string: (err?: string | undefined) => import("valleyed/lib/api/strings").VString;
|
|
55
|
+
number: (err?: string | undefined) => import("valleyed/lib/api/numbers").VNumber;
|
|
56
|
+
boolean: (err?: string | undefined) => import("valleyed/lib/api/booleans").VBoolean;
|
|
57
|
+
time: (err?: string | undefined) => import("valleyed/lib/api/times").VTime<Date>;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
isValid: <T>(value: T) => {
|
|
61
|
+
valid: true;
|
|
62
|
+
errors: string[];
|
|
63
|
+
value: T;
|
|
64
|
+
};
|
|
65
|
+
isInvalid: <T_1>(errors: string[], value: T_1) => {
|
|
66
|
+
valid: false;
|
|
67
|
+
errors: string[];
|
|
68
|
+
value: unknown;
|
|
69
|
+
};
|
|
70
|
+
makeRule: <T_2>(func: Validate.Rule<T_2>) => Validate.Rule<T_2>;
|
|
71
|
+
makeSanitizer: <T_3>(func: Validate.Sanitizer<T_3>) => (val: T_3) => T_3;
|
|
72
|
+
check: <T_4>(value: T_4, rules: Validate.Rule<T_4>[], options?: Partial<Validate.Options> | undefined) => {
|
|
73
|
+
errors: string[];
|
|
74
|
+
value: T_4;
|
|
75
|
+
valid: boolean;
|
|
76
|
+
};
|
|
77
|
+
isEqualTo: <Type>(compare: Type, comparer?: ((val: any, compare: Type) => boolean) | undefined, error?: string | undefined) => Validate.Rule<Type>;
|
|
78
|
+
arrayContains: <Type_1>(array: Type_1[], comparer?: ((val: any, arrayItem: Type_1) => boolean) | undefined, error?: string | undefined) => Validate.Rule<Type_1>;
|
|
79
|
+
isString: (error?: string | undefined) => Validate.Rule<any>;
|
|
80
|
+
isLengthOf: (length: number, stripHTMLTags?: boolean | undefined, error?: string | undefined) => Validate.Rule<string>;
|
|
81
|
+
isMinOf: (length: number, stripHTMLTags?: boolean | undefined, error?: string | undefined) => Validate.Rule<string>;
|
|
82
|
+
isMaxOf: (length: number, stripHTMLTags?: boolean | undefined, error?: string | undefined) => Validate.Rule<string>;
|
|
83
|
+
isEmail: (error?: string | undefined) => Validate.Rule<string>;
|
|
84
|
+
isUrl: (error?: string | undefined) => Validate.Rule<string>;
|
|
85
|
+
isNumber: (error?: string | undefined) => Validate.Rule<any>;
|
|
86
|
+
isMoreThan: (compare: number, error?: string | undefined) => Validate.Rule<number>;
|
|
87
|
+
isMoreThanOrEqualTo: (compare: number, error?: string | undefined) => Validate.Rule<number>;
|
|
88
|
+
isLessThan: (compare: number, error?: string | undefined) => Validate.Rule<number>;
|
|
89
|
+
isLessThanOrEqualTo: (compare: number, error?: string | undefined) => Validate.Rule<number>;
|
|
90
|
+
isArray: (error?: string | undefined) => Validate.Rule<any>;
|
|
91
|
+
hasLengthOf: <Type_2>(length: number, error?: string | undefined) => Validate.Rule<Type_2[]>;
|
|
92
|
+
hasMinOf: <Type_3>(length: number, error?: string | undefined) => Validate.Rule<Type_3[]>;
|
|
93
|
+
hasMaxOf: <Type_4>(length: number, error?: string | undefined) => Validate.Rule<Type_4[]>;
|
|
94
|
+
isArrayOf: <Type_5>(comparer: (cur: Type_5, idx: number) => boolean, error?: string | undefined) => Validate.Rule<Type_5[]>;
|
|
95
|
+
isUndefined: (error?: string | undefined) => Validate.Rule<undefined>;
|
|
96
|
+
isNull: (error?: string | undefined) => Validate.Rule<null>;
|
|
97
|
+
isBoolean: (error?: string | undefined) => Validate.Rule<boolean>;
|
|
98
|
+
isInstanceOf: <T_5>(classDef: new () => T_5, error?: string | undefined) => Validate.Rule<T_5>;
|
|
99
|
+
fileMimeTypes: string[];
|
|
100
|
+
videoMimeTypes: string[];
|
|
101
|
+
audioMimeTypes: string[];
|
|
102
|
+
imageMimeTypes: string[];
|
|
103
|
+
isImage: (error?: string | undefined) => Validate.Rule<any>;
|
|
104
|
+
isAudio: (error?: string | undefined) => Validate.Rule<any>;
|
|
105
|
+
isVideo: (error?: string | undefined) => Validate.Rule<any>;
|
|
106
|
+
isFile: (error?: string | undefined) => Validate.Rule<any>;
|
|
107
|
+
isTuple: <T_6 extends readonly ((v: any, idx: number) => boolean)[]>(comparer: readonly [...T_6], error?: string | undefined) => Validate.Rule<{ [K in keyof T_6]: T_6[K] extends (v: infer V, idx: number) => boolean ? V : never; }>;
|
|
108
|
+
isRecord: <V_1>(com: (cur: V_1) => boolean, error?: string | undefined) => Validate.Rule<Record<string, V_1>>;
|
|
109
|
+
isMap: <K_1, V_2>(kCom: (cur: K_1) => boolean, vCom: (cur: V_2) => boolean, error?: string | undefined) => Validate.Rule<Map<K_1, V_2>>;
|
|
110
|
+
isCustom: <T_7>(validity: (v: T_7) => boolean, error?: string | undefined) => Validate.Rule<T_7>;
|
|
111
|
+
isTime: <T_8 extends Validate.Timeable>(error?: string | undefined) => Validate.Rule<T_8>;
|
|
112
|
+
isLaterThan: <T_9 extends Validate.Timeable>(compare: Validate.Timeable, error?: string | undefined) => Validate.Rule<T_9>;
|
|
113
|
+
isEarlierThan: <T_10 extends Validate.Timeable>(compare: Validate.Timeable, error?: string | undefined) => Validate.Rule<T_10>;
|
|
114
|
+
capitalize: (text: string) => string;
|
|
115
|
+
stripHTML: (html: string) => string;
|
|
116
|
+
trimToLength: (body: string, length: number) => string;
|
|
117
|
+
extractUrls: (text: string) => {
|
|
118
|
+
original: string;
|
|
119
|
+
normalized: string;
|
|
120
|
+
}[];
|
|
121
|
+
formatNumber: (num: number, dp?: number | undefined) => string;
|
|
122
|
+
pluralize: (count: number, singular: string, plural: string) => string;
|
|
123
|
+
getRandomValue: () => string;
|
|
124
|
+
groupBy: <Type_6, Unique extends string | number>(array: Type_6[], func: (item: Type_6) => Unique) => {
|
|
125
|
+
key: Unique;
|
|
126
|
+
values: Type_6[];
|
|
127
|
+
}[];
|
|
128
|
+
getAlphabet: (num: number) => string;
|
|
129
|
+
addToArray: <T_11>(array: T_11[], item: T_11, getKey: (a: T_11) => any, getComparer: (a: T_11) => string | number, asc?: boolean | undefined) => T_11[];
|
|
130
|
+
divideByZero: (num: number, den: number) => number;
|
|
131
|
+
getPercentage: (num: number, den: number) => number;
|
|
132
|
+
getRandomSample: <Type_7>(population: Type_7[], n: number) => Type_7[];
|
|
133
|
+
shuffleArray: <Type_8>(array: Type_8[]) => Type_8[];
|
|
134
|
+
};
|
|
135
|
+
type Rules<T> = {
|
|
136
|
+
required?: boolean | (() => boolean);
|
|
137
|
+
nullable?: boolean;
|
|
138
|
+
rules: Validate.Rule<T>[];
|
|
139
|
+
};
|
|
140
|
+
export declare const validate: <Keys extends Record<string, any>>(data: Keys, rules: Record<keyof Keys, Rules<any>>) => Keys;
|
|
141
|
+
export declare const validateReq: <T extends Record<string, VCore<any, any>>>(schema: T, value: Record<string, any>) => { [K in keyof T]: import("valleyed/lib/api/base").ExtractO<T[K]>; };
|
|
142
|
+
export declare const Hash: {
|
|
143
|
+
hash: (password: string) => Promise<string>;
|
|
144
|
+
compare: (plainPassword: string, hashed: string) => Promise<boolean>;
|
|
145
|
+
};
|
|
146
|
+
export {};
|