Many changes on user profile and login system

- Fixed #80
- Better UI
- Fixed some bugs
This commit is contained in:
Pinga 2024-02-26 21:25:29 +02:00
parent 5831b2d7db
commit e032e7575b
10 changed files with 230 additions and 170 deletions

View file

@ -7,6 +7,7 @@ use App\Controllers\Controller;
use Respect\Validation\Validator as v;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Pinga\Session;
/**
* AuthController
@ -59,7 +60,13 @@ class AuthController extends Controller
global $container;
$data = $request->getParsedBody();
$db = $container->get('db');
$is2FAEnabled = $db->selectValue('SELECT tfa_enabled, tfa_secret FROM users WHERE email = ?', [$data['email']]);
$is2FAEnabled = $db->selectValue('SELECT tfa_enabled FROM users WHERE email = ?', [$data['email']]);
$isWebaEnabled = $db->selectValue('SELECT auth_method FROM users WHERE email = ?', [$data['email']]);
if ($isWebaEnabled == 'webauthn') {
$container->get('flash')->addMessage('error', 'WebAuthn enabled for this account');
return $response->withHeader('Location', '/login')->withStatus(302);
}
// If 2FA is enabled and no code is provided, redirect to 2FA code entry
if($is2FAEnabled && !isset($data['code'])) {
@ -219,7 +226,7 @@ class AuthController extends Controller
// Send success response
$user = $db->selectRow('SELECT * FROM users WHERE id = ?', [$user_id]);
Session::regenerate(true);
session_regenerate_id();
$_SESSION['auth_logged_in'] = true;
$_SESSION['auth_user_id'] = $user['id'];
$_SESSION['auth_email'] = $user['email'];
@ -237,7 +244,7 @@ class AuthController extends Controller
'users_audit',
[
'user_id' => $_SESSION['auth_user_id'],
'user_event' => 'user.login',
'user_event' => 'user.login.webauthn',
'user_resource' => 'control.panel',
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'user_ip' => get_client_ip(),

View file

@ -60,19 +60,15 @@ class ProfileController extends Controller
[$userId]
);
$is_weba_activated = $db->select(
'SELECT * FROM users_webauthn WHERE user_id = ?',
[$userId]
);
$user_audit = $db->select(
'SELECT * FROM users_audit WHERE user_id = ? ORDER BY event_time DESC',
'SELECT * FROM users_webauthn WHERE user_id = ? ORDER BY created_at DESC LIMIT 5',
[$userId]
);
if ($is_2fa_activated) {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue, 'userAudit' => $user_audit]);
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue]);
} else if ($is_weba_activated) {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue, 'weba' => $is_weba_activated, 'userAudit' => $user_audit]);
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue, 'weba' => $is_weba_activated]);
} else {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue, 'userAudit' => $user_audit]);
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue]);
}
}
@ -203,10 +199,19 @@ class ProfileController extends Controller
'sign_count' => $counter
]
);
$msg = 'registration success.';
$db->update(
'users',
[
'auth_method' => 'webauthn'
],
[
'id' => $userId
]
);
$msg = 'Registration success.';
if ($credential->rootValid === false) {
$msg = 'registration ok, but certificate does not match any of the selected root ca.';
$msg = 'Registration ok, but certificate does not match any of the selected root ca.';
}
$return = new \stdClass();

View file

@ -134,17 +134,23 @@
{% endif %}
</div>
<div class="card tab-pane" id="tabs-webauthn">
{% if weba is defined %}
<div class="card-body">
<h3 class="card-title">{{ __('WebAuthn Authentication') }}</h3>
<p>{{ __('Secure your account with WebAuthn. Click the button below to register your device for passwordless sign-in.') }}</p>
<button type="button" class="btn btn-success" id="connectWebAuthnButton">{{ __('Connect WebAuthn Device') }}</button>
<div class="d-flex align-items-center">
<span class="badge bg-green text-green-fg me-3"><svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3" /><path d="M12 11m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0" /><path d="M12 12l0 2.5" /></svg></span>
<div>
<h5 class="card-title mb-1">{{ __('Your account is secured with an additional layer of protection.') }}</h5>
<p class="text-muted mb-2">{{ __('WebAuthn is currently') }} <strong>{{ __('enabled') }}</strong> {{ __('for your account. If you encounter any issues or need to disable WebAuthn, please contact our support team for assistance.') }}</p>
</div>
</div>
<button type="button" class="btn btn-primary mt-4" id="connectWebAuthnButton">{{ __('Connect WebAuthn Device') }}</button>
<div class="table-responsive mt-4">
<table class="table table-striped">
<thead>
<tr>
<th>{{ __('Device/Browser Info') }}</th>
<th>{{ __('Registration Date') }}</th>
<th>{{ __('Action') }}</th>
</tr>
</thead>
<tbody>
@ -152,9 +158,6 @@
<tr>
<td>{{ device.user_agent }}</td>
<td>{{ device.created_at }}</td>
<td>
<a href="/path/to/action?deviceId={{ device.id }}">{{ __('Edit') }}</a>
</td>
</tr>
{% else %}
<tr>
@ -165,38 +168,20 @@
</table>
</div>
</div>
{% else %}
<div class="card-body">
<h3 class="card-title">{{ __('WebAuthn Authentication') }}</h3>
<p>{{ __('Secure your account with WebAuthn. Click the button below to register your device for passwordless sign-in.') }}</p>
<button type="button" class="btn btn-primary" id="connectWebAuthnButton">{{ __('Connect WebAuthn Device') }}</button>
</div>
{% endif %}
</div>
<div class="card tab-pane" id="tabs-log">
<div class="card-body">
<h3 class="card-title">{{ __('User Audit Log') }}</h3>
<p>{{ __('Track and review all user activities in your account below. Monitor logins, profile changes, and other key actions to ensure security and transparency.') }}</p>
<div class="table-responsive mt-4">
<table class="table table-striped">
<thead>
<tr>
<th>{{ __('Event') }}</th>
<th>{{ __('User Agent') }}</th>
<th>IP</th>
<th>{{ __('Location') }}</th>
<th>{{ __('Timestamp') }}</th>
</tr>
</thead>
<tbody>
{% for user in userAudit %}
<tr>
<td>{{ user.user_event }}</td>
<td>{{ user.user_agent }}</td>
<td>{{ user.user_ip }}</td>
<td>{{ user.user_location }}</td>
<td>{{ user.event_time }}</td>
</tr>
{% else %}
<tr>
<td colspan="5">{{ __('No log data for user.') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="auditTable"></div>
</div>
</div>
</div>
@ -205,108 +190,4 @@
</div>
{% include 'partials/footer.twig' %}
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const connectButton = document.getElementById('connectWebAuthnButton');
connectButton.addEventListener('click', async function() {
try {
// check browser support
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
throw new Error('Browser not supported.');
}
// get create args
let rep = await window.fetch('/webauthn/register/challenge', {method:'GET', cache:'no-cache'});
const createArgs = await rep.json();
// error handling
if (createArgs.success === false) {
throw new Error(createArgs.msg || 'unknown error occured');
}
// replace binary base64 data with ArrayBuffer. a other way to do this
// is the reviver function of JSON.parse()
recursiveBase64StrToArrayBuffer(createArgs);
// create credentials
const cred = await navigator.credentials.create(createArgs);
// create object
const authenticatorAttestationResponse = {
transports: cred.response.getTransports ? cred.response.getTransports() : null,
clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
attestationObject: cred.response.attestationObject ? arrayBufferToBase64(cred.response.attestationObject) : null
};
// check auth on server side
rep = await window.fetch('/webauthn/register/verify', {
method : 'POST',
body : JSON.stringify(authenticatorAttestationResponse),
cache : 'no-cache'
});
const authenticatorAttestationServerResponse = await rep.json();
// prompt server response
if (authenticatorAttestationServerResponse.success) {
//location.reload();
window.alert(authenticatorAttestationServerResponse.msg || 'registration success');
} else {
throw new Error(authenticatorAttestationServerResponse.msg);
}
} catch (err) {
//location.reload();
window.alert(err.message || 'unknown error occured');
}
});
/**
* convert RFC 1342-like base64 strings to array buffer
* @param {mixed} obj
* @returns {undefined}
*/
function recursiveBase64StrToArrayBuffer(obj) {
let prefix = '=?BINARY?B?';
let suffix = '?=';
if (typeof obj === 'object') {
for (let key in obj) {
if (typeof obj[key] === 'string') {
let str = obj[key];
if (str.substring(0, prefix.length) === prefix && str.substring(str.length - suffix.length) === suffix) {
str = str.substring(prefix.length, str.length - suffix.length);
let binary_string = window.atob(str);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
obj[key] = bytes.buffer;
}
} else {
recursiveBase64StrToArrayBuffer(obj[key]);
}
}
}
}
/**
* Convert a ArrayBuffer to Base64
* @param {ArrayBuffer} buffer
* @returns {String}
*/
function arrayBufferToBase64(buffer) {
let binary = '';
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa(binary);
}
});
</script>
{% endblock %}

