-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
202 lines (173 loc) · 8.58 KB
/
Copy pathindex.html
File metadata and controls
202 lines (173 loc) · 8.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.7.7/axios.min.js" integrity="sha512-DdX/YwF5e41Ok+AI81HI8f5/5UsoxCVT9GKYZRIzpLxb8Twz4ZwPPX+jQMwMhNQ9b5+zDEefc+dcvQoPWGNZ3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/jwt-decode.min.js"></script>
</head>
<body>
<div class="container-fluid">
<h1 class="row">Login</h1>
<main id="content">
<div class="row mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Enter your username">
</div>
<div class="row mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter your password">
</div>
<div>
<button class="btn btn-primary" onclick="login()">Login</button>
</div>
</main>
<div>
<button class="btn btn-primary" onclick="getDashboard()">Dashboard</button>
<button class="btn btn-primary" onclick="getSettings()">Settings</button>
</div>
</div>
<script>
// Check token expiration on page load
window.onload = function () {
const token = localStorage.getItem('jwtToken');
if (token) {
const decodedToken = jwtDecode(token); // Decode the JWT token
const currentTime = Date.now() / 1000; // Current time in seconds
// Check if the token has expired
if (decodedToken.exp < currentTime) {
alert('Session expired. Please log in again.');
localStorage.removeItem('jwtToken'); // Remove expired token
window.location.href = '/'; // Redirect to login page
} else {
handleRouteChange(); // Call the route handler if token is still valid
}
} else {
handleRouteChange(); // No token, proceed to handle routes
}
};
var token = ''; // Local variable to store token
// Function to handle navigation to different pages
function navigate(event, route) {
event.preventDefault(); // Prevent the default link behavior (page reload)
history.pushState(null, null, route); // Update the URL without reloading
handleRouteChange(); // Call the route handler
}
// Function to handle content changes based on the route
function handleRouteChange() {
const path = window.location.pathname;
const content = document.getElementById('content');
if (path === '/') {
// Render the login form without overwriting the buttons
content.innerHTML = `
<div class="row mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Enter your username">
</div>
<div class="row mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Enter your password">
</div>
<div>
<button class="btn btn-primary" onclick="login()">Login</button>
</div>`;
} else if (path === '/dashboard') {
getDashboard(); // Fetch dashboard content
} else if (path === '/settings') {
getSettings(); // Fetch settings content
} else {
content.innerHTML = `<p>Page not found</p>`;
}
}
// Function to handle the login process
function login() {
const data = {
username: document.getElementById('username').value,
password: document.getElementById('password').value,
};
if (!data.username || !data.password) {
alert('Please enter both username and password.');
return;
}
axios.post('/api/login', data)
.then(response => {
console.log(response.data);
document.getElementById('username').value = '';
document.getElementById('password').value = '';
if (response && response.data && response.data.success) {
alert('Login successful!');
token = response.data.token;
// Store the JWT token in localStorage
localStorage.setItem('jwtToken', token);
history.pushState(null, null, '/dashboard'); // Navigate to the dashboard after login
handleRouteChange();
} else {
alert('Login failed: ' + response.data.err);
}
})
.catch(error => {
console.error('Login error:', error.response ? error.response.data : error.message);
alert('An error occurred during login.');
});
}
// Function to fetch and display the dashboard content
function getDashboard() {
const token = localStorage.getItem('jwtToken'); // Retrieve token from localStorage
if (!token) {
alert('Session expired. Redirecting to login...');
window.location.href = '/'; // Redirect to login if no token is found
return;
}
axios.get('/api/dashboard', {
headers: {
'Authorization': `Bearer ${token}`
}
}).then(res => {
if (res && res.data && res.data.success) {
document.querySelector('h1.row').innerHTML = 'Dashboard';
document.querySelector('main').innerHTML = res.data.myContent;
}
}).catch(error => {
handleUnauthorized(error); // Handle token expiration or unauthorized access
});
}
// Function to fetch and display the settings content
function getSettings() {
const token = localStorage.getItem('jwtToken'); // Retrieve token from localStorage
if (!token) {
alert('Session expired. Redirecting to login...');
window.location.href = '/'; // Redirect to login if no token is found
return;
}
axios.get('/api/settings', {
headers: {
'Authorization': `Bearer ${token}`
}
}).then(res => {
if (res && res.data && res.data.success) {
document.querySelector('h1.row').innerHTML = 'Settings';
document.querySelector('main').innerHTML = res.data.myContent;
}
}).catch(error => {
handleUnauthorized(error); // Handle token expiration or unauthorized access
});
}
// Function to handle unauthorized access or expired token
function handleUnauthorized(error) {
if (error.response && error.response.status === 401) {
alert('Session expired. Redirecting to login...');
token = ''; // Clear the token
localStorage.removeItem('jwtToken'); // Remove token from localStorage
window.location.href = '/'; // Redirect to root address (login page)
} else {
console.error('Error:', error.response ? error.response.data : error.message);
alert('An error occurred.');
}
}
// Listen for the back/forward button actions and handle the route change
window.onpopstate = handleRouteChange;
</script>
</body>
</html>