Added ability to create more users from CP

This commit is contained in:
Pinga 2024-11-26 16:07:14 +02:00
parent 3c86dc19ad
commit 63b544c915
8 changed files with 345 additions and 6 deletions

View file

@ -43,9 +43,14 @@ class ProfileController extends Controller
} else {
$status = "Unknown";
}
$roles = $_SESSION['auth_roles'];
if ($roles == 0) {
$role = "Admin";
$role = "Administrator";
} else if ($roles == 4) {
$role = "Registrar";
} else if ($roles == 6) {
$role = "Registrar Assistant";
} else {
$role = "Unknown";
}

View file

@ -6,6 +6,7 @@ use App\Models\User;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Container\ContainerInterface;
use Respect\Validation\Validator as v;
class UsersController extends Controller
{
@ -19,4 +20,156 @@ class UsersController extends Controller
$users = $userModel->getAllUsers();
return view($response,'admin/users/listUsers.twig', compact('users'));
}
public function createUser(Request $request, Response $response)
{
// Registrars can not create new users, then need to ask the registry
if ($_SESSION["auth_roles"] != 0) {
return $response->withHeader('Location', '/dashboard')->withStatus(302);
}
if ($request->getMethod() === 'POST') {
// Retrieve POST data
$data = $request->getParsedBody();
$db = $this->container->get('db');
$email = $data['email'] ?? null;
$username = $data['username'] ?? null;
$password = $data['password'] ?? null;
$password_confirmation = $data['password_confirmation'] ?? null;
$status = $data['status'] ?? null;
$verified = $data['verified'] ?? null;
$role = $data['role'] ?? null;
$registrar_id = $data['registrar_id'] ?? null;
// Define validation rules
$validators = [
'email' => v::email()->notEmpty()->setName('Email'),
'username' => v::regex('/^[a-zA-Z0-9_-]+$/')->length(3, 20)->setName('Username'),
'password' => v::stringType()->notEmpty()->length(6, 255)->setName('Password'),
'password_confirmation' => v::equals($data['password'] ?? '')->setName('Password Confirmation'),
'status' => v::in(['active', 'inactive'])->setName('Status'),
'role' => v::in(['admin', 'registrar'])->setName('Role'),
];
// Add registrar_id validation if role is registrar
if (($data['role'] ?? '') === 'registrar') {
$validators['registrar_id'] = v::numericVal()->notEmpty()->setName('Registrar ID');
}
// Validate data
$errors = [];
foreach ($validators as $field => $validator) {
try {
$validator->assert($data[$field] ?? null);
} catch (\Respect\Validation\Exceptions\ValidationException $exception) {
$errors[$field] = $exception->getMessages(); // Collect all error messages
}
}
// If errors exist, return with errors
if (!empty($errors)) {
// Flatten the errors array into a string
$errorMessages = [];
foreach ($errors as $field => $fieldErrors) {
$fieldMessages = implode(', ', $fieldErrors); // Concatenate messages for the field
$errorMessages[] = ucfirst($field) . ': ' . $fieldMessages; // Prefix with field name
}
$errorString = implode('; ', $errorMessages); // Join all fields' errors
// Add the flattened error string as a flash message
$this->container->get('flash')->addMessage('error', 'Error: ' . $errorString);
// Redirect back to the form
return $response->withHeader('Location', '/user/create')->withStatus(302);
}
$registrars = $db->select("SELECT id, clid, name FROM registrar");
if ($_SESSION["auth_roles"] != 0) {
$registrar = true;
} else {
$registrar = null;
}
if ($email) {
if ($registrar_id) {
$db->beginTransaction();
$password_hashed = password_hash($password, PASSWORD_ARGON2ID, ['memory_cost' => 1024 * 128, 'time_cost' => 6, 'threads' => 4]);
try {
$db->insert(
'users',
[
'email' => $email,
'password' => $password_hashed,
'username' => $username,
'verified' => $verified,
'roles_mask' => 6,
'registered' => \time()
]
);
$user_id = $db->getLastInsertId();
$db->insert(
'registrar_users',
[
'registrar_id' => $registrar_id,
'user_id' => $user_id
]
);
$db->commit();
} catch (Exception $e) {
$db->rollBack();
$this->container->get('flash')->addMessage('error', 'Database failure: ' . $e->getMessage());
return $response->withHeader('Location', '/user/create')->withStatus(302);
}
$this->container->get('flash')->addMessage('success', 'User ' . $email . ' has been created successfully');
return $response->withHeader('Location', '/users')->withStatus(302);
} else {
$db->beginTransaction();
$password_hashed = password_hash($password, PASSWORD_ARGON2ID, ['memory_cost' => 1024 * 128, 'time_cost' => 6, 'threads' => 4]);
try {
$db->insert(
'users',
[
'email' => $email,
'password' => $password_hashed,
'username' => $username,
'verified' => $verified,
'roles_mask' => 0,
'registered' => \time()
]
);
$db->commit();
} catch (Exception $e) {
$db->rollBack();
$this->container->get('flash')->addMessage('error', 'Database failure: ' . $e->getMessage());
return $response->withHeader('Location', '/user/create')->withStatus(302);
}
$this->container->get('flash')->addMessage('success', 'User ' . $email . ' has been created successfully');
return $response->withHeader('Location', '/users')->withStatus(302);
}
}
}
$db = $this->container->get('db');
$registrars = $db->select("SELECT id, clid, name FROM registrar");
if ($_SESSION["auth_roles"] != 0) {
$registrar = true;
} else {
$registrar = null;
}
// Default view for GET requests or if POST data is not set
return view($response,'admin/users/createUser.twig', [
'registrars' => $registrars,
'registrar' => $registrar,
]);
}
}

