Skip to content

Commit

Permalink
Re-organize backend core helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
big213 committed Apr 8, 2021
1 parent c811d69 commit da8b76d
Show file tree
Hide file tree
Showing 43 changed files with 210 additions and 212 deletions.
2 changes: 1 addition & 1 deletion backend/functions/src/helpers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { User } from "../schema/services";
import { userRoleKenum, userPermissionEnum } from "../schema/enums";
import { userRoleToPermissionsMap } from "../schema/helpers/permissions";
import type { ContextUser } from "../types";
import * as sqlHelper from "../schema/helpers/sql";
import * as sqlHelper from "../schema/core/helpers/sql";

export async function validateToken(auth: string): Promise<ContextUser> {
if (auth.split(" ")[0] !== "Bearer") {
Expand Down
4 changes: 2 additions & 2 deletions backend/functions/src/schema/core/generators/edge.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { BaseService, NormalService } from "../services";

import * as Scalars from "../../scalars";
import { generateTypenameField } from "../../helpers/typeDef";
import { atob } from "../../helpers/shared";
import { generateTypenameField } from "../helpers/typeDef";
import { atob } from "../helpers/shared";
import type { ObjectTypeDefinition } from "giraffeql";

export function generateEdgeTypeDef(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BaseService, EnumService } from "../services";
import * as Scalars from "../../scalars";
import type { ObjectTypeDefinition } from "giraffeql";
import { generateTypenameField } from "../../helpers/typeDef";
import { generateTypenameField } from "../helpers/typeDef";

export function generateEnumPaginatorTypeDef(
service: EnumService,
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/core/generators/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
generateCreatedByField,
generateJoinableField,
generateTypenameField,
} from "../../helpers/typeDef";
} from "../helpers/typeDef";
import { ObjectTypeDefinition, ObjectTypeDefinitionField } from "giraffeql";

type ServicesObjectMap = {
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/core/generators/paginator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
BaseService,
} from "../services";

import { generateTypenameField } from "../../helpers/typeDef";
import { generateTypenameField } from "../helpers/typeDef";
import type { ObjectTypeDefinition } from "giraffeql";
import { PaginatorData } from "../../../types";

Expand Down
4 changes: 2 additions & 2 deletions backend/functions/src/schema/core/generators/paginatorInfo.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { BaseService, NormalService } from "../services";

import * as Scalars from "../../scalars";
import { atob } from "../../helpers/shared";
import { atob } from "../helpers/shared";
import type { ObjectTypeDefinition } from "giraffeql";
import { generateTypenameField } from "../../helpers/typeDef";
import { generateTypenameField } from "../helpers/typeDef";
import { PaginatorData } from "../../../types";

export function generatePaginatorInfoTypeDef(
Expand Down
151 changes: 151 additions & 0 deletions backend/functions/src/schema/core/helpers/permissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { userRoleKenum } from "../../enums";
import { BaseService, NormalService } from "../services";
import * as errorHelper from "./error";
import { ServiceFunctionInputs, AccessControlFunction } from "../../../types";
import { StringKeyObject } from "giraffeql";

export function generateItemCreatedByUserGuard(
service: NormalService
): AccessControlFunction {
return async function ({ req, args, fieldPath }) {
// args should be validated already
const validatedArgs = <StringKeyObject>args;
//check if logged in
if (!req.user) return false;

try {
const itemRecord = await service.lookupRecord(
[{ field: "createdBy" }],
validatedArgs.item ?? validatedArgs,
fieldPath
);

return itemRecord?.createdBy === req.user.id;
} catch (err) {
return false;
}
};
}

export function generateUserAdminGuard(): AccessControlFunction {
return generateUserRoleGuard([userRoleKenum.ADMIN]);
}

export function generateUserRoleGuard(
allowedRoles: userRoleKenum[]
): AccessControlFunction {
return async function ({ req }) {
//check if logged in
if (!req.user) return false;

try {
// role is loaded in helpers/auth on token decode
/*
const userRecords = await sqlHelper.fetchTableRows({
select: [{ field: "role" }],
from: User.typename,
where: {
fields: [{ field: "id", value: req.user.id }],
},
});
*/

if (!req.user.role) return false;
return allowedRoles.includes(req.user.role);
} catch (err) {
return false;
}
};
}

/*
export function userRoleGuard(allowedRoles: userRoleKenum[]) {
return function (
target: BaseService,
propertyName: string,
propertyDescriptor: PropertyDescriptor
): PropertyDescriptor {
// target === Employee.prototype
// propertyName === "greet"
// propertyDesciptor === Object.getOwnPropertyDescriptor(Employee.prototype, "greet")
const method = propertyDescriptor.value;
propertyDescriptor.value = async function (req, args, query) {
// convert list of greet arguments to string
//const params = args.map((a) => JSON.stringify(a)).join();
const params = "bar";
//if it does not pass the access control, throw an error
if (!(await target.testPermissions("get", req, args, query))) {
throw errorHelper.badPermissionsError();
}
// invoke greet() and get its return value
const result = await method.apply(this, [req, args, query]);
// convert result to string
const r = JSON.stringify(result);
// display in console the function call details
console.log(`Call: ${propertyName}(${params}) => ${r}`);
// return the result of invoking the method
return result;
};
return propertyDescriptor;
};
}
*/

export function permissionsCheck(methodKey: string) {
return function (
target: BaseService,
propertyName: string,
propertyDescriptor: PropertyDescriptor
): PropertyDescriptor {
// target === Employee.prototype
// propertyName === "greet"
// propertyDesciptor === Object.getOwnPropertyDescriptor(Employee.prototype, "greet")
const method = propertyDescriptor.value;

propertyDescriptor.value = async function ({
req,
fieldPath,
args,
query,
data,
isAdmin = false,
}: ServiceFunctionInputs) {
//if it does not pass the access control, throw an error
if (
!(await target.testPermissions.apply(this, [
methodKey,
{
req,
fieldPath,
args,
query,
data,
isAdmin,
},
]))
) {
throw errorHelper.badPermissionsError(fieldPath);
}
// invoke greet() and get its return value
const result = await method.apply(this, [
{
req,
fieldPath,
args,
query,
data,
isAdmin,
},
]);

// return the result of invoking the method
return result;
};
return propertyDescriptor;
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
SqlSelectQueryObject,
SqlWhereObject,
} from "./sql";
import { CustomResolverFunction } from "../../types";
import { CustomResolverFunction } from "../../../types";

import { isObject } from "../helpers/shared";
import type { Request } from "express";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
GiraffeqlObjectType,
GiraffeqlInputFieldType,
} from "giraffeql";
import { NormalService, PaginatedService, EnumService } from "../core/services";
import { NormalService, PaginatedService, EnumService } from "../services";
import { generatePaginatorPivotResolverObject } from "../helpers/typeDef";
import { capitalizeString, isObject } from "../helpers/shared";
type BaseRootResolverTypes =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { StringKeyObject } from "../../types";
import { StringKeyObject } from "../../../types";
export function getUnixTimestamp(): number {
return new Date().getTime();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
objectTypeDefs,
} from "giraffeql";
import Knex = require("knex");
import { isDev } from "../../config";
import { executeDBQuery, knex } from "../../utils/knex";
import { linkDefs } from "../links";
import { isDev } from "../../../config";
import { executeDBQuery, knex } from "../../../utils/knex";
import { linkDefs } from "../../links";

type FieldInfo = {
alias: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getPusher } from "../../utils/pusher";
import { NormalService } from "../core/services";
import { getPusher } from "../../../utils/pusher";
import { NormalService } from "../services";

import * as randomstring from "randomstring";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@ import {
GiraffeqlInputFieldType,
ArrayOptions,
inputTypeDefs,
ObjectTypeDefinition,
} from "giraffeql";
import { knex } from "../../utils/knex";
import { knex } from "../../../utils/knex";
import * as Resolver from "./resolver";
import { deepAssign, isObject, snakeToCamel } from "./shared";
import { BaseService, NormalService, PaginatedService } from "../core/services";
import { linkDefs } from "../links";
import * as Scalars from "../scalars";
import type { ObjectTypeDefSqlOptions, SqlType } from "../../types";
import { FieldObject } from "../core/services/normal";
import { BaseService, NormalService, PaginatedService } from "../services";
import * as Scalars from "../../scalars";
import type { ObjectTypeDefSqlOptions, SqlType } from "../../../types";

type GenerateFieldParams = {
name?: string;
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/core/services/enum.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BaseService, EnumPaginatorService } from ".";
import { ServiceFunctionInputs } from "../../../types";
import { generateEnumRootResolver } from "../../helpers/rootResolver";
import { generateEnumRootResolver } from "../helpers/rootResolver";
import { GiraffeqlRootResolverType } from "giraffeql";

export class EnumService extends BaseService {
Expand Down
12 changes: 6 additions & 6 deletions backend/functions/src/schema/core/services/normal.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import * as errorHelper from "../../helpers/error";
import * as errorHelper from "../helpers/error";
import { BaseService } from ".";
import {
fetchTableRows,
SqlOrderByObject,
SqlSelectQueryObject,
SqlWhereFieldOperator,
SqlWhereObject,
} from "../../helpers/sql";
import { permissionsCheck } from "../../helpers/permissions";
import { handleJqlSubscription } from "../../helpers/subscription";
} from "../helpers/sql";
import { permissionsCheck } from "../helpers/permissions";
import { handleJqlSubscription } from "../helpers/subscription";

import * as Resolver from "../../helpers/resolver";
import * as Resolver from "../helpers/resolver";

import {
GiraffeqlObjectType,
Expand All @@ -28,7 +28,7 @@ import {

import { ServiceFunctionInputs } from "../../../types";

import { btoa, isObject } from "../../helpers/shared";
import { btoa, isObject } from "../helpers/shared";

export type FieldObject = {
field?: string;
Expand Down
4 changes: 2 additions & 2 deletions backend/functions/src/schema/core/services/paginator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SimpleService, PaginatedService } from ".";

import * as Resolver from "../../helpers/resolver";
import { itemNotFoundError } from "../../helpers/error";
import * as Resolver from "../helpers/resolver";
import { itemNotFoundError } from "../helpers/error";
import { generatePaginatorTypeDef } from "../generators";
import { PaginatorData, ServiceFunctionInputs } from "../../../types";

Expand Down
4 changes: 2 additions & 2 deletions backend/functions/src/schema/core/services/paginatorInfo.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NormalService, SimpleService } from ".";
import * as Resolver from "../../helpers/resolver";
import { itemNotFoundError } from "../../helpers/error";
import * as Resolver from "../helpers/resolver";
import { itemNotFoundError } from "../helpers/error";
import { generatePaginatorInfoTypeDef } from "../generators";
import { ServiceFunctionInputs } from "../../../types";
import { lookupSymbol, GiraffeqlObjectType } from "giraffeql";
Expand Down
4 changes: 2 additions & 2 deletions backend/functions/src/schema/core/services/simple.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { BaseService } from ".";
import { GiraffeqlObjectType } from "giraffeql";
import * as Resolver from "../../helpers/resolver";
import * as errorHelper from "../../helpers/error";
import * as Resolver from "../helpers/resolver";
import * as errorHelper from "../helpers/error";
import { ServiceFunctionInputs } from "../../../types";

export class SimpleService extends BaseService {
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/enums/scoreMethod.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum } from "../helpers/enum";
import { Enum } from "../core/helpers/enum";

export class scoreMethodEnum extends Enum {
static readonly STANDARD = new scoreMethodEnum("STANDARD");
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/enums/userPermission.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum } from "../helpers/enum";
import { Enum } from "../core/helpers/enum";

export class userPermissionEnum extends Enum {
static readonly A_A = new userPermissionEnum("A_A");
Expand Down
2 changes: 1 addition & 1 deletion backend/functions/src/schema/enums/userRole.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Kenum } from "../helpers/enum";
import { Kenum } from "../core/helpers/enum";

export class userRoleKenum extends Kenum {
static readonly NORMAL = new userRoleKenum("NORMAL", 1);
Expand Down
Loading

0 comments on commit da8b76d

Please sign in to comment.