Keep auth params when onboarding (#6182)

This commit is contained in:
Paulus Schoutsen 2020-06-17 10:32:27 -07:00 committed by GitHub
parent 9ff2eece3a
commit cc71ccaafa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 86 additions and 47 deletions

View File

@ -6,19 +6,18 @@ import {
property, property,
PropertyValues, PropertyValues,
} from "lit-element"; } from "lit-element";
import { AuthProvider, fetchAuthProviders } from "../data/auth"; import {
AuthProvider,
fetchAuthProviders,
AuthUrlSearchParams,
} from "../data/auth";
import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin"; import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin";
import { registerServiceWorker } from "../util/register-service-worker"; import { registerServiceWorker } from "../util/register-service-worker";
import "./ha-auth-flow"; import "./ha-auth-flow";
import { extractSearchParamsObject } from "../common/url/search-params";
import(/* webpackChunkName: "pick-auth-provider" */ "./ha-pick-auth-provider"); import(/* webpackChunkName: "pick-auth-provider" */ "./ha-pick-auth-provider");
interface QueryParams {
client_id?: string;
redirect_uri?: string;
state?: string;
}
class HaAuthorize extends litLocalizeLiteMixin(LitElement) { class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
@property() public clientId?: string; @property() public clientId?: string;
@ -33,14 +32,7 @@ class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
constructor() { constructor() {
super(); super();
this.translationFragment = "page-authorize"; this.translationFragment = "page-authorize";
const query: QueryParams = {}; const query = extractSearchParamsObject() as AuthUrlSearchParams;
const values = location.search.substr(1).split("&");
for (const item of values) {
const value = item.split("=");
if (value.length > 1) {
query[decodeURIComponent(value[0])] = decodeURIComponent(value[1]);
}
}
if (query.client_id) { if (query.client_id) {
this.clientId = query.client_id; this.clientId = query.client_id;
} }
@ -145,7 +137,7 @@ class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
response.status === 400 && response.status === 400 &&
authProviders.code === "onboarding_required" authProviders.code === "onboarding_required"
) { ) {
location.href = "/?"; location.href = `/onboarding.html${location.search}`;
return; return;
} }

View File

@ -0,0 +1,8 @@
export const extractSearchParamsObject = (): { [key: string]: string } => {
const query = {};
const searchParams = new URLSearchParams(location.search);
for (const [key, value] of searchParams.entries()) {
query[key] = value;
}
return query;
};

View File

@ -1,5 +1,11 @@
import { HomeAssistant } from "../types"; import { HomeAssistant } from "../types";
export interface AuthUrlSearchParams {
client_id?: string;
redirect_uri?: string;
state?: string;
}
export interface AuthProvider { export interface AuthProvider {
name: string; name: string;
id: string; id: string;

View File

@ -51,7 +51,7 @@ export const onboardCoreConfigStep = (hass: HomeAssistant) =>
export const onboardIntegrationStep = ( export const onboardIntegrationStep = (
hass: HomeAssistant, hass: HomeAssistant,
params: { client_id: string } params: { client_id: string; redirect_uri: string }
) => ) =>
hass.callApi<OnboardingIntegrationStepResponse>( hass.callApi<OnboardingIntegrationStepResponse>(
"POST", "POST",

View File

@ -1,9 +1,9 @@
import { import {
Auth, Auth,
createConnection, createConnection,
genClientId,
getAuth, getAuth,
subscribeConfig, subscribeConfig,
genClientId,
} from "home-assistant-js-websocket"; } from "home-assistant-js-websocket";
import { import {
customElement, customElement,
@ -14,12 +14,12 @@ import {
} from "lit-element"; } from "lit-element";
import { HASSDomEvent } from "../common/dom/fire_event"; import { HASSDomEvent } from "../common/dom/fire_event";
import { subscribeOne } from "../common/util/subscribe-one"; import { subscribeOne } from "../common/util/subscribe-one";
import { hassUrl } from "../data/auth"; import { hassUrl, AuthUrlSearchParams } from "../data/auth";
import { import {
fetchOnboardingOverview, fetchOnboardingOverview,
OnboardingResponses, OnboardingResponses,
OnboardingStep, OnboardingStep,
ValidOnboardingStep, onboardIntegrationStep,
} from "../data/onboarding"; } from "../data/onboarding";
import { subscribeUser } from "../data/ws-user"; import { subscribeUser } from "../data/ws-user";
import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin"; import { litLocalizeLiteMixin } from "../mixins/lit-localize-lite-mixin";
@ -28,19 +28,28 @@ import { HomeAssistant } from "../types";
import { registerServiceWorker } from "../util/register-service-worker"; import { registerServiceWorker } from "../util/register-service-worker";
import "./onboarding-create-user"; import "./onboarding-create-user";
import "./onboarding-loading"; import "./onboarding-loading";
import { extractSearchParamsObject } from "../common/url/search-params";
interface OnboardingEvent<T extends ValidOnboardingStep> { type OnboardingEvent =
type: T; | {
result: OnboardingResponses[T]; type: "user";
} result: OnboardingResponses["user"];
}
| {
type: "core_config";
result: OnboardingResponses["core_config"];
}
| {
type: "integration";
};
declare global { declare global {
interface HASSDomEvents { interface HASSDomEvents {
"onboarding-step": OnboardingEvent<ValidOnboardingStep>; "onboarding-step": OnboardingEvent;
} }
interface GlobalEventHandlersEventMap { interface GlobalEventHandlersEventMap {
"onboarding-step": HASSDomEvent<OnboardingEvent<ValidOnboardingStep>>; "onboarding-step": HASSDomEvent<OnboardingEvent>;
} }
} }
@ -150,9 +159,7 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
} }
} }
private async _handleStepDone( private async _handleStepDone(ev: HASSDomEvent<OnboardingEvent>) {
ev: HASSDomEvent<OnboardingEvent<ValidOnboardingStep>>
) {
const stepResult = ev.detail; const stepResult = ev.detail;
this._steps = this._steps!.map((step) => this._steps = this._steps!.map((step) =>
step.step === stepResult.type ? { ...step, done: true } : step step.step === stepResult.type ? { ...step, done: true } : step
@ -176,9 +183,41 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
} else if (stepResult.type === "core_config") { } else if (stepResult.type === "core_config") {
// We do nothing // We do nothing
} else if (stepResult.type === "integration") { } else if (stepResult.type === "integration") {
const result = stepResult.result as OnboardingResponses["integration"];
this._loading = true; this._loading = true;
// Determine if oauth redirect has been provided
const externalAuthParams = extractSearchParamsObject() as AuthUrlSearchParams;
const authParams =
externalAuthParams.client_id && externalAuthParams.redirect_uri
? externalAuthParams
: {
client_id: genClientId(),
redirect_uri: `${location.protocol}//${location.host}/?auth_callback=1`,
state: btoa(
JSON.stringify({
hassUrl: `${location.protocol}//${location.host}`,
clientId: genClientId(),
})
),
};
let result: OnboardingResponses["integration"];
try {
result = await onboardIntegrationStep(this.hass!, {
client_id: authParams.client_id!,
redirect_uri: authParams.redirect_uri!,
});
} catch (err) {
this.hass!.connection.close();
await this.hass!.auth.revoke();
alert(`Unable to finish onboarding: ${err.message}`);
document.location.assign("/?");
return;
}
// If we don't close the connection manually, the connection will be // If we don't close the connection manually, the connection will be
// closed when we navigate away from the page. Firefox allows JS to // closed when we navigate away from the page. Firefox allows JS to
// continue to execute, and so HAWS will automatically reconnect once // continue to execute, and so HAWS will automatically reconnect once
@ -191,17 +230,17 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
// Revoke current auth token. // Revoke current auth token.
await this.hass!.auth.revoke(); await this.hass!.auth.revoke();
const state = btoa( // Build up the url to redirect to
JSON.stringify({ let redirectUrl = authParams.redirect_uri!;
hassUrl: `${location.protocol}//${location.host}`, redirectUrl +=
clientId: genClientId(), (redirectUrl.includes("?") ? "&" : "?") +
}) `code=${encodeURIComponent(result.auth_code)}`;
);
document.location.assign( if (authParams.state) {
`/?auth_callback=1&code=${encodeURIComponent( redirectUrl += `&state=${encodeURIComponent(authParams.state)}`;
result.auth_code }
)}&state=${state}`
); document.location.assign(redirectUrl);
} }
} }

View File

@ -1,5 +1,4 @@
import "@material/mwc-button/mwc-button"; import "@material/mwc-button/mwc-button";
import { genClientId } from "home-assistant-js-websocket";
import { import {
css, css,
CSSResult, CSSResult,
@ -21,7 +20,6 @@ import {
} from "../data/config_flow"; } from "../data/config_flow";
import { DataEntryFlowProgress } from "../data/data_entry_flow"; import { DataEntryFlowProgress } from "../data/data_entry_flow";
import { domainToName } from "../data/integration"; import { domainToName } from "../data/integration";
import { onboardIntegrationStep } from "../data/onboarding";
import { import {
loadConfigFlowDialog, loadConfigFlowDialog,
showConfigFlowDialog, showConfigFlowDialog,
@ -169,12 +167,8 @@ class OnboardingIntegrations extends LitElement {
} }
private async _finish() { private async _finish() {
const result = await onboardIntegrationStep(this.hass, {
client_id: genClientId(),
});
fireEvent(this, "onboarding-step", { fireEvent(this, "onboarding-step", {
type: "integration", type: "integration",
result,
}); });
} }