Skip to content

Commit

Permalink
chore: SSO Apps portal widget RELEASE (#780)
Browse files Browse the repository at this point in the history
## Related Issues

Related to descope/etc#7215

---------

Co-authored-by: Nir Gur Arie <nir@descope.com>
Co-authored-by: nirgur <nirgur@users.noreply.github.com>
  • Loading branch information
3 people authored Sep 19, 2024
1 parent a45de60 commit 68ef671
Show file tree
Hide file tree
Showing 42 changed files with 2,610 additions and 511 deletions.
21 changes: 21 additions & 0 deletions packages/libs/sdk-component-drivers/src/AppsListDriver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { BaseDriver } from './BaseDriver';

type Data = { name: string; icon: string; url: string }[];

export class AppsListDriver extends BaseDriver {
nodeName = 'descope-apps-list';

set data(data: Data) {
if (this.ele) this.ele.data = data;
}

get data() {
return this.ele?.data;
}

get ele() {
return super.ele as Element & {
data: Data;
};
}
}
3 changes: 1 addition & 2 deletions packages/libs/sdk-component-drivers/src/BaseDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ export class BaseDriver {
const ele = typeof this.#ele === 'function' ? this.#ele() : this.#ele;
if (!ele) {
this.logger?.debug(
`no element for driver `,
this.constructor.name,
`Driver element is not available for ${this.nodeName}`,
new Error(),
);

Expand Down
1 change: 1 addition & 0 deletions packages/libs/sdk-component-drivers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export * from './AvatarDriver';
export * from './UserAttributeDriver';
export * from './UserAuthMethodDriver';
export * from './FlowDriver';
export * from './AppsListDriver';
87 changes: 87 additions & 0 deletions packages/widgets/applications-portal-widget/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
{
"root": true,
"env": {
"browser": true,
"es2021": true
},
"extends": [
"airbnb-base",
"airbnb-typescript",
"plugin:import/typescript",
"prettier",
"plugin:jest-dom/recommended"
],
"parser": "@typescript-eslint/parser",
"ignorePatterns": ["build/*", "dist/*", "bundle/*", "coverage/*"],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": [
"@typescript-eslint",
"prettier",
"import",
"prefer-arrow",
"jest-dom",
"jest",
"jest-formatting",
"no-only-tests"
],
"settings": {
"import/parsers": {
"@typescript-eslint/parser": [".ts", ".tsx"]
},
"import/resolver": {
"typescript": {
"alwaysTryTypes": true
}
}
},
"rules": {
// override airbnb-typescript rule
"react/jsx-filename-extension": 0,
"semi": [2, "always"],
"no-tabs": ["error", { "allowIndentationTabs": true }],
"@typescript-eslint/indent": ["off"],
"quotes": [
"error",
"single",
{ "avoidEscape": true, "allowTemplateLiterals": true }
],
"@typescript-eslint/quotes": [
"error",
"single",
{ "avoidEscape": true, "allowTemplateLiterals": true }
],
"@typescript-eslint/comma-dangle": ["off"],
"comma-dangle": ["off"],
"no-console": 2,
"no-only-tests/no-only-tests": 2,
"no-warning-comments": 2,
"import/no-unresolved": 2,
"import/named": 2,
"import/no-relative-packages": 2,
"import/no-cycle": 2,
"import/newline-after-import": 2,
"import/no-namespace": 2,
"import/no-duplicates": 2,
"import/first": 2,
"import/exports-last": 0,
"import/no-absolute-path": 2,
"import/no-dynamic-require": 2,
"import/no-self-import": 2,
"import/no-useless-path-segments": 2,
"import/prefer-default-export": 0,
"@typescript-eslint/dot-notation": 0,
"import/no-extraneous-dependencies": [
2,
{
"devDependencies": ["!./src/**/*"]
}
]
}
}
21 changes: 21 additions & 0 deletions packages/widgets/applications-portal-widget/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Descope <help@descope.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
100 changes: 100 additions & 0 deletions packages/widgets/applications-portal-widget/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# @descope/applications-portal-widget

## Setup

### Create an `.env` file

In the widget package create an `.env` file which includes;

```
DESCOPE_BASE_URL= # env base url
DESCOPE_PROJECT_ID= # project ID
DESCOPE_WIDGET_ID= # default: applications-portal-widget
DEBUG_MODE= # "true" / "false", default: "false"
DESCOPE_THEME= # "light" / "dark" / "os", default: "light"
```

### Example

```
// replace x.x.x with the latest release of the widget: https://www.npmjs.com/package/@descope/applications-portal-widget
<script src="https://static.descope.com/npm/@descope/applications-portal-widget@x.x.x/dist/index.js"></script>
<descope-applications-portal-widget
base-url="<DESCOPE_BASE_URL>"
project-id="<DESCOPE_PROJECT_ID>"
tenant="<DESCOPE_TENANT>"
debug="<DEBUG_MODE>"
theme="<DESCOPE_THEME>"
widget-id="<DESCOPE_WIDGET_ID>"
></descope-applications-portal-widget>
<script>
function onLogout(error) {
window.location.reload();
}
const descopeWidgetEle = document.getElementsByTagName('descope-applications-portal-widget')[0];
descopeWidgetEle.logout = onLogout;
</script>
```

### Authenticate

In order to work with the widget, you must be logged in
In case you are not authenticated, a login flow will run first, and after logging in, the widget will be rendered

### Start the widget

run `npm start` to start the widget.

## Architecture

## Project Structure

- `/app` - contains `index.html`
- `/lib` - widget's source code
- `lib/widget` - widget related implementations
- `lib/widget/api` - Logic related to API calls
- `lib/widget/mixins` - Widget specific logic
- `lib/widget/state` - State management logic

### API

---

### Mixins

The widget is composed of mixins, each mixin contains specific logic parts, and sometime exposes an API that can be used in other mixins.

Mixins can be composed on top of each other, so we can create new mixins by composing several mixins together.

#### Mixins Creators

Functions that create mixins, can get a configuration, and returns the mixin functions.

#### Singleton Mixin

Since mixins are composable, in some cases we want to make sure a mixin is loaded only once. For example: When there is no need for its logic to run multiple times when composed in different mixins.

For this case we have a wrapper function (`createSingletonMixin`) to ensure that a mixin is loaded only once, regardless how many times it will be composed.

Mixins should be wrapped with the `createSingletonMixin` wrapper function, unless there is a reason for running the mixin's logic multiple times.

### State

We're using several tools to handle the widget's state:

- [Redux Toolkit](https://redux-toolkit.js.org/) for the widget's state management.
- [Redux Thunk](https://github.com/reduxjs/redux-thunk) for API calls and async operations we're using
- [Reselect](https://github.com/reduxjs/reselect) to compute derived data without hitting performance or triggering state recalculation when state is not mutated.

### Drivers

An abstraction layer that provides an API for components, and enables handling interactions with components within the widget.

The motivation to use drivers is to decouple the widget's code from the component's implementation, and therefore it's important to interact with components only using drivers (and not relying on component's implementation details).

## Dev

### Use mock screens

Since screen are fetched dynamically, when developing a new screen for the widget you will probably want to use mock templates. To do so, simply replace the call to `fetchWidgetPage` with a string which includes your HTML.
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { test, expect } from '@playwright/test';
import mockTheme from '../test/mocks/mockTheme';
import { apiPaths } from '../src/lib/widget/api/apiPaths';
import rootMock from '../test/mocks/rootMock';
import { mockSsoApps } from '../test/mocks/mockSsoApps';
import { SSOAppType } from '../src/lib/widget/api/types';

const configContent = {
flows: {
flow1: { version: 1 },
},
componentsVersion: '1.2.3',
};

const apiPath = (prop: 'ssoApps', path: string) =>
`**/*${apiPaths[prop][path]}`;

const samlApps = mockSsoApps.filter((app) => app.appType === SSOAppType.saml);

test.describe('widget', () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() =>
window.localStorage.setItem(
'base.ui.components.url',
'http://localhost:8769/umd/index.js',
),
);

await page.route('*/**/config.json', async (route) =>
route.fulfill({ json: configContent }),
);

await page.route('*/**/theme.json', async (route) =>
route.fulfill({ json: mockTheme }),
);

await page.route('*/**/root.html', async (route) =>
route.fulfill({ body: rootMock }),
);

await page.route(apiPath('ssoApps', 'load'), async (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ apps: mockSsoApps }),
}),
);

await page.route('**/auth/me', async (route) =>
route.fulfill({
json: {
userTenants: [
{
tenantId: 'tid',
roleNames: ['Tenant Admin'],
},
],
},
}),
);

await page.goto('http://localhost:5560');
});

