8000 feat: hydate req.account in jwt middleware by stevelikesmusic · Pull Request #15599 · lightdash/lightdash · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: hydate req.account in jwt middleware #15599

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/backend/src/auth/lightdashJwt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable */
import {
CreateEmbedJwt,
EmbedJwt,
EmbedJwtSchema,
ForbiddenError,
getErrorMessage,
Expand Down Expand Up @@ -45,15 +44,15 @@ export function encodeLightdashJwt(
export function decodeLightdashJwt(
token: string,
encodedSecret: string | Buffer,
): EmbedJwt {
): CreateEmbedJwt {
try {
const encryptionUtil = new EncryptionUtil({ lightdashConfig });
const secret = encryptionUtil.decrypt(
Buffer.isBuffer(encodedSecret)
? encodedSecret
: Buffer.from(encodedSecret),
);
const decodedToken = verify(token, secret) as EmbedJwt;
const decodedToken = verify(token, secret) as CreateEmbedJwt;

// Alert if the token is not in the expected format so we can inform the org before enforcing validation
try {
Expand Down
31 changes: 14 additions & 17 deletions packages/backend/src/ee/controllers/embedController.ts
< 8000 td class="blob-code blob-code-deletion js-file-line"> throw new ForbiddenError('Account is missing');
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ApiCalculateTotalResponse,
ApiErrorPayload,
ApiSuccessEmpty,
assertEmbeddedAuth,
CacheMetadata,
CreateEmbed,
CreateEmbedJwt,
Expand All @@ -16,8 +17,6 @@ import {
EmbedUrl,
Explore,
FieldValueSearchResult,
FilterInteractivityValues,
ForbiddenError,
Item,
MetricQueryResponse,
SavedChart,
Expand Down Expand Up @@ -176,9 +175,9 @@ export class EmbedController extends BaseController {
@Path() projectUuid: string,
): Promise<ApiEmbedDashboardResponse> {
this.setStatus(200);
if (!req.account) {
}

assertEmbeddedAuth(req.account);

return {
status: 'ok',
results: await this.getEmbedService().getDashboard(
Expand All @@ -197,9 +196,9 @@ export class EmbedController extends BaseController {
@Body() body: SavedChartsInfoForDashboardAvailableFilters,
): Promise<ApiEmbedDashboardAvailableFiltersResponse> {
this.setStatus(200);
if (!req.account) {
throw new ForbiddenError('Account is missing');
}

assertEmbeddedAuth(req.account);

return {
status: 'ok',
results:
Expand All @@ -226,9 +225,9 @@ export class EmbedController extends BaseController {
},
): Promise<ApiEmbedChartAndResultsResponse> {
this.setStatus(200);
if (!req.account) {
throw new ForbiddenError('Account is missing');
}

assertEmbeddedAuth(req.account);

return {
status: 'ok',
results: await this.getEmbedService().getChartAndResults(
Expand Down Expand Up @@ -256,9 +255,9 @@ export class EmbedController extends BaseController {
},
): Promise<ApiCalculateTotalResponse> {
this.setStatus(200);
if (!req.account) {
throw new ForbiddenError('Account is missing');
}

assertEmbeddedAuth(req.account);

return {
status: 'ok',
results: await this.getEmbedService().calculateTotalFromSavedChart(
Expand Down Expand Up @@ -292,9 +291,7 @@ export class EmbedController extends BaseController {
this.setStatus(200);
const { search, limit, filters, forceRefresh } = body;

if (!req.account) {
throw new ForbiddenError('Account is missing');
}
assertEmbeddedAuth(req.account);

const results = await this.getEmbedService().searchFilterValues({
account: req.account,
Expand Down
15 changes: 13 additions & 2 deletions packages/backend/src/ee/models/EmbedModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@ export class EmbedModel {
const [embed] = await this.database('embedding')
.select()
.leftJoin('users', 'embedding.created_by', 'users.user_uuid')
.where('project_uuid', projectUuid);
.leftJoin(
'projects',
'projects.project_uuid',
'embedding.project_uuid',
)
.leftJoin(
'organizations',
'organizations.organization_id',
'projects.organization_id',
)
.where('embedding.project_uuid', projectUuid);

if (!embed) {
throw new NotFoundError(
Expand All @@ -41,7 +51,8 @@ export class EmbedModel {
return {
projectUuid: embed.project_uuid,
organization: {
organizationUuid: embed.user_organization_uuid,
organizationUuid: embed.organization_uuid,
name: embed.organization_name,
},
encodedSecret: embed.encoded_secret,
dashboardUuids: validDashboardUuids,
Expand Down
36 changes: 17 additions & 19 deletions packages/backend/src/ee/services/EmbedService/EmbedService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { subject } from '@casl/ability';
import {
Account,
addDashboardFiltersToMetricQuery,
AndFilterGroup,
CommercialFeatureFlags,
Expand All @@ -14,17 +13,16 @@ import {
DateGranularity,
DecodedEmbed,
Embed,
EmbedJwt,
EmbedUrl,
Explore,
ExploreError,
ExternalAccount,
FieldValueSearchResult,
FilterableDimension,
ForbiddenError,
formatRows,
getDashboardFiltersForTileAndTables,
getDimensions,
getEmbeddedAuth,
getFilterInteractivityValue,
getItemId,
InteractivityOptions,
Expand Down Expand Up @@ -289,7 +287,7 @@ export class EmbedService extends BaseService {
if (!isEnabled.enabled) throw new ForbiddenError('Feature not enabled');
}

private async getDashboardUuidFromContent(
async getDashboardUuidFromJwt(
decodedToken: CreateEmbedJwt,
projectUuid: string,
) {
Expand All @@ -315,15 +313,15 @@ export class EmbedService extends BaseService {

async getDashboard(
projectUuid: string,
account: Account,
account: ExternalAccount,
// TODO: WHY IS THIS OPTIONAL??
checkPermissions: boolean = true,
): Promise<Dashboard & InteractivityOptions> {
const { data: decodedToken, source: embedToken } =
getEmbeddedAuth(account);
account.authentication;
const { dashboardUuids, allowAllDashboards, user } =
await this.embedModel.get(projectUuid);
const dashboardUuid = await this.getDashboardUuidFromContent(
const dashboardUuid = await this.getDashboardUuidFromJwt(
decodedToken,
projectUuid,
);
Expand Down Expand Up @@ -398,11 +396,11 @@ export class EmbedService extends BaseService {

async getAvailableFiltersForSavedQueries(
projectUuid: string,
account: Account,
account: ExternalAccount,
savedChartUuidsAndTileUuids: SavedChartsInfoForDashboardAvailableFilters,
checkPermissions: boolean = true,
): Promise<DashboardAvailableFilters> {
const { data: decodedToken } = getEmbeddedAuth(account);
const { data: decodedToken } = account.authentication;
const { dashboardUuids, allowAllDashboards } =
await this.embedModel.get(projectUuid);

Expand All @@ -423,7 +421,7 @@ export class EmbedService extends BaseService {
filters: CompiledDimension[];
}[] = [];

const dashboardUuid = await this.getDashboardUuidFromContent(
const dashboardUuid = await this.getDashboardUuidFromJwt(
decodedToken,
projectUuid,
);
Expand Down Expand Up @@ -739,19 +737,19 @@ export class EmbedService extends BaseService {

async getChartAndResults(
projectUuid: string,
account: Account,
account: ExternalAccount,
tileUuid: string,
dashboardFilters?: DashboardFilters,
dateZoomGranularity?: DateGranularity,
dashboardSorts?: SortField[],
checkPermissions: boolean = true,
) {
const { data: decodedToken, source: embedToken } =
getEmbeddedAuth(account);
account.authentication;
const { dashboardUuids, allowAllDashboards, user } =
await this.embedModel.get(projectUuid);

const dashboardUuid = await this.getDashboardUuidFromContent(
const dashboardUuid = await this.getDashboardUuidFromJwt(
decodedToken,
projectUuid,
);
Expand Down Expand Up @@ -857,15 +855,15 @@ export class EmbedService extends BaseService {
}

async calculateTotalFromSavedChart(
account: Account,
account: ExternalAccount,
projectUuid: string,
savedChartUuid: string,
dashboardFilters?: DashboardFilters,
invalidateCache?: boolean,
) {
const { data: decodedToken } = getEmbeddedAuth(account);
const { data: decodedToken } = account.authentication;

const dashboardUuid = await this.getDashboardUuidFromContent(
const dashboardUuid = await this.getDashboardUuidFromJwt(
decodedToken,
projectUuid,
);
Expand Down Expand Up @@ -968,7 +966,7 @@ export class EmbedService extends BaseService {
filters,
forceRefresh,
}: {
account: Account;
account: ExternalAccount;
projectUuid: string;
filterUuid: string;
search: string;
Expand All @@ -977,10 +975,10 @@ export class EmbedService extends BaseService {
forceRefresh: boolean;
}): Promise<FieldValueSearchResult> {
const { data: decodedToken, source: embedToken } =
getEmbeddedAuth(account);
account.authentication;
const { dashboardUuids, allowAllDashboards } =
await this.embedModel.get(projectUuid);
const dashboardUuid = await this.getDashboardUuidFromContent(
const dashboardUuid = await this.getDashboardUuidFromJwt(
decodedToken,
projectUuid,
);
Expand Down
8152
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call */
import { Ability, AbilityBuilder } from '@casl/ability';
import {
applyEmbeddedAbility,
CreateEmbedJwt,
ExternalAccount,
MemberAbility,
Organization,
} from '@lightdash/common';

function getExternalId(
decodedToken: CreateEmbedJwt,
embedToken: string,
organization: Pick<Organization, 'organizationUuid' | 'name'>,
): string {
return (
decodedToken.user?.externalId ||
`anonymous-jwt::${organization.organizationUuid}_${embedToken}`
);
}

/**
* Builds CASL abilities for the embedded user based on JWT content
*/
function buildEmbedAbilities(
embedJwt: CreateEmbedJwt,
dashboardUuid: string,
): MemberAbility {
const builder = new AbilityBuilder<MemberAbility>(Ability);
applyEmbeddedAbility(embedJwt, dashboardUuid, builder);

return builder.build();
}

export function hydrateEmbeddedAccount(
organization: Pick<Organization, 'organizationUuid' | 'name'>,
embedJwt: CreateEmbedJwt,
rawToken: string,
dashboardUuid: string,
): ExternalAccount {
const abilities: MemberAbility = buildEmbedAbilities(
embedJwt,
dashboardUuid,
);

return {
authentication: {
type: 'jwt',
data: embedJwt,
source: rawToken,
},
organization,
// Create the fields we're able to set from the JWT
user: {
id: getExternalId(embedJwt, rawToken, organization),
type: 'external',
ability: abilities,
abilityRules: abilities.rules,
email: embedJwt.user?.email,
isActive: true,
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { jwtAuthMiddleware } from './jwtAuthMiddleware';
Loading
Loading
0