Change export convention for helper functions

This commit is contained in:
Tuan Dang
2023-06-05 21:00:23 +01:00
parent 0c18bd71c4
commit 5f5ed5d0a9
22 changed files with 133 additions and 176 deletions

View File

@@ -13,7 +13,7 @@ import {
} from '../../variables'; } from '../../variables';
import { BadRequestError } from '../../utils/errors'; import { BadRequestError } from '../../utils/errors';
import { EELogService } from '../../ee/services'; import { EELogService } from '../../ee/services';
import { getChannelFromUserAgent } from '../../utils/posthog'; // TODO: move this import { getChannelFromUserAgent } from '../../utils/posthog';
import { import {
getJwtRefreshSecret, getJwtRefreshSecret,
getJwtAuthLifetime, getJwtAuthLifetime,
@@ -24,6 +24,7 @@ import {
declare module 'jsonwebtoken' { declare module 'jsonwebtoken' {
export interface UserIDJwtPayload extends jwt.JwtPayload { export interface UserIDJwtPayload extends jwt.JwtPayload {
userId: string; userId: string;
refreshVersion?: number;
} }
} }
@@ -173,9 +174,7 @@ export const login2 = async (req: Request, res: Response) => {
*/ */
export const logout = async (req: Request, res: Response) => { export const logout = async (req: Request, res: Response) => {
try { try {
await clearTokens({ await clearTokens(req.user._id);
userId: req.user._id.toString()
});
// clear httpOnly cookie // clear httpOnly cookie
res.cookie('jid', '', { res.cookie('jid', '', {
@@ -223,7 +222,7 @@ export const checkAuth = async (req: Request, res: Response) => {
} }
/** /**
* Return new token by redeeming refresh token * Return new JWT access token by first validating the refresh token
* @param req * @param req
* @param res * @param res
* @returns * @returns
@@ -233,7 +232,7 @@ export const getNewToken = async (req: Request, res: Response) => {
const refreshToken = req.cookies.jid; const refreshToken = req.cookies.jid;
if (!refreshToken) { if (!refreshToken) {
throw new Error('Failed to find token in request cookies'); throw new Error('Failed to find refresh token in request cookies');
} }
const decodedToken = <jwt.UserIDJwtPayload>( const decodedToken = <jwt.UserIDJwtPayload>(
@@ -242,12 +241,16 @@ export const getNewToken = async (req: Request, res: Response) => {
const user = await User.findOne({ const user = await User.findOne({
_id: decodedToken.userId _id: decodedToken.userId
}).select('+publicKey'); }).select('+publicKey +refreshVersion');
if (!user) throw new Error('Failed to authenticate unfound user'); if (!user) throw new Error('Failed to authenticate unfound user');
if (!user?.publicKey) if (!user?.publicKey)
throw new Error('Failed to authenticate not fully set up account'); throw new Error('Failed to authenticate not fully set up account');
if (decodedToken?.refreshVersion !== user.refreshVersion) throw BadRequestError({
message: 'Failed to validate refresh token'
});
const token = createToken({ const token = createToken({
payload: { payload: {
userId: decodedToken.userId userId: decodedToken.userId

View File

@@ -4,12 +4,20 @@ import * as Sentry from '@sentry/node';
const jsrp = require('jsrp'); const jsrp = require('jsrp');
import * as bigintConversion from 'bigint-conversion'; import * as bigintConversion from 'bigint-conversion';
import { User, BackupPrivateKey, LoginSRPDetail } from '../../models'; import { User, BackupPrivateKey, LoginSRPDetail } from '../../models';
import { createToken } from '../../helpers/auth'; import {
import { sendMail } from '../../helpers/nodemailer'; createToken,
sendMail,
clearTokens
} from '../../helpers';
import { TokenService } from '../../services'; import { TokenService } from '../../services';
import { TOKEN_EMAIL_PASSWORD_RESET } from '../../variables'; import { TOKEN_EMAIL_PASSWORD_RESET } from '../../variables';
import { BadRequestError } from '../../utils/errors'; import { BadRequestError } from '../../utils/errors';
import { getSiteURL, getJwtSignupLifetime, getJwtSignupSecret } from '../../config'; import {
getSiteURL,
getJwtSignupLifetime,
getJwtSignupSecret,
getHttpsEnabled
} from '../../config';
/** /**
* Password reset step 1: Send email verification link to email [email] * Password reset step 1: Send email verification link to email [email]
@@ -117,6 +125,7 @@ export const emailPasswordResetVerify = async (req: Request, res: Response) => {
*/ */
export const srp1 = async (req: Request, res: Response) => { export const srp1 = async (req: Request, res: Response) => {
// return salt, serverPublicKey as part of first step of SRP protocol // return salt, serverPublicKey as part of first step of SRP protocol
try { try {
const { clientPublicKey } = req.body; const { clientPublicKey } = req.body;
const user = await User.findOne({ const user = await User.findOne({
@@ -221,6 +230,17 @@ export const changePassword = async (req: Request, res: Response) => {
new: true new: true
} }
); );
// await clearTokens(user._id);
// // clear httpOnly cookie
// res.cookie('jid', '', {
// httpOnly: true,
// path: '/',
// sameSite: 'strict',
// secure: (await getHttpsEnabled()) as boolean
// });
return res.status(200).send({ return res.status(200).send({
message: 'Successfully changed password' message: 'Successfully changed password'

View File

@@ -34,7 +34,7 @@ import {
* @param {Object} obj * @param {Object} obj
* @param {Object} obj.headers - HTTP request headers object * @param {Object} obj.headers - HTTP request headers object
*/ */
const validateAuthMode = ({ export const validateAuthMode = ({
headers, headers,
acceptedAuthModes acceptedAuthModes
}: { }: {
@@ -96,7 +96,7 @@ const validateAuthMode = ({
* @param {String} obj.authTokenValue - JWT token value * @param {String} obj.authTokenValue - JWT token value
* @returns {User} user - user corresponding to JWT token * @returns {User} user - user corresponding to JWT token
*/ */
const getAuthUserPayload = async ({ export const getAuthUserPayload = async ({
authTokenValue authTokenValue
}: { }: {
authTokenValue: string; authTokenValue: string;
@@ -122,7 +122,7 @@ const getAuthUserPayload = async ({
* @param {String} obj.authTokenValue - service token value * @param {String} obj.authTokenValue - service token value
* @returns {ServiceTokenData} serviceTokenData - service token data * @returns {ServiceTokenData} serviceTokenData - service token data
*/ */
const getAuthSTDPayload = async ({ export const getAuthSTDPayload = async ({
authTokenValue authTokenValue
}: { }: {
authTokenValue: string; authTokenValue: string;
@@ -168,7 +168,7 @@ const getAuthSTDPayload = async ({
* @param {String} obj.authTokenValue - service account access token value * @param {String} obj.authTokenValue - service account access token value
* @returns {ServiceAccount} serviceAccount * @returns {ServiceAccount} serviceAccount
*/ */
const getAuthSAAKPayload = async ({ export const getAuthSAAKPayload = async ({
authTokenValue authTokenValue
}: { }: {
authTokenValue: string; authTokenValue: string;
@@ -197,7 +197,7 @@ const getAuthSAAKPayload = async ({
* @param {String} obj.authTokenValue - API key value * @param {String} obj.authTokenValue - API key value
* @returns {APIKeyData} apiKeyData - API key data * @returns {APIKeyData} apiKeyData - API key data
*/ */
const getAuthAPIKeyPayload = async ({ export const getAuthAPIKeyPayload = async ({
authTokenValue authTokenValue
}: { }: {
authTokenValue: string; authTokenValue: string;
@@ -254,7 +254,10 @@ const getAuthAPIKeyPayload = async ({
* @return {String} obj.token - issued JWT token * @return {String} obj.token - issued JWT token
* @return {String} obj.refreshToken - issued refresh token * @return {String} obj.refreshToken - issued refresh token
*/ */
const issueAuthTokens = async ({ userId }: { userId: string }) => { export const issueAuthTokens = async ({ userId }: { userId: string }) => {
const user = await User.findById(userId).select('+refreshVersion');
if (!user) throw AccountNotFoundError();
// issue tokens // issue tokens
const token = createToken({ const token = createToken({
@@ -267,7 +270,8 @@ const issueAuthTokens = async ({ userId }: { userId: string }) => {
const refreshToken = createToken({ const refreshToken = createToken({
payload: { payload: {
userId userId,
refreshVersion: user.refreshVersion
}, },
expiresIn: await getJwtRefreshLifetime(), expiresIn: await getJwtRefreshLifetime(),
secret: await getJwtRefreshSecret() secret: await getJwtRefreshSecret()
@@ -284,9 +288,9 @@ const issueAuthTokens = async ({ userId }: { userId: string }) => {
* @param {Object} obj * @param {Object} obj
* @param {String} obj.userId - id of user whose tokens are cleared. * @param {String} obj.userId - id of user whose tokens are cleared.
*/ */
const clearTokens = async ({ userId }: { userId: string }): Promise<void> => { export const clearTokens = async (userId: Types.ObjectId): Promise<void> => {
// increment refreshVersion on user by 1 // increment refreshVersion on user by 1
User.findOneAndUpdate({ await User.findOneAndUpdate({
_id: userId _id: userId
}, { }, {
$inc: { $inc: {
@@ -303,7 +307,7 @@ const clearTokens = async ({ userId }: { userId: string }): Promise<void> => {
* @param {String} obj.secret - (JWT) secret such as [JWT_AUTH_SECRET] * @param {String} obj.secret - (JWT) secret such as [JWT_AUTH_SECRET]
* @param {String} obj.expiresIn - string describing time span such as '10h' or '7d' * @param {String} obj.expiresIn - string describing time span such as '10h' or '7d'
*/ */
const createToken = ({ export const createToken = ({
payload, payload,
expiresIn, expiresIn,
secret secret
@@ -315,15 +319,4 @@ const createToken = ({
return jwt.sign(payload, secret, { return jwt.sign(payload, secret, {
expiresIn expiresIn
}); });
}; };
export {
validateAuthMode,
getAuthUserPayload,
getAuthSTDPayload,
getAuthSAAKPayload,
getAuthAPIKeyPayload,
createToken,
issueAuthTokens,
clearTokens
};

View File

@@ -31,7 +31,7 @@ import { InternalServerError } from "../utils/errors";
* @param {String} obj.name - name of bot * @param {String} obj.name - name of bot
* @param {String} obj.workspaceId - id of workspace that bot belongs to * @param {String} obj.workspaceId - id of workspace that bot belongs to
*/ */
const createBot = async ({ export const createBot = async ({
name, name,
workspaceId, workspaceId,
}: { }: {
@@ -93,7 +93,7 @@ const createBot = async ({
* @param {String} obj.workspaceId - id of workspace * @param {String} obj.workspaceId - id of workspace
* @param {String} obj.environment - environment * @param {String} obj.environment - environment
*/ */
const getSecretsHelper = async ({ export const getSecretsBotHelper = async ({
workspaceId, workspaceId,
environment, environment,
}: { }: {
@@ -136,7 +136,7 @@ const getSecretsHelper = async ({
* @param {String} obj.workspaceId - id of workspace * @param {String} obj.workspaceId - id of workspace
* @returns {String} key - decrypted workspace key * @returns {String} key - decrypted workspace key
*/ */
const getKey = async ({ workspaceId }: { workspaceId: string }) => { export const getKey = async ({ workspaceId }: { workspaceId: string }) => {
const encryptionKey = await getEncryptionKey(); const encryptionKey = await getEncryptionKey();
const rootEncryptionKey = await getRootEncryptionKey(); const rootEncryptionKey = await getRootEncryptionKey();
@@ -194,7 +194,7 @@ const getKey = async ({ workspaceId }: { workspaceId: string }) => {
* @param {String} obj1.workspaceId - id of workspace * @param {String} obj1.workspaceId - id of workspace
* @param {String} obj1.plaintext - plaintext to encrypt * @param {String} obj1.plaintext - plaintext to encrypt
*/ */
const encryptSymmetricHelper = async ({ export const encryptSymmetricHelper = async ({
workspaceId, workspaceId,
plaintext, plaintext,
}: { }: {
@@ -222,7 +222,7 @@ const encryptSymmetricHelper = async ({
* @param {String} obj.iv - iv * @param {String} obj.iv - iv
* @param {String} obj.tag - tag * @param {String} obj.tag - tag
*/ */
const decryptSymmetricHelper = async ({ export const decryptSymmetricHelper = async ({
workspaceId, workspaceId,
ciphertext, ciphertext,
iv, iv,
@@ -242,11 +242,4 @@ const decryptSymmetricHelper = async ({
}); });
return plaintext; return plaintext;
}; };
export {
createBot,
getSecretsHelper,
encryptSymmetricHelper,
decryptSymmetricHelper
};

View File

@@ -7,7 +7,7 @@ import { getLogger } from '../utils/logger';
* @param {String} obj.mongoURL - mongo connection string * @param {String} obj.mongoURL - mongo connection string
* @returns * @returns
*/ */
const initDatabaseHelper = async ({ export const initDatabaseHelper = async ({
mongoURL mongoURL
}: { }: {
mongoURL: string; mongoURL: string;
@@ -30,7 +30,7 @@ const initDatabaseHelper = async ({
/** /**
* Close database conection * Close database conection
*/ */
const closeDatabaseHelper = async () => { export const closeDatabaseHelper = async () => {
return Promise.all([ return Promise.all([
new Promise((resolve) => { new Promise((resolve) => {
if (mongoose.connection && mongoose.connection.readyState == 1) { if (mongoose.connection && mongoose.connection.readyState == 1) {
@@ -41,9 +41,4 @@ const closeDatabaseHelper = async () => {
} }
}) })
]); ]);
}
export {
initDatabaseHelper,
closeDatabaseHelper
} }

View File

@@ -18,7 +18,7 @@ interface Event {
* @param {String} obj.event.workspaceId - id of workspace that event is part of * @param {String} obj.event.workspaceId - id of workspace that event is part of
* @param {Object} obj.event.payload - payload of event (depends on event) * @param {Object} obj.event.payload - payload of event (depends on event)
*/ */
const handleEventHelper = async ({ event }: { event: Event }) => { export const handleEventHelper = async ({ event }: { event: Event }) => {
const { workspaceId, environment } = event; const { workspaceId, environment } = event;
// TODO: moduralize bot check into separate function // TODO: moduralize bot check into separate function
@@ -37,6 +37,4 @@ const handleEventHelper = async ({ event }: { event: Event }) => {
}); });
break; break;
} }
}; };
export { handleEventHelper };

View File

@@ -0,0 +1,17 @@
export * from './auth';
export * from './bot';
export * from './database';
export * from './event';
export * from './integration';
export * from './key';
export * from './membership';
export * from './membershipOrg';
export * from './nodemailer';
export * from './organization';
export * from './rateLimiter';
export * from './secret';
export * from './secrets';
export * from './signup';
export * from './token';
export * from './user';
export * from './workspace';

View File

@@ -37,7 +37,7 @@ interface Update {
* @param {String} obj.code - code * @param {String} obj.code - code
* @returns {IntegrationAuth} integrationAuth - integration auth after OAuth2 code-token exchange * @returns {IntegrationAuth} integrationAuth - integration auth after OAuth2 code-token exchange
*/ */
const handleOAuthExchangeHelper = async ({ export const handleOAuthExchangeHelper = async ({
workspaceId, workspaceId,
integration, integration,
code, code,
@@ -118,7 +118,7 @@ const handleOAuthExchangeHelper = async ({
* @param {Object} obj * @param {Object} obj
* @param {Object} obj.workspaceId - id of workspace * @param {Object} obj.workspaceId - id of workspace
*/ */
const syncIntegrationsHelper = async ({ export const syncIntegrationsHelper = async ({
workspaceId, workspaceId,
environment environment
}: { }: {
@@ -177,7 +177,7 @@ const syncIntegrationsHelper = async ({
* @param {String} obj.integrationAuthId - id of integration auth * @param {String} obj.integrationAuthId - id of integration auth
* @param {String} refreshToken - decrypted refresh token * @param {String} refreshToken - decrypted refresh token
*/ */
const getIntegrationAuthRefreshHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => { export const getIntegrationAuthRefreshHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {
let refreshToken; let refreshToken;
try { try {
@@ -214,7 +214,7 @@ const syncIntegrationsHelper = async ({
* @param {String} obj.integrationAuthId - id of integration auth * @param {String} obj.integrationAuthId - id of integration auth
* @returns {String} accessToken - decrypted access token * @returns {String} accessToken - decrypted access token
*/ */
const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => { export const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {
let accessId; let accessId;
let accessToken; let accessToken;
try { try {
@@ -277,7 +277,7 @@ const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrati
* @param {String} obj.integrationAuthId - id of integration auth * @param {String} obj.integrationAuthId - id of integration auth
* @param {String} obj.refreshToken - refresh token * @param {String} obj.refreshToken - refresh token
*/ */
const setIntegrationAuthRefreshHelper = async ({ export const setIntegrationAuthRefreshHelper = async ({
integrationAuthId, integrationAuthId,
refreshToken refreshToken
}: { }: {
@@ -326,7 +326,7 @@ const setIntegrationAuthRefreshHelper = async ({
* @param {String} obj.accessToken - access token * @param {String} obj.accessToken - access token
* @param {Date} obj.accessExpiresAt - expiration date of access token * @param {Date} obj.accessExpiresAt - expiration date of access token
*/ */
const setIntegrationAuthAccessHelper = async ({ export const setIntegrationAuthAccessHelper = async ({
integrationAuthId, integrationAuthId,
accessId, accessId,
accessToken, accessToken,
@@ -378,13 +378,4 @@ const setIntegrationAuthAccessHelper = async ({
} }
return integrationAuth; return integrationAuth;
} }
export {
handleOAuthExchangeHelper,
syncIntegrationsHelper,
getIntegrationAuthRefreshHelper,
getIntegrationAuthAccessHelper,
setIntegrationAuthRefreshHelper,
setIntegrationAuthAccessHelper
}

View File

@@ -17,7 +17,7 @@ interface Key {
* @param {String} obj.keys.nonce - nonce for encryption * @param {String} obj.keys.nonce - nonce for encryption
* @param {String} obj.keys.userId - id of receiver user * @param {String} obj.keys.userId - id of receiver user
*/ */
const pushKeys = async ({ export const pushKeys = async ({
userId, userId,
workspaceId, workspaceId,
keys keys
@@ -50,6 +50,4 @@ const pushKeys = async ({
workspace: workspaceId workspace: workspaceId
})) }))
); );
}; };
export { pushKeys };

View File

@@ -17,7 +17,7 @@ import {
* @param {String} obj.workspaceId - id of workspace * @param {String} obj.workspaceId - id of workspace
* @returns {Membership} membership - membership of user with id [userId] for workspace with id [workspaceId] * @returns {Membership} membership - membership of user with id [userId] for workspace with id [workspaceId]
*/ */
const validateMembership = async ({ export const validateMembership = async ({
userId, userId,
workspaceId, workspaceId,
acceptedRoles, acceptedRoles,
@@ -50,7 +50,7 @@ const validateMembership = async ({
* @param {Object} queryObj - query object * @param {Object} queryObj - query object
* @return {Object} membership - membership * @return {Object} membership - membership
*/ */
const findMembership = async (queryObj: any) => { export const findMembership = async (queryObj: any) => {
let membership; let membership;
try { try {
membership = await Membership.findOne(queryObj); membership = await Membership.findOne(queryObj);
@@ -71,7 +71,7 @@ const findMembership = async (queryObj: any) => {
* @param {String} obj.workspaceId - id of workspace. * @param {String} obj.workspaceId - id of workspace.
* @param {String[]} obj.roles - roles of users. * @param {String[]} obj.roles - roles of users.
*/ */
const addMemberships = async ({ export const addMemberships = async ({
userIds, userIds,
workspaceId, workspaceId,
roles roles
@@ -112,7 +112,7 @@ const addMemberships = async ({
* @param {Object} obj * @param {Object} obj
* @param {String} obj.membershipId - id of membership to delete * @param {String} obj.membershipId - id of membership to delete
*/ */
const deleteMembership = async ({ membershipId }: { membershipId: string }) => { export const deleteMembership = async ({ membershipId }: { membershipId: string }) => {
let deletedMembership; let deletedMembership;
try { try {
deletedMembership = await Membership.findOneAndDelete({ deletedMembership = await Membership.findOneAndDelete({
@@ -134,11 +134,4 @@ const deleteMembership = async ({ membershipId }: { membershipId: string }) => {
} }
return deletedMembership; return deletedMembership;
}; };
export {
validateMembership,
addMemberships,
findMembership,
deleteMembership
};

View File

@@ -18,7 +18,7 @@ import {
* @param {Types.ObjectId} obj.organizationId * @param {Types.ObjectId} obj.organizationId
* @param {String[]} obj.acceptedRoles * @param {String[]} obj.acceptedRoles
*/ */
const validateMembershipOrg = async ({ export const validateMembershipOrg = async ({
userId, userId,
organizationId, organizationId,
acceptedRoles, acceptedRoles,
@@ -59,7 +59,7 @@ const validateMembershipOrg = async ({
* @param {Object} queryObj - query object * @param {Object} queryObj - query object
* @return {Object} membershipOrg - membership * @return {Object} membershipOrg - membership
*/ */
const findMembershipOrg = (queryObj: any) => { export const findMembershipOrg = (queryObj: any) => {
const membershipOrg = MembershipOrg.findOne(queryObj); const membershipOrg = MembershipOrg.findOne(queryObj);
return membershipOrg; return membershipOrg;
}; };
@@ -72,7 +72,7 @@ const findMembershipOrg = (queryObj: any) => {
* @param {String} obj.organizationId - id of organization. * @param {String} obj.organizationId - id of organization.
* @param {String[]} obj.roles - roles of users. * @param {String[]} obj.roles - roles of users.
*/ */
const addMembershipsOrg = async ({ export const addMembershipsOrg = async ({
userIds, userIds,
organizationId, organizationId,
roles, roles,
@@ -111,7 +111,7 @@ const addMembershipsOrg = async ({
* @param {Object} obj * @param {Object} obj
* @param {String} obj.membershipOrgId - id of organization membership to delete * @param {String} obj.membershipOrgId - id of organization membership to delete
*/ */
const deleteMembershipOrg = async ({ export const deleteMembershipOrg = async ({
membershipOrgId membershipOrgId
}: { }: {
membershipOrgId: string; membershipOrgId: string;
@@ -148,11 +148,4 @@ const deleteMembershipOrg = async ({
} }
return deletedMembershipOrg; return deletedMembershipOrg;
}; };
export {
validateMembershipOrg,
findMembershipOrg,
addMembershipsOrg,
deleteMembershipOrg
};

View File

@@ -14,7 +14,7 @@ let smtpTransporter: nodemailer.Transporter;
* @param {String[]} obj.recipients - email addresses of people to send email to * @param {String[]} obj.recipients - email addresses of people to send email to
* @param {Object} obj.substitutions - object containing template substitutions * @param {Object} obj.substitutions - object containing template substitutions
*/ */
const sendMail = async ({ export const sendMail = async ({
template, template,
subjectLine, subjectLine,
recipients, recipients,
@@ -48,8 +48,6 @@ const sendMail = async ({
} }
}; };
const setTransporter = (transporter: nodemailer.Transporter) => { export const setTransporter = (transporter: nodemailer.Transporter) => {
smtpTransporter = transporter; smtpTransporter = transporter;
}; };
export { sendMail, setTransporter };

View File

@@ -28,7 +28,7 @@ import {
* @param {String} obj.email - POC email that will receive invoice info * @param {String} obj.email - POC email that will receive invoice info
* @param {Object} organization - new organization * @param {Object} organization - new organization
*/ */
const createOrganization = async ({ export const createOrganization = async ({
name, name,
email, email,
}: { }: {
@@ -70,7 +70,7 @@ const createOrganization = async ({
* @return {Object} obj.stripeSubscription - new stripe subscription * @return {Object} obj.stripeSubscription - new stripe subscription
* @return {Subscription} obj.subscription - new subscription * @return {Subscription} obj.subscription - new subscription
*/ */
const initSubscriptionOrg = async ({ export const initSubscriptionOrg = async ({
organizationId, organizationId,
}: { }: {
organizationId: Types.ObjectId; organizationId: Types.ObjectId;
@@ -125,7 +125,7 @@ const initSubscriptionOrg = async ({
* @param {Object} obj * @param {Object} obj
* @param {Number} obj.organizationId - id of subscription's organization * @param {Number} obj.organizationId - id of subscription's organization
*/ */
const updateSubscriptionOrgQuantity = async ({ export const updateSubscriptionOrgQuantity = async ({
organizationId, organizationId,
}: { }: {
organizationId: string; organizationId: string;
@@ -171,10 +171,4 @@ const updateSubscriptionOrgQuantity = async ({
} }
return stripeSubscription; return stripeSubscription;
}; };
export {
createOrganization,
initSubscriptionOrg,
updateSubscriptionOrgQuantity
};

View File

@@ -1,7 +1,7 @@
import rateLimit from 'express-rate-limit'; import rateLimit from 'express-rate-limit';
// 120 requests per minute // 120 requests per minute
const apiLimiter = rateLimit({ export const apiLimiter = rateLimit({
windowMs: 60 * 1000, windowMs: 60 * 1000,
max: 240, max: 240,
standardHeaders: true, standardHeaders: true,
@@ -20,23 +20,17 @@ const authLimit = rateLimit({
}); });
// 10 requests per hour // 10 requests per hour
const passwordLimiter = rateLimit({ export const passwordLimiter = rateLimit({
windowMs: 60 * 60 * 1000, windowMs: 60 * 60 * 1000,
max: 10, max: 10,
standardHeaders: true, standardHeaders: true,
legacyHeaders: false legacyHeaders: false
}); });
const authLimiter = (req: any, res: any, next: any) => { export const authLimiter = (req: any, res: any, next: any) => {
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === 'production') {
authLimit(req, res, next); authLimit(req, res, next);
} else { } else {
next(); next();
} }
}; };
export {
apiLimiter,
authLimiter,
passwordLimiter
};

View File

@@ -62,7 +62,7 @@ interface Update {
* @param {String} obj.environment - environment for secrets * @param {String} obj.environment - environment for secrets
* @param {Object[]} obj.secrets - secrets to push * @param {Object[]} obj.secrets - secrets to push
*/ */
const v1PushSecrets = async ({ export const v1PushSecrets = async ({
userId, userId,
workspaceId, workspaceId,
environment, environment,
@@ -305,7 +305,7 @@ const v1PushSecrets = async ({
* @param {String} obj.channel - channel (web/cli/auto) * @param {String} obj.channel - channel (web/cli/auto)
* @param {String} obj.ipAddress - ip address of request to push secrets * @param {String} obj.ipAddress - ip address of request to push secrets
*/ */
const v2PushSecrets = async ({ export const v2PushSecrets = async ({
userId, userId,
workspaceId, workspaceId,
environment, environment,
@@ -530,7 +530,7 @@ const v2PushSecrets = async ({
* @param {String} obj.workspaceId - id of workspace to pull from * @param {String} obj.workspaceId - id of workspace to pull from
* @param {String} obj.environment - environment for secrets * @param {String} obj.environment - environment for secrets
*/ */
const getSecrets = async ({ export const getSecrets = async ({
userId, userId,
workspaceId, workspaceId,
environment, environment,
@@ -570,7 +570,7 @@ const getSecrets = async ({
* @param {String} obj.channel - channel (web/cli/auto) * @param {String} obj.channel - channel (web/cli/auto)
* @param {String} obj.ipAddress - ip address of request to push secrets * @param {String} obj.ipAddress - ip address of request to push secrets
*/ */
const pullSecrets = async ({ export const pullSecrets = async ({
userId, userId,
workspaceId, workspaceId,
environment, environment,
@@ -614,7 +614,7 @@ const pullSecrets = async ({
* @param {Object} obj * @param {Object} obj
* @param {Object} obj.secrets * @param {Object} obj.secrets
*/ */
const reformatPullSecrets = ({ secrets }: { secrets: ISecret[] }) => { export const reformatPullSecrets = ({ secrets }: { secrets: ISecret[] }) => {
const reformatedSecrets = secrets.map((s) => ({ const reformatedSecrets = secrets.map((s) => ({
_id: s._id, _id: s._id,
workspace: s.workspace, workspace: s.workspace,
@@ -644,6 +644,4 @@ const reformatPullSecrets = ({ secrets }: { secrets: ISecret[] }) => {
})); }));
return reformatedSecrets; return reformatedSecrets;
}; };
export { v1PushSecrets, v2PushSecrets, pullSecrets, reformatPullSecrets };

View File

@@ -52,7 +52,7 @@ import {
* @param {Object} obj * @param {Object} obj
* @param {Types.ObjectId} obj.workspaceId * @param {Types.ObjectId} obj.workspaceId
*/ */
const createSecretBlindIndexDataHelper = async ({ export const createSecretBlindIndexDataHelper = async ({
workspaceId workspaceId
}: { }: {
workspaceId: Types.ObjectId; workspaceId: Types.ObjectId;
@@ -106,7 +106,7 @@ const createSecretBlindIndexDataHelper = async ({
* @param {Types.ObjectId} obj.workspaceId - id of workspace to get salt for * @param {Types.ObjectId} obj.workspaceId - id of workspace to get salt for
* @returns * @returns
*/ */
const getSecretBlindIndexSaltHelper = async ({ export const getSecretBlindIndexSaltHelper = async ({
workspaceId workspaceId
}: { }: {
workspaceId: Types.ObjectId; workspaceId: Types.ObjectId;
@@ -150,7 +150,7 @@ const getSecretBlindIndexSaltHelper = async ({
* @param {String} obj.secretName - name of secret to generate blind index for * @param {String} obj.secretName - name of secret to generate blind index for
* @param {String} obj.salt - base64-salt * @param {String} obj.salt - base64-salt
*/ */
const generateSecretBlindIndexWithSaltHelper = async ({ export const generateSecretBlindIndexWithSaltHelper = async ({
secretName, secretName,
salt salt
}: { }: {
@@ -179,7 +179,7 @@ const getSecretBlindIndexSaltHelper = async ({
* @param {Stringj} obj.secretName - name of secret to generate blind index for * @param {Stringj} obj.secretName - name of secret to generate blind index for
* @param {Types.ObjectId} obj.workspaceId - id of workspace that secret belongs to * @param {Types.ObjectId} obj.workspaceId - id of workspace that secret belongs to
*/ */
const generateSecretBlindIndexHelper = async ({ export const generateSecretBlindIndexHelper = async ({
secretName, secretName,
workspaceId workspaceId
}: { }: {
@@ -220,7 +220,7 @@ const generateSecretBlindIndexHelper = async ({
* @param {AuthData} obj.authData - authentication data on request * @param {AuthData} obj.authData - authentication data on request
* @returns * @returns
*/ */
const createSecretHelper = async ({ export const createSecretHelper = async ({
secretName, secretName,
workspaceId, workspaceId,
environment, environment,
@@ -362,7 +362,7 @@ const createSecretHelper = async ({
* @param {AuthData} obj.authData - authentication data on request * @param {AuthData} obj.authData - authentication data on request
* @returns * @returns
*/ */
const getSecretsHelper = async ({ export const getSecretsHelper = async ({
workspaceId, workspaceId,
environment, environment,
authData authData
@@ -434,7 +434,7 @@ const getSecretsHelper = async ({
* @param {AuthData} obj.authData - authentication data on request * @param {AuthData} obj.authData - authentication data on request
* @returns * @returns
*/ */
const getSecretHelper = async ({ export const getSecretHelper = async ({
secretName, secretName,
workspaceId, workspaceId,
environment, environment,
@@ -519,7 +519,7 @@ const getSecretHelper = async ({
* @param {AuthData} obj.authData - authentication data on request * @param {AuthData} obj.authData - authentication data on request
* @returns * @returns
*/ */
const updateSecretHelper = async ({ export const updateSecretHelper = async ({
secretName, secretName,
workspaceId, workspaceId,
environment, environment,
@@ -656,7 +656,7 @@ const updateSecretHelper = async ({
* @param {AuthData} obj.authData - authentication data on request * @param {AuthData} obj.authData - authentication data on request
* @returns * @returns
*/ */
const deleteSecretHelper = async ({ export const deleteSecretHelper = async ({
secretName, secretName,
workspaceId, workspaceId,
environment, environment,
@@ -754,16 +754,4 @@ const deleteSecretHelper = async ({
secrets, secrets,
secret secret
}); });
}
export {
createSecretBlindIndexDataHelper,
getSecretBlindIndexSaltHelper,
generateSecretBlindIndexWithSaltHelper,
generateSecretBlindIndexHelper,
createSecretHelper,
getSecretsHelper,
getSecretHelper,
updateSecretHelper,
deleteSecretHelper
} }

View File

@@ -14,7 +14,7 @@ import { TOKEN_EMAIL_CONFIRMATION } from '../variables';
* @param {String} obj.email - email * @param {String} obj.email - email
* @returns {Boolean} success - whether or not operation was successful * @returns {Boolean} success - whether or not operation was successful
*/ */
const sendEmailVerification = async ({ email }: { email: string }) => { export const sendEmailVerification = async ({ email }: { email: string }) => {
try { try {
const token = await TokenService.createToken({ const token = await TokenService.createToken({
type: TOKEN_EMAIL_CONFIRMATION, type: TOKEN_EMAIL_CONFIRMATION,
@@ -45,7 +45,7 @@ const sendEmailVerification = async ({ email }: { email: string }) => {
* @param {String} obj.email - emai * @param {String} obj.email - emai
* @param {String} obj.code - code that was sent to [email] * @param {String} obj.code - code that was sent to [email]
*/ */
const checkEmailVerification = async ({ export const checkEmailVerification = async ({
email, email,
code code
}: { }: {
@@ -72,7 +72,7 @@ const checkEmailVerification = async ({
* @param {String} obj.organizationName - name of organization to initialize * @param {String} obj.organizationName - name of organization to initialize
* @param {IUser} obj.user - user who we are initializing for * @param {IUser} obj.user - user who we are initializing for
*/ */
const initializeDefaultOrg = async ({ export const initializeDefaultOrg = async ({
organizationName, organizationName,
user user
}: { }: {
@@ -96,6 +96,4 @@ const initializeDefaultOrg = async ({
} catch (err) { } catch (err) {
throw new Error(`Failed to initialize default organization and workspace [err=${err}]`); throw new Error(`Failed to initialize default organization and workspace [err=${err}]`);
} }
}; };
export { sendEmailVerification, checkEmailVerification, initializeDefaultOrg };

View File

@@ -20,7 +20,7 @@ import { getSaltRounds } from "../config";
* @param {Types.ObjectId} obj.organizationId * @param {Types.ObjectId} obj.organizationId
* @returns {String} token - the created token * @returns {String} token - the created token
*/ */
const createTokenHelper = async ({ export const createTokenHelper = async ({
type, type,
email, email,
phoneNumber, phoneNumber,
@@ -121,7 +121,7 @@ const createTokenHelper = async ({
* @param {String} obj.email - email associated with the token * @param {String} obj.email - email associated with the token
* @param {String} obj.token - value of the token * @param {String} obj.token - value of the token
*/ */
const validateTokenHelper = async ({ export const validateTokenHelper = async ({
type, type,
email, email,
phoneNumber, phoneNumber,
@@ -212,6 +212,4 @@ const validateTokenHelper = async ({
// case: token is valid // case: token is valid
await TokenData.findByIdAndDelete(tokenData._id); await TokenData.findByIdAndDelete(tokenData._id);
}; };
export { createTokenHelper, validateTokenHelper };

View File

@@ -16,7 +16,7 @@ import { SecretService } from '../services';
* @param {String} organizationId - id of organization to create workspace in * @param {String} organizationId - id of organization to create workspace in
* @param {Object} workspace - new workspace * @param {Object} workspace - new workspace
*/ */
const createWorkspace = async ({ export const createWorkspace = async ({
name, name,
organizationId organizationId
}: { }: {
@@ -58,7 +58,7 @@ const createWorkspace = async ({
* @param {Object} obj * @param {Object} obj
* @param {String} obj.id - id of workspace to delete * @param {String} obj.id - id of workspace to delete
*/ */
const deleteWorkspace = async ({ id }: { id: string }) => { export const deleteWorkspace = async ({ id }: { id: string }) => {
try { try {
await Workspace.deleteOne({ _id: id }); await Workspace.deleteOne({ _id: id });
await Bot.deleteOne({ await Bot.deleteOne({
@@ -78,9 +78,4 @@ const deleteWorkspace = async ({ id }: { id: string }) => {
Sentry.captureException(err); Sentry.captureException(err);
throw new Error('Failed to delete workspace'); throw new Error('Failed to delete workspace');
} }
}; };
export {
createWorkspace,
deleteWorkspace
};

View File

@@ -15,7 +15,7 @@ export interface IUser extends Document {
tag?: string; tag?: string;
salt?: string; salt?: string;
verifier?: string; verifier?: string;
refreshVersion?: number; refreshVersion: number;
isMfaEnabled: boolean; isMfaEnabled: boolean;
mfaMethods: boolean; mfaMethods: boolean;
devices: { devices: {

View File

@@ -1,6 +1,6 @@
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { import {
getSecretsHelper, getSecretsBotHelper,
encryptSymmetricHelper, encryptSymmetricHelper,
decryptSymmetricHelper decryptSymmetricHelper
} from '../helpers/bot'; } from '../helpers/bot';
@@ -25,7 +25,7 @@ class BotService {
workspaceId: Types.ObjectId; workspaceId: Types.ObjectId;
environment: string; environment: string;
}) { }) {
return await getSecretsHelper({ return await getSecretsBotHelper({
workspaceId, workspaceId,
environment environment
}); });