Skip to content

Commit

Permalink
Merge pull request #272 from matt8707/hassurl
Browse files Browse the repository at this point in the history
Revert hass_url configuration option
  • Loading branch information
matt8707 authored Jan 24, 2024
2 parents 1eb1588 + fe4b2f0 commit e9615b8
Show file tree
Hide file tree
Showing 8 changed files with 44 additions and 22 deletions.
1 change: 1 addition & 0 deletions data/configuration.yaml
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
locale: en
hassUrl: http://192.168.1.241:8123
1 change: 0 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ if (HASS_URL) {
app.use(handler);

app.listen(PORT, () => {
console.debug(`ENV HASS_URL: ${HASS_URL}`);
console.debug(`ENV PORT: ${PORT}`);
console.debug(`ENV ADDON ${process.env.ADDON || false}`);
});
15 changes: 10 additions & 5 deletions src/lib/Modal/LoginModal.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script lang="ts">
import { configuration, lang, motion } from '$lib/Stores';
import { lang, motion } from '$lib/Stores';
import Modal from '$lib/Modal/Index.svelte';
import { Auth } from 'home-assistant-js-websocket';
import { closeModal } from 'svelte-modals';
Expand All @@ -11,6 +11,7 @@
export let isOpen: boolean;
export let clientId: string | undefined;
export let hassUrl: string | undefined;
export let flow_id: string | undefined;
let invalidAuth: string | undefined;
Expand All @@ -24,12 +25,16 @@
let code = '';
async function handleSubmit() {
if (!flow_id || (step === 'mfa' && code === '')) return;
if (!flow_id || !hassUrl || (step === 'mfa' && code === '')) {
console.error({ flow_id, hassUrl, code });
return;
}
disabled = true;
try {
// submit data
const payload = step === 'init' ? { username, password, clientId } : { code, clientId };
const payload =
step === 'init' ? { username, password, clientId, hassUrl } : { code, clientId, hassUrl };
const response = await fetch(`${base}/api/auth/${flow_id}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
Expand Down Expand Up @@ -67,14 +72,14 @@
async function handleSuccess(data: any) {
// update data
data.clientId = clientId;
data.hassUrl = $configuration?.hassUrl;
data.hassUrl = hassUrl;
data.expires = data.expires_in * 1000 + Date.now();
// save localStorage
localStorage.setItem('auth', JSON.stringify(data));
// connect to websocket
const auth = new Auth({ ...data, hassUrl: $configuration?.hassUrl, clientId });
const auth = new Auth({ ...data, hassUrl, clientId });
await webSocket(auth);
closeModal();
Expand Down
9 changes: 5 additions & 4 deletions src/lib/Socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { states, connection, config, connected } from '$lib/Stores';
import { openModal } from 'svelte-modals';
import { base } from '$app/paths';

export async function authenticate() {
export async function authenticate(hassUrl: string) {
const storage = localStorage.getItem('auth');
const data = storage ? JSON.parse(storage) : null;

Expand All @@ -27,7 +27,8 @@ export async function authenticate() {
const clientId = genClientId();
openModal(async () => import('$lib/Modal/LoginModal.svelte'), {
clientId,
flow_id: await getFlowId(clientId)
hassUrl,
flow_id: await getFlowId(clientId, hassUrl)
});
}
}
Expand Down Expand Up @@ -96,14 +97,14 @@ export async function webSocket(auth: Auth) {
}
}

export async function getFlowId(clientId: string) {
export async function getFlowId(clientId: string, hassUrl: string) {
try {
const response = await fetch(`${base}/api/auth`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ clientId })
body: JSON.stringify({ clientId, hassUrl })
});

const data = await response.json();
Expand Down
23 changes: 20 additions & 3 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readFile } from 'fs/promises';
import { readFile, writeFile } from 'fs/promises';
import { dev } from '$app/environment';
import yaml from 'js-yaml';
import type { Configuration, Dashboard, Translations } from '$lib/Types';
Expand Down Expand Up @@ -30,7 +30,7 @@ async function loadFile(file: string) {
/**
* Server load function
*/
export async function load(): Promise<{
export async function load({ request }): Promise<{
configuration: Configuration;
dashboard: Dashboard;
theme: any;
Expand All @@ -42,7 +42,24 @@ export async function load(): Promise<{
loadFile('./data/dashboard.yaml')
]);

configuration.hassUrl = process.env.HASS_URL;
// determine hassUrl
let hassUrl = process.env.ADDON ? configuration.hassUrl : process.env.HASS_URL;

if (!hassUrl) {
const proto = request.headers.get('x-forwarded-proto');
const host = request.headers.get('x-forwarded-host');
if (proto && host) hassUrl = `${proto}://${host}`;
}

// update hassUrl
if (hassUrl && hassUrl !== configuration.hassUrl) {
configuration.hassUrl = hassUrl;
try {
await writeFile('./data/configuration.yaml', yaml.dump(configuration), 'utf8');
} catch (error) {
console.error('error updating configuration.yaml:', error);
}
}

// initialize keys if missing
dashboard.views = dashboard.views || [];
Expand Down
7 changes: 6 additions & 1 deletion src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@
/**
* Connect to websocket
*/
if (browser) authenticate();
$: console.log('$configuration?.hassUrl', $configuration?.hassUrl);
if (browser && $configuration?.hassUrl) {
authenticate($configuration.hassUrl);
}
onMount(async () => {
/**
Expand Down
5 changes: 1 addition & 4 deletions src/routes/api/auth/+server.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import type { RequestHandler } from './$types';
import { json, error } from '@sveltejs/kit';
import dotenv from 'dotenv';
dotenv.config();

export const POST: RequestHandler = async ({ request }) => {
try {
const hassUrl = process.env.HASS_URL;
const { clientId } = await request.json();
const { clientId, hassUrl } = await request.json();

const response = await fetch(`${hassUrl}/auth/login_flow`, {
method: 'POST',
Expand Down
5 changes: 1 addition & 4 deletions src/routes/api/auth/[flow_id]/+server.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import type { RequestHandler } from '@sveltejs/kit';
import { json, error } from '@sveltejs/kit';
import dotenv from 'dotenv';
dotenv.config();

export const POST: RequestHandler = async ({ params, request }) => {
try {
const hassUrl = process.env.HASS_URL;
const { flow_id } = params;
const { username, password, code, clientId } = await request.json();
const { username, password, code, clientId, hassUrl } = await request.json();

let payload;
if (username && password && clientId) {
Expand Down

0 comments on commit e9615b8

Please sign in to comment.