view release on metacpan or search on metacpan
bin/amberdb_cli.pl view on Meta::CPAN
}
elsif ( $curr =~ /^(?:--?)?token=(.*)$/i ) {
$opt_token = $1;
}
elsif ( ( $curr =~ /^--(?:token)$/i || $curr =~ /^-k$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$opt_token = $ARGV[++$arg_idx];
}
elsif ( ( $curr =~ /^--(?:user|username)$/i || $curr =~ /^-u$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$opt_user = $ARGV[++$arg_idx];
}
elsif ( ( $curr =~ /^--(?:pass|password|passwd)$/i || $curr =~ /^-p$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$opt_pass = $ARGV[++$arg_idx];
}
elsif ( ( $curr =~ /^--(?:format)$/i || $curr =~ /^-f$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$opt_format = lc($ARGV[++$arg_idx]);
}
elsif ( ( $curr =~ /^--(?:limit)$/i || $curr =~ /^-l$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$method_args{limit} = parse_value($ARGV[++$arg_idx]);
}
elsif ( ( $curr =~ /^--(?:offset)$/i || $curr =~ /^-o$/i ) && $arg_idx + 1 < @ARGV && $ARGV[$arg_idx + 1] !~ /^-/ ) {
$method_args{offset} = parse_value($ARGV[++$arg_idx]);
bin/amberdb_cli.pl view on Meta::CPAN
$adb->set_datadir($abs);
$explicit_db = 1;
$has_path_updates = 1;
}
elsif ( $k eq 'data' ) {
$method_args{data} = $val;
}
elsif ( $k eq 'user' || $k eq 'username' ) {
$opt_user = $val;
}
elsif ( $k eq 'pass' || $k eq 'password' || $k eq 'passwd' ) {
$opt_pass = $val;
}
elsif ( $k eq 'database' || $k eq 'dbname' ) {
$opt_database = $val;
$adb->{_connect}->{database} = $val;
$adb->clear_cache('ramdisk');
$adb->ramdisk_setup();
}
else {
if ( $k =~ /[-.]/ ) {
bin/amberdb_cli.pl view on Meta::CPAN
# Authenticate and generate token
my $conn_user = 'cli';
my $entered_user = shift @pos_args if @pos_args;
my $conn_pass = $opt_pass // shift @pos_args // '';
my $token = eval {
$adb->connect(
database => $conn_db,
username => $conn_user,
( defined $conn_pass && length $conn_pass ? ( password => $conn_pass ) : () ),
);
};
if ( $@ || !$token ) {
my $err = $@ || $adb->last_error() || "Authentication failed";
$err =~ s/ at .* line \d+.*//s;
die "[AMBERDB_ERROR] $err\n";
}
# Save session with canonical absolute path in ~/.amberdb/session/sess_$token
my $sess_data = {
bin/amberdb_cli.pl view on Meta::CPAN
}
else {
print "Database: " . ($adb->connect('database') || 'unknown') . "\n";
print "=" x 60, "\n";
printf( "%-20s %-15s %-15s\n", "Username", "Role", "Password Set" );
print "-" x 60, "\n";
for my $u (@users) {
printf( "%-20s %-15s %-15s\n",
$u->{username},
$u->{role},
$u->{has_password} ? "Yes (Shadow)" : "No (Passwordless)"
);
}
print "-" x 60, "\n";
}
exit 0;
}
elsif ( $subcmd eq 'add' ) {
my $u = shift @pos_args // $opt_user;
my $p = shift @pos_args // $opt_pass // '';
my $role = shift @pos_args // 'user';
die "[AMBERDB_ERROR] Usage: amberdb user add <username> [password] [role]\n" unless defined $u && length $u;
$adb->user_add( $u, $p, role => $role );
output_result( { status => 'ok', action => 'user_add', username => $u, role => $role }, $opt_format );
exit 0;
}
elsif ( $subcmd eq 'passwd' ) {
my $u = shift @pos_args // $opt_user;
my $p = shift @pos_args // $opt_pass // '';
die "[AMBERDB_ERROR] Usage: amberdb user passwd <username> <new_password>\n" unless defined $u && length $u;
$adb->user_passwd( $u, $p );
output_result( { status => 'ok', action => 'user_passwd', username => $u }, $opt_format );
exit 0;
}
elsif ( $subcmd eq 'del' || $subcmd eq 'delete' ) {
my $u = shift @pos_args // $opt_user;
die "[AMBERDB_ERROR] Usage: amberdb user del <username>\n" unless defined $u && length $u;
$adb->user_del($u);
output_result( { status => 'ok', action => 'user_del', username => $u }, $opt_format );
exit 0;
docs/EN.AmberDB_User-Guide.md view on Meta::CPAN
| `summernote` | Summernote | Rich WYSIWYG HTML visual editor for articles/descriptions. |
| `select` | Dropdown Select | Single-selection dropdown list `<select>`. |
| `checkbox` | Checkbox | Multi-selection checkboxes `<input type="checkbox">` (Use `type => "num"` for Boolean). |
| `radio` | Radio Buttons | Single-selection radio options `<input type="radio">`. |
| `file` | File Upload | Attachment or image file uploader `<input type="file">`. |
| `hidden` | Hidden Field | Hidden form element `<input type="hidden">` (for primary IDs). |
| `email` | Email Input | HTML5 email input field `<input type="email">`. |
| `ascii` | ASCII Field | User/code input box constrained to ASCII charset. |
| `number` | Number Input | Numeric stepper `<input type="number">`. |
| `date` | Date Picker | Interactive date calendar selector `<input type="date">`. |
| `password` | Password Field | Obscured security input `<input type="password">`. |
| `repeat` / `repeats` | Repeater Table | Dynamic sub-row table input with add/remove row buttons (Order items, invoice lines). |
| `search_block` | Search Box | Search-assisted dynamic filter input. |
| `selectbyfind` | SelectByFind | Foreign relation selector populated via dynamic search. |
| `selectbylist` | SelectByList | Multi-item picker component from list. |
#### 9.7.4 Repeating Child Row Blocks (`repeat_start` and `repeat_ids`)
AmberDB natively supports dynamic repeating child rows (e.g. order line items, invoice product rows) horizontally across the flat parent record without relational child tables or `JOIN` operations:
- **Horizontal Row Slicing (`@record[15..$#record]`):** Repeating items, each field index beyond fixed blocks (`$record[15]`, `$record[16]`, `$record[17]`, ...) holds an individual repeating record item (e.g. `[ 101, 'Book', 2, '150.00' ]`).
docs/EN.AmberDB_User-Guide.md view on Meta::CPAN
| :--- | :--- | :--- |
| `none` | No Validation | Field accepts any input without validation (default). |
| `not_null` | Required | Field cannot be null, undefined, or empty string. |
| `unique` | Unique Value | Asserts that no other record in the table contains this value. |
| `email` | Email Format | Validates RFC-compliant email pattern. |
| `telefon` | Phone Number | Validates national/international phone format. |
| `ascii` | ASCII Only | Restricts character set strictly to ASCII [0-127]. |
| `numeric` | Numeric Only | Enforces that value is a valid numeric scalar. |
| `regex` | Regular Expression | Tests against custom regex pattern rule. |
| `auto_num` | Auto Number | Automatically assigns an incrementing numerical sequence. |
| `auto_pass` | Auto Password | Generates random secure password and stores salted hash. |
| `auto_date` | Auto Date | Automatically populates with current system timestamp. |
| `auto_str` | Template String | Pre-populates predefined template text. |
#### 9.7.6 Unique Constraints & Bidirectional String/ID Dictionary (`.unq`)
AmberDB uses `.unq` (Unique & Dictionary) index files (`${table}.unq`) to manage both **uniqueness validation** and **relational string $\leftrightarrow$ numeric ID translation** with $O(1)$ disk lookup speed:
1. **Extension Clarity:** Uses `.unq` for unique constraints and relational string dictionary mappings.
2. **$O(1)$ Duplicate Enforcement (`valid => "unique"`):**
- When `valid => "unique"` is specified (e.g. `username`, `email`, `barcode`), `insert_id` and `modify_id` perform an instantaneous $O(1)$ check on `s:$value` in `${table}.unq`.
docs/TR.AmberDB_Veritabani_Sistemi.md view on Meta::CPAN
| `summernote` | Summernote | Zengin WYSIWYG görsel HTML editörü. |
| `select` | Açılır Menü | Tekli seçim kutusu `<select>`. |
| `checkbox` | Onay Kutusu | Ãoklu seçim onay kutuları `<input type="checkbox">` (Boolean için `type => "num"`). |
| `radio` | Radyo Butonu | Tekli seçim radyo butonları `<input type="radio">`. |
| `file` | Dosya Yükleme | Dosya veya görsel yükleme bileÅeni `<input type="file">`. |
| `hidden` | Gizli Alan | Gizli form elemanı `<input type="hidden">` (birincil ID için). |
| `email` | E-Posta Kutusu | HTML5 e-posta giriŠalanı `<input type="email">`. |
| `ascii` | ASCII Alanı | Yalnızca ASCII karakterlere izin veren metin kutusu. |
| `number` | Sayı Kutusu | Sayısal giriŠkutusu `<input type="number">`. |
| `date` | Tarih Seçici | EtkileÅimli takvim tarih seçici `<input type="date">`. |
| `password` | Åifre Kutusu | Maskeli Åifre giriÅ alanı `<input type="password">`. |
| `repeat` / `repeats` | Tekrarlayan Tablo | Dinamik alt satır ekleme/çıkarma formu (SipariŠkalemleri, fatura satırları). |
| `search_block` | Arama Kutusu | Arama destekli dinamik filtre giriŠalanı. |
| `selectbyfind` | Arayarak Seç | İliÅkili tablodan dinamik arama ile seçim bileÅeni. |
| `selectbylist` | Listeden Seç | Listeden çoklu seçim bileÅeni. |
#### 9.7.4 Tekrarlayan Alt Satır Blokları (`repeat_start` ve `repeat_ids`)
AmberDB, iliÅkisel alt tablolara (child table) ve `JOIN` sorgularına ihtiyaç duymadan, ana kayıt içerisine gömülü tekrarlayan dinamik alt satırları (örn. sipariÅ kalemleri, fatura ürün satırları) yatay düzende doÄrudan destekler:
- **Yatay Dizi Yapısı (`@record[15..$#record]`):** Tekrarlayan alt satırlar, sabit bloklardan sonra gelen her bir indeks (`$record[15]`, `$record[16]`, `$record[17]`, ...), baÄımsız birer alt satır kaydıdır (örn: `[ 101, 'Kitap', 2, 150.00 ...
lib/AmberDB.pm view on Meta::CPAN
}
$self->{_cache} ||= {};
$self->{_auth} ||= {};
$self->{_pid} ||= {};
$self->{_date} = {};
# Normalize connect parameters
$self->{_connect}->{database} //= delete $self->{database} // delete $self->{dbase} // delete $self->{dbname} // delete $self->{db};
$self->{_connect}->{username} //= delete $self->{username} // delete $self->{user} // delete $self->{_cfg}->{user} // "user_system";
$self->{_connect}->{password} //= delete $self->{password} // delete $self->{pass} // delete $self->{passwd};
$self->{_connect}->{token} = '';
$self->{_connect}->{user} = '';
$self->{_connect}->{pass} = '';
$self->{_connect}->{dbase} = '';
$self->{_connect}->{dbname} = '';
$self->{_cfg}->{user} ||= $self->{_connect}->{username};
$self->{_cfg}->{language} ||= "gb";
if ( exists $self->{_cfg}->{simple} ) {
$self->{_cfg}->{use_simple} //= delete $self->{_cfg}->{simple};
lib/AmberDB/Base.pm view on Meta::CPAN
delete $self->{_table}->{$tbl}->{_path}
if ref( $self->{_table}->{$tbl} ) eq 'HASH';
}
}
}
# ============================================================================
# AUTHENTICATION & PASSWORD CRYPTOGRAPHY (Salted SHA-256)
# ============================================================================
# my $shadow = $adb->hash_password($password, [$salt]);
# ---------------------------------------------------------------------
sub hash_password {
my ( $self, $password, $salt ) = @_;
return '' unless defined $password && length $password;
# 16-character cryptographically secure hex salt
$salt //= sprintf( "%08x%08x", int( rand(0xFFFFFFFF) ), int( rand(0xFFFFFFFF) ) );
my $hash = sha256_hex( $salt . $password );
return "sha256\$$salt\$$hash";
}
# my $ok = $adb->verify_password($password, $stored_shadow);
# ---------------------------------------------------------------------
sub verify_password {
my ( $self, $password, $stored_shadow ) = @_;
# Passwordless allowed if stored shadow is empty or undef
return 1 if !defined $stored_shadow || !length $stored_shadow;
$password //= '';
my ( $algo, $salt, $expected ) = split /\$/, $stored_shadow;
return 0 unless defined $algo && defined $salt && defined $expected;
if ( $algo eq 'sha256' ) {
my $computed = sha256_hex( $salt . $password );
return lc($computed) eq lc($expected) ? 1 : 0;
}
return $stored_shadow eq $password ? 1 : 0;
}
# ============================================================================
# DATABASE CONNECTION & CLIENT AUTH PROFILE (connect.pl)
# ============================================================================
sub _connect_file {
my ($self) = @_;
my $config_dir = $self->path('config_dir') || ( ( $self->path('dbase_dir') || "." ) . "/config" );
return "$config_dir/connect.pl";
lib/AmberDB/Base.pm view on Meta::CPAN
sub _load_connect_config {
my ($self) = @_;
my $file = $self->_connect_file();
return undef unless -f $file;
my $target = ( $file =~ m{^(?:\./|[a-zA-Z]:|/|\\)} ) ? $file : "./$file";
my $data = do $target;
return undef unless ref($data) eq 'HASH';
# Auto-upgrade: if any user entry or top-level entry has plain 'password', hash into 'shadow' and delete 'password'
my $modified = 0;
if ( defined $data->{password} && length $data->{password} ) {
$data->{shadow} = $self->hash_password( delete $data->{password} );
$modified = 1;
}
if ( $data->{users} && ref( $data->{users} ) eq 'HASH' ) {
for my $u ( keys %{ $data->{users} } ) {
my $u_info = $data->{users}->{$u};
next unless ref($u_info) eq 'HASH';
if ( defined $u_info->{password} && length $u_info->{password} ) {
$u_info->{shadow} = $self->hash_password( delete $u_info->{password} );
$modified = 1;
}
}
}
if ($modified) {
$self->_save_connect_config($data);
}
return $data;
}
lib/AmberDB/Base.pm view on Meta::CPAN
# my $val_or_token = $adb->connect([$key | %args]);
# ---------------------------------------------------------------------
sub connect {
my ( $self, @args ) = @_;
# 1. Single scalar argument: attribute getter -> $adb->connect('database')
if ( @args == 1 && !ref( $args[0] ) ) {
my $k = $args[0];
$k = 'database' if $k eq 'dbase' || $k eq 'dbname';
$k = 'username' if $k eq 'user' || $k eq 'usr';
$k = 'password' if $k eq 'pass' || $k eq 'passwd';
return $self->{_connect}->{$k} // '';
}
# If called with no args and already connected with valid token, return active token
if ( !@args && defined $self->{_connect}->{token} && length $self->{_connect}->{token} ) {
return $self->{_connect}->{token};
}
# 2. Connection / Authentication Action -> $adb->connect(%args) or $adb->connect()
my %opts = ( @args == 1 && ref( $args[0] ) eq 'HASH' ) ? %{ $args[0] } : @args;
my $token = delete $opts{token} // delete $opts{tok};
my $database = delete $opts{database} // delete $opts{dbase} // delete $opts{dbname} // delete $opts{db} // $self->{_connect}->{database};
my $username = delete $opts{username} // delete $opts{user} // delete $opts{usr} // $self->{_connect}->{username};
my $password = delete $opts{password} // delete $opts{pass} // delete $opts{passwd} // $self->{_connect}->{password};
# Sub-case A: Resume session via token
if ( defined $token && length $token ) {
my $sess = $self->_load_session($token);
if ( $sess && ref($sess) eq 'HASH' ) {
$self->{_connect}->{token} = $token;
$self->{_connect}->{database} = $sess->{connect}->{database} // $sess->{database} // $self->{_connect}->{database} // '';
$self->{_connect}->{username} = $sess->{connect}->{username} // $sess->{username} // $self->{_connect}->{username} // 'user_system';
$self->{_connect}->{password} = $sess->{connect}->{password} // $sess->{password} // '';
$self->{_cfg}->{user} = $self->{_connect}->{username};
return $token;
}
return undef;
}
# Sub-case B: Authenticate credentials & generate session token
my $connect_cfg = $self->_load_connect_config();
# Database default if not specified in connect
lib/AmberDB/Base.pm view on Meta::CPAN
if ( $connect_cfg && $connect_cfg->{database} ) {
$database = $connect_cfg->{database};
}
else {
$database = 'amberdb';
}
}
$username //= 'cli';
$password //= '';
# Bootstrap connect.pl on first connection if missing or empty
if ( !$connect_cfg || !ref($connect_cfg->{users}) || !keys %{ $connect_cfg->{users} } ) {
$connect_cfg = {
database => $database,
created_at => time(),
users => {
$username => {
shadow => ( defined $password && length $password ) ? $self->hash_password($password) : '',
role => 'admin',
},
web => {
shadow => '',
role => 'web',
},
cli => {
shadow => '',
role => 'cli',
},
lib/AmberDB/Base.pm view on Meta::CPAN
croak "[AMBERDB_AUTH_ERROR] Database mismatch: requested '$database' but store is '$connect_cfg->{database}'";
}
$database = $connect_cfg->{database} if $connect_cfg->{database};
# Check user
my $user_info = $connect_cfg->{users}->{$username};
if ( !$user_info ) {
croak "[AMBERDB_AUTH_ERROR] User '$username' not authorized for database '$database'";
}
# Auto-upgrade plain text password in connect.pl to shadow if present
if ( exists $user_info->{password} && defined $user_info->{password} && length $user_info->{password} ) {
my $plain = delete $user_info->{password};
$user_info->{shadow} = $self->hash_password($plain);
$self->_save_connect_config($connect_cfg);
}
# Password check:
# If both shadow and password are empty/missing: passwordless access allowed (local trust / backwards compat)
my $shadow = $user_info->{shadow} // '';
if ( length $shadow ) {
if ( !defined $password || !length $password ) {
croak "[AMBERDB_AUTH_ERROR] Password required for user '$username'";
}
if ( !$self->verify_password( $password, $shadow ) ) {
croak "[AMBERDB_AUTH_ERROR] Invalid password for user '$username'";
}
}
}
# Authentication successful: issue token
my $new_token = $self->generate_token();
$self->{_connect}->{database} = $database;
$self->{_connect}->{username} = $username;
$self->{_connect}->{password} = $password;
$self->{_connect}->{token} = $new_token;
$self->{_cfg}->{user} = $username;
# Save session
my $sess_data = {
token => $new_token,
created_at => time(),
updated_at => time(),
connect => {
database => $database,
lib/AmberDB/Base.pm view on Meta::CPAN
return $new_token;
}
sub disconnect {
my ( $self, $token ) = @_;
$token //= $self->{_connect}->{token};
if ( defined $token && length $token ) {
$self->_delete_session($token);
}
$self->{_connect}->{token} = '';
$self->{_connect}->{password} = '';
return 1;
}
# ============================================================================
# USER MANAGEMENT METHODS (connect.pl API)
# ============================================================================
sub user_add {
my ( $self, $username, $password, %opts ) = @_;
croak "Username required" unless defined $username && length $username;
my $cfg = $self->_load_connect_config() // { database => $self->connect('database') || 'amberdb', users => {} };
$cfg->{users} //= {};
my $shadow = ( defined $password && length $password ) ? $self->hash_password($password) : '';
$cfg->{users}->{$username} = {
shadow => $shadow,
role => $opts{role} // 'user',
created_at => time(),
};
$self->_save_connect_config($cfg);
return 1;
}
sub user_passwd {
my ( $self, $username, $password ) = @_;
croak "Username required" unless defined $username && length $username;
my $cfg = $self->_load_connect_config();
croak "Database connection config not found" unless $cfg && $cfg->{users}->{$username};
$cfg->{users}->{$username}->{shadow} = ( defined $password && length $password ) ? $self->hash_password($password) : '';
$cfg->{users}->{$username}->{updated_at} = time();
$self->_save_connect_config($cfg);
return 1;
}
sub user_del {
my ( $self, $username ) = @_;
croak "Username required" unless defined $username && length $username;
my $cfg = $self->_load_connect_config();
lib/AmberDB/Base.pm view on Meta::CPAN
my ($self) = @_;
my $cfg = $self->_load_connect_config();
return () unless $cfg && ref($cfg->{users}) eq 'HASH';
my @list;
for my $u ( sort keys %{ $cfg->{users} } ) {
my $ud = $cfg->{users}->{$u};
push @list, {
username => $u,
role => $ud->{role} // 'user',
has_password => ( defined $ud->{shadow} && length $ud->{shadow} ) ? 1 : 0,
created_at => $ud->{created_at} // 0,
};
}
return @list;
}
sub user_verify {
my ( $self, $username, $password ) = @_;
return 0 unless defined $username && length $username;
my $cfg = $self->_load_connect_config();
return 0 unless $cfg && ref($cfg->{users}) eq 'HASH';
my $ud = $cfg->{users}->{$username};
return 0 unless $ud;
my $shadow = $ud->{shadow} // '';
return 1 if !length($shadow); # Passwordless allowed
return 0 unless defined $password && length $password;
return $self->verify_password( $password, $shadow );
}
# my ($count, @records) = $adb->recs_cutting($offset, $limit, @records);
# ------------------------------------------------
sub recs_cutting {
my ( $self, $offset, $limit, @records ) = @_;
$offset ||= 0;
$limit ||= 0;
$offset = 0 if $offset < 0;
t/amberdb_connect_lifecycle.t view on Meta::CPAN
$ENV{AMBERDB_TEST_RAMDISK} = '0';
my $tmp = tempdir( CLEANUP => 1 );
my $db_dir = "$tmp/testdb";
make_path($db_dir);
# 1. Cryptographic Password Hashing & Verification
{
my $adb = AmberDB->new( path => { dbase_dir => $db_dir } );
my $plain = 'MyS3cretP@ss';
my $shadow = $adb->hash_password($plain);
like( $shadow, qr/^sha256\$[0-9a-fA-F]{16}\$[0-9a-fA-F]{64}$/, "hash_password generates salted sha256 shadow format" );
ok( $adb->verify_password( $plain, $shadow ), "verify_password matches correct password" );
ok( !$adb->verify_password( "WrongPass", $shadow ), "verify_password rejects incorrect password" );
ok( !$adb->verify_password( "", $shadow ), "verify_password rejects empty password when shadow is set" );
# Passwordless behavior (backwards compatibility)
ok( $adb->verify_password( "", "" ), "verify_password accepts empty password when shadow is empty (passwordless)" );
ok( $adb->verify_password( "any", "" ), "verify_password accepts any password when shadow is empty" );
ok( $adb->verify_password( "", undef ), "verify_password accepts empty password when shadow is undef" );
}
# 2. Auto-Upgrade Plain-Text Passwords to Salted Shadow in connect.pl
{
my $conf_dir = "$db_dir/config";
make_path($conf_dir);
my $conn_file = "$conf_dir/connect.pl";
my $initial_content = <<'PERL';
return {
database => 'testdb',
users => {
legacy_admin => {
password => 'admin_plain_pass',
role => 'admin',
created_at => 1234567890,
},
passwordless_web => {
shadow => '',
role => 'web',
created_at => 1234567890,
},
},
};
PERL
open my $fh, '>', $conn_file or die $!;
print $fh $initial_content;
close $fh;
my $adb = AmberDB->new( path => { dbase_dir => $db_dir } );
my $cfg = $adb->_load_connect_config();
is( $cfg->{users}->{legacy_admin}->{password}, undef, "Plain-text password removed from in-memory config" );
like( $cfg->{users}->{legacy_admin}->{shadow}, qr/^sha256\$/, "Plain-text password upgraded to shadow in memory" );
# Check that connect.pl on disk was updated
my $disk_cfg = do $conn_file;
is( $disk_cfg->{users}->{legacy_admin}->{password}, undef, "Plain-text password deleted from connect.pl file on disk" );
like( $disk_cfg->{users}->{legacy_admin}->{shadow}, qr/^sha256\$/, "Salted shadow saved to connect.pl file on disk" );
ok( $adb->verify_password( 'admin_plain_pass', $disk_cfg->{users}->{legacy_admin}->{shadow} ), "Upgraded shadow verifies against original password" );
}
# 3. Connection Lifecycle, Authentication & Token Generation
{
my $adb = AmberDB->new(
path => { dbase_dir => $db_dir },
connect => {
database => 'testdb',
username => 'legacy_admin',
password => 'admin_plain_pass',
}
);
is( $adb->connect('database'), 'testdb', "Connected database attribute getter" );
is( $adb->connect('username'), 'legacy_admin', "Connected username attribute getter" );
is( $adb->config('user'), 'legacy_admin', "config('user') aligned with connect username" );
my $token = $adb->connect();
like( $token, qr/^\d{4}$/, "connect() returns 4-digit session token" );
is( $adb->connect('token'), $token, "connect('token') matches returned session token" );
t/amberdb_connect_lifecycle.t view on Meta::CPAN
my $sess_file = $adb->session_file($token);
ok( -f $sess_file, "Session file created in database session directory" );
# Resuming session with another AmberDB instance
my $adb2 = AmberDB->new( path => { dbase_dir => $db_dir } );
my $resumed = $adb2->connect( token => $token );
is( $resumed, $token, "Second instance resumes session via token" );
is( $adb2->connect('username'), 'legacy_admin', "Resumed instance has authenticated user" );
is( $adb2->connect('database'), 'testdb', "Resumed instance has correct database" );
# Connecting with passwordless user
my $token_web = $adb2->connect( username => 'passwordless_web', password => '' );
like( $token_web, qr/^\d{4}$/, "Passwordless user connects without password" );
# Connecting with invalid password fails
eval {
$adb2->connect( username => 'legacy_admin', password => 'wrong_pass' );
};
ok( $@, "Authentication fails with incorrect password" );
# Disconnect
ok( $adb->disconnect($token), "disconnect() successfully clears session" );
ok( ! -f $sess_file, "Session file deleted upon disconnect" );
}
# 4. User Management API (user_add, user_passwd, user_list, user_del)
{
my $adb = AmberDB->new( path => { dbase_dir => $db_dir } );
# user_add
ok( $adb->user_add( 'new_operator', 'operator123', role => 'cli' ), "user_add adds new user" );
ok( $adb->user_verify( 'new_operator', 'operator123' ), "user_verify confirms new user credentials" );
ok( !$adb->user_verify( 'new_operator', 'badpass' ), "user_verify rejects bad password" );
# user_list
my @users = $adb->user_list();
my ($op) = grep { $_->{username} eq 'new_operator' } @users;
ok( $op, "user_list includes new user" );
is( $op->{role}, 'cli', "user_list provides user role" );
is( $op->{has_password}, 1, "user_list indicates password is set" );
ok( !exists $op->{shadow}, "user_list does not expose shadow hash" );
# user_passwd
ok( $adb->user_passwd( 'new_operator', 'new_pass_456' ), "user_passwd updates password" );
ok( !$adb->user_verify( 'new_operator', 'operator123' ), "Old password no longer works" );
ok( $adb->user_verify( 'new_operator', 'new_pass_456' ), "New password verified successfully" );
# user_del
ok( $adb->user_del('new_operator'), "user_del removes user" );
my @after_del = $adb->user_list();
my ($del_op) = grep { $_->{username} eq 'new_operator' } @after_del;
ok( !$del_op, "User removed from user_list after user_del" );
}