Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Discussions related to customizing hooks. Hooks are documented at http://bigprof.com/appgini/help/advanced-topics/hooks/
Post Reply
fgazza
Veteran Member
Posts:210
Joined: 2019-04-30 17:37

Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by fgazza » 2025-09-17 18:32

In my app generated with appgini, I'd like to create a group that can create new users, assign them to specific groups (possibly limiting the groups to which a user can be assigned), and, if necessary, change the password of users in those specific groups. How can I achieve this function in the simplest and most secure way possible?

I tried writing this code, but something isn't working: I see the appgini layout with links, header, and footer, but the content page is completely blank.
I believe the page view permissions are working correctly, because if I'm not logged in as the Admins or allprivileges group, I see the message that I'm not logged in to the site.

Here is my user_manager.php page:

Code: Select all

<?php
define('PREPEND_PATH', '../');
include_once(PREPEND_PATH . 'lib.php');
include_once(PREPEND_PATH . 'incCommon.php');
include_once(PREPEND_PATH . 'header.php');

// 💡 RIGA DA RIMUOVERE: AppGini non ne ha bisogno
// include_once('__global.php');

// Inizializza l’array error options
$eo = [];

// 🔐 Accesso consentito solo ai gruppi specifici
$allowedGroups = ['allprivileges', 'Admins'];
$targetGroup   = 'beneficiari';

// **Il problema era qui:** la verifica dei permessi deve includere la stampa dell'intero form.
if (!in_array(getLoggedGroup(), $allowedGroups)) {
    echo "<div class='alert alert-danger'>Accesso non autorizzato.</div>";
    include_once(PREPEND_PATH . 'footer.php');
    exit;
}

// 🔍 Recupera utenti del gruppo beneficiari
$filteredUsers = [];
$gid = sqlValue("SELECT groupID FROM membership_groups WHERE name='{$targetGroup}'", $eo);
if ($gid) {
    $res = sql("SELECT memberID FROM membership_users WHERE groupID='{$gid}'", $eo);
    while ($row = db_fetch_assoc($res)) {
        $filteredUsers[] = $row['memberID'];
    }
}

// 📥 Creazione utente (forzato al gruppo beneficiari)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_user'])) {
    $username = makeSafe($_POST['username']);
    $password = $_POST['password'];
    $confirm  = $_POST['confirm_password'];

    // 🔎 Controllo username duplicato
    $exists = sqlValue("SELECT COUNT(*) FROM membership_users WHERE memberID='{$username}'", $eo);

    if ($password !== $confirm) {
        echo "<div class='alert alert-warning'>Le password non coincidono.</div>";
    } elseif ($exists > 0) {
        echo "<div class='alert alert-danger'>Errore: lo username <b>{$username}</b> esiste già.</div>";
    } elseif (!$gid) {
        echo "<div class='alert alert-danger'>Errore: gruppo beneficiari non trovato.</div>";
    } else {
        $userCreated = sql("INSERT INTO membership_users 
            SET 
                memberID = '{$username}', 
                passMD5 = '" . md5($password) . "', 
                groupID = '{$gid}', 
                signupDate = NOW(), 
                isApproved = 1", $eo);

        if ($userCreated) {
            echo "<div class='alert alert-success'>Utente <b>{$username}</b> creato con successo e assegnato al gruppo {$targetGroup}!</div>";
        } else {
            echo "<div class='alert alert-danger'>Errore nella creazione utente.</div>";
        }
    }
}

// 🔄 Cambio password (solo utenti beneficiari)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $targetUser      = makeSafe($_POST['target_user']);
    $newPassword     = $_POST['new_password'];
    $confirmPassword = $_POST['confirm_password'];

    if ($newPassword !== $confirmPassword) {
        echo "<div class='alert alert-warning'>Le password non coincidono.</div>";
    } elseif (!in_array($targetUser, $filteredUsers)) {
        echo "<div class='alert alert-danger'>Utente non autorizzato o non trovato.</div>";
    } else {
        sql("UPDATE membership_users 
            SET passMD5 = '" . md5($newPassword) . "' 
            WHERE memberID = '{$targetUser}'", $eo);

        echo "<div class='alert alert-success'>Password aggiornata per {$targetUser}.</div>";
    }
}
?>

