Improved UI SDk and modal demo

This commit is contained in:
dqj
2026-01-18 21:48:19 +09:00
parent 9bbbae8dd2
commit 055d59f979
7 changed files with 373 additions and 167 deletions

View File

@@ -1,15 +1,15 @@
/**
* amiPro utils
* amiPro utils - jQuery-free version
*/
'use strict';
function setI18NText(i18n_map){
for (const key of i18n_map.keys()) {
const elm = $("#"+key);
const elm = document.getElementById(key);
if(elm){
const lang = window.navigator.language;
var elem = i18n_map.get(key)
var elem = i18n_map.get(key)
var msg = null
if(elem){
msg = elem.get(lang)
@@ -17,14 +17,14 @@ function setI18NText(i18n_map){
}
if(!msg)msg = key+"-"+lang
$("#"+key).html(msg);
elm.textContent = msg;
}
}
}
function getI18NText(i18n_map, key){
const lang = window.navigator.language;
var elem = i18n_map.get(key)
var elem = i18n_map.get(key)
var msg = null
if(elem){
msg = elem.get(lang)

View File

@@ -2,6 +2,8 @@ const DFIDO2_LIB_LOCALSTG_NAME_USER_SESSION = 'fido2_user_session'
const DFIDO2_LIB_LOCALSTG_NAME_REGISTERED = 'dfido2_lib_registered'
const DFIDO2_LIB_LOCALSTG_NAME_SVR_URL = 'dfido2_lib_svr_url'
let configuredServerUrl = null;
/** ===APIs=== */
if(!localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL)){
@@ -9,9 +11,25 @@ if(!localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL)){
}
function setFidoServerURL(url){
if (!url || !url.startsWith('https://')) {
throw new Error('serverUrl must be a valid HTTPS URL');
}
configuredServerUrl = url;
localStorage.setItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL, url);
}
function getServerUrl() {
if (configuredServerUrl) {
return configuredServerUrl;
}
const stored = localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL);
if (stored) {
configuredServerUrl = stored;
return stored;
}
return 'https://fido2.amipro.me';
}
function canTryAutoAuthentication(){
//const session_text = localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_USER_SESSION)
//alert('canTryAuth:'+session_text+"|"+(null != localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_REGISTERED)))
@@ -67,7 +85,7 @@ async function listUserDevicesFido2(rpId = null) {
req.rp = { id: rpId };
}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/usr/dvc/lst", {
const response = await fetch(getServerUrl() + "/usr/dvc/lst", {
method: "POST",
cache: "no-cache",
headers: {
@@ -104,7 +122,7 @@ async function delUserDeviceFido2(device_id, rpId = null) {
req.rp = { id: rpId };
}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/usr/dvc/rm", {
const response = await fetch(getServerUrl() + "/usr/dvc/rm", {
method: "POST",
cache: "no-cache",
headers: {
@@ -154,7 +172,7 @@ async function validSession(rpId = null) {
req.rp = { id: rpId };
}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/usr/validsession", {
const response = await fetch(getServerUrl() + "/usr/validsession", {
method: "POST",
cache: "no-cache",
headers: {
@@ -177,7 +195,7 @@ async function logoutFido2UserSession(){
const session_data = JSON.parse(session_text)
let req = {session: session_data['session'], username: session_data['uid']}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/usr/delsession", {
const response = await fetch(getServerUrl() + "/usr/delsession", {
method: "POST",
cache: "no-cache",
headers: {
@@ -192,7 +210,7 @@ async function logoutFido2UserSession(){
async function getRegistrationUser(reg_session_id){
try {
let req = {session_id: reg_session_id}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/reg/username", {
const response = await fetch(getServerUrl() + "/reg/username", {
method: "POST",
cache: "no-cache",
headers: {
@@ -410,7 +428,7 @@ async function doAttestation(username, displayName, rpId, userVerification = 'pr
attestationOptions.rp = { id: rpId }
}
const svrUrl = localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL)
const svrUrl = getServerUrl()
const response = await fetch(svrUrl + "/attestation/options", {
method: "POST",
cache: "no-cache",
@@ -445,7 +463,7 @@ async function doAttestation(username, displayName, rpId, userVerification = 'pr
attResult.transports = res.response.getTransports();
}
const result = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/attestation/result", {
const result = await fetch(getServerUrl() + "/attestation/result", {
method: "POST",
cache: "no-cache",
headers: {
@@ -524,7 +542,7 @@ async function doAssertion(username = null, rpId = null, userVerification = 'pre
authnOptions.rp = { id: rpId };
}
const response = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/assertion/options", {
const response = await fetch(getServerUrl() + "/assertion/options", {
method: "POST",
cache: "no-cache",
headers: {
@@ -566,7 +584,7 @@ async function doAssertion(username = null, rpId = null, userVerification = 'pre
userHandle: _toBase64URL(btoa(_bufferToString(cred.response.userHandle))) //_toBase64URL(btoa(_bufferToString(cred.response.userHandle)))
}
};
const res = await fetch(localStorage.getItem(DFIDO2_LIB_LOCALSTG_NAME_SVR_URL) + "/assertion/result", {
const res = await fetch(getServerUrl() + "/assertion/result", {
method: "POST",
cache: "no-cache",
headers: {

View File

@@ -1,6 +1,19 @@
(function(window) {
'use strict';
// Check required dependencies
if (typeof authenticateFido2 === 'undefined' ||
typeof registerFido2 === 'undefined' ||
typeof listUserDevicesFido2 === 'undefined' ||
typeof delUserDeviceFido2 === 'undefined' ||
typeof setFidoServerURL === 'undefined' ||
typeof logoutFido2UserSession === 'undefined') {
throw new Error(
'FIDO2 UI SDK requires dfido2-lib.js to be loaded first. ' +
'Please add: <script src="files/dfido2-lib.js"></script> before fido2-ui-sdk.js'
);
}
const FIDO2_UI_VERSION = '1.0.0';
const DEFAULT_CONFIG = {
@@ -459,8 +472,8 @@
showRemainingAttempts: true,
},
callbacks: {
onFido2Success: null,
onFido2Error: null,
onLoginSuccess: null,
onLoginError: null,
onPasswordLogin: null,
onPasswordExhausted: null,
onLoginClosed: null,
@@ -513,18 +526,30 @@
container.innerHTML = '';
const uniqueId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
const modalId = 'fido2LoginModal_' + uniqueId;
const titleId = 'fido2LoginModalTitle_' + uniqueId;
const errorId = 'fido2LoginError_' + uniqueId;
const hintId = 'fido2LoginHint_' + uniqueId;
const userIdId = 'fido2UserId_' + uniqueId;
const passwordId = 'fido2Password_' + uniqueId;
const passwordSectionId = 'fido2PasswordSection_' + uniqueId;
const mainBtnId = 'fido2MainBtn_' + uniqueId;
const toggleLinkId = 'fido2ToggleModeLink_' + uniqueId;
const modal = document.createElement('div');
modal.className = 'modal fade fido2-sdk-login-modal';
modal.id = 'fido2LoginModal';
modal.id = modalId;
modal.tabIndex = -1;
modal.setAttribute('aria-hidden', 'true');
modal.innerHTML = this._getModalHTML();
modal.innerHTML = this._getModalHTML(uniqueId, titleId, errorId, hintId, userIdId, passwordId, passwordSectionId, mainBtnId, toggleLinkId);
container.appendChild(modal);
this.modalElement = modal;
this.containerElement = container;
this._uniqueId = uniqueId;
this._debugLog('[Fido2Login] Modal element created');
this._debugLog('[Fido2Login] Modal element created with ID:', modalId);
this.themeManager.applyTheme(modal);
@@ -545,7 +570,7 @@
return modal;
};
Fido2Login.prototype._getModalHTML = function() {
Fido2Login.prototype._getModalHTML = function(uniqueId, titleId, errorId, hintId, userIdId, passwordId, passwordSectionId, mainBtnId, toggleLinkId) {
const theme = this.config.theme;
const features = this.config.features;
@@ -554,45 +579,45 @@
<div class="modal-content fido2-sdk-card">
<div class="modal-header fido2-sdk-header">
${theme.logo ? `<img src="${theme.logo}" class="fido2-sdk-logo me-2" alt="Logo">` : ''}
<h5 class="modal-title fido2-sdk-text" id="fido2LoginModalTitle">${this.i18n.getText('title_login')}</h5>
<h5 class="modal-title fido2-sdk-text" id="${titleId}">${this.i18n.getText('title_login')}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body fido2-sdk-container">
${this._getBodyHTML()}
${this._getBodyHTML(uniqueId, errorId, hintId, userIdId, passwordId, passwordSectionId, mainBtnId, toggleLinkId)}
</div>
</div>
</div>
`;
};
Fido2Login.prototype._getBodyHTML = function() {
Fido2Login.prototype._getBodyHTML = function(uniqueId, errorId, hintId, userIdId, passwordId, passwordSectionId, mainBtnId, toggleLinkId) {
const features = this.config.features;
const theme = this.config.theme;
let html = '';
html += `
<div id="fido2LoginError" class="alert alert-danger mb-3" style="display:none;"></div>
<div id="fido2LoginHint" class="alert alert-info mb-3" style="display:none;"></div>
<div id="${errorId}" class="alert alert-danger mb-3" style="display:none;"></div>
<div id="${hintId}" class="alert alert-info mb-3" style="display:none;"></div>
`;
html += `
<div class="mb-3">
<label for="fido2UserId" class="form-label fido2-sdk-text">${this.i18n.getText('placeholder_user_id')}</label>
<input type="text" class="form-control" id="fido2UserId" placeholder="${this.i18n.getText('placeholder_user_id')}">
<label for="${userIdId}" class="form-label fido2-sdk-text">${this.i18n.getText('placeholder_user_id')}</label>
<input type="text" class="form-control" id="${userIdId}" placeholder="${this.i18n.getText('placeholder_user_id')}">
</div>
`;
html += `
<div class="mb-3" id="fido2PasswordSection" style="display:none;">
<label for="fido2Password" class="form-label fido2-sdk-text">${this.i18n.getText('placeholder_password')}</label>
<input type="password" class="form-control" id="fido2Password" placeholder="${this.i18n.getText('placeholder_password')}">
<div class="mb-3" id="${passwordSectionId}" style="display:none;">
<label for="${passwordId}" class="form-label fido2-sdk-text">${this.i18n.getText('placeholder_password')}</label>
<input type="password" class="form-control" id="${passwordId}" placeholder="${this.i18n.getText('placeholder_password')}">
</div>
`;
html += `
<div class="d-grid gap-2">
<button type="button" class="btn btn-primary fido2-sdk-btn fido2-sdk-btn-primary" id="fido2MainBtn">
<button type="button" class="btn btn-primary fido2-sdk-btn fido2-sdk-btn-primary" id="${mainBtnId}">
${this.i18n.getText('btn_fido2_login')}
</button>
</div>
@@ -603,7 +628,7 @@
if (features.enablePasswordLogin) {
html += `
<div class="text-center">
<a href="javascript:void(0)" class="fido2-sdk-link" id="fido2ToggleModeLink">${this.i18n.getText('link_use_password')}</a>
<a href="javascript:void(0)" class="fido2-sdk-link" id="${toggleLinkId}">${this.i18n.getText('link_use_password')}</a>
</div>
`;
}
@@ -612,7 +637,7 @@
const remaining = this.maxAttempts - this.attemptCount;
html += `
<div class="text-center mt-3">
<small class="text-muted fido2-sdk-text" id="fido2RemainingAttempts">
<small class="text-muted fido2-sdk-text" id="fido2RemainingAttempts_${uniqueId}">
${this.i18n.getText('msg_remaining_attempts').replace('{n}', remaining)}
</small>
</div>
@@ -627,7 +652,7 @@
const container = this.modalElement || this.containerElement;
if (!container) return;
const mainBtn = container.querySelector('#fido2MainBtn');
const mainBtn = container.querySelector('[id^="fido2MainBtn_"]');
if (mainBtn) {
mainBtn.addEventListener('click', () => {
if (self.mode === LoginMode.FIDO2) {
@@ -638,15 +663,15 @@
});
}
const toggleLink = container.querySelector('#fido2ToggleModeLink');
const toggleLink = container.querySelector('[id^="fido2ToggleModeLink_"]');
if (toggleLink) {
toggleLink.addEventListener('click', () => {
this._debugLog('[Fido2Login] Toggle link clicked, current mode:', this.mode);
this._debugLog('[Fido2Login] Toggle link clicked, current mode:', self.mode);
self._toggleMode();
});
}
const userIdInput = container.querySelector('#fido2UserId');
const userIdInput = container.querySelector('[id^="fido2UserId_"]');
if (userIdInput) {
userIdInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
@@ -659,7 +684,7 @@
});
}
const passwordInput = container.querySelector('#fido2Password');
const passwordInput = container.querySelector('[id^="fido2Password_"]');
if (passwordInput) {
passwordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
@@ -683,10 +708,15 @@
this._stopLoading();
if (result.status === 'ok') {
this.state = LoginState.CLOSED;
this._emit('fido2Success', result.username, result.session);
this._emit('fido2Success', {
method: 'fido2',
username: result.username,
session: result.session
});
this._closeUI();
} else {
this._emit('fido2Error', {
method: 'fido2',
code: 'AUTH_FAILED',
message: result.errorMessage || this.i18n.getText('msg_fido2_failed'),
originalError: result
@@ -696,12 +726,14 @@
this._stopLoading();
if (error.name === 'AbortError' || (error.message && error.message.toLowerCase().includes('canceled'))) {
this._emit('fido2Error', {
method: 'fido2',
code: 'CANCELED',
message: this.i18n.getText('msg_fido2_canceled'),
originalError: error
});
} else {
this._emit('fido2Error', {
method: 'fido2',
code: 'AUTH_FAILED',
message: error.message || this.i18n.getText('msg_fido2_failed'),
originalError: error
@@ -727,6 +759,11 @@
this._hideError();
this._startLoading();
// Clear any existing FIDO2 session before password login
if (typeof logoutFido2UserSession === 'function') {
logoutFido2UserSession();
}
const passwordCallback = this.config.callbacks.onPasswordLogin;
if (typeof passwordCallback !== 'function') {
this._stopLoading();
@@ -738,7 +775,11 @@
this._stopLoading();
if (success) {
this.state = LoginState.CLOSED;
this._emit('fido2Success', userId, null);
this._emit('fido2Success', {
method: 'password',
username: userId,
session: null
});
this._closeUI();
} else {
this.attemptCount++;
@@ -769,11 +810,11 @@
const container = this.modalElement || this.containerElement;
if (!container) return;
const passwordSection = container.querySelector('#fido2PasswordSection');
const mainBtn = container.querySelector('#fido2MainBtn');
const toggleLink = container.querySelector('#fido2ToggleModeLink');
const titleEl = document.getElementById('fido2LoginModalTitle');
const remainingEl = container.querySelector('#fido2RemainingAttempts');
const passwordSection = container.querySelector('[id^="fido2PasswordSection_"]');
const mainBtn = container.querySelector('[id^="fido2MainBtn_"]');
const toggleLink = container.querySelector('[id^="fido2ToggleModeLink_"]');
const titleEl = container.querySelector('[id^="fido2LoginModalTitle_"]');
const remainingEl = container.querySelector('[id^="fido2RemainingAttempts_"]');
if (this.mode === LoginMode.FIDO2) {
this.mode = LoginMode.PASSWORD;
@@ -789,7 +830,7 @@
} else if (this.config.features.showRemainingAttempts) {
const remainingContainer = document.createElement('div');
remainingContainer.className = 'text-center mt-3';
remainingContainer.innerHTML = `<small class="text-muted fido2-sdk-text" id="fido2RemainingAttempts">${this.i18n.getText('msg_remaining_attempts').replace('{n}', remaining)}</small>`;
remainingContainer.innerHTML = `<small class="text-muted fido2-sdk-text" id="fido2RemainingAttempts_${this._uniqueId}">${this.i18n.getText('msg_remaining_attempts').replace('{n}', remaining)}</small>`;
toggleLink.parentNode.parentNode.insertBefore(remainingContainer, toggleLink.parentNode.nextSibling);
}
} else {
@@ -808,18 +849,21 @@
};
Fido2Login.prototype._getUserIdInput = function() {
const input = document.getElementById('fido2UserId');
const container = this.modalElement || this.containerElement;
const input = container ? container.querySelector('[id^="fido2UserId_"]') : null;
return input ? input.value.trim() : '';
};
Fido2Login.prototype._getPasswordInput = function() {
const input = document.getElementById('fido2Password');
const container = this.modalElement || this.containerElement;
const input = container ? container.querySelector('[id^="fido2Password_"]') : null;
return input ? input.value : '';
};
Fido2Login.prototype._showError = function(message) {
const errorEl = document.getElementById('fido2LoginError');
const hintEl = document.getElementById('fido2LoginHint');
const container = this.modalElement || this.containerElement;
const errorEl = container ? container.querySelector('[id^="fido2LoginError_"]') : null;
const hintEl = container ? container.querySelector('[id^="fido2LoginHint_"]') : null;
if (hintEl) hintEl.style.display = 'none';
if (errorEl) {
errorEl.textContent = message;
@@ -828,12 +872,14 @@
};
Fido2Login.prototype._hideError = function() {
const errorEl = document.getElementById('fido2LoginError');
const container = this.modalElement || this.containerElement;
const errorEl = container ? container.querySelector('[id^="fido2LoginError_"]') : null;
if (errorEl) errorEl.style.display = 'none';
};
Fido2Login.prototype._showHint = function(message) {
const hintEl = document.getElementById('fido2LoginHint');
const container = this.modalElement || this.containerElement;
const hintEl = container ? container.querySelector('[id^="fido2LoginHint_"]') : null;
if (hintEl) {
hintEl.textContent = message;
hintEl.style.display = 'block';
@@ -841,12 +887,14 @@
};
Fido2Login.prototype._hideHint = function() {
const hintEl = document.getElementById('fido2LoginHint');
const container = this.modalElement || this.containerElement;
const hintEl = container ? container.querySelector('[id^="fido2LoginHint_"]') : null;
if (hintEl) hintEl.style.display = 'none';
};
Fido2Login.prototype._startLoading = function() {
const mainBtn = document.getElementById('fido2MainBtn');
const container = this.modalElement || this.containerElement;
const mainBtn = container ? container.querySelector('[id^="fido2MainBtn_"]') : null;
if (mainBtn) {
mainBtn.disabled = true;
mainBtn.dataset.originalText = mainBtn.textContent;
@@ -855,7 +903,8 @@
};
Fido2Login.prototype._stopLoading = function() {
const mainBtn = document.getElementById('fido2MainBtn');
const container = this.modalElement || this.containerElement;
const mainBtn = container ? container.querySelector('[id^="fido2MainBtn_"]') : null;
if (mainBtn) {
mainBtn.disabled = false;
mainBtn.textContent = mainBtn.dataset.originalText ||
@@ -867,17 +916,24 @@
const container = this.modalElement || this.containerElement;
if (!container) return;
const remainingEl = container.querySelector('#fido2RemainingAttempts');
const remainingEl = container.querySelector('[id^="fido2RemainingAttempts_"]');
if (remainingEl) {
const remaining = this.maxAttempts - this.attemptCount;
remainingEl.textContent = this.i18n.getText('msg_remaining_attempts').replace('{n}', remaining);
}
};
Fido2Login.prototype._emit = function(event, ...args) {
const callback = this.config.callbacks['on' + event.charAt(0).toUpperCase() + event.slice(1)];
Fido2Login.prototype._emit = function(event, data) {
const callbackName = 'on' + event.charAt(0).toUpperCase() + event.slice(1);
const callback = this.config.callbacks[callbackName];
if (typeof callback === 'function') {
callback.apply(this, args);
if (event === 'fido2Success') {
callback(data.username, data.session, data);
} else if (event === 'fido2Error') {
callback(data, data.originalError);
} else {
callback(data);
}
}
};
@@ -934,11 +990,16 @@
this._hideHint();
if (result.status === 'ok') {
this.state = LoginState.CLOSED;
this._emit('fido2Success', result.username, result.session);
this._emit('fido2Success', {
method: 'fido2',
username: result.username,
session: result.session
});
this._closeUI();
} else {
this.state = LoginState.FIDO2;
this._emit('fido2Error', {
method: 'fido2',
code: 'AUTH_FAILED',
message: result.errorMessage || this.i18n.getText('msg_fido2_failed'),
originalError: result
@@ -951,6 +1012,7 @@
if (error.name === 'AbortError' || (error.message && error.message.toLowerCase().includes('canceled'))) {
this.state = LoginState.FIDO2;
this._emit('fido2Error', {
method: 'fido2',
code: 'CANCELED',
message: this.i18n.getText('msg_fido2_canceled'),
originalError: error
@@ -958,6 +1020,7 @@
} else {
this.state = LoginState.FIDO2;
this._emit('fido2Error', {
method: 'fido2',
code: 'AUTH_FAILED',
message: error.message || this.i18n.getText('msg_fido2_failed'),
originalError: error
@@ -974,6 +1037,7 @@
} else {
this.state = LoginState.FIDO2;
this._emit('fido2Error', {
method: 'fido2',
code: 'NO_REGISTRATION',
message: this.i18n.getText('msg_no_registration'),
originalError: null
@@ -1009,9 +1073,9 @@
const container = this.modalElement || this.containerElement;
if (!container) return;
const passwordSection = container.querySelector('#fido2PasswordSection');
const mainBtn = container.querySelector('#fido2MainBtn');
const toggleLink = container.querySelector('#fido2ToggleModeLink');
const passwordSection = container.querySelector('[id^="fido2PasswordSection_"]');
const mainBtn = container.querySelector('[id^="fido2MainBtn_"]');
const toggleLink = container.querySelector('[id^="fido2ToggleModeLink_"]');
if (passwordSection) passwordSection.style.display = 'none';
if (mainBtn) mainBtn.textContent = this.i18n.getText('btn_fido2_login');
@@ -1027,10 +1091,10 @@
const container = this.modalElement || this.containerElement;
if (!container) return;
const passwordSection = container.querySelector('#fido2PasswordSection');
const mainBtn = container.querySelector('#fido2MainBtn');
const toggleLink = container.querySelector('#fido2ToggleModeLink');
const titleEl = document.getElementById('fido2LoginModalTitle');
const passwordSection = container.querySelector('[id^="fido2PasswordSection_"]');
const mainBtn = container.querySelector('[id^="fido2MainBtn_"]');
const toggleLink = container.querySelector('[id^="fido2ToggleModeLink_"]');
const titleEl = container.querySelector('[id^="fido2LoginModalTitle_"]');
if (passwordSection) passwordSection.style.display = 'block';
if (mainBtn) mainBtn.textContent = this.i18n.getText('btn_password_login');
@@ -1285,6 +1349,7 @@
const result = await registerFido2(effectiveUserId, displayName || 'Device-' + effectiveUserId, this.config.rpId);
if (result.status === 'ok') {
// registerFido2 automatically creates/updates session in sessionStorage
await this.loadDevices();
this.eventManager.emit('deviceAdded', result);
return result;
@@ -1330,25 +1395,11 @@
DeviceManager.prototype.checkSession = async function() {
try {
const sessionUserId = this.getSessionUserId();
if (!sessionUserId) {
this.sessionStatus = false;
this.eventManager.emit('sessionStatusChanged', false);
return false;
}
const validation = this.validateUserId();
if (!validation.valid) {
this.sessionStatus = false;
this.eventManager.emit('sessionStatusChanged', false);
this.eventManager.emit('userMismatch', validation.error);
return false;
}
this.sessionStatus = true;
this.eventManager.emit('sessionStatusChanged', true);
return true;
// Simply validate session with server, same as devices.html does
const sessionOk = await validSession(this.config.rpId);
this.sessionStatus = !!sessionOk;
this.eventManager.emit('sessionStatusChanged', this.sessionStatus);
return this.sessionStatus;
} catch (error) {
this.sessionStatus = false;
this.eventManager.emit('sessionStatusChanged', false);
@@ -1420,16 +1471,23 @@
container.innerHTML = '';
const uniqueId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
const modalId = 'fido2SdkModal_' + uniqueId;
const sessionStatusId = 'fido2SessionStatus_' + uniqueId;
const addBtnId = 'fido2AddDeviceBtn_' + uniqueId;
const devicesListId = 'fido2DevicesList_' + uniqueId;
const modal = document.createElement('div');
modal.className = 'modal fade fido2-sdk-modal';
modal.id = 'fido2SdkModal';
modal.id = modalId;
modal.tabIndex = -1;
modal.setAttribute('aria-hidden', 'true');
modal.innerHTML = this._getModalHTML();
modal.innerHTML = this._getModalHTML(uniqueId, sessionStatusId, addBtnId, devicesListId);
container.appendChild(modal);
this.modalElement = modal;
this.containerElement = container;
this._uniqueId = uniqueId;
this.themeManager.applyTheme(modal);
@@ -1445,12 +1503,12 @@
this.cleanup();
});
this._bindEvents();
this._bindEvents(uniqueId, addBtnId, devicesListId);
return modal;
};
UIRenderer.prototype._getModalHTML = function() {
UIRenderer.prototype._getModalHTML = function(uniqueId, sessionStatusId, addBtnId, devicesListId) {
const theme = this.config.theme;
return `
@@ -1459,11 +1517,11 @@
<div class="modal-header fido2-sdk-header">
${theme.logo ? `<img src="${theme.logo}" class="fido2-sdk-logo" alt="Logo">` : ''}
<h5 class="modal-title fido2-sdk-text">${this.i18n.getText('my_devices')}</h5>
${this.config.features.showSessionStatus ? '<span class="badge fido2-sdk-status-badge" id="fido2SessionStatus"></span>' : ''}
${this.config.features.showSessionStatus ? `<span class="badge fido2-sdk-status-badge" id="${sessionStatusId}"></span>` : ''}
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body fido2-sdk-container">
${this._getBodyHTML()}
${this._getBodyHTML(uniqueId, addBtnId, devicesListId)}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary fido2-sdk-btn" data-bs-dismiss="modal">${this.i18n.getText('btn_close')}</button>
@@ -1473,7 +1531,7 @@
`;
};
UIRenderer.prototype._getBodyHTML = function() {
UIRenderer.prototype._getBodyHTML = function(uniqueId, addBtnId, devicesListId) {
const features = this.config.features;
const dm = window.Fido2UIManager ? window.Fido2UIManager.deviceManager : null;
const userId = dm ? dm.getEffectiveUserId() : (this.config.userId || '');
@@ -1488,7 +1546,7 @@
if (features.showAddButton) {
html += `
<button type="button" class="btn btn-info mb-3 fido2-sdk-btn fido2-sdk-btn-primary" id="fido2AddDeviceBtn">
<button type="button" class="btn btn-info mb-3 fido2-sdk-btn fido2-sdk-btn-primary" id="${addBtnId}">
${this.i18n.getText('btn_add')}
</button>
`;
@@ -1504,7 +1562,7 @@
${features.showDeleteButton ? `<th>${this.i18n.getText('title_act')}</th>` : ''}
</tr>
</thead>
<tbody id="fido2DevicesList">
<tbody id="${devicesListId}">
<tr>
<td colspan="3" class="text-center fido2-sdk-text">${this.i18n.getText('title_empty_list')}</td>
</tr>
@@ -1516,7 +1574,7 @@
return html;
};
UIRenderer.prototype._bindEvents = function() {
UIRenderer.prototype._bindEvents = function(uniqueId, addBtnId, devicesListId) {
const container = this.modalElement || this.containerElement;
if (!container) return;
@@ -1524,10 +1582,10 @@
btn.replaceWith(btn.cloneNode(true));
});
const addBtn = container.querySelector('#fido2AddDeviceBtn');
const addBtn = container.querySelector('#' + addBtnId);
if (addBtn) {
addBtn.replaceWith(addBtn.cloneNode(true));
const newAddBtn = container.querySelector('#fido2AddDeviceBtn');
const newAddBtn = container.querySelector('#' + addBtnId);
newAddBtn.addEventListener('click', () => {
this.eventManager.emit('addDevice');
});
@@ -1545,7 +1603,8 @@
};
UIRenderer.prototype.updateDevicesList = function(devices) {
const tbody = document.getElementById('fido2DevicesList');
const container = this.modalElement || this.containerElement;
const tbody = container ? container.querySelector('[id^="fido2DevicesList_"]') : null;
if (!tbody) return;
if (!devices || devices.length === 0) {
@@ -1583,12 +1642,13 @@
});
tbody.innerHTML = html;
this._bindEvents();
this._bindEvents(this._uniqueId, 'fido2AddDeviceBtn_' + this._uniqueId, 'fido2DevicesList_' + this._uniqueId);
};
UIRenderer.prototype.updateSessionStatus = function(isValid) {
const badge = document.getElementById('fido2SessionStatus');
const addBtn = document.getElementById('fido2AddDeviceBtn');
const container = this.modalElement || this.containerElement;
const badge = container ? container.querySelector('[id^="fido2SessionStatus_"]') : null;
const addBtn = container ? container.querySelector('[id^="fido2AddDeviceBtn_"]') : null;
if (badge) {
if (isValid) {
@@ -1601,7 +1661,7 @@
}
if (addBtn) {
addBtn.disabled = !isValid;
addBtn.disabled = false;
}
};
@@ -1773,10 +1833,6 @@
return this;
}
if (!window.jQuery) {
throw new Error('jQuery is required. Please include jQuery before fido2-ui-sdk.js');
}
if (!window.bootstrap) {
throw new Error('Bootstrap is required. Please include Bootstrap JS before fido2-ui-sdk.js');
}
@@ -1856,7 +1912,9 @@
try {
await self.deviceManager.addDevice();
self.uiRenderer.updateDevicesList(self.deviceManager.devices);
// Re-check session after device list is updated
await self.deviceManager.checkSession();
self.uiRenderer.updateSessionStatus(self.deviceManager.sessionStatus);
alert(self.i18n.getText('msg_register_ok'));
} catch (error) {
console.error('Add device error:', error);
@@ -1913,6 +1971,13 @@
}
};
Fido2UIManager.prototype.logout = function() {
if (typeof logoutFido2UserSession === 'function') {
logoutFido2UserSession();
}
this.eventManager.emit('logout');
};
Fido2UIManager.prototype.destroy = function() {
if (this.deviceManager) {
this.deviceManager.stopAutoRefresh();
@@ -1926,10 +1991,6 @@
};
Fido2UIManager.prototype.renderLogin = function(config) {
if (!window.jQuery) {
throw new Error('jQuery is required. Please include jQuery before fido2-ui-sdk.js');
}
if (!window.bootstrap) {
throw new Error('Bootstrap is required. Please include Bootstrap JS before fido2-ui-sdk.js');
}
@@ -1954,6 +2015,11 @@
window.Fido2UIManager.refresh();
}
};
window.Fido2UIManager.logout = function() {
if (window.Fido2UIManager && window.Fido2UIManager.logout) {
window.Fido2UIManager.logout();
}
};
window.Fido2UIManager.destroy = function() {
if (window.Fido2UIManager && window.Fido2UIManager.destroy) {
window.Fido2UIManager.destroy();