Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG-7.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,28 @@ to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes).

## Breaking Changes

### Passwords are hashed with bcrypt

`UserModel` hashes passwords with the new `PasswordBcryptMapper` instead of `PasswordSha1Mapper`
(unsalted SHA-1).

- **Widen the password column** to `VARCHAR(255)`: a bcrypt hash has 60 characters, and a new user
or a changed password does not fit in the `CHAR(40)` of a SHA-1 column.
- **Existing users keep logging in.** The bcrypt mapper verifies a 40-character SHA-1 hash too, and
the new `UsersService::rehashPasswordIfNeeded()` replaces it with a bcrypt hash at that user's next
login: `createAuthToken()` calls it; a login of your own calls it after `isValidUser()`, which only
checks the password. It reads the new hash back and keeps the old one when the column is too short
(rejected or truncated), so nobody is locked out before the column is widened.
- **To keep SHA-1**, select `PasswordSha1Mapper` on the password field of your user model:
`#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]`.
- `UsersServiceInterface` has the new `rehashPasswordIfNeeded()`.
- **Custom password mappers** implement two new methods of `PasswordMapperInterface`:
`verifyPassword(string $password, string $hash): bool` and `needsRehash(string $hash): bool`.
`isValidUser()` uses them instead of comparing the hash of the password with `===`; a SHA-1 or
MD5 mapper verifies with `hash_equals()` and returns `false` from `needsRehash()`.
- `UserModel::setPassword()` asks the password mapper whether a value is already a hash (it skipped
the password definition for any 40-character value).

### Dependencies

| Package | 6.x | 7.0 |
Expand Down
44 changes: 40 additions & 4 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,55 @@ The `isValidUser()` method uses the login field configured in your `UsersService

## Password Hashing

By default, passwords are automatically hashed using SHA-1 when saved. The library uses the `PasswordSha1Mapper` for this purpose.
By default, passwords are hashed with bcrypt when saved, by the `PasswordBcryptMapper` of
`UserModel`. The password column needs 60 characters; `VARCHAR(255)` leaves room for other algorithms.

```php
<?php
// Password is automatically hashed when saved
$user->setPassword('plaintext password');
$users->save($user);

// The password is stored as SHA-1 hash in the database
// The password is stored as a bcrypt hash ($2y$...) in the database
```

:::warning SHA-1 Deprecation
SHA-1 is used for backward compatibility. For new projects, consider implementing a custom password hasher using bcrypt or Argon2. See [Mappers](mappers.md) for details.
The bcrypt mapper also reads the SHA-1 hashes of `PasswordSha1Mapper`, the default before 7.0: a
stored 40-character hash still logs in. At login, `createAuthToken()` replaces it with a bcrypt hash,
so users move to bcrypt as they log in, without a password reset. A bcrypt hash with a lower cost than
PHP's current one is replaced the same way. `isValidUser()` only checks the password and never writes.

A login of your own (without `createAuthToken()`) upgrades the hash with `rehashPasswordIfNeeded()`:

```php
<?php
$user = $users->isValidUser($login, $password);
if ($user !== null) {
$users->rehashPasswordIfNeeded($user, $password);
}
```

`rehashPasswordIfNeeded()` reads the new hash back. If the password column is too short for it (the
`CHAR(40)` of a SHA-1 schema), the new hash is rejected or truncated by the database; the method then
keeps the old hash and returns `false`, so the user can still log in. Widen the column to upgrade.

To keep SHA-1, select its mapper in your user model:

```php
<?php
use ByJG\Authenticate\MapperFunctions\PasswordSha1Mapper;
use ByJG\Authenticate\Model\UserModel;
use ByJG\MicroOrm\Attributes\FieldAttribute;