<div class="container mt-5">
    <h2>Gestione Utenti (solo gruppo beneficiari)</h2>

    <form method="POST">
        <input type="hidden" name="create_user" value="1">
        <div class="form-group">
            <label>Username</label>
            <input name="username" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input name="password" type="password" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Conferma Password</label>
            <input name="confirm_password" type="password" class="form-control" required>
        </div>
        <button class="btn btn-primary mt-3">Crea Utente</button>
    </form>

    <hr class="my-5">
    <h3>Cambia Password Utente (beneficiari)</h3>
    <form method="POST">
        <input type="hidden" name="change_password" value="1">
        <div class="form-group">
            <label>Seleziona Utente</label>
            <select name="target_user" class="form-control" required>
                <?php foreach ($filteredUsers as $user): ?>
                    <option value="<?= $user ?>"><?= $user ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Nuova Password</label>
            <input name="new_password" type="password" class="form-control" required>
        </div>
        <div class="form-group">
            <label>Conferma Password</label>
            <input name="confirm_password" type="password" class="form-control" required>
        </div>
        <button class="btn btn-warning mt-3">Aggiorna Password</button>
    </form>
</div>

<?php include_once(PREPEND_PATH . 'footer.php'); ?>

I hope someone can help me.

Thanks!

User avatar
onoehring
AppGini Super Hero
AppGini Super Hero
Posts:1464
Joined: 2019-05-21 22:42
Location: Germany
Contact:

Re: Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by onoehring » 2025-09-18 05:45

Hi fgazza,

this is the code for a custom page I built - maybe it helps.
Make sure, you have the check for credentials in your code.

Note: This sits in the root directory, the page itself is in hooks (hooks/platzuebersicht.php)

this code is the ecomo_platzuebersicht_view.php code

Code: Select all

<?php	
	session_start();
	$currDir = dirname(__FILE__);
	include("$currDir/defaultLang.php");
	include("$currDir/language.php");
	include("$currDir/lib.php");

	include_once("$currDir/header.php");

	/* grant access to all users who have access to the ..... table */
	$user_can_access = get_sql_from('ecomo_platzuebersicht');
	if(!$user_can_access) exit(error_message('Access denied!', false));

        include("hooks/platzuebersicht.php");

        if(!$footerCode){
		include_once("$currDir/footer.php"); 
	}else{
		ob_start(); include_once("$currDir/footer.php"); $dFooter=ob_get_contents(); ob_end_clean();
		echo str_replace('<%%FOOTER%%>', $dFooter, $footerCode);
	}
	?>

This is the ecomo_platzuebersicht.php code

Code: Select all

<?php	
$currDir = dirname(__FILE__);
require("$currDir/ecomo_platzuebersicht_view.php");	
?>
HOWEVER
Also, maybe it's easier to create your own user management. Create a tablestructure the same as the original and let AG create the HTML. Assign permissions to ADMINs and allprivileges to view/add/update/delete this table. Set the "usergroup" field to "beneficiari" (hidden, or simply assigned by code later.
Upon save update your members tables with the people from your custom page.


Olaf

saymaad
AppGini Super Hero
AppGini Super Hero
Posts:131
Joined: 2024-06-03 16:17

Re: Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by saymaad » 2025-09-19 09:52

fgazza wrote: ↑
2025-09-17 18:32
I hope someone can help me.
To start with, this needs to go: getLoggedGroup(), try replacing the code:

Code: Select all

if (!in_array(getLoggedGroup(), $allowedGroups)) {
    echo "<div class='alert alert-danger'>Accesso non autorizzato.</div>";
    include_once(PREPEND_PATH . 'footer.php');
    exit;
}
with:

Code: Select all

$mi = getMemberInfo();
if(!in_array($mi['group'], array('allprivileges', 'Admins'))){
    echo error_message($Translation['tableAccessDenied']);
    include_once(PREPEND_PATH . 'footer.php');
    exit;
}
Also, the issue with these AI generated codes is that they add additionaly parameter $eo to function sqlValue() which it is not expecting and can create issues with some interpreters.