View file

@ -65,7 +65,7 @@
<div class="datagrid-item">
<div class="datagrid-title">{{ __('Role') }}</div>
<div class="datagrid-content">
<span class="status status-{% if role == 'Admin' %}primary{% else %}green{% endif %}">
<span class="status status-{% if role == 'Administrator' %}purple{% elseif role == 'Registrar' %}indigo{% elseif role == 'Registrar Assistant' %}azure{% endif %}">
{{ role }}
</span>
</div>

View file

@ -0,0 +1,162 @@
{% extends "layouts/app.twig" %}
{% block title %}{{ __('Create New User') }}{% endblock %}
{% block content %}
<div class="page-wrapper">
<!-- Page header -->
<div class="page-header d-print-none">
<div class="container-xl">
<div class="row g-2 align-items-center">
<div class="col">
<!-- Page pre-title -->
<div class="page-pretitle">
{{ __('Overview') }}
</div>
<h2 class="page-title">
{{ __('Create New User') }}
</h2>
</div>
</div>
</div>
</div>
<!-- Page body -->
<div class="page-body">
<div class="container-xl">
<div class="col-12">
{% include 'partials/flash.twig' %}
<form method="post" action="/user/create" id="create-user-form">
{{ csrf.field | raw }}
<div class="card">
<div class="card-body">
<div class="row">
<!-- Email -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Email') }}</label>
<input type="email" class="form-control" name="email" placeholder="{{ __('Enter email') }}" required>
</div>
</div>
<!-- Username -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Username') }}</label>
<input type="text" class="form-control" name="username" placeholder="{{ __('Enter username') }}" required>
</div>
</div>
</div>
<div class="row">
<!-- Password -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Password') }}</label>
<input type="password" class="form-control" name="password" placeholder="{{ __('Enter password') }}" required>
</div>
</div>
<!-- Confirm Password -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Confirm Password') }}</label>
<input type="password" class="form-control" name="password_confirmation" placeholder="{{ __('Confirm password') }}" required>
</div>
</div>
</div>
<div class="row">
<!-- Status -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Status') }}</label>
<select class="form-select" name="status" required>
<option value="active">{{ __('Active') }}</option>
<option value="inactive">{{ __('Inactive') }}</option>
</select>
</div>
</div>
<!-- Verified -->
<div class="col-md-6">
<div class="mb-3">
<label class="form-label required">{{ __('Verified') }}</label>
<select class="form-select" name="verified" required>
<option value="1">{{ __('Yes') }}</option>
<option value="0">{{ __('No') }}</option>
</select>
</div>
</div>
</div>
<!-- Role -->
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label">Role</label>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="role-toggle" name="role" value="admin">
<label class="form-check-label" for="role-toggle" id="role-label">Registrar</label>
</div>
<!-- Hidden input to ensure "registrar" is sent when the toggle is off -->
<input type="hidden" name="role" id="hidden-role" value="registrar">
</div>
</div>
</div>
<!-- Registrar-specific fields -->
<div id="registrar-fields" style="display: none;">
<div class="mb-3">
<label class="form-label">Registrar Association</label>
<select class="form-select" name="registrar_id">
<option value="" disabled selected>Select registrar</option>
{% for registrar in registrars %}
<option value="{{ registrar.id }}">{{ registrar.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="card-footer text-end">
<div class="d-flex">
<button type="submit" class="btn btn-primary">{{ __('Create User') }}</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
{% include 'partials/footer.twig' %}
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const roleToggle = document.getElementById("role-toggle");
const hiddenRoleInput = document.getElementById("hidden-role");
const registrarFields = document.getElementById("registrar-fields");
const roleLabel = document.getElementById("role-label");
// Function to toggle registrar fields, role value, and label text
function updateRole() {
if (roleToggle.checked) {
// Admin role selected
hiddenRoleInput.value = "admin";
roleLabel.textContent = "Admin"; // Update label to Admin
registrarFields.style.display = "none"; // Hide registrar-specific fields
} else {
// Registrar role selected
hiddenRoleInput.value = "registrar";
roleLabel.textContent = "Registrar"; // Update label to Registrar
registrarFields.style.display = "block"; // Show registrar-specific fields
}
}
// Attach event listener to the toggle
roleToggle.addEventListener("change", updateRole);
// Set initial state on page load
updateRole();
});
</script>
{% endblock %}