class User extends UserModel
{
#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]
protected ?string $password = null;
}
```

:::warning SHA-1
`PasswordSha1Mapper` stores an unsalted SHA-1 hash, which is fast to brute-force. Keep it only for a
system that cannot store longer hashes.
:::

:::tip Enforce Password Strength
Expand Down
2 changes: 1 addition & 1 deletion docs/custom-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ CREATE TABLE users
name VARCHAR(50),
email VARCHAR(120),
username VARCHAR(15) NOT NULL,
password CHAR(40) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME,
Expand Down
12 changes: 6 additions & 6 deletions docs/database-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ CREATE TABLE users
name VARCHAR(50),
email VARCHAR(120),
username VARCHAR(15) NOT NULL,
password CHAR(40) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT (now()),
updated_at DATETIME ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME,
Expand Down Expand Up @@ -60,7 +60,7 @@ CREATE TABLE users
name VARCHAR(50),
email VARCHAR(120),
username VARCHAR(15) NOT NULL,
password CHAR(40) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT (datetime('now')),
updated_at DATETIME DEFAULT (datetime('now')),
deleted_at DATETIME,
Expand Down Expand Up @@ -103,7 +103,7 @@ CREATE TABLE users
name VARCHAR(50),
email VARCHAR(120),
username VARCHAR(15) NOT NULL,
password CHAR(40) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT now(),
updated_at TIMESTAMP DEFAULT now(),
deleted_at TIMESTAMP,
Expand Down Expand Up @@ -154,7 +154,7 @@ CREATE TABLE users
name VARCHAR(50),
email VARCHAR(120),
username VARCHAR(15) NOT NULL,
password CHAR(40) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT GETDATE(),
updated_at DATETIME DEFAULT GETDATE(),
deleted_at DATETIME,
Expand Down Expand Up @@ -242,7 +242,7 @@ If you have an existing database with different table or column names, create a
```php
<?php
use ByJG\Authenticate\Model\UserModel;
use ByJG\Authenticate\MapperFunctions\PasswordSha1Mapper;
use ByJG\Authenticate\MapperFunctions\PasswordBcryptMapper;
use ByJG\MicroOrm\Attributes\FieldAttribute;
use ByJG\MicroOrm\Attributes\TableAttribute;
use ByJG\MicroOrm\MapperFunctions\ReadOnlyMapper;
Expand All @@ -264,7 +264,7 @@ class CustomUserModel extends UserModel
#[FieldAttribute(fieldName: 'user_name')]
protected ?string $username = null;

#[FieldAttribute(fieldName: 'password_hash', updateFunction: PasswordSha1Mapper::class)]
#[FieldAttribute(fieldName: 'password_hash', updateFunction: PasswordBcryptMapper::class)]
protected ?string $password = null;

#[FieldAttribute(fieldName: 'date_created', updateFunction: ReadOnlyMapper::class, insertFunction: NowUtcMapper::class)]
Expand Down
8 changes: 7 additions & 1 deletion docs/mappers.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,13 @@ class CustomUserModel extends UserModel

This package ships with a few mapper utilities that complement the ones provided by Micro ORM:

- **PasswordSha1Mapper** – hashes passwords using SHA-1 (the default on `UserModel`). Replace it with your own mapper to change the hashing algorithm.
- **PasswordBcryptMapper** – hashes passwords with bcrypt (the default on `UserModel`). It also verifies the SHA-1 hashes of `PasswordSha1Mapper`, which are upgraded to bcrypt at the next login.
- **PasswordSha1Mapper** – hashes passwords with unsalted SHA-1 (the default before 7.0).