With these changes you'll have your page display the username, password, confirm password fields and buttons.

fgazza
Veteran Member
Posts:210
Joined: 2019-04-30 17:37

Re: Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by fgazza » 2025-09-20 16:32

Thanks for your replies. I created these two codes, but they don't work: I get the error: "Cannot save new record."

file name: user_password_beneficiari.php

Code: Select all

<?php

function user_password_beneficiari_before_insert(&$data, $memberInfo, &$args) {
    return crea_o_aggiorna_utente($data, $args);
}

function user_password_beneficiari_before_update(&$data, $memberInfo, &$args) {
    return crea_o_aggiorna_utente($data, $args, true);
}

function crea_o_aggiorna_utente(&$data, &$args, $update = false) {
    $gruppoConsentito = 'beneficiari';
    $username = makeSafe($data['username']);
    $email = makeSafe($data['email']);
    $group = makeSafe($data['gruppo']);
    $attivo = ($data['attivo'] ? 1 : 0);
    $password = $data['password'];

    // ✅ Controllo gruppo
    if (strtolower($group) !== strtolower($gruppoConsentito)) {
        $args['message'] = "Gruppo non autorizzato.";
        return false;
    }

    // ✅ Validazione email: accetto vuoto, ma se valorizzato deve essere corretto
    if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $args['message'] = "Formato email non valido.";
        return false;
    }

    // ✅ Validazione password se presente
    if(!empty($password) && !password_valida($password, $username)) {
        $args['message'] = "La password non soddisfa i requisiti di sicurezza.";
        return false;
    }

    // ✅ Recupero groupID
    $resGroup = sql("SELECT groupID FROM membership_groups WHERE LOWER(name) = LOWER('{$group}')");
    if($rowGroup = db_fetch_assoc($resGroup)) {
        $groupID = $rowGroup['groupID'];
    } else {
        $args['message'] = "Gruppo non trovato.";
        return false;
    }

    // ✅ Controllo se utente esiste
    $res = sql("SELECT memberID FROM membership_users WHERE LOWER(memberID) = LOWER('{$username}')");

    if(db_num_rows($res)) {
        // 🔄 Aggiorna utente
        sql("UPDATE membership_users 
             SET email = '{$email}', 
                 groupID = {$groupID}, 
                 isApproved = {$attivo}, 
                 isBanned = " . ($attivo ? 0 : 1) . " 
             WHERE memberID = '{$username}'");

        if(!empty($password)) {
            sql("UPDATE membership_users 
                 SET passMD5 = '" . md5($password) . "' 
                 WHERE memberID = '{$username}'");
        }
    } else {
        // ➕ Crea nuovo utente
        sql("INSERT INTO membership_users 
             (memberID, passMD5, email, groupID, isApproved, isBanned) 
             VALUES (
                '{$username}',
                '" . md5($password) . "',
                '{$email}',
                {$groupID},
                {$attivo},
                " . ($attivo ? 0 : 1) . "
             )");
    }

    return true;
}

function password_valida($pwd, $username){
    if(strlen($pwd) < 8) return false;
    if(!preg_match('/[A-Z]/', $pwd)) return false;
    if(!preg_match('/[a-z]/', $pwd)) return false;
    if(!preg_match('/[0-9]/', $pwd)) return false;
    if(!preg_match('/[\W]/', $pwd)) return false;

    // Controllo somiglianza con username
    $pwdLower = strtolower($pwd);
    $userLower = strtolower($username);
    if($pwdLower === $userLower) return false;
    if(similar_text($pwdLower, $userLower, $percent) && $percent > 70) return false;

    return true;
}
file name user_password_beneficiari-dv.js

Code: Select all

$j(function(){
    // ✅ Limita il campo gruppo al solo valore "beneficiari"
    var gruppoConsentito = 'beneficiari';
    $j('#gruppo').find('option').each(function(){
        if($j(this).val().toLowerCase() !== gruppoConsentito){
            $j(this).remove();
        }
    });

    // ✅ Contenitore messaggio errore password
    if($j('#pwd-error').length === 0){
        $j('#password').after('<div id="pwd-error" style="color:red; font-weight:bold; margin-top:5px;"></div>');
    }

    // ✅ Contenitore messaggio errore email
    if($j('#email-error').length === 0){
        $j('#email').after('<div id="email-error" style="color:red; font-weight:bold; margin-top:5px;"></div>');
    }

    // 🔐 Validazione password
    $j('#password').on('blur', function(){
        var pwd = $j(this).val();
        var username = $j('#username').val();
        var msg = '';

        if(pwd.length < 8){
            msg += '• Minimo 8 caratteri<br>';
        }
        if(!/[A-Z]/.test(pwd)){
            msg += '• Almeno una lettera maiuscola<br>';
        }
        if(!/[a-z]/.test(pwd)){
            msg += '• Almeno una lettera minuscola<br>';
        }
        if(!/[0-9]/.test(pwd)){
            msg += '• Almeno un numero<br>';
        }
        if(!/[!@#$%^&*(),.?":{}|<>]/.test(pwd)){
            msg += '• Almeno un carattere speciale<br>';
        }

        var pwdLower = pwd.toLowerCase();
        var userLower = username.toLowerCase();
        var similarity = 0;

        for(var i = 0; i < Math.min(pwdLower.length, userLower.length); i++){
            if(pwdLower[i] === userLower[i]) similarity++;
        }
        var percent = (similarity / userLower.length) * 100;
        if(pwdLower === userLower || percent > 70){
            msg += '• Non deve essere uguale o troppo simile allo username<br>';
        }

        if(msg){
            $j('#pwd-error').html(msg);
            $j('#password').addClass('invalid-password');
        } else {
            $j('#pwd-error').html('');
            $j('#password').removeClass('invalid-password');
        }
    });

    // 📧 Validazione email
    $j('#email').on('blur', function(){
        var email = $j(this).val().trim();
        var msg = '';

        if(email.length > 0){
            var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if(!emailRegex.test(email)){
                msg = '• Inserisci un indirizzo email valido';
            }
        }

        if(msg){
            $j('#email-error').html(msg);
            $j('#email').addClass('invalid-email');
        } else {
            $j('#email-error').html('');
            $j('#email').removeClass('invalid-email');
        }
    });

    // 🚫 Blocca salvataggio se errori
    $j('#insert, #update').on('click', function(e){
        if($j('#password').hasClass('invalid-password') || $j('#email').hasClass('invalid-email')){
            e.preventDefault();
            if($j('#password').hasClass('invalid-password')){
                $j('#password').focus();
            } else if($j('#email').hasClass('invalid-email')){
                $j('#email').focus();
            }
        }
    });
});
Hope someone can help me.

Thank you very much

fgazza
Veteran Member
Posts:210
Joined: 2019-04-30 17:37

Re: Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by fgazza » 2025-09-22 10:08

I'm finally starting to get some working code (so far I've solved the part of creating new users by forcing them to be assigned to the group I want.

But now I'm concerned about the security of the code because I've read that MD5 authentication is very vulnerable.

Below is my code in the hope that someone can give me some guidance on how to secure it.

user_password_beneficiari.php

Code: Select all

<?php
    // For help on using hooks, please refer to https://bigprof.com/appgini/help/advanced-topics/hooks/

    function user_password_beneficiari_init(&$options, $memberInfo, &$args) {
        return TRUE;
    }

    function user_password_beneficiari_header($contentType, $memberInfo, &$args) {
        $header='';

        switch($contentType) {
            case 'tableview':
                $header='';
                break;

            case 'detailview':
                $header='';
                break;

            case 'tableview+detailview':
                $header='';
                break;

            case 'print-tableview':
                $header='';
                break;

            case 'print-detailview':
                $header='';
                break;

            case 'filters':
                $header='';
                break;
        }

        return $header;
    }

    function user_password_beneficiari_footer($contentType, $memberInfo, &$args) {
        $footer='';

        switch($contentType) {
            case 'tableview':
                $footer='';
                break;

            case 'detailview':
                $footer='';
                break;

            case 'tableview+detailview':
                $footer='';
                break;

            case 'print-tableview':
                $footer='';
                break;

            case 'print-detailview':
                $footer='';
                break;

            case 'filters':
                $footer='';
                break;
        }

        return $footer;
    }

    function user_password_beneficiari_before_insert(&$data, $memberInfo, &$args) {
        // Imposta automaticamente il gruppo come "beneficiari"
        $data['gruppo'] = 'beneficiari';
        return TRUE;
    }

    function user_password_beneficiari_after_insert($data, $memberInfo, &$args) {
        $eo = [];
        $targetGroup = 'beneficiari';
        $gid = sqlValue("SELECT groupID FROM membership_groups WHERE name='{$targetGroup}'", $eo);

        if (!$gid) return FALSE;

        $username = makeSafe($data['username']);
        $password = $data['password'];
        $email    = makeSafe($data['email']);
        $attivo   = strtolower(trim($data['attivo'])) === 'si' ? 1 : 0;

        $exists = sqlValue("SELECT COUNT(*) FROM membership_users WHERE memberID='{$username}'", $eo);
        if ($exists > 0) return FALSE;

        sql("INSERT INTO membership_users SET 
            memberID = '{$username}', 
            passMD5 = '" . md5($password) . "', 
            email = '{$email}', 
            groupID = '{$gid}', 
            signupDate = NOW(), 
            isApproved = {$attivo}", $eo);

        return TRUE;
    }

    function user_password_beneficiari_before_update(&$data, $memberInfo, &$args) {
        return TRUE;
    }

    function user_password_beneficiari_after_update($data, $memberInfo, &$args) {
        return TRUE;
    }

    function user_password_beneficiari_before_delete($selectedID, &$skipChecks, $memberInfo, &$args) {
        return TRUE;
    }

    function user_password_beneficiari_after_delete($selectedID, $memberInfo, &$args) {
    }

    function user_password_beneficiari_dv($selectedID, $memberInfo, &$html, &$args) {
    }

    function user_password_beneficiari_csv($query, $memberInfo, &$args) {
        return $query;
    }

    function user_password_beneficiari_batch_actions(&$args) {
        return [];
    }
user_password_beneficiari-dv.js

Code: Select all

$j(function(){
    $j('#password').on('input', function(){
        const pwd = $j(this).val();
        if(pwd.length < 6){
            this.setCustomValidity('La password deve contenere almeno 6 caratteri.');
        } else {
            this.setCustomValidity('');
        }
    });

    // Imposta il campo gruppo come readonly e predefinito
    $j('#gruppo').val('beneficiari').prop('readonly', true);
});
Besides, it's not clear to me whether, beyond the code I put in the hook file, there is any additional native protection in AppGini that makes everything more secure.

In fact, I read that: "Passwords should be hashed with password_hash(), which uses modern algorithms like bcrypt or argon2, and automatically includes a salt.

Furthermore, interpolating variables directly in the query ('{$username}', {$attivo}, etc.) is vulnerable to SQL injection, unless AppGini handles the escaping internally (which can vary)."

User avatar
onoehring
AppGini Super Hero
AppGini Super Hero
Posts:1464
Joined: 2019-05-21 22:42
Location: Germany
Contact:

Re: Create a non-admin group that create users and assign them to "beneficiari" group via my user_manager.php page

Post by onoehring » 2025-09-22 10:34

Hi,

quick checking, I do not see any problems sticking out (if someone else - enlighten us please. always eager to learn).

Concerning this
In fact, I read that: "Passwords should be hashed with password_hash(), which uses modern algorithms like bcrypt or argon2, and automatically includes a salt.
I think you do not need to worry. You are putting the PW as md5 into the database. As soon as the user logs in the first time, AG will make it a stronger PW - which from my perspective is totally fine (most likely users will login quite soon). AG creates a stronger, non md5 PW (currently I do not remember the details).

For variables, instead of taking them directly, you can use the makesafe function (does not work for arrays if I remember correct - but as $attivo is a simple variable it will work for this; same for $password which you take from the $data array). I suggest relying on implemented functions as they have been carefully designed and are "tested" by all AG users all the time.

Olaf

Post Reply