Add login function
TODO ws request auth Signed-off-by: YoungSoo Shin <shinys000114@gmail.com>
This commit is contained in:
@@ -8,7 +8,33 @@
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<main class="container">
|
||||
<div id="login-container" class="d-flex flex-column justify-content-center align-items-center vh-100" style="display: none;">
|
||||
<div class="card p-4 shadow-lg" style="width: 100%; max-width: 400px;">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-center mb-4">Login to ODROID Power Mate</h2>
|
||||
<div id="login-alert" class="alert alert-danger d-none" role="alert"></div>
|
||||
<form id="login-form">
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Username</label>
|
||||
<input type="text" class="form-control" id="username" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<input type="password" class="form-control" id="password" required>
|
||||
</div>
|
||||
<div class="d-grid">
|
||||
<button type="submit" class="btn btn-primary">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="form-check form-switch d-flex justify-content-center mt-4">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="theme-toggle-login">
|
||||
<label class="form-check-label ms-2" for="theme-toggle-login"><i id="theme-icon-login" class="bi bi-moon-stars-fill"></i></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<main class="container" style="display: none;">
|
||||
<header class="d-flex justify-content-between align-items-center mb-3 main-header">
|
||||
<div class="order-md-1" style="flex: 1;">
|
||||
<div class="d-flex align-items-center">
|
||||
@@ -37,6 +63,9 @@
|
||||
data-bs-target="#settingsModal">
|
||||
<i class="bi bi-gear"></i>
|
||||
</button>
|
||||
<button class="btn btn-outline-secondary ms-3" id="logout-button">
|
||||
<i class="bi bi-box-arrow-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
120
page/src/api.js
120
page/src/api.js
@@ -4,15 +4,63 @@
|
||||
* It abstracts the fetch logic, error handling, and JSON parsing for network and control operations.
|
||||
*/
|
||||
|
||||
// Function to get authentication headers
|
||||
export function getAuthHeaders() {
|
||||
const token = localStorage.getItem('authToken');
|
||||
if (token) {
|
||||
return { 'Authorization': `Bearer ${token}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
// Global error handler for unauthorized responses
|
||||
export async function handleResponse(response) {
|
||||
if (response.status === 401) {
|
||||
// Unauthorized, log out the user
|
||||
localStorage.removeItem('authToken');
|
||||
// Redirect to login or trigger a logout event
|
||||
// For now, we'll just reload the page, which will trigger the login screen
|
||||
window.location.reload();
|
||||
throw new Error('Unauthorized: Session expired or invalid token.');
|
||||
}
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || `HTTP error! status: ${response.status}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates a user with the provided username and password.
|
||||
* @param {string} username The user's username.
|
||||
* @param {string} password The user's password.
|
||||
* @returns {Promise<Object>} A promise that resolves to the server's JSON response containing a token.
|
||||
* @throws {Error} Throws an error if the authentication fails.
|
||||
*/
|
||||
export async function login(username, password) {
|
||||
const response = await fetch('/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
// Login function does not use handleResponse as it's for obtaining the token
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || `Login failed with status: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the list of available Wi-Fi networks from the server.
|
||||
* @returns {Promise<Array<Object>>} A promise that resolves to an array of Wi-Fi access point objects.
|
||||
* @throws {Error} Throws an error if the network request fails.
|
||||
*/
|
||||
export async function fetchWifiScan() {
|
||||
const response = await fetch('/api/wifi/scan');
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return await response.json();
|
||||
const response = await fetch('/api/wifi/scan', {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return await handleResponse(response).then(res => res.json());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,16 +71,15 @@ export async function fetchWifiScan() {
|
||||
* @throws {Error} Throws an error if the connection request fails.
|
||||
*/
|
||||
export async function postWifiConnect(ssid, password) {
|
||||
const response = await fetch('/api/setting', { // Updated URL
|
||||
const response = await fetch('/api/setting', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify({ssid, password}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || `Connection failed with status: ${response.status}`);
|
||||
}
|
||||
return await response.json();
|
||||
return await handleResponse(response).then(res => res.json());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,16 +89,15 @@ export async function postWifiConnect(ssid, password) {
|
||||
* @throws {Error} Throws an error if the request fails.
|
||||
*/
|
||||
export async function postNetworkSettings(payload) {
|
||||
const response = await fetch('/api/setting', { // Updated URL
|
||||
const response = await fetch('/api/setting', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || `Failed to apply settings with status: ${response.status}`);
|
||||
}
|
||||
return response;
|
||||
return await handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,14 +109,13 @@ export async function postNetworkSettings(payload) {
|
||||
export async function postBaudRateSetting(baudrate) {
|
||||
const response = await fetch('/api/setting', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify({baudrate}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || `Failed to apply baudrate with status: ${response.status}`);
|
||||
}
|
||||
return response;
|
||||
return await handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,9 +124,10 @@ export async function postBaudRateSetting(baudrate) {
|
||||
* @throws {Error} Throws an error if the network request fails.
|
||||
*/
|
||||
export async function fetchSettings() {
|
||||
const response = await fetch('/api/setting'); // Updated URL
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return await response.json();
|
||||
const response = await fetch('/api/setting', {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return await handleResponse(response).then(res => res.json());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,9 +136,10 @@ export async function fetchSettings() {
|
||||
* @throws {Error} Throws an error if the network request fails.
|
||||
*/
|
||||
export async function fetchControlStatus() {
|
||||
const response = await fetch('/api/control');
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return await response.json();
|
||||
const response = await fetch('/api/control', {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return await handleResponse(response).then(res => res.json());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,11 +151,13 @@ export async function fetchControlStatus() {
|
||||
export async function postControlCommand(command) {
|
||||
const response = await fetch('/api/control', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(command)
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return response;
|
||||
return await handleResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,7 +166,8 @@ export async function postControlCommand(command) {
|
||||
* @throws {Error} Throws an error if the network request fails.
|
||||
*/
|
||||
export async function fetchVersion() {
|
||||
const response = await fetch('/api/version');
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
return await response.json();
|
||||
const response = await fetch('/api/version', {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return await handleResponse(response).then(res => res.json());
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as api from './api.js';
|
||||
import * as ui from './ui.js';
|
||||
import {clearTerminal, downloadTerminalOutput, fitTerminal} from './terminal.js';
|
||||
import {debounce, isMobile} from './utils.js';
|
||||
import {getAuthHeaders, handleResponse} from './api.js'; // Import auth functions
|
||||
|
||||
// A flag to track if charts have been initialized
|
||||
let chartsInitialized = false;
|
||||
@@ -28,7 +29,10 @@ function updateSliderValue(slider, span) {
|
||||
}
|
||||
|
||||
function loadCurrentLimitSettings() {
|
||||
fetch('/api/setting')
|
||||
fetch('/api/setting', {
|
||||
headers: getAuthHeaders(), // Add auth headers
|
||||
})
|
||||
.then(handleResponse) // Handle response for 401
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.vin_current_limit !== undefined) {
|
||||
@@ -58,13 +62,6 @@ export function setupEventListeners() {
|
||||
}
|
||||
console.log("Attaching event listeners...");
|
||||
|
||||
// --- Theme Toggle ---
|
||||
dom.themeToggle.addEventListener('change', () => {
|
||||
const newTheme = dom.themeToggle.checked ? 'dark' : 'light';
|
||||
localStorage.setItem('theme', newTheme);
|
||||
ui.applyTheme(newTheme);
|
||||
});
|
||||
|
||||
// --- Terminal Controls ---
|
||||
dom.clearButton.addEventListener('click', clearTerminal);
|
||||
dom.downloadButton.addEventListener('click', downloadTerminalOutput);
|
||||
@@ -86,8 +83,12 @@ export function setupEventListeners() {
|
||||
if (dom.rebootButton) {
|
||||
dom.rebootButton.addEventListener('click', () => {
|
||||
if (confirm('Are you sure you want to reboot the device?')) {
|
||||
fetch('/api/reboot', {method: 'POST'})
|
||||
.then(response => response.ok ? response.json() : Promise.reject('Network response was not ok'))
|
||||
fetch('/api/reboot', {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(), // Add auth headers
|
||||
})
|
||||
.then(handleResponse) // Handle response for 401
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log('Reboot command sent:', data);
|
||||
ui.hideSettingsModal();
|
||||
@@ -115,10 +116,14 @@ export function setupEventListeners() {
|
||||
|
||||
fetch('/api/setting', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(), // Add auth headers
|
||||
},
|
||||
body: JSON.stringify(settings),
|
||||
})
|
||||
.then(response => response.ok ? response.json() : Promise.reject('Failed to apply settings'))
|
||||
.then(handleResponse) // Handle response for 401
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log('Current limit settings applied:', data);
|
||||
})
|
||||
|
||||
118
page/src/main.js
118
page/src/main.js
@@ -31,6 +31,20 @@ import {setupEventListeners} from './events.js';
|
||||
// --- Globals ---
|
||||
// StatusMessage is imported directly from the generated proto.js file.
|
||||
|
||||
// --- DOM Elements ---
|
||||
const loginContainer = document.getElementById('login-container');
|
||||
const mainContent = document.querySelector('main.container');
|
||||
const loginForm = document.getElementById('login-form');
|
||||
const usernameInput = document.getElementById('username');
|
||||
const passwordInput = document.getElementById('password');
|
||||
const loginAlert = document.getElementById('login-alert');
|
||||
const logoutButton = document.getElementById('logout-button');
|
||||
const themeToggleLogin = document.getElementById('theme-toggle-login');
|
||||
const themeIconLogin = document.getElementById('theme-icon-login');
|
||||
const themeToggleMain = document.getElementById('theme-toggle');
|
||||
const themeIconMain = document.getElementById('theme-icon');
|
||||
|
||||
|
||||
// --- WebSocket Event Handlers ---
|
||||
|
||||
function onWsOpen() {
|
||||
@@ -111,6 +125,80 @@ function onWsMessage(event) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Authentication Functions ---
|
||||
|
||||
function checkAuth() {
|
||||
const token = localStorage.getItem('authToken');
|
||||
if (token) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogin(event) {
|
||||
event.preventDefault();
|
||||
const username = usernameInput.value;
|
||||
const password = passwordInput.value;
|
||||
|
||||
try {
|
||||
const response = await api.login(username, password);
|
||||
if (response && response.token) {
|
||||
localStorage.setItem('authToken', response.token);
|
||||
loginAlert.classList.add('d-none');
|
||||
loginContainer.style.setProperty('display', 'none', 'important');
|
||||
initializeMainAppContent(); // After successful login, initialize the main app
|
||||
} else {
|
||||
loginAlert.textContent = 'Login failed: No token received.';
|
||||
loginAlert.classList.remove('d-none');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
loginAlert.textContent = `Login failed: ${error.message}`;
|
||||
loginAlert.classList.remove('d-none');
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
localStorage.removeItem('authToken');
|
||||
// Hide main content and show login form
|
||||
loginContainer.style.setProperty('display', 'flex', 'important');
|
||||
mainContent.style.setProperty('display', 'none', 'important');
|
||||
// Optionally, disconnect WebSocket or perform other cleanup
|
||||
// For now, just hide the main content.
|
||||
}
|
||||
|
||||
// --- Theme Toggle Functions ---
|
||||
function setupThemeToggles() {
|
||||
// Initialize theme for login page
|
||||
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||
applyTheme(savedTheme);
|
||||
themeToggleLogin.checked = savedTheme === 'dark';
|
||||
themeIconLogin.className = savedTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||
|
||||
// Sync main theme toggle with login theme toggle (initial state)
|
||||
themeToggleMain.checked = savedTheme === 'dark';
|
||||
themeIconMain.className = savedTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||
|
||||
themeToggleLogin.addEventListener('change', () => {
|
||||
const newTheme = themeToggleLogin.checked ? 'dark' : 'light';
|
||||
applyTheme(newTheme);
|
||||
localStorage.setItem('theme', newTheme);
|
||||
themeIconLogin.className = newTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||
themeToggleMain.checked = themeToggleLogin.checked; // Keep main toggle in sync
|
||||
themeIconMain.className = themeIconLogin.className; // Keep main icon in sync
|
||||
});
|
||||
|
||||
themeToggleMain.addEventListener('change', () => {
|
||||
const newTheme = themeToggleMain.checked ? 'dark' : 'light';
|
||||
applyTheme(newTheme);
|
||||
localStorage.setItem('theme', newTheme);
|
||||
themeIconMain.className = newTheme === 'dark' ? 'bi bi-moon-stars-fill' : 'bi bi-sun-fill';
|
||||
themeToggleLogin.checked = themeToggleMain.checked; // Keep login toggle in sync
|
||||
themeIconLogin.className = themeIconMain.className; // Keep login icon in sync
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// --- Application Initialization ---
|
||||
|
||||
@@ -131,18 +219,34 @@ function connect() {
|
||||
initWebSocket({ onOpen: onWsOpen, onClose: onWsClose, onMessage: onWsMessage });
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
// New function to initialize main app content after successful login or on initial load if authenticated
|
||||
function initializeMainAppContent() {
|
||||
loginContainer.style.setProperty('display', 'none', 'important');
|
||||
mainContent.style.setProperty('display', 'block', 'important');
|
||||
|
||||
initUI();
|
||||
setupTerminal();
|
||||
initializeVersion();
|
||||
|
||||
const savedTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
|
||||
applyTheme(savedTheme);
|
||||
|
||||
setupEventListeners();
|
||||
|
||||
setupEventListeners(); // Attach main app event listeners
|
||||
logoutButton.addEventListener('click', handleLogout); // Attach logout listener
|
||||
connect();
|
||||
}
|
||||
|
||||
function initialize() {
|
||||
setupThemeToggles(); // Setup theme toggles for both login and main (initial sync)
|
||||
|
||||
// Always attach login form listener
|
||||
loginForm.addEventListener('submit', handleLogin);
|
||||
|
||||
if (checkAuth()) { // Check authentication status
|
||||
// If authenticated, initialize main content
|
||||
initializeMainAppContent();
|
||||
} else {
|
||||
// If not authenticated, show login form
|
||||
loginContainer.style.setProperty('display', 'flex', 'important');
|
||||
mainContent.style.setProperty('display', 'none', 'important');
|
||||
}
|
||||
}
|
||||
|
||||
// --- Start Application ---
|
||||
document.addEventListener('DOMContentLoaded', initialize);
|
||||
|
||||
Reference in New Issue
Block a user