diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 3a9251f..0000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,3 +0,0 @@ -# These are supported funding model platforms - -github: byjg diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index fc5f29a..08505e1 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -18,12 +18,13 @@ jobs: strategy: matrix: php-version: + - "8.6" - "8.5" - "8.4" - "8.3" steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v7 - run: composer install - run: composer test @@ -34,12 +35,12 @@ jobs: # for github/codeql-action/upload-sarif to upload SARIF results security-events: write container: - image: byjg/php:8.4-cli + image: byjg/php:8.5-cli options: --user root --privileged steps: - name: Git checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Composer run: composer install @@ -47,7 +48,7 @@ jobs: - name: Psalm # Note: Ignoring error code 2, which just signals that some # flaws were found, not that Psalm itself failed to run. - run: ./vendor/bin/psalm + run: ./vendor/bin/psalm.phar --show-info=true --report=psalm-results.sarif || [ $? = 2 ] diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md new file mode 100644 index 0000000..2a719ed --- /dev/null +++ b/CHANGELOG-7.0.md @@ -0,0 +1,142 @@ +# Changelog - Version 7.0 + +> **Status: in development.** This document tracks changes landing on the `7.0` branch. +> Nothing here is released yet, and the contents may still change. + +## Overview + +Version 7.0 upgrades the underlying persistence stack to `byjg/micro-orm` 7.0 and +`byjg/anydataset-db` 7.0. `UsersService`, `UsersRepository`, `UserPropertiesRepository`, models +and mapper interfaces keep the same signatures as 6.x; the only API change is the renaming of the +`UserField` enum cases to PascalCase (see below). + +Since 6.0 the library was already wired exclusively through `DatabaseExecutor` — the API that +became mandatory in anydataset-db 7.0 — so apart from that rename, the library code changed only +to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes). + +## Breaking Changes + +### Dependencies + +| Package | 6.x | 7.0 | +|---|---|---| +| `byjg/micro-orm` | `^6.0` | `^7.0` | +| `byjg/anydataset-db` (transitive) | `^6.0` | `^7.0` | + +### Removed driver query methods (via anydataset-db 7.0) + +The query methods deprecated on the drivers since anydataset-db 6.0 no longer exist +(`$dbDriver->execute()`, `getIterator()`, `getScalar()`, `executeAndGetId()`, `getAllFields()`). +If your application still calls them on the driver instance it passes to AuthUser, migrate to: + +```php +execute($sql, $params); +``` + +The recommended wiring is unchanged and keeps working as-is: + +```php +value`, `from()`, `tryFrom()` and stored data are not affected; only code that +names a case (or reads `->name`) has to be updated. + +| Enum | Before (6.x) | After (7.0) | +|---|---|---| +| `UserField` | `Created_at`, `uUpdated_at`, `Deleted_at` | `CreatedAt`, `UpdatedAt`, `DeletedAt` | + +Not a plain change of casing: `UserField::uUpdated_at` is now `UserField::UpdatedAt`. + +## Bug Fixes + +- `UserPropertiesRepository` converted the user id for its queries without the database at + hand (`getUpdateFunctionValue($userid, null)`), so a UUID user id was always written as + `X'…'`. With byjg/micro-orm 7.0, which writes a UUID in the syntax of each database, the + repository now passes its executor, and the queries work on PostgreSQL (a native `uuid`) + and SQL Server too. +- `SessionContext::registerLogin($userId, $data)` lost `$data`: it stored the cache item in + place of the array, so `getSessionData()` never found the values passed at login. + +## Migration from 6.x + +1. Update the composer constraint: + +```json +{ + "require": { + "byjg/authuser": "^7.0" + } +} +``` + +2. If your application already wires AuthUser through `DatabaseExecutor::using()` (the documented + pattern since 6.0), no code changes are required. +3. If you still call the removed query methods directly on the `DbDriverInterface` instance, + migrate those calls to `DatabaseExecutor` (see table in the + [anydataset-db 7.0 changelog](https://github.com/byjg/anydataset-db/blob/master/CHANGELOG-7.0.md)). + +## Requirements + +- PHP 8.3, 8.4, 8.5 and 8.6 are now supported: `"php": ">=8.3 <8.7"`. + The previous `<8.6` upper bound excluded PHP 8.6, since `<8.6` is exclusive. + +### ByJG dependencies + +- `byjg/cache-engine` is now `^7.0`. +- `byjg/jwt-wrapper` is now `^7.0`. +- `byjg/micro-orm` is now `^7.0`. + +While 7.0 is unreleased these resolve to `7.0.x-dev` from each component's +`7.0` branch, via `minimum-stability: dev` with `prefer-stable: true`. + +## Toolchain + +- PHPUnit updated to `^12.5`. +- Psalm is installed as `psalm/phar` instead of `vimeo/psalm`. + + `vimeo/psalm` lists the PHP versions it supports and no published release includes + 8.6, so as a dev dependency it made `composer install` fail on the 8.6 build job + before any test ran. `psalm/phar` requires only `php ^8.2` and bundles its own + dependencies, so it installs on every PHP version in the matrix and cannot conflict + with the project's. Psalm itself still refuses to *run* on 8.6, which is why the + Psalm job uses 8.5. `composer psalm` runs it. + +- PHPUnit 13 is deliberately **not** used. It requires PHP `>=8.4.1`, breaking the + 8.3 floor. + +## Continuous Integration + +- The build matrix now includes PHP 8.6. +- The Psalm job runs on PHP 8.5. + +## Housekeeping + +- `phpunit.xml.dist` renamed to `phpunit.xml`. +- The root `example.php` script was removed; see the [Examples](docs/examples.md) page. diff --git a/README.md b/README.md index db477b9..cefeb80 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ A simple and customizable library for user authentication in PHP applications us [![Sponsor](https://img.shields.io/badge/Sponsor-%23ea4aaa?logo=githubsponsors&logoColor=white&labelColor=0d1117)](https://github.com/sponsors/byjg) [![Build Status](https://github.com/byjg/php-authuser/actions/workflows/phpunit.yml/badge.svg?branch=master)](https://github.com/byjg/php-authuser/actions/workflows/phpunit.yml) -[![Opensource ByJG](https://img.shields.io/badge/opensource-byjg-success.svg)](http://opensource.byjg.com) +[![Opensource ByJG](https://img.shields.io/badge/opensource-byjg-success.svg)](https://opensource.byjg.com) +[![Install MCP Server](https://img.shields.io/badge/Install-MCP_Server-8A2BE2?logo=modelcontextprotocol&logoColor=white)](https://opensource.byjg.com/docs/ai/mcpserver-byjg-docs/) [![GitHub source](https://img.shields.io/badge/Github-source-informational?logo=github)](https://github.com/byjg/php-authuser/) [![GitHub license](https://img.shields.io/github/license/byjg/php-authuser.svg)](https://opensource.byjg.com/license) [![GitHub release](https://img.shields.io/github/release/byjg/php-authuser.svg)](https://github.com/byjg/php-authuser/releases/) @@ -32,9 +33,7 @@ This class can persist user data into session (or file, memcache, etc.) between - [Mappers](docs/mappers.md) - [Examples](docs/examples.md) -## Quick Start - -### Installation +## Installation ```bash composer require byjg/authuser @@ -91,14 +90,6 @@ See [Getting Started](docs/getting-started.md) for a complete introduction and [ - **Field Mappers** - Transform data during read/write. See [Mappers](docs/mappers.md) - **Extensible Model** - Add custom fields easily. See [Custom Fields](docs/custom-fields.md) -## Running Tests - -Because this project uses PHP Session you need to run the unit test the following manner: - -```bash -./vendor/bin/phpunit --stderr -``` - ## Architecture ```text @@ -128,14 +119,13 @@ Because this project uses PHP Session you need to run the unit test the followin This project is licensed under the MIT License - see the [LICENSE](https://github.com/byjg/php-authuser/blob/master/LICENSE) file for details. -## Dependencies +## Running Tests -```mermaid -flowchart TD - byjg/authuser --> byjg/micro-orm - byjg/authuser --> byjg/cache-engine - byjg/authuser --> byjg/jwt-wrapper +Because this project uses PHP Session you need to run the unit test the following manner: + +```bash +./vendor/bin/phpunit --stderr ``` ---- -[Open source ByJG](http://opensource.byjg.com) +[Open source ByJG](https://opensource.byjg.com) diff --git a/composer.json b/composer.json index 9fd678e..c483679 100644 --- a/composer.json +++ b/composer.json @@ -14,18 +14,18 @@ "minimum-stability": "dev", "prefer-stable": true, "require": { - "php": ">=8.3 <8.6", - "byjg/micro-orm": "^6.0", - "byjg/cache-engine": "^6.0", - "byjg/jwt-wrapper": "^6.0" + "php": ">=8.3 <8.7", + "byjg/micro-orm": "^7.0", + "byjg/cache-engine": "^7.0", + "byjg/jwt-wrapper": "^7.0" }, "require-dev": { - "phpunit/phpunit": "^10.5|^11.5", - "vimeo/psalm": "^5.9|^6.13" + "phpunit/phpunit": "^12.5", + "psalm/phar": "^6.16" }, "scripts": { "test": "vendor/bin/phpunit", - "psalm": "vendor/bin/psalm --threads=1" + "psalm": "vendor/bin/psalm.phar" }, "license": "MIT" } diff --git a/docs/authentication.md b/docs/authentication.md index 352aa04..8123fd7 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -22,7 +22,7 @@ if ($user !== null) { ``` :::tip Login Field -The `isValidUser()` method uses the login field configured in your `UsersService` constructor. Pass either `LoginField::Email` or `LoginField::Username` when creating the service. +The `isValidUser()` method uses the login field configured in your `UsersService` constructor. Pass `LoginField::Email`, `LoginField::Username` or `LoginField::EmailOrUsername` when creating the service. ::: `LoginField` lives in the `ByJG\Authenticate\Enum` namespace. @@ -75,7 +75,7 @@ if ($userToken !== null) { } ``` -Need to include standard user columns (name, email, etc.) automatically? Pass the optional seventh argument with `User` enum values or strings. See [JWT Tokens](jwt-tokens.md#copy-user-fields-automatically) for details. +Need to include standard user columns (name, email, etc.) automatically? Pass the optional seventh argument with `UserField` enum values or strings. See [JWT Tokens](jwt-tokens.md#copy-user-fields-automatically) for details. :::tip UserToken Return Type Both `createAuthToken()` and `createInsecureAuthToken()` return a `UserToken` object with three properties: diff --git a/docs/custom-fields.md b/docs/custom-fields.md index 845b30d..73d0506 100644 --- a/docs/custom-fields.md +++ b/docs/custom-fields.md @@ -41,11 +41,11 @@ class CustomUserModel extends UserModel string $email = "", string $username = "", string $password = "", - string $admin = "no", + string $role = "", string $phone = "", string $department = "" ) { - parent::__construct($name, $email, $username, $password, $admin); + parent::__construct($name, $email, $username, $password, $role); $this->phone = $phone; $this->department = $department; } @@ -186,6 +186,7 @@ You can mark fields as read-only to prevent updates using the `ReadOnlyMapper`: ```php 'Method not allowed'], 405); } @@ -324,20 +326,19 @@ try { 'last_ip' => $_SERVER['REMOTE_ADDR'] ], [ + 'login' => $username, 'ip' => $_SERVER['REMOTE_ADDR'] ] ); - if ($userToken === null) { - jsonResponse(['error' => 'Invalid credentials'], 401); - } - jsonResponse([ 'success' => true, 'token' => $userToken->token, 'expires_in' => 3600 ]); +} catch (UserNotFoundException $e) { + jsonResponse(['error' => 'Invalid credentials'], 401); } catch (Exception $e) { jsonResponse(['error' => $e->getMessage()], 500); } @@ -363,7 +364,7 @@ $token = $matches[1]; try { // Decode token to get username $jwtData = $jwtWrapper->extractData($token); - $username = $jwtData->data['login'] ?? null; + $username = $jwtData->data->login ?? null; if (!$username) { jsonResponse(['error' => 'Invalid token'], 401); @@ -638,7 +639,7 @@ $refreshToken = $matches[1]; try { // Decode refresh token $jwtData = $refreshWrapper->extractData($refreshToken); - $userId = $jwtData->data['userid'] ?? null; + $userId = $jwtData->data->userid ?? null; if (!$userId) { jsonResponse(['error' => 'Invalid refresh token'], 401); @@ -652,7 +653,7 @@ try { } // Verify refresh token is valid - $userToken = $users->isValidToken($user->getEmail(), $refreshWrapper, $refreshToken); + $userToken = $users->isValidToken($users->getLoginValue($user), $refreshWrapper, $refreshToken); if ($userToken === null) { jsonResponse(['error' => 'Invalid or expired refresh token'], 401); diff --git a/docs/jwt-tokens.md b/docs/jwt-tokens.md index 22cd7f5..b3ad3e7 100644 --- a/docs/jwt-tokens.md +++ b/docs/jwt-tokens.md @@ -45,23 +45,28 @@ Use your API hostname (or any issuer string you want to validate) as the first a ```php createAuthToken( - 'johndoe', // Login (username or email) - 'password123', // Password - $jwtWrapper, // JWT wrapper instance - 3600 // Expires in 1 hour (seconds) -); +use ByJG\Authenticate\Exception\UserNotFoundException; + +try { + $userToken = $users->createAuthToken( + 'johndoe', // Login (username or email) + 'password123', // Password + $jwtWrapper, // JWT wrapper instance + 3600 // Expires in 1 hour (seconds) + ); -if ($userToken !== null) { // Return token to client echo json_encode(['token' => $userToken->token]); -} else { +} catch (UserNotFoundException $e) { // Authentication failed http_response_code(401); echo json_encode(['error' => 'Invalid credentials']); } ``` +`createAuthToken()` throws `UserNotFoundException` when the login or the password is invalid. +`createInsecureAuthToken()` throws the same exception when the login does not exist. + ### Token with Custom Data You can include additional data in the JWT payload: @@ -106,7 +111,7 @@ $userToken = $users->createAuthToken( ### Copy User Fields Automatically -Instead of manually adding every field to `$updateTokenInfo`, pass a seventh argument with an array of `User` enum values or string property names. The service will read the corresponding getters (or custom properties) from the `UserModel` and copy them into the token payload. +Instead of manually adding every field to `$updateTokenInfo`, pass a seventh argument with an array of `UserField` enum values or string property names. The service will read the corresponding getters (or custom properties) from the `UserModel` and copy them into the token payload. ```php createAuthToken( In the example above, the token payload receives the user's `name`, `email`, and the value returned by `$user->get('department')` automatically. +When the argument is omitted, it defaults to `[UserField::Userid, UserField::Name, UserField::Role]`. An entry written as `'field' => 'default'` uses `'default'` when the user has no value for that field. + ### Creating Tokens Without Password Validation The `createInsecureAuthToken()` method creates JWT tokens without validating the user's password. This is useful for: @@ -271,6 +278,7 @@ try { 'last_ip' => $_SERVER['REMOTE_ADDR'] ], [ + 'login' => $input['username'], 'ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ] @@ -317,7 +325,7 @@ $token = $matches[1]; // Extract username from token (you need to decode it first) try { $jwtData = $jwtWrapper->extractData($token); - $username = $jwtData->data['login'] ?? null; + $username = $jwtData->data->login ?? null; if (!$username) { throw new Exception('Invalid token structure'); @@ -363,7 +371,7 @@ if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) { try { $jwtData = $jwtWrapper->extractData($token); - $username = $jwtData->data['login'] ?? null; + $username = $jwtData->data->login ?? null; $user = $users->getByLogin($username); if ($user !== null) { diff --git a/docs/mappers.md b/docs/mappers.md index f881e3f..0041a6d 100644 --- a/docs/mappers.md +++ b/docs/mappers.md @@ -51,11 +51,12 @@ This package ships with a few mapper utilities that complement the ones provided use ByJG\Authenticate\MapperFunctions\UserIdGeneratorMapper; use ByJG\Authenticate\Model\UserModel; use ByJG\MicroOrm\Attributes\FieldAttribute; + use ByJG\MicroOrm\Literal\Literal; class UsernameAsIdModel extends UserModel { #[FieldAttribute(primaryKey: true, updateFunction: UserIdGeneratorMapper::class)] - protected string|int|null $userid = null; + protected string|int|Literal|null $userid = null; } ``` - **ClosureMapper** – wraps anonymous functions so they implement `MapperFunctionInterface`. This is handy when you need a small transformation in place. @@ -154,24 +155,21 @@ protected array $preferences = []; ## Entity Processors -Where mappers transform *fields*, entity processors transform the entire model before it is inserted or updated. They implement `EntityProcessorInterface` and can be attached through `TableAttribute` or by calling `setBeforeInsert()` / `setBeforeUpdate()` on the repository. +Where mappers transform *fields*, entity processors transform the entire row before it is inserted or updated. They implement `EntityProcessorInterface` and can be attached through `TableAttribute` or by calling `setBeforeInsert()` / `setBeforeUpdate()` on the repository. + +`process()` receives the row as an array keyed by database column name and must return the (modified) array. ```php getUsername(); + $username = (string) ($instance['username'] ?? ''); if (strlen($username) < 3) { throw new \InvalidArgumentException('Username must have at least 3 characters.'); } @@ -179,6 +177,8 @@ class UsernameValidationProcessor implements EntityProcessorInterface if (!preg_match('/^[A-Za-z0-9_]+$/', $username)) { throw new \InvalidArgumentException('Username can only contain letters, numbers, and underscores.'); } + + return $instance; } } @@ -188,12 +188,12 @@ class AuditProcessor implements EntityProcessorInterface { } - public function process(mixed $instance): void + public function process(array $instance): array { - if ($instance instanceof UserModel) { - $instance->set('modified_by', (string) $this->actorId); - $instance->set('modified_at', date('Y-m-d H:i:s')); - } + // Assumes the users table has the modified_by and modified_at columns + $instance['modified_by'] = $this->actorId; + $instance['modified_at'] = date('Y-m-d H:i:s'); + return $instance; } } ``` diff --git a/docs/session-context.md b/docs/session-context.md index 697c4fe..db608a6 100644 --- a/docs/session-context.md +++ b/docs/session-context.md @@ -67,7 +67,8 @@ $sessionContext = new SessionContext($cachePool, $uniquePrefix); // After validating user credentials $sessionContext->registerLogin($userId); ``` -Call `setSessionData()` after `registerLogin()` if you need to store extra session metadata (e.g., IP address, login time). +To store extra session metadata (e.g., IP address, login time), pass it as the second argument, +`registerLogin($userId, ['ip' => $ip])`, or call `setSessionData()` after `registerLogin()`. ### Check Authentication Status @@ -125,9 +126,11 @@ $cart = $sessionContext->getSessionData('shopping_cart'); $lastPage = $sessionContext->getSessionData('last_page'); ``` -Returns `false` if: -- The user is not authenticated -- The key doesn't exist +Returns `false` if the key doesn't exist. + +:::warning Authentication Required +`getSessionData()` also requires an authenticated user and throws a `NotAuthenticatedException` otherwise. +::: ### Session Data Lifecycle diff --git a/docs/user-management.md b/docs/user-management.md index c100d4e..786f558 100644 --- a/docs/user-management.md +++ b/docs/user-management.md @@ -83,13 +83,15 @@ $user = $users->getByUsername('johndoe'); ### Get User by Login Field -The login field is determined by the `UsersService` constructor (either email or username): +The login field is determined by the `UsersService` constructor (email, username, or `LoginField::EmailOrUsername` for either): ```php getByLogin('johndoe'); ``` +`getLoginField()` returns the configured `LoginField`, and `getLoginValue($user)` returns the value of that field for a given user (the username first, then the email, for `LoginField::EmailOrUsername`). + ### Using Custom Queries For advanced queries, use the repository directly: @@ -105,11 +107,13 @@ $usersRepo = $users->getUsersRepository(); $query = Query::getInstance() ->table('users') ->where('email = :email', ['email' => 'john@example.com']) - ->where('admin = :admin', ['admin' => 'yes']); + ->where('role = :role', ['role' => 'admin']); $results = $usersRepo->getRepository()->getByQuery($query); ``` +`UsersRepository` also provides `getAll()` and `getByField($field, $value)`. These return the raw models: unlike the `UsersService` methods, they do not load the user properties. + ## Updating Users ```php diff --git a/docs/user-properties.md b/docs/user-properties.md index e721387..a3397ff 100644 --- a/docs/user-properties.md +++ b/docs/user-properties.md @@ -228,15 +228,11 @@ Properties are stored in a separate table (default: `users_property`): | Column | Description | |------------|--------------------------| -| customid | Property ID | +| id | Property ID | | userid | User ID (foreign key) | | name | Property name | | value | Property value | -### XML/AnyDataset Storage - -Properties are stored as fields within each user's record, with arrays used for multiple values. - ## Next Steps - [User Management](user-management.md) - Basic user operations diff --git a/example.php b/example.php deleted file mode 100644 index e1657e9..0000000 --- a/example.php +++ /dev/null @@ -1,52 +0,0 @@ -addUser('Some User Full Name', 'someuser', 'someuser@someemail.com', '12345'); -echo "User created with ID: " . $user->getUserid() . "\n"; - -// Validate user credentials -$authenticatedUser = $users->isValidUser('someuser', '12345'); -var_dump($authenticatedUser); - -if ($authenticatedUser !== null) { - // Create session context - $session = new SessionContext(Factory::createSessionPool()); - - // Register login - $session->registerLogin($authenticatedUser->getUserid()); - - echo "Authenticated: " . ($session->isAuthenticated() ? 'yes' : 'no') . "\n"; - echo "User ID: " . $session->userInfo() . "\n"; - - // Store some session data - $session->setSessionData('login_time', time()); - - // Get the user info - $currentUser = $users->getById($session->userInfo()); - echo "Welcome, " . $currentUser->getName() . "\n"; -} - - diff --git a/phpunit.xml.dist b/phpunit.xml similarity index 98% rename from phpunit.xml.dist rename to phpunit.xml index 90e6448..b41e556 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml @@ -20,7 +20,7 @@ and open the template in the editor. failOnDeprecation="true" failOnPhpunitDeprecation="true" stopOnFailure="false" - xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"> + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/12.5/phpunit.xsd"> diff --git a/psalm.xml b/psalm.xml index 037de8b..37a8931 100644 --- a/psalm.xml +++ b/psalm.xml @@ -7,7 +7,7 @@ cacheDirectory="/tmp/psalm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" - xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" + xsi:schemaLocation="https://getpsalm.org/schema/config https://raw.githubusercontent.com/vimeo/psalm/6.x/config.xsd" > diff --git a/src/Enum/UserField.php b/src/Enum/UserField.php index efc5e79..199322d 100644 --- a/src/Enum/UserField.php +++ b/src/Enum/UserField.php @@ -10,8 +10,8 @@ enum UserField: string case Email = 'email'; case Username = 'username'; case Password = 'password'; - case Created_at = 'created_at'; - case uUpdated_at = 'updated_at'; - case Deleted_at = 'deleted_at'; + case CreatedAt = 'created_at'; + case UpdatedAt = 'updated_at'; + case DeletedAt = 'deleted_at'; case Role = 'role'; } diff --git a/src/Repository/UserPropertiesRepository.php b/src/Repository/UserPropertiesRepository.php index 38be2ad..4c37bee 100644 --- a/src/Repository/UserPropertiesRepository.php +++ b/src/Repository/UserPropertiesRepository.php @@ -85,7 +85,7 @@ public function getByUserId(string|Literal|int $userid): array $userIdField = $userIdMapping->getFieldName(); $query = Query::getInstance() ->table($this->mapper->getTable()) - ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null)]); + ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null, $this->repository->getExecutor())]); return $this->repository->getByQuery($query); } @@ -116,7 +116,7 @@ public function getByUserIdAndName(string|Literal|int $userid, string $propertyN $query = Query::getInstance() ->table($this->mapper->getTable()) - ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null)]) + ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null, $this->repository->getExecutor())]) ->where("$nameField = :name", ['name' => $propertyName]); return $this->repository->getByQuery($query); @@ -142,7 +142,7 @@ public function deleteByUserId(string|Literal|int $userid): void $deleteQuery = DeleteQuery::getInstance() ->table($this->mapper->getTable()) - ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null)]); + ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null, $this->repository->getExecutor())]); $this->repository->deleteByQuery($deleteQuery); } @@ -174,7 +174,7 @@ public function deleteByUserIdAndName(string|Literal|int $userid, string $proper $deleteQuery = DeleteQuery::getInstance() ->table($this->mapper->getTable()) - ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null)]) + ->where("$userIdField = :userid", ['userid' => $userIdMapping->getUpdateFunctionValue($userid, null, $this->repository->getExecutor())]) ->where("$nameField = :name", ['name' => $propertyName]); if ($value !== null) { diff --git a/src/SessionContext.php b/src/SessionContext.php index 214d134..03874d4 100644 --- a/src/SessionContext.php +++ b/src/SessionContext.php @@ -73,9 +73,9 @@ public function registerLogin(string|int $userId, array $data = []): void $item->set($userId); $this->session->saveDeferred($item); - $data = $this->session->getItem("user.$this->key.data"); - $data->set($data); - $this->session->saveDeferred($data); + $dataItem = $this->session->getItem("user.$this->key.data"); + $dataItem->set($data); + $this->session->saveDeferred($dataItem); $this->session->commit(); } diff --git a/tests/PasswordMd5MapperTest.php b/tests/PasswordMd5MapperTest.php index 6257082..ab20070 100644 --- a/tests/PasswordMd5MapperTest.php +++ b/tests/PasswordMd5MapperTest.php @@ -25,7 +25,8 @@ class PasswordMd5MapperTest extends TestCase public function setUp(): void { $this->db = Factory::getDbInstance(self::CONNECTION_STRING); - $this->db->execute('create table users ( + $executor = DatabaseExecutor::using($this->db); + $executor->execute('create table users ( userid integer primary key autoincrement, name varchar(45), email varchar(200), @@ -37,7 +38,7 @@ public function setUp(): void role varchar(20));' ); - $this->db->execute('create table users_property ( + $executor->execute('create table users_property ( id integer primary key autoincrement, userid integer, name varchar(45), @@ -45,7 +46,6 @@ public function setUp(): void ); // Create repositories and service with custom MD5 password mapper via UserModelMd5 - $executor = DatabaseExecutor::using($this->db); $usersRepository = new UsersRepository($executor, UserModelMd5::class); $propertiesRepository = new UserPropertiesRepository($executor, UserPropertiesModel::class); $this->service = new UsersService( diff --git a/tests/SessionContextTest.php b/tests/SessionContextTest.php index f09f672..94dc879 100644 --- a/tests/SessionContextTest.php +++ b/tests/SessionContextTest.php @@ -46,6 +46,16 @@ public function testUserContext(): void $this->assertFalse($this->object->isAuthenticated()); } + public function testRegisterLoginKeepsTheData(): void + { + $this->object->registerLogin(10, ['property1' => 'value1']); + + $this->assertEquals('value1', $this->object->getSessionData('property1')); + $this->assertFalse($this->object->getSessionData('property2')); + + $this->object->registerLogout(); + } + public function testUserContextNotActiveSession(): void { $this->expectException(\ByJG\Authenticate\Exception\NotAuthenticatedException::class); diff --git a/tests/UsersDBDataset2ByUserNameTestUsersBase.php b/tests/UsersDBDataset2ByUserNameTestUsersBase.php index 25c9687..5622d87 100644 --- a/tests/UsersDBDataset2ByUserNameTestUsersBase.php +++ b/tests/UsersDBDataset2ByUserNameTestUsersBase.php @@ -22,8 +22,9 @@ public function __setUp($loginField) $this->prefix = ""; $this->loginField = $loginField; - $this->db = Factory::getDbRelationalInstance(self::CONNECTION_STRING); - $this->db->execute('create table mytable ( + $this->db = Factory::getDbInstance(self::CONNECTION_STRING); + $executor = DatabaseExecutor::using($this->db); + $executor->execute('create table mytable ( myuserid integer primary key autoincrement, myname varchar(45), myemail varchar(200), @@ -35,14 +36,13 @@ public function __setUp($loginField) myrole varchar(20));' ); - $this->db->execute('create table theirproperty ( + $executor->execute('create table theirproperty ( theirid integer primary key autoincrement, theiruserid integer, theirname varchar(45), theirvalue varchar(45));' ); - $executor = DatabaseExecutor::using($this->db); $usersRepository = new UsersRepository($executor, CustomUserModel::class); $propertiesRepository = new UserPropertiesRepository($executor, CustomUserPropertiesModel::class); $this->object = new UsersService( diff --git a/tests/UsersDBDatasetByUsernameTestUsersBase.php b/tests/UsersDBDatasetByUsernameTestUsersBase.php index 4a5b266..3c9f2e1 100644 --- a/tests/UsersDBDatasetByUsernameTestUsersBase.php +++ b/tests/UsersDBDatasetByUsernameTestUsersBase.php @@ -26,7 +26,8 @@ public function __setUp($loginField) $this->loginField = $loginField; $this->db = Factory::getDbInstance(self::CONNECTION_STRING); - $this->db->execute('create table users ( + $executor = DatabaseExecutor::using($this->db); + $executor->execute('create table users ( userid integer primary key autoincrement, name varchar(45), email varchar(200), @@ -38,14 +39,13 @@ public function __setUp($loginField) role varchar(20));' ); - $this->db->execute('create table users_property ( + $executor->execute('create table users_property ( id integer primary key autoincrement, userid integer, name varchar(45), value varchar(45));' ); - $executor = DatabaseExecutor::using($this->db); $usersRepository = new UsersRepository($executor, UserModel::class); $propertiesRepository = new UserPropertiesRepository($executor, UserPropertiesModel::class); $this->object = new UsersService( diff --git a/tests/UsersDBDatasetDefinitionTest.php b/tests/UsersDBDatasetDefinitionTest.php index e3479d5..de544ca 100644 --- a/tests/UsersDBDatasetDefinitionTest.php +++ b/tests/UsersDBDatasetDefinitionTest.php @@ -38,7 +38,8 @@ public function __setUp($loginField) $this->loginField = $loginField; $this->db = Factory::getDbInstance(self::CONNECTION_STRING); - $this->db->execute('create table mytable ( + $executor = DatabaseExecutor::using($this->db); + $executor->execute('create table mytable ( myuserid integer primary key autoincrement, myname varchar(45), myemail varchar(200), @@ -51,14 +52,13 @@ public function __setUp($loginField) myrole varchar(20));' ); - $this->db->execute('create table theirproperty ( + $executor->execute('create table theirproperty ( theirid integer primary key autoincrement, theiruserid integer, theirname varchar(45), theirvalue varchar(45));' ); - $executor = DatabaseExecutor::using($this->db); $usersRepository = new UsersRepository($executor, MyUserModel::class); $propertiesRepository = new UserPropertiesRepository($executor, MyUserPropertiesModel::class); $this->object = new UsersService(