Skip to content

Commit

Permalink
add type guard
Browse files Browse the repository at this point in the history
  • Loading branch information
villebro committed Apr 13, 2022
1 parent a21ddaf commit 0a24c83
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
8 changes: 6 additions & 2 deletions superset-frontend/src/dashboard/util/findPermission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
import memoizeOne from 'memoize-one';
import {
isUserWithPermissionsAndRoles,
UndefinedUser,
UserWithPermissionsAndRoles,
} from 'src/types/bootstrapTypes';
Expand All @@ -42,19 +43,22 @@ const ADMIN_ROLE_NAME = 'admin';
export const isUserAdmin = (
user: UserWithPermissionsAndRoles | UndefinedUser,
) =>
isUserWithPermissionsAndRoles(user) &&
Object.keys(user.roles || {}).some(
role => role.toLowerCase() === ADMIN_ROLE_NAME,
);

const isUserDashboardOwner = (
dashboard: Dashboard,
user: UserWithPermissionsAndRoles | UndefinedUser,
) => dashboard.owners.some(owner => owner.username === user.username);
) =>
isUserWithPermissionsAndRoles(user) &&
dashboard.owners.some(owner => owner.username === user.username);

export const canUserEditDashboard = (
dashboard: Dashboard,
user?: UserWithPermissionsAndRoles | UndefinedUser | null,
) =>
!!user?.roles &&
isUserWithPermissionsAndRoles(user) &&
(isUserAdmin(user) || isUserDashboardOwner(dashboard, user)) &&
findPermission('can_write', 'Dashboard', user.roles);
11 changes: 11 additions & 0 deletions superset-frontend/src/types/bootstrapTypes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { JsonObject, Locale } from '@superset-ui/core';
import { isPlainObject } from 'lodash';

/**
* Licensed to the Apache Software Foundation (ASF) under one
Expand Down Expand Up @@ -64,3 +65,13 @@ export interface CommonBootstrapData {
locale: Locale;
feature_flags: Record<string, boolean>;
}

export function isUser(user: any): user is User {
return isPlainObject(user) && 'username' in user;
}

export function isUserWithPermissionsAndRoles(
user: any,
): user is UserWithPermissionsAndRoles {
return isUser(user) && 'permissions' in user && 'roles' in user;
}

0 comments on commit 0a24c83

Please sign in to comment.