A password mapper implements `PasswordMapperInterface`: `processedValue()` hashes a plain password,
`isPasswordEncrypted()` recognizes a stored hash, `verifyPassword()` checks a password against a hash,
and `needsRehash()` tells `UsersService::rehashPasswordIfNeeded()` (called by `createAuthToken()`)
to replace a hash at a successful login.
- **UserIdGeneratorMapper** – derives a user ID from the username when the primary key is empty.
```php
<?php
Expand Down
24 changes: 12 additions & 12 deletions docs/user-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,18 +174,18 @@ The `hasRole()` method performs case-insensitive comparison, so `hasRole('admin'

The `UserModel` class provides the following properties:

| Property | Type | Description |
|-------------|-----------------------------------|------------------------------------------------------------------|
| `userid` | string\|int\|Literal\|null | Primary key. Generated by the database unless you override it. |
| `name` | string\|null | User's display name. |
| `email` | string\|null | User's email address. |
| `username` | string\|null | Unique username (used when `LoginField::Username` is selected). |
| `password` | string\|null | Hashed password. Uses `PasswordSha1Mapper` by default. |
| `role` | string\|null | Optional application role. |
| `createdAt` | string\|null | Automatically set when the record is inserted. |
| `updatedAt` | string\|null | Automatically updated whenever the record is saved. |
| `deletedAt` | string\|null | Nullable soft-delete timestamp (requires manual handling). |
| `properties`| `UserPropertiesModel[]` (array) | Loaded via `getProperties()` or manipulated through helpers. |
| Property | Type | Description |
|--------------|---------------------------------|-----------------------------------------------------------------|
| `userid` | string\|int\|Literal\|null | Primary key. Generated by the database unless you override it. |
| `name` | string\|null | User's display name. |
| `email` | string\|null | User's email address. |
| `username` | string\|null | Unique username (used when `LoginField::Username` is selected). |
| `password` | string\|null | Hashed password. Uses `PasswordBcryptMapper` by default. |
| `role` | string\|null | Optional application role. |
| `createdAt` | string\|null | Automatically set when the record is inserted. |
| `updatedAt` | string\|null | Automatically updated whenever the record is saved. |
| `deletedAt` | string\|null | Nullable soft-delete timestamp (requires manual handling). |
| `properties` | `UserPropertiesModel[]` (array) | Loaded via `getProperties()` or manipulated through helpers. |

## Next Steps

Expand Down
13 changes: 13 additions & 0 deletions src/Interfaces/PasswordMapperInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,18 @@

interface PasswordMapperInterface extends MapperFunctionInterface
{
/**
* Whether the value is a hash this mapper reads (stored as is), not a plain password.
*/
public function isPasswordEncrypted(mixed $password): bool;

/**
* Whether the plain password matches the stored hash.
*/
public function verifyPassword(string $password, string $hash): bool;

/**
* Whether the stored hash should be replaced with a new one, done at the next successful login.
*/
public function needsRehash(string $hash): bool;
}
14 changes: 14 additions & 0 deletions src/Interfaces/UsersServiceInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ public function removeById(string|Literal|int $userid): bool;
*/
public function isValidUser(string $login, string $password): ?UserModel;

/**
* Replace the user's stored hash when the password mapper says so (a SHA-1 hash, or bcrypt with
* a lower cost than the current one), now that the plain password is known. createAuthToken()
* calls it at login; call it after isValidUser() in a login of your own.
*
* The new hash is read back: if it was not stored (a password column too short for it), the
* old hash is kept and the method returns false, so the user can still log in.
*
* @param UserModel $user A user isValidUser() returned for this password
* @param string $password The plain password
* @return bool Whether the hash was replaced
*/
public function rehashPasswordIfNeeded(UserModel $user, string $password): bool;

/**
* Check if user has a property
*
Expand Down
66 changes: 66 additions & 0 deletions src/MapperFunctions/PasswordBcryptMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace ByJG\Authenticate\MapperFunctions;

use ByJG\AnyDataset\Db\DatabaseExecutor;
use ByJG\Authenticate\Interfaces\PasswordMapperInterface;

/**
* Mapper function to hash passwords with bcrypt (the default on UserModel).
*
* It also reads the SHA-1 hashes of PasswordSha1Mapper, so a database created with it keeps
* working: a SHA-1 hash still verifies, and UsersService::rehashPasswordIfNeeded() (called by
* createAuthToken() at login) replaces it with a bcrypt hash. The password column needs 60 characters.
*/
class PasswordBcryptMapper implements PasswordMapperInterface
{
#[\Override]
public function processedValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed
{
// Already a hash (bcrypt, or SHA-1 not upgraded yet)
if ($this->isPasswordEncrypted($value)) {
return $value;
}

// Leave null
if (empty($value)) {
return null;
}

return password_hash((string)$value, PASSWORD_BCRYPT);
}

#[\Override]
public function isPasswordEncrypted(mixed $password): bool
{
return is_string($password) && ($this->isBcrypt($password) || $this->isSha1($password));
}

#[\Override]
public function verifyPassword(string $password, string $hash): bool
{
if ($this->isBcrypt($hash)) {
return password_verify($password, $hash);
}
if ($this->isSha1($hash)) {
return hash_equals(strtolower($hash), sha1($password));
}
return false;
}

#[\Override]
public function needsRehash(string $hash): bool
{
return !$this->isBcrypt($hash) || password_needs_rehash($hash, PASSWORD_BCRYPT);
}

private function isBcrypt(string $hash): bool
{
return strlen($hash) === 60 && password_get_info($hash)['algo'] === PASSWORD_BCRYPT;
}

private function isSha1(string $hash): bool
{
return strlen($hash) === 40 && ctype_xdigit($hash);
}
}
15 changes: 14 additions & 1 deletion src/MapperFunctions/PasswordSha1Mapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
use ByJG\Authenticate\Interfaces\PasswordMapperInterface;

/**
* Mapper function to hash passwords using SHA1
* Mapper function to hash passwords using SHA1 (unsalted). PasswordBcryptMapper, the default,
* also reads these hashes and upgrades them; select this mapper only to keep SHA-1.
*/
class PasswordSha1Mapper implements PasswordMapperInterface
{
Expand All @@ -32,4 +33,16 @@ public function isPasswordEncrypted(mixed $password): bool
{
return (is_string($password) && strlen($password) === 40);
}

#[\Override]
public function verifyPassword(string $password, string $hash): bool
{
return hash_equals(strtolower($hash), sha1($password));
}

#[\Override]
public function needsRehash(string $hash): bool
{
return false;
}
}
21 changes: 17 additions & 4 deletions src/Model/UserModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace ByJG\Authenticate\Model;

use ByJG\Authenticate\Definition\PasswordDefinition;
use ByJG\Authenticate\MapperFunctions\PasswordSha1Mapper;
use ByJG\Authenticate\MapperFunctions\PasswordBcryptMapper;
use ByJG\MicroOrm\Attributes\FieldAttribute;
use ByJG\MicroOrm\Attributes\TableAttribute;
use ByJG\MicroOrm\Literal\Literal;
Expand All @@ -30,7 +30,7 @@ class UserModel
#[FieldAttribute]
protected ?string $username = null;

#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]
#[FieldAttribute(updateFunction: PasswordBcryptMapper::class)]
protected ?string $password = null;

#[FieldAttribute]
Expand Down Expand Up @@ -136,8 +136,8 @@ public function getPassword(): ?string
*/
public function setPassword(?string $password): void
{
// Password len equals to 40 means that the password is already encrypted with sha1
if (!empty($this->passwordDefinition) && !empty($password) && strlen($password) != 40) {
// A hash (read from the database) is not checked against the password definition
if (!empty($this->passwordDefinition) && !empty($password) && !$this->isPasswordHash($password)) {
$match = $this->passwordDefinition->matchPassword($password);
if ($match != PasswordDefinition::SUCCESS) {
throw new InvalidArgumentException("Password does not match the password definition [$match]");
Expand All @@ -147,6 +147,19 @@ public function setPassword(?string $password): void
$this->password = $password;
}

/**
* Whether the value is a hash, by the password mapper UsersService registers on the
* password definition; the default mapper when there is none.
*/
protected function isPasswordHash(string $password): bool
{
$mapper = $this->passwordDefinition?->getPasswordMapper() ?? PasswordBcryptMapper::class;
if (is_string($mapper)) {
$mapper = new $mapper();
}
return $mapper->isPasswordEncrypted($password);
}

/**
* @return string|null
*/
Expand Down
Loading
Loading