View file

@ -17,6 +17,18 @@
{{ __('List Users') }}
</h2>
</div>
<!-- Page title actions -->
<div class="col-auto ms-auto d-print-none">
<div class="btn-list">
<a href="{{route('createUser')}}" class="btn btn-primary d-none d-sm-inline-block">
<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"/><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>
{{ __('Create New User') }}
</a>
<a href="{{route('createUser')}}" class="btn btn-primary d-sm-none btn-icon" aria-label="{{ __('Create New User') }}">
<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"/><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>
</a>
</div>
</div>
</div>
</div>
</div>
@ -24,6 +36,7 @@
<div class="page-body">
<div class="container-xl">
<div class="col-12">
{% include 'partials/flash.twig' %}
<div class="card">
<div class="card-body py-3">
<div class="d-flex">

View file

@ -150,7 +150,7 @@
</a>
</div>
</li>
{% if roles == 0 %}<li {{ is_current_url('registrars') or is_current_url('listUsers') or is_current_url('registrarcreate') or 'registrar' in currentUri ? 'class="nav-item dropdown active"' : 'class="nav-item dropdown"' }}>
{% if roles == 0 %}<li {{ is_current_url('registrars') or is_current_url('listUsers') or is_current_url('createUser') or is_current_url('registrarcreate') or 'registrar' in currentUri ? 'class="nav-item dropdown active"' : 'class="nav-item dropdown"' }}>
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown" data-bs-auto-close="outside" role="button" aria-expanded="false">
<span class="nav-link-icon d-md-none d-lg-inline-block"><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><path d="M12 13a3 3 0 1 0 0 -6a3 3 0 0 0 0 6z"></path><path d="M12 3c7.2 0 9 1.8 9 9s-1.8 9 -9 9s-9 -1.8 -9 -9s1.8 -9 9 -9z"></path><path d="M6 20.05v-.05a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v.05"></path></svg>
</span>
@ -169,6 +169,9 @@
<a class="dropdown-item" href="{{route('listUsers')}}">
{{ __('List Users') }}
</a>
<a class="dropdown-item" href="{{route('createUser')}}">
{{ __('Create User') }}
</a>
</div>
</li>{% endif %}
<li {{ is_current_url('deposit') or is_current_url('transactions') or is_current_url('overview') or is_current_url('invoices') or is_current_url('successStripe') or 'invoice' in currentUri ? 'class="nav-item dropdown active"' : 'class="nav-item dropdown"' }}>

View file

@ -26,6 +26,8 @@
return '<span class="status status-purple">Administrator</span>';
} else if (value === 4) {
return '<span class="status status-indigo">Registrar</span>';
} else if (value === 6) {
return '<span class="status status-azure">Registrar Assistant</span>';
}
return value; // If the value is neither 0 nor 4, return it as is
}

View file

@ -99,6 +99,7 @@ $app->group('', function ($route) {
$route->get('/leave_impersonation', RegistrarsController::class . ':leave_impersonation')->setName('leave_impersonation');
$route->get('/users', UsersController::class .':listUsers')->setName('listUsers');
$route->map(['GET', 'POST'], '/user/create', UsersController::class . ':createUser')->setName('createUser');
$route->get('/epphistory', LogsController::class .':view')->setName('epphistory');
$route->get('/poll', LogsController::class .':poll')->setName('poll');