View file

@ -56,20 +56,15 @@
</div>
</div>
</div>
<script src="/assets/js/sweetalert2.min.js" defer></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const loginButton = document.getElementById('loginWebAuthnButton');
const emailInput = document.querySelector('input[name="email"]');
const passwordInput = document.querySelector('input[name="password"]');
const codeInput = document.querySelector('input[name="code"]');
loginButton.addEventListener('click', async function() {
try {
// Disable password and 2FA fields
passwordInput.disabled = true;
codeInput.disabled = true;
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
throw new Error('Browser not supported.');
}
@ -112,19 +107,41 @@ document.addEventListener('DOMContentLoaded', function() {
body: JSON.stringify(authenticatorAttestationResponse),
cache:'no-cache'
});
const authenticatorAttestationServerResponse = await rep.json();
// Check the Content-Type of the response
const contentType = rep.headers.get('Content-Type');
// check server response
if (authenticatorAttestationServerResponse.success) {
//reloadServerPreview();
window.alert(authenticatorAttestationServerResponse.msg || 'login success');
if (contentType && contentType.includes('application/json')) {
// If the response is JSON, proceed with parsing
const authenticatorAttestationServerResponse = await rep.json();
// check server response
if (authenticatorAttestationServerResponse.success) {
Swal.fire({
title: 'WebAuthn Login',
text: authenticatorAttestationServerResponse.msg || 'Login success',
icon: "success"
});
} else {
Swal.fire({
title: 'WebAuthn Login',
text: authenticatorAttestationServerResponse.msg,
icon: "error"
});
}
} else if (contentType && (contentType.includes('text/html') || contentType.includes('application/xhtml+xml'))) {
// If the response is HTML, redirect to /dashboard
window.location.href = '/dashboard';
} else {
throw new Error(authenticatorAttestationServerResponse.msg);
// Handle other content types or unexpected responses
console.error('Unexpected response type:', contentType);
}
} catch (err) {
//reloadServerPreview();
window.alert(err.message || 'unknown error occured');
Swal.fire({
title: 'WebAuthn Login',
text: err.message || 'Unknown error occured',
icon: "error"
});
}
});