test('saml apps are in the list', async ({ page }) => {
for (const app of samlApps) {
await expect(page.locator(`text=${app.name}`).first()).toBeVisible();
}
});
test('click app opens a new tab', async ({ page }) => {
const newTabPromise = page.waitForEvent('popup');

const app = page.locator(`text=${samlApps[0].name}`).first();
await app.click();

const newTab = await newTabPromise;
await newTab.waitForLoadState();

await expect(newTab).toHaveURL(samlApps[0].samlSettings.idpInitiatedUrl);
});
});
42 changes: 42 additions & 0 deletions packages/widgets/applications-portal-widget/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.json');

module.exports = {
clearMocks: true,

collectCoverage: true,
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/lib/**/*.ts'],
coverageThreshold: {
global: {
branches: 0,
functions: 14,
lines: 38,
statements: 38,
},
},
globals: {
BUILD_VERSION: '1.2.3',
},
transform: {
'^.+\\.ts?$': [
'ts-jest',
{
tsconfig: 'tsconfig.json',
},
],
},

preset: 'ts-jest',
testEnvironment: 'jsdom',
moduleDirectories: ['node_modules', 'src'],

testTimeout: 5000,

roots: ['src', 'test'],

moduleNameMapper: {
'\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/config/fileMock.js',
},
};
Loading

0 comments on commit 68ef671

Please sign in to comment.