Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Update helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Aug 4, 2020
1 parent 582e8ef commit 4dc4bf6
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 84 deletions.
33 changes: 13 additions & 20 deletions src/_staart/helpers/authorization.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import {
ORGANIZATION_NOT_FOUND,
USER_NOT_FOUND,
INVALID_TOKEN,
} from "@staart/errors";
import { OrgScopes, Tokens, UserScopes, SudoScopes } from "../interfaces/enum";
import { ApiKeyResponse, AccessTokenResponse } from "./jwt";
import {
users,
groups,
memberships,
accessTokens,
apiKeys,
groups,
memberships,
users,
} from "@prisma/client";
import { prisma } from "./prisma";
import { getUserById } from "../services/user.service";
import { INVALID_TOKEN, USER_NOT_FOUND } from "@staart/errors";
import { OrgScopes, SudoScopes, Tokens, UserScopes } from "../interfaces/enum";
import { getGroupById } from "../services/group.service";
import { getUserById } from "../services/user.service";
import { AccessTokenResponse, ApiKeyResponse } from "./jwt";
import { prisma } from "./prisma";

/**
* Whether a user can perform an action on another user
Expand Down Expand Up @@ -64,7 +60,8 @@ const canAccessTokenUser = (

if (!accessToken.scopes) return false;

if (accessToken.scopes.includes(action)) return true;
if (Array.isArray(accessToken.scopes) && accessToken.scopes.includes(action))
return true;

return false;
};
Expand All @@ -87,9 +84,6 @@ const canUserGroup = async (user: users, action: OrgScopes, target: groups) => {
// An group admin can do anything too
if (membership.role === "ADMIN") allowed = true;

// An group reseller can do anything too
if (membership.role === "RESELLER") allowed = true;

// An group member can read, not edit/delete/invite
if (
membership.role === "MEMBER" &&
Expand Down Expand Up @@ -125,9 +119,7 @@ const canUserMembership = async (
// An admin, owner, or reseller can edit
if (
membership.groupId === target.groupId &&
(membership.role === "OWNER" ||
membership.role === "ADMIN" ||
membership.role === "RESELLER")
(membership.role === "OWNER" || membership.role === "ADMIN")
)
allowed = true;

Expand Down Expand Up @@ -163,7 +155,8 @@ const canApiKeyGroup = (apiKey: apiKeys, action: OrgScopes, target: groups) => {
// If it has no scopes, it has no permissions
if (!apiKey.scopes) return false;

if (apiKey.scopes.includes(action)) return true;
if (Array.isArray(apiKey.scopes) && apiKey.scopes.includes(action))
return true;

return false;
};
Expand Down
2 changes: 1 addition & 1 deletion src/_staart/helpers/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import redis from "@staart/redis";
import { RESOURCE_NOT_FOUND } from "@staart/errors";
import { redis } from "@staart/redis";

/**
* Get an item from Redis cache
Expand Down
3 changes: 1 addition & 2 deletions src/_staart/helpers/errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { EXPIRED_TOKEN, INVALID_TOKEN } from "@staart/errors";
import { warn } from "@staart/errors";
import { EXPIRED_TOKEN, INVALID_TOKEN, warn } from "@staart/errors";
import { ValidationError } from "@staart/validate";
import { HTTPError } from "../interfaces/general";

Expand Down
24 changes: 11 additions & 13 deletions src/_staart/helpers/jwt.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
accessTokensCreateInput,
accessTokensUpdateInput,
users,
} from "@prisma/client";
import {
IP_RANGE_CHECK_FAIL,
REFERRER_CHECK_FAIL,
Expand All @@ -21,26 +26,19 @@ import {
} from "../../config";
import { EventType, Templates, Tokens } from "../interfaces/enum";
import { Locals } from "../interfaces/general";
import {
checkApprovedLocation,
getUserPrimaryEmail,
updateSessionByJwt,
} from "../services/user.service";
import { getGeolocationFromIp } from "./location";
import { mail } from "./mail";
import { prisma } from "./prisma";
import {
deleteSensitiveInfoUser,
includesDomainInCommaList,
removeFalsyValues,
} from "./utils";
import {
accessTokensCreateInput,
accessTokensUpdateInput,
users,
apiKeysCreateInput,
apiKeysUpdateInput,
} from "@prisma/client";
import { prisma } from "./prisma";
import {
updateSessionByJwt,
checkApprovedLocation,
getUserPrimaryEmail,
} from "../services/user.service";

/**
* Generate a new JWT
Expand Down
2 changes: 1 addition & 1 deletion src/_staart/helpers/location.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { success } from "@staart/errors";
import geolite2 from "geolite2-redist";
import maxmind, { CityResponse, Reader } from "maxmind";
import { success } from "@staart/errors";

export interface GeoLocation {
city?: string;
Expand Down
22 changes: 17 additions & 5 deletions src/_staart/helpers/mail.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { logError } from "@staart/errors";
import { sendMail, Mail } from "@staart/mail";
import { Mail, sendMail } from "@staart/mail";
import { render } from "@staart/mustache-markdown";
import { redisQueue } from "@staart/redis";
import { readFile } from "fs-extra";
import { join } from "path";
import { FRONTEND_URL, REDIS_QUEUE_PREFIX } from "../../config";
import { PartialBy } from "../../_staart/helpers/utils";

const MAIL_QUEUE = `${REDIS_QUEUE_PREFIX}outbound-emails`;

Expand All @@ -23,7 +24,7 @@ export const receiveEmailMessage = async () => {
qname: MAIL_QUEUE,
});
if ("id" in result) {
const data: Mail & {
const data: PartialBy<PartialBy<Mail, "subject">, "message"> & {
template?: string;
data?: any;
tryNumber: number;
Expand Down Expand Up @@ -59,7 +60,10 @@ export const receiveEmailMessage = async () => {
* Send a new email using AWS SES or SMTP
*/
export const mail = async (
options: Mail & { template?: string; data?: any }
options: PartialBy<PartialBy<Mail, "subject">, "message"> & {
template?: string;
data?: any;
}
) => {
await setupQueue();
await redisQueue.sendMessageAsync({
Expand All @@ -69,7 +73,10 @@ export const mail = async (
};

const safeSendEmail = async (
options: Mail & { template?: string; data?: any }
options: PartialBy<PartialBy<Mail, "subject">, "message"> & {
template?: string;
data?: any;
}
) => {
options.subject = options.subject || "";
options.message = options.message || "";
Expand Down Expand Up @@ -97,5 +104,10 @@ const safeSendEmail = async (
.split("\n", 1)[0]
.replace(/<\/?[^>]+(>|$)/g, "");
}
return sendMail(options);
return sendMail(
options as Mail & {
template?: string;
data?: any;
}
);
};
6 changes: 2 additions & 4 deletions src/_staart/helpers/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@ import { constructWebhookEvent } from "@staart/payments";
import {
NextFunction,
RateLimit,
RawRequest,
Request,
Response,
slowDown,
} from "@staart/server";
import { RawRequest } from "@staart/server";
import { ms } from "@staart/text";
import { SchemaMap } from "@staart/validate";
import { joiValidate } from "@staart/validate";
import { joiValidate, SchemaMap } from "@staart/validate";
import pkg from "../../../package.json";
import {
BRUTE_FORCE_COUNT,
Expand All @@ -30,7 +29,6 @@ import {
} from "../../config";
import { Tokens } from "../interfaces/enum";
import { StripeLocals } from "../interfaces/general";

import { safeError } from "./errors";
import {
ApiKeyResponse,
Expand Down
4 changes: 2 additions & 2 deletions src/_staart/helpers/prisma.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { PrismaClient } from "@prisma/client";
import { cleanup } from "@staart/server";
import { complete, success } from "@staart/errors";
import { getConfig } from "@staart/config";
import { complete, success } from "@staart/errors";
import { cleanup } from "@staart/server";

export const prisma = new PrismaClient({
log: getConfig("NODE_ENV") === "production" ? ["warn"] : ["info", "warn"],
Expand Down
2 changes: 1 addition & 1 deletion src/_staart/helpers/tracking.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Request, Response } from "@staart/server";
import { Tokens } from "../interfaces/enum";
import { Locals, Event } from "../interfaces/general";
import { Event, Locals } from "../interfaces/general";
import { verifyToken } from "./jwt";

let trackingData: Array<any> = [];
Expand Down
36 changes: 1 addition & 35 deletions src/_staart/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import { users } from "@prisma/client";
import { Request, Response } from "@staart/server";
import { isMatch } from "@staart/text";
import { Joi, joiValidate } from "@staart/validate";
import { ORGANIZATION_NOT_FOUND, USER_NOT_FOUND } from "@staart/errors";
import dns from "dns";
import { Tokens } from "../interfaces/enum";
import { ApiKeyResponse } from "./jwt";
import { users } from "@prisma/client";
import { prisma } from "../helpers/prisma";
import { getGroupById } from "../services/group.service";
import { getUserById } from "../services/user.service";

/**
* Make s single property optional
Expand All @@ -25,36 +21,6 @@ export const deleteSensitiveInfoUser = (user: users) => {
return user;
};

export const groupUsernameToId = async (id: string) => {
const result = (
await prisma.groups.findOne({
select: { id: true },
where: {
username: id,
},
})
)?.id.toString();
if (result) return result;
throw new Error(ORGANIZATION_NOT_FOUND);
};

export const userUsernameToId = async (id: string, tokenUserId?: string) => {
if (id === "me" && tokenUserId) {
return String(tokenUserId);
} else {
const result = (
await prisma.users.findOne({
select: { id: true },
where: {
username: id,
},
})
)?.id.toString();
if (result) return result;
throw new Error(USER_NOT_FOUND);
}
};

export const localsToTokenOrKey = (res: Response) => {
if (res.locals.token.sub == Tokens.API_KEY) {
return res.locals.token as ApiKeyResponse;
Expand Down

0 comments on commit 4dc4bf6

Please sign in to comment.