View file

@ -6,7 +6,7 @@
<meta http-equiv="X-UA-Compatible" content="ie=edge"/>
<title>{% block title %}{% endblock %} | Namingo</title>
<!-- CSS files -->
{% if route_is('domains') or route_is('applications') or route_is('contacts') or route_is('hosts') or route_is('epphistory') or route_is('registrars') or route_is('transactions') or route_is('overview') or route_is('reports') or route_is('transfers') or route_is('users') or is_current_url('ticketview') or route_is('poll') or route_is('log') or route_is('invoices') or route_is('registry/tlds') %}{% include 'partials/css-tables.twig' %}{% else %}{% include 'partials/css.twig' %}{% endif %}
{% if route_is('domains') or route_is('applications') or route_is('contacts') or route_is('hosts') or route_is('epphistory') or route_is('registrars') or route_is('transactions') or route_is('overview') or route_is('reports') or route_is('transfers') or route_is('users') or is_current_url('ticketview') or route_is('poll') or route_is('log') or route_is('invoices') or route_is('registry/tlds') or route_is('profile') %}{% include 'partials/css-tables.twig' %}{% else %}{% include 'partials/css.twig' %}{% endif %}
<style>
@import url('https://rsms.me/inter/inter.css');
:root {
@ -293,6 +293,8 @@
{% include 'partials/js-invoices.twig' %}
{% elseif route_is('registry/tlds') %}
{% include 'partials/js-tlds.twig' %}
{% elseif route_is('profile') %}
{% include 'partials/js-profile.twig' %}
{% else %}
{% include 'partials/js.twig' %}
{% endif %}

View file

@ -7,6 +7,7 @@
<title>{% block title %}{% endblock %} | Namingo</title>
<!-- CSS files -->
{% include 'partials/css.twig' %}
<link href="/assets/css/sweetalert2.min.css" rel="stylesheet">
<style>
@import url('https://rsms.me/inter/inter.css');
:root {

View file

@ -0,0 +1,144 @@
<script src="/assets/js/tabulator.min.js" defer></script>
<script src="/assets/js/sweetalert2.min.js" defer></script>
<script src="/assets/js/tabler.min.js" defer></script>
<script>
var table;
document.addEventListener("DOMContentLoaded", function(){
const connectButton = document.getElementById('connectWebAuthnButton');
connectButton.addEventListener('click', async function() {
try {
// check browser support
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
throw new Error('Browser not supported.');
}
// get create args
let rep = await window.fetch('/webauthn/register/challenge', {method:'GET', cache:'no-cache'});
const createArgs = await rep.json();
// error handling
if (createArgs.success === false) {
throw new Error(createArgs.msg || 'unknown error occured');
}
// replace binary base64 data with ArrayBuffer. a other way to do this
// is the reviver function of JSON.parse()
recursiveBase64StrToArrayBuffer(createArgs);
// create credentials
const cred = await navigator.credentials.create(createArgs);
// create object
const authenticatorAttestationResponse = {
transports: cred.response.getTransports ? cred.response.getTransports() : null,
clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
attestationObject: cred.response.attestationObject ? arrayBufferToBase64(cred.response.attestationObject) : null
};
// check auth on server side
rep = await window.fetch('/webauthn/register/verify', {
method : 'POST',
body : JSON.stringify(authenticatorAttestationResponse),
cache : 'no-cache'
});
const authenticatorAttestationServerResponse = await rep.json();
// prompt server response
if (authenticatorAttestationServerResponse.success) {
Swal.fire({
title: 'WebAuthn Passkey',
text: authenticatorAttestationServerResponse.msg || 'Created successfully',
icon: "success"
});
} else {
throw new Error(authenticatorAttestationServerResponse.msg);
}
} catch (err) {
Swal.fire({
title: 'WebAuthn Passkey',
text: err.message || 'Unknown error occured',
icon: "error"
});
}
});
/**
* convert RFC 1342-like base64 strings to array buffer
* @param {mixed} obj
* @returns {undefined}
*/
function recursiveBase64StrToArrayBuffer(obj) {
let prefix = '=?BINARY?B?';
let suffix = '?=';
if (typeof obj === 'object') {
for (let key in obj) {
if (typeof obj[key] === 'string') {
let str = obj[key];
if (str.substring(0, prefix.length) === prefix && str.substring(str.length - suffix.length) === suffix) {
str = str.substring(prefix.length, str.length - suffix.length);
let binary_string = window.atob(str);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
obj[key] = bytes.buffer;
}
} else {
recursiveBase64StrToArrayBuffer(obj[key]);
}
}
}
}
/**
* Convert a ArrayBuffer to Base64
* @param {ArrayBuffer} buffer
* @returns {String}
*/
function arrayBufferToBase64(buffer) {
let binary = '';
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa(binary);
}
table = new Tabulator("#auditTable", {
ajaxURL:"/api/records/users_audit", // Set the URL for your JSON data
ajaxConfig:"GET",
pagination:"local",
paginationSize:10,
ajaxResponse:function(url, params, response){
return response.records;
},
layout:"fitDataFill",
responsiveLayout: "collapse",
responsiveLayoutCollapseStartOpen:false,
resizableColumns:false,
initialSort:[
{column:"event_time", dir:"desc"},
],
columns: [
{formatter:"responsiveCollapse", width:30, minWidth:30, hozAlign:"center", resizable:false, headerSort:false, responsive:0},
{title: "{{ __('Event') }}", field: "user_event", minWidth:30, width:120, headerSort:false, responsive:0},
{title: "{{ __('User Agent') }}", field: "user_agent", minWidth:30, width:500, headerSort:false, responsive:2},
{title: "{{ __('IP') }}", field: "user_ip", minWidth:30, width:150, headerSort:false, responsive:0},
{title: "{{ __('Location') }}", field: "user_location", minWidth:30, width:100, headerSort:false, responsive:0},
{title: "{{ __('Timestamp') }}", field: "event_time", minWidth:30, width:250, headerSort:false, responsive:0},
],
placeholder:function(){
return this.getHeaderFilters().length ? "No Matching Data" : "{{ __('No log data for user.') }}"; //set placeholder based on if there are currently any header filters
}
});
});
</script>

View file

@ -248,13 +248,14 @@ $app->any('/api[/{params:.*}]', function (
'registrar' => 'id',
'payment_history' => 'registrar_id',
'statement' => 'registrar_id',
'support_tickets' => 'user_id', // Note: this still uses user_id
'support_tickets' => 'user_id', // Continues to use user_id
'users_audit' => 'user_id', // Continues to use user_id
];
if (array_key_exists($tableName, $columnMap)) {
// Use registrarId for tables where 'registrar_id' is the filter
// For 'support_tickets', continue to use userId
return [$columnMap[$tableName] => ($tableName === 'support_tickets' ? $_SESSION['auth_user_id'] : $registrarId)];
// For 'support_tickets' and 'users_audit', use userId
return [$columnMap[$tableName] => (in_array($tableName, ['support_tickets', 'users_audit']) ? $_SESSION['auth_user_id'] : $registrarId)];
}
return ['1' => '0'];

View file

@ -616,7 +616,8 @@ CREATE TABLE IF NOT EXISTS `registry`.`users_audit` (
`user_data` JSON default NULL,
KEY `user_id` (`user_id`),
KEY `user_event` (`user_event`),
KEY `user_ip` (`user_ip`)
KEY `user_ip` (`user_ip`),
FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Panel User Audit';
CREATE TABLE IF NOT EXISTS `registry`.`users_confirmations` (

View file

@ -877,5 +877,6 @@ ALTER TABLE promotion_pricing ADD FOREIGN KEY ("tld_id") REFERENCES domain_tld("
ALTER TABLE premium_domain_pricing ADD FOREIGN KEY ("tld_id") REFERENCES domain_tld("id");
ALTER TABLE premium_domain_pricing ADD FOREIGN KEY ("category_id") REFERENCES premium_domain_categories("category_id");
ALTER TABLE support_tickets ADD FOREIGN KEY ("user_id") REFERENCES users(id);
ALTER TABLE users_audit ADD FOREIGN KEY ("user_id") REFERENCES users(id);
ALTER TABLE support_tickets ADD FOREIGN KEY ("category_id") REFERENCES ticket_categories(id);
ALTER TABLE ticket_responses ADD FOREIGN KEY ("ticket_id") REFERENCES support_tickets(id);