Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI updates: Add BASIC auth login mechanism and various code cleanup

Rich Turner0ba373a9f281
diff --git a/ui/app/or-app/src/index.ts b/ui/app/or-app/src/index.ts
index fae4b6e55..5aedaf6d2 100644
--- a/ui/app/or-app/src/index.ts
+++ b/ui/app/or-app/src/index.ts
@@ -9,20 +9,22 @@ import {
TemplateResult,
unsafeCSS
} from "lit-element";
-import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';
-
+import {unsafeHTML} from "lit-html/directives/unsafe-html";
+import "@openremote/or-translate";
+import "@openremote/or-mwc-components/dist/or-mwc-menu";
+import "./or-header";
+import "@openremote/or-icon";
import {updateMetadata} from "pwa-helpers/metadata";
import i18next from "i18next";
import Navigo from "navigo";
-import manager, {Auth, DefaultColor2, DefaultColor3, DefaultHeaderHeight, ManagerConfig, Util} from "@openremote/core";
-import "@openremote/or-mwc-components/dist/or-mwc-menu";
-import "./or-header";
+import manager, {Auth, DefaultColor2, DefaultColor3, DefaultHeaderHeight, ManagerConfig, Util, BasicLoginResult} from "@openremote/core";
import {DEFAULT_LANGUAGES, HeaderConfig, HeaderItem, Languages} from "./or-header";
import {DialogConfig, OrMwcDialog} from "@openremote/or-mwc-components/dist/or-mwc-dialog";
import {AnyAction, EnhancedStore, Unsubscribe, Action} from "@reduxjs/toolkit";
import {AppStateKeyed, updatePage, updateParams} from "./app";
import {ThunkMiddleware} from "redux-thunk";
import { translate } from "@openremote/or-translate";
+import { InputType, OrInputChangedEvent } from "@openremote/or-input";
export * from "./app";
export * from "./or-header";
@@ -55,11 +57,11 @@ export interface AppConfig<S extends AppStateKeyed> {
pages?: {
default: PageProvider<S>;
[name: string]: PageProvider<S>;
- }
+ };
default?: DefaultAppConfig;
realms?: {
[realm: string]: RealmAppConfig;
- }
+ };
}
export interface PageProvider<S extends AppStateKeyed> {
@@ -213,7 +215,7 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
protected _store: EnhancedStore<S, AnyAction, ReadonlyArray<ThunkMiddleware<S>>>;
protected _storeUnsubscribe!: Unsubscribe;
- //language=CSS
+ // language=CSS
static get styles() {
return css`
:host {
@@ -326,6 +328,7 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
}
const managerConfig = this.managerConfig || DEFAULT_MANAGER_CONFIG;
+ managerConfig.basicLoginProvider = (u, p) => this.doBasicLogin(u, p);
console.info("Initialising the manager");
@@ -339,6 +342,54 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
});
}
+ protected doBasicLogin(username: string | undefined, password: string | undefined): PromiseLike<BasicLoginResult> {
+ const deferred = new Util.Deferred<BasicLoginResult>();
+
+ let u = username;
+ let p = password;
+
+ // language=CSS
+ const styles = html`
+ #login-logo {
+ width: 24px;
+ height: 24px;
+ }
+
+ #login_wrapper > or-input {
+ margin: 10px 0;
+ width: 100%;
+ }
+ `;
+
+ this.showModal({
+ styles: html`<style>${styles}</style>`,
+ title: html`<img id="login-logo" src="${this._config.logoMobile || this._config.logo}" /></or-icon><or-translate value="login"></or-translate>`,
+ content: html`
+ <div id="login_wrapper">
+ <or-input .label="${i18next.t("user")}" .type="${InputType.TEXT}" min="1" required .value="${username}" @or-input-changed="${(e: OrInputChangedEvent) => u = e.detail.value}"></or-input>
+ <or-input .label="${i18next.t("password")}" .type="${InputType.PASSWORD}" min="1" required .value="${password}" @or-input-changed="${(e: OrInputChangedEvent) => p = e.detail.value}"></or-input>
+ </div>
+ `,
+ actions: [
+ {
+ actionName: "submit",
+ default: true,
+ action: () => {
+ deferred.resolve({
+ cancel: false,
+ username: u,
+ password: p,
+ closeCallback: () => { this.closeModal(); }
+ });
+ },
+ content: html`<or-input .type=${InputType.BUTTON} .label="${i18next.t("submit")}" raised></or-input>`
+ }
+ ]
+ });
+
+ return deferred.promise;
+ }
+
protected updated(changedProps: PropertyValues) {
super.updated(changedProps);
@@ -416,7 +467,7 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
content: i18next.t("ok"),
default: true
}]
- })
+ });
}
public showModal(config: DialogConfig) {
@@ -426,6 +477,12 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
}
}
+ public closeModal() {
+ if (this._appModal) {
+ this._appModal.close();
+ }
+ }
+
public stateChanged(state: S) {
this._page = state.app!.page;
}
diff --git a/ui/app/or-app/src/or-header.ts b/ui/app/or-app/src/or-header.ts
index 4954b161c..f62975f29 100644
--- a/ui/app/or-app/src/or-header.ts
+++ b/ui/app/or-app/src/or-header.ts
@@ -1,13 +1,18 @@
-import {customElement, html, LitElement, property, query, TemplateResult, css, unsafeCSS} from "lit-element";
+import {css, customElement, html, LitElement, property, query, TemplateResult, unsafeCSS} from "lit-element";
import {until} from "lit-html/directives/until";
-import { ifDefined } from 'lit-html/directives/if-defined.js';
-import i18next from "i18next";
-import {DefaultColor1, DefaultColor2, DefaultColor3, DefaultColor4, DefaultBoxShadowBottom, DefaultHeaderHeight} from "@openremote/core";
-import manager from "@openremote/core";
+import {ifDefined} from "lit-html/directives/if-defined.js";
+import manager, {
+ DefaultBoxShadowBottom,
+ DefaultColor1,
+ DefaultColor2,
+ DefaultColor3,
+ DefaultColor4,
+ DefaultHeaderHeight
+} from "@openremote/core";
import "@openremote/or-mwc-components/dist/or-mwc-dialog";
import "@openremote/or-icon";
-import {MenuItem, getContentWithMenuTemplate} from "@openremote/or-mwc-components/dist/or-mwc-menu";
-import { Tenant } from "@openremote/model";
+import {getContentWithMenuTemplate, MenuItem} from "@openremote/or-mwc-components/dist/or-mwc-menu";
+import {Tenant} from "@openremote/model";
export interface HeaderConfig {
mainMenu: HeaderItem[];
@@ -29,15 +34,15 @@ export interface Languages {
}
export const DEFAULT_LANGUAGES: Languages = {
- "en": "english",
- "nl": "dutch",
- "fr": "french",
- "de": "german",
- "es": "spanish"
+ en: "english",
+ nl: "dutch",
+ fr: "french",
+ de: "german",
+ es: "spanish"
};
function getHeaderMenuItems(items: HeaderItem[]): MenuItem[] {
- return items.filter(option => !option.roles || option.roles.some(r => manager.hasRole(r))).map(option => {
+ return items.filter((option) => !option.roles || option.roles.some((r) => manager.hasRole(r))).map((option) => {
return {
text: option.text,
value: option.value ? option.value : "",
@@ -50,29 +55,6 @@ function getHeaderMenuItems(items: HeaderItem[]): MenuItem[] {
@customElement("or-header")
class OrHeader extends LitElement {
- @property({type: Boolean})
- private _drawerOpened = false;
-
- @property({type: String})
- public logo?: string;
-
- @property({ type: String })
- public logoMobile? : string;
-
- @property({ type: Object })
- public config?: HeaderConfig;
-
- @property({ type: String })
- private activeMenu: string | undefined = window.location.hash ? window.location.hash : "#!map";
-
- @query("div[id=mobile-bottom]")
- protected _mobileBottomDiv!: HTMLDivElement;
-
- protected _tenants?: Tenant[];
- protected _hashCallback = (e: Event) => {
- this._onHashChanged(e);
- };
-
// language=CSS
static get styles() {
return css`
@@ -294,21 +276,49 @@ class OrHeader extends LitElement {
`;
}
- connectedCallback(): void {
+ @property({type: String})
+ public logo?: string;
+
+ @property({ type: String })
+ public logoMobile?: string;
+
+ @property({ type: Object })
+ public config?: HeaderConfig;
+
+ @query("div[id=mobile-bottom]")
+ protected _mobileBottomDiv!: HTMLDivElement;
+
+ protected _tenants?: Tenant[];
+
+ @property({type: Boolean})
+ private _drawerOpened = false;
+
+ @property({ type: String })
+ private activeMenu: string | undefined = window.location.hash ? window.location.hash : "#!map";
+
+ public connectedCallback(): void {
super.connectedCallback();
window.addEventListener("hashchange", this._hashCallback, false);
}
- disconnectedCallback(): void {
+ public disconnectedCallback(): void {
super.disconnectedCallback();
window.removeEventListener("hashchange", this._hashCallback);
}
- _onHashChanged(e: Event) {
- const menu = window.location.hash.split('/')[0];
+ public _onHashChanged(e: Event) {
+ const menu = window.location.hash.split("/")[0];
this.activeMenu = menu;
}
+ public _onRealmSelect(realm: string) {
+ manager.displayRealm = realm;
+ this.requestUpdate();
+ }
+ protected _hashCallback = (e: Event) => {
+ this._onHashChanged(e);
+ }
+
protected render() {
const mainItems = this.config ? this.config.mainMenu : undefined;
@@ -323,10 +333,10 @@ class OrHeader extends LitElement {
<!-- This gets hidden on a small screen-->
<nav id="toolbar-list">
<div id="desktop-left">
- ${mainItems ? mainItems.filter(option => !option.roles || option.roles.some(r => manager.hasRole(r))).map(headerItem => {
+ ${mainItems ? mainItems.filter((option) => !option.roles || option.roles.some((r) => manager.hasRole(r))).map((headerItem) => {
return html`
<a class="menu-item" href="${headerItem.href}" @click="${(e: MouseEvent) => this._onHeaderItemSelect(headerItem)}" ?selected="${this.activeMenu === headerItem.href}"><or-icon icon="${headerItem.icon}"></or-icon><or-translate value="${headerItem.text}"></or-translate></a>
- `
+ `;
}) : ``}
</div>
</nav>
@@ -348,20 +358,20 @@ class OrHeader extends LitElement {
<div>
<div id="mobile-top">
<nav id="drawer-list">
- ${mainItems ? mainItems.filter(option => !option.hideMobile && (!option.roles || option.roles.some(r => manager.hasRole(r)))).map(headerItem => {
+ ${mainItems ? mainItems.filter((option) => !option.hideMobile && (!option.roles || option.roles.some((r) => manager.hasRole(r)))).map((headerItem) => {
return html`
<a class="menu-item" href="${headerItem.href}" @click="${(e: MouseEvent) => this._onHeaderItemSelect(headerItem)}" ?selected="${this.activeMenu === headerItem.href}"><or-icon icon="${headerItem.icon}"></or-icon><or-translate value="${headerItem.text}"></or-translate></a>
- `
+ `;
}) : ``}
</nav>
</div>
${secondaryItems ? html`
<div id="mobile-bottom">
- ${secondaryItems.filter(option => !option.hideMobile && (!option.roles || option.roles.some(r => manager.hasRole(r)))).map(headerItem => {
+ ${secondaryItems.filter((option) => !option.hideMobile && (!option.roles || option.roles.some((r) => manager.hasRole(r)))).map((headerItem) => {
return html`
<a class="menu-item" href="${ifDefined(headerItem.href)}" @click="${(e: MouseEvent) => this._onHeaderItemSelect(headerItem)}" ?selected="${this.activeMenu === headerItem.href}"><or-icon icon="${headerItem.icon}"></or-icon><or-translate value="${headerItem.text}"></or-translate></a>
- `
+ `;
})}
</div>` : ``}
</div>
@@ -424,11 +434,6 @@ class OrHeader extends LitElement {
}
}
- _onRealmSelect(realm: string) {
- manager.displayRealm = realm;
- this.requestUpdate();
- }
-
protected _closeDrawer() {
this._drawerOpened = false;
}
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 3dee77212..ed477c01e 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -15,6 +15,7 @@ import {
} from "@openremote/model";
import * as Util from "./util";
import orIconSet from "./or-icon-set";
+import { Deferred } from "./util";
// Re-exports
export {Util};
@@ -48,7 +49,7 @@ export declare type Keycloak = {
export enum ORError {
MANAGER_FAILED_TO_LOAD = "MANAGER_FAILED_TO_LOAD",
- KEYCLOAK_FAILED_TO_LOAD = "KEYCLOAK_FAILED_TO_LOAD",
+ AUTH_FAILED = "AUTH_FAILED",
AUTH_TYPE_UNSUPPORTED = "AUTH_TYPE_UNSUPPORTED",
CONSOLE_ERROR = "CONSOLE_INIT_ERROR",
EVENTS_CONNECTION_ERROR = "EVENTS_CONNECTION_ERROR",
@@ -89,6 +90,13 @@ export interface LoginOptions {
credentials?: Credentials;
}
+export interface BasicLoginResult {
+ username: string;
+ password: string;
+ cancel: boolean;
+ closeCallback: undefined | ((authenticated: boolean) => void);
+}
+
export interface ManagerConfig {
managerUrl: string;
keycloakUrl?: string;
@@ -106,6 +114,7 @@ export interface ManagerConfig {
loadTranslations?: string[];
translationsLoadPath?: string;
configureTranslationsOptions?: (i18next: i18next.InitOptions) => void;
+ basicLoginProvider?: (username: string | undefined, password: string | undefined) => PromiseLike<BasicLoginResult>;
}
export class IconSetAddedEvent extends CustomEvent<void> {
@@ -491,9 +500,11 @@ export class Manager implements EventProviderFactory {
private _config!: ManagerConfig;
private _authenticated: boolean = false;
private _ready: boolean = false;
+ private _readyCallback?: () => PromiseLike<any>;
private _name: string = "";
private _username: string = "";
private _keycloak?: Keycloak;
+ private _basicToken?: string;
private _keycloakUpdateTokenInterval?: number = undefined;
private _managerVersion: string = "";
private _listeners: EventCallback[] = [];
@@ -544,13 +555,9 @@ export class Manager implements EventProviderFactory {
success = this.doRestApiInit();
}
- if (success) {
- success = await this.doConsoleInit();
- }
+ success = await this.doConsoleInit() && success;
- if (success) {
- success = await this.doTranslateInit();
- }
+ success = await this.doTranslateInit() && success;
if (success) {
success = await this.doDescriptorsInit();
@@ -561,6 +568,9 @@ export class Manager implements EventProviderFactory {
// success = await this.doEventsSubscriptionInit();
// }
if (success) {
+ if (this._readyCallback) {
+ await this._readyCallback();
+ }
this._ready = true;
this._emitEvent(OREvent.READY);
}
@@ -615,7 +625,7 @@ export class Manager implements EventProviderFactory {
});
// Look for language preference in local storage
- const language = await this.console.retrieveData("LANGUAGE");
+ const language = !this.console ? undefined : await this.console.retrieveData("LANGUAGE");
const initOptions: i18next.InitOptions = {
lng: language,
fallbackLng: "en",
@@ -687,39 +697,40 @@ export class Manager implements EventProviderFactory {
let success = true;
switch (this._config.auth) {
case Auth.BASIC:
- // TODO: Implement Basic auth support
- if (this._config.credentials) {
- rest.setBasicAuth(this._config.credentials.username, this._config.credentials.password);
- }
- this._setError(ORError.AUTH_TYPE_UNSUPPORTED);
- success = false;
+ success = await this.initialiseBasicAuth();
break;
case Auth.KEYCLOAK:
success = await this.loadAndInitialiseKeycloak();
- // Add interceptor to inject authorization header on each request
- rest.addRequestInterceptor(
- (config: AxiosRequestConfig) => {
- if (!config.headers.Authorization) {
- const token = this.getKeycloakToken();
-
- if (token) {
- config.headers.Authorization = "Bearer " + token;
- }
- }
-
- return config;
- }
- );
+
+ if (!success) {
+ // Try fallback to BASIC
+ console.log("Falling back to basic auth");
+ this._config.auth = Auth.BASIC;
+ return this.doAuthInit();
+ }
break;
case Auth.NONE:
// Nothing for us to do here
- break;
+ return true;
default:
this._setError(ORError.AUTH_TYPE_UNSUPPORTED);
- success = false;
- break;
+ return false;
}
+ // Add interceptor to inject authorization header on each request
+ rest.addRequestInterceptor(
+ (config: AxiosRequestConfig) => {
+ if (!config.headers.Authorization) {
+ const authHeader = this.getAuthorizationHeader();
+
+ if (authHeader) {
+ config.headers.Authorization = authHeader;
+ }
+ }
+
+ return config;
+ }
+ );
return success;
}
@@ -787,25 +798,23 @@ export class Manager implements EventProviderFactory {
}
const options = redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : null;
this._keycloak.logout(options);
+ } else if (this._basicToken) {
+ this._basicToken = undefined;
+ if (redirectUrl) {
+ window.location.href = redirectUrl;
+ } else {
+ window.location.reload();
+ }
}
}
public login(options?: LoginOptions) {
- if (!this.ready) {
- return;
- }
switch (this._config.auth) {
case Auth.BASIC:
if (options && options.credentials) {
this._config.credentials = Object.assign({}, options.credentials);
}
- const username = this._config.credentials ? this._config.credentials.username : null;
- const password = this._config.credentials ? this._config.credentials.password : null;
-
- if (username && password && username !== "" && password !== "") {
- // TODO: Perform some request to check basic auth credentials
- this._setAuthenticated(true);
- }
+ this.doBasicLogin();
break;
case Auth.KEYCLOAK:
if (this._keycloak) {
@@ -824,6 +833,83 @@ export class Manager implements EventProviderFactory {
}
}
+ protected async initialiseBasicAuth(): Promise<boolean> {
+
+ if (!this.config.basicLoginProvider) {
+ console.log("No basicLoginProvider defined on config so cannot display login UI");
+ return false;
+ }
+
+ if (this.config.autoLogin) {
+ // Delay basic login until other inits are done
+ this._readyCallback = () => {
+ return this.doBasicLogin();
+ };
+ }
+
+ return true;
+ }
+
+ protected async doBasicLogin() {
+
+ if (!this.config.basicLoginProvider) {
+ return;
+ }
+
+ let result: BasicLoginResult = {
+ username: this._config.credentials ? this._config.credentials.username : "",
+ password: this._config.credentials ? this._config.credentials.password : "",
+ cancel: false,
+ closeCallback: undefined
+ };
+ let authenticated = false;
+
+ const url = this.config.managerUrl + "/api/" + this.config.realm + "/asset/user/current";
+
+ while (!authenticated) {
+ result = await this.config.basicLoginProvider(result.username, result.password);
+
+ if (result.cancel) {
+ console.log("Basic authentication cancelled by user");
+ if (result.closeCallback) {
+ result.closeCallback(false);
+ }
+ break;
+ }
+
+ if (!result.username || !result.password) {
+ continue;
+ }
+
+ const response = await fetch(url, {
+ method: "GET",
+ credentials: "include",
+ headers: {
+ Authorization: "Basic " + btoa(result.username + ":" + result.password)
+ }
+ });
+
+ const status = response.status;
+ if (status === 200) {
+ console.log("Basic authentication successful");
+ authenticated = true;
+ this._basicToken = btoa(result.username + ":" + result.password);
+ // Undertow incorrectly returns 403 when no authorization header and a 401 when it is set and not valid
+ } else if (status === 401 || status === 403) {
+ console.log("Basic authentication invalid credentials, trying again");
+ } else {
+ console.log("Unkown response so aborting");
+ break;
+ }
+ }
+
+ this._setAuthenticated(authenticated);
+
+ if (result.closeCallback) {
+ result.closeCallback(authenticated);
+ }
+ }
+
public isSuperUser() {
return this.getRealm() && this.getRealm() === "master" && this.hasRealmRole("admin");
}
@@ -852,6 +938,10 @@ export class Manager implements EventProviderFactory {
return "Bearer " + this._keycloak.token;
}
+ if (this._basicToken && this.authenticated) {
+ return "Basic " + this._basicToken;
+ }
+
return undefined;
}
@@ -862,6 +952,10 @@ export class Manager implements EventProviderFactory {
return undefined;
}
+ public getBasicToken(): string | undefined {
+ return this._basicToken;
+ }
+
public getRealm(): string | undefined {
if (this._config) {
return this._config.realm;
@@ -891,12 +985,17 @@ export class Manager implements EventProviderFactory {
protected async loadAndInitialiseKeycloak(): Promise<boolean> {
try {
+
+ // There's a bug in some Keycloak versions which means the init promise doesn't resolve
+ // so putting a check in place; wrap keycloak promise in proper ES6 promise
+ let keycloakPromise: any = null;
+
// Load the keycloak JS API
await Util.loadJs(this._config.keycloakUrl + "/js/keycloak.js");
// Should have Keycloak global var now
if (!(window as any).Keycloak) {
- this._setError(ORError.KEYCLOAK_FAILED_TO_LOAD);
+ console.log("Keycloak global variable not found probably failed to load keycloak or manager doesn't support it");
return false;
}
@@ -917,9 +1016,6 @@ export class Manager implements EventProviderFactory {
this._setAuthenticated(false);
};
- // There's a bug in some Keycloak versions which means the init promise doesn't resolve
- // so putting a check in place; wrap keycloak promise in proper ES6 promise
- let keycloakPromise: any = null;
try {
// Try to use a stored offline refresh token if defined
const offlineToken = await this._getNativeOfflineRefreshToken();
@@ -964,7 +1060,7 @@ export class Manager implements EventProviderFactory {
return false;
}
} catch (error) {
- this._setError(ORError.KEYCLOAK_FAILED_TO_LOAD);
+ this._setError(ORError.AUTH_FAILED);
console.error("Failed to load Keycloak");
return false;
}
diff --git a/ui/component/or-attribute-history/src/index.ts b/ui/component/or-attribute-history/src/index.ts
index 7d10077dd..d2e8953e3 100644
--- a/ui/component/or-attribute-history/src/index.ts
+++ b/ui/component/or-attribute-history/src/index.ts
@@ -311,9 +311,9 @@ export class OrAttributeHistory extends translate(i18next)(LitElement) {
return html`
<div id="container">
<div id="controls">
- <or-input .checkAssetWrite="${false}" .type="${InputType.SELECT}" ?disabled="${disabled}" .label="${i18next.t("timeframe")}" @or-input-changed="${(evt: OrInputChangedEvent) => this.period = evt.detail.value}" .value="${this.period}" .options="${this._getPeriodOptions().map(item => item.value)}"></or-input>
+ <or-input .type="${InputType.SELECT}" ?disabled="${disabled}" .label="${i18next.t("timeframe")}" @or-input-changed="${(evt: OrInputChangedEvent) => this.period = evt.detail.value}" .value="${this.period}" .options="${this._getPeriodOptions().map(item => item.value)}"></or-input>
<div id="ending-controls">
- <or-input id="ending-date" .checkAssetWrite="${false}" .type="${InputType.DATETIME}" ?disabled="${disabled}" label="${i18next.t("ending")}" .value="${this.fromTimestamp}" @or-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate())}"></or-input>
+ <or-input id="ending-date" .type="${InputType.DATETIME}" ?disabled="${disabled}" label="${i18next.t("ending")}" .value="${this.fromTimestamp}" @or-input-changed="${(evt: OrInputChangedEvent) => this._updateTimestamp(moment(evt.detail.value as string).toDate())}"></or-input>
<or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-left" @click="${() => this.fromTimestamp = this._updateTimestamp(this.fromTimestamp!, false)}"></or-icon>
<or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-right" @click="${() => this.fromTimestamp = this._updateTimestamp(this.fromTimestamp!, true)}"></or-icon>
<or-icon class="button button-icon" ?disabled="${disabled}" icon="chevron-double-right" @click="${() => this.fromTimestamp = this._updateTimestamp(new Date())}"></or-icon>
diff --git a/ui/component/or-input/src/index.ts b/ui/component/or-input/src/index.ts
index 46e77db14..b2a0dda11 100644
--- a/ui/component/or-input/src/index.ts
+++ b/ui/component/or-input/src/index.ts
@@ -7,15 +7,12 @@ import {MDCRipple} from "@material/ripple";
import {MDCCheckbox} from "@material/checkbox";
import {MDCSwitch} from "@material/switch";
import {MDCSelect, MDCSelectEvent } from "@material/select";
-import {MDCList, MDCListActionEvent} from '@material/list';
+import {MDCList, MDCListActionEvent} from "@material/list";
import {MDCFormField, MDCFormFieldInput} from "@material/form-field";
import {MDCIconButtonToggle, MDCIconButtonToggleEventDetail} from "@material/icon-button";
import moment from "moment";
-import manager, {DefaultColor1, DefaultColor4, DefaultColor8} from "@openremote/core";
-
-import i18next from "i18next";
-import { ClientRole } from "@openremote/model/src";
+import {DefaultColor4, DefaultColor8} from "@openremote/core";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const buttonStyle = require("!!raw-loader!@material/button/dist/mdc.button.css");
@@ -279,10 +276,6 @@ export class OrInput extends LitElement {
@property({type: Boolean})
public autoSelect?: boolean;
-
- @property({type: Boolean})
- public checkAssetWrite: boolean = true;
-
/* STYLING PROPERTIES BELOW */
@property({type: String})
@@ -355,8 +348,7 @@ export class OrInput extends LitElement {
}
protected render() {
- const readonly = this.checkAssetWrite ? !manager.hasRole(ClientRole.WRITE_ASSETS) || this.readonly : false;
-
+
if (this.type) {
const showLabel = !this.fullWidth && this.label;
@@ -372,14 +364,14 @@ export class OrInput extends LitElement {
case InputType.SWITCH:
return html`
<span id="wrapper">
- <div id="component" class="mdc-switch ${this.disabled || readonly ? "mdc-switch--disabled" : ""} ${this.value ? "mdc-switch--checked" : ""}">
+ <div id="component" class="mdc-switch ${this.disabled || this.readonly ? "mdc-switch--disabled" : ""} ${this.value ? "mdc-switch--checked" : ""}">
<div class="mdc-switch__track"></div>
<div class="mdc-switch__thumb-underlay">
<div class="mdc-switch__thumb">
<input type="checkbox" id="elem" class="mdc-switch__native-control"
?checked="${this.value}"
?required="${this.required}"
- ?disabled="${this.disabled || readonly}"
+ ?disabled="${this.disabled || this.readonly}"
@change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).checked)}"
role="switch">
</div>
@@ -428,7 +420,7 @@ export class OrInput extends LitElement {
case InputType.SELECT:
const classes = {
"mdc-select--outlined": outlined,
- "mdc-select--disabled": this.disabled || readonly,
+ "mdc-select--disabled": this.disabled || this.readonly,
"mdc-select--required": this.required,
"mdc-select--dense": false, // this.dense,
"mdc-select--no-label": !this.label,
@@ -481,7 +473,7 @@ export class OrInput extends LitElement {
case InputType.BUTTON_TOGGLE:
return html`
<button id="component" class="mdc-icon-button ${this.value ? "mdc-icon-button--on" : ""}"
- ?readonly="${readonly}"
+ ?readonly="${this.readonly}"
?disabled="${this.disabled}"
@MDCIconButtonToggle:change="${(evt: MDCIconButtonToggleEventDetail) => this.onValueChange(undefined, evt.isOn)}">
${this.icon ? html`<or-icon class="mdc-icon-button__icon" aria-hidden="true" icon="${this.icon}"></or-icon>` : ``}
@@ -506,7 +498,7 @@ export class OrInput extends LitElement {
};
return html`
<button id="component" class="${classMap(classes)}"
- ?readonly="${readonly}"
+ ?readonly="${this.readonly}"
?disabled="${this.disabled}"
@onmousedown="${() => {if (isMomentary) this.onValueChange(undefined, true)}}" @onmouseup="${() => isMomentary ? this.onValueChange(undefined, false) : this.onValueChange(undefined, true)}">
${!isIconButton ? html`<div class="mdc-button__ripple"></div>` : ``}
@@ -523,7 +515,7 @@ export class OrInput extends LitElement {
<input type="checkbox"
?checked="${this.value}"
?required="${this.required}"
- ?disabled="${this.disabled || readonly}"
+ ?disabled="${this.disabled || this.readonly}"
@change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).checked)}"
class="mdc-checkbox__native-control" id="elem"/>
<div class="mdc-checkbox__background">
@@ -613,7 +605,7 @@ export class OrInput extends LitElement {
${this.type === InputType.TEXTAREA || this.type === InputType.JSON ? html`
<textarea id="elem" class="mdc-text-field__input"
?required="${this.required}"
- ?readonly="${readonly}"
+ ?readonly="${this.readonly}"
?disabled="${this.disabled}"
@change="${(e: Event) => this.onValueChange((e.target as HTMLTextAreaElement), (e.target as HTMLTextAreaElement).value)}"
minlength="${ifDefined(this.minLength)}"
@@ -625,7 +617,7 @@ export class OrInput extends LitElement {
` :
html`<input type="${this.type}" id="elem" class="mdc-text-field__input"
?required="${this.required}"
- ?readonly="${readonly}"
+ ?readonly="${this.readonly}"
?disabled="${this.disabled}"
@change="${(e: Event) => this.onValueChange((e.target as HTMLInputElement), (e.target as HTMLInputElement).value)}"
.value="${val !== null && val !== undefined ? val : ""}"
@@ -644,7 +636,7 @@ export class OrInput extends LitElement {
${hasHelper ? html`
<div class="mdc-text-field-helper-line">
<div class="mdc-text-field-helper-text ${classMap(helperClasses)}">${showValidationMessage ? this.validationMessage : this.helperText}</div>
- ${this.charCounter && !readonly ? html`<div class="mdc-text-field-character-counter"></div>` : ``}
+ ${this.charCounter && !this.readonly ? html`<div class="mdc-text-field-character-counter"></div>` : ``}
</div>
` : ``}
`;
diff --git a/ui/component/or-mwc-components/src/or-mwc-dialog.ts b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
index 9359795d1..ae4cae26b 100644
--- a/ui/component/or-mwc-components/src/or-mwc-dialog.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-dialog.ts
@@ -6,7 +6,8 @@ import {
property,
query,
TemplateResult,
- unsafeCSS
+ unsafeCSS,
+ CSSResult
} from "lit-element";
import {MDCDialog} from "@material/dialog";
import "@openremote/or-translate";
@@ -17,10 +18,11 @@ const dialogStyle = require("!!raw-loader!@material/dialog/dist/mdc.dialog.css")
const listStyle = require("!!raw-loader!@material/list/dist/mdc.list.css");
export interface DialogConfig {
- title?: string;
+ title?: TemplateResult | string;
content?: TemplateResult;
actions?: DialogAction[];
avatar?: boolean;
+ styles?: TemplateResult | string;
}
export interface DialogAction {
@@ -68,15 +70,9 @@ const style = css`
position: relative;
}
- .mdc-dialog .mdc-dialog__surface {
- width: 600px;
- height: calc(100vh - 50%);
- }
-
.dialog-container {
display: flex;
flex-direction: row;
- flex: 1 1 0;
}
.dialog-container > * {
@@ -86,7 +82,6 @@ const style = css`
.mdc-list {
padding: 0 24px
}
-
`;
@customElement("or-mwc-dialog")
@@ -106,11 +101,12 @@ export class OrMwcDialog extends LitElement {
this.dialogContent = config.content;
this.dialogActions = config.actions;
this.avatar = config.avatar;
+ this.styles = config.styles;
}
};
@property({type: String})
- public dialogTitle?: string;
+ public dialogTitle?: string | TemplateResult;
@property({type: Object, attribute: false})
public dialogContent?: TemplateResult;
@@ -121,6 +117,9 @@ export class OrMwcDialog extends LitElement {
@property({type: Boolean})
public avatar?: boolean;
+ @property()
+ public styles?: TemplateResult | string;
+
@query("#dialog")
protected _mdcElem!: HTMLElement;
@@ -152,6 +151,9 @@ export class OrMwcDialog extends LitElement {
protected render() {
return html`
+
+ ${typeof(this.styles) === "string" ? html`<style></style>${this.styles}<style>` : this.styles}
+
<div id="dialog"
class="mdc-dialog"
role="alertdialog"
@@ -162,7 +164,8 @@ export class OrMwcDialog extends LitElement {
@MDCDialog:closed="${(evt: any) => this._onDialogClosed(evt.detail.action)}">
<div class="mdc-dialog__container">
<div class="mdc-dialog__surface">
- <h2 class="mdc-dialog__title" id="dialog-title"><or-translate value="${this.dialogTitle}"></or-translate></h2>
+ ${typeof(this.dialogTitle) === "string" ? html`<h2 class="mdc-dialog__title" id="dialog-title"><or-translate value="${this.dialogTitle}"></or-translate></h2>`
+ : html`<span class="mdc-dialog__title" id="dialog-title">${this.dialogTitle}</span>`}
${this.dialogContent ? html`
<div class="dialog-container mdc-dialog__content" id="dialog-content">
${this.dialogContent ? this.dialogContent : html`<slot></slot>`}
@@ -172,7 +175,7 @@ export class OrMwcDialog extends LitElement {
return html`
<div class="mdc-button mdc-dialog__button" ?data-mdc-dialog-button-default="${action.default}" data-mdc-dialog-action="${action.actionName}">
${typeof(action.content) === "string" ? html`<or-input .type="${InputType.BUTTON}" .label="${action.content}"></or-input>` : action.content}
- </div>`
+ </div>`;
}) : ``}
</footer>
` : html`
diff --git a/ui/component/or-translate/src/index.ts b/ui/component/or-translate/src/index.ts
index 7bbf6203f..4b1d77d00 100644
--- a/ui/component/or-translate/src/index.ts
+++ b/ui/component/or-translate/src/index.ts
@@ -32,6 +32,6 @@ export class OrTranslate extends translate(i18next)(LitElement) {
}
protected _getTranslatedValue() {
- return this.value ? i18next.t(this.value, this.options) : "";
+ return this.value ? i18next.isInitialized ? i18next.t(this.value, this.options) : this.value : "";
}
}
diff --git a/ui/component/rest/src/index.ts b/ui/component/rest/src/index.ts
index db94671d6..74d53d736 100644
--- a/ui/component/rest/src/index.ts
+++ b/ui/component/rest/src/index.ts
@@ -15,9 +15,9 @@ export class RestApi {
this._axiosInstance = axios.create();
this._axiosInstance.defaults.headers["Content-Type"] = "application/json";
this._axiosInstance.interceptors.request.use((config) => {
- config.paramsSerializer = params => Qs.stringify(params, {arrayFormat: 'repeat'});
+ config.paramsSerializer = (params) => Qs.stringify(params, {arrayFormat: "repeat"});
return config;
- })
+ });
}
get axiosInstance() {
@@ -28,13 +28,6 @@ export class RestApi {
this._axiosInstance.defaults.timeout = timeout;
}
- public setBasicAuth(username: string, password: string) {
- this._axiosInstance.defaults.auth = {
- password: password,
- username: username
- };
- }
-
public addRequestInterceptor(interceptor: (config: AxiosRequestConfig) => AxiosRequestConfig) {
this._axiosInstance.interceptors.request.use(interceptor);
}