Skip to content

FOUR-11378 Loggin and Password improvements #5722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Dec 1, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ProcessMaker\Http\Controllers\Api;

use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand Down Expand Up @@ -35,6 +36,10 @@ public function update(Request $request)

$user->setAttribute('password', Hash::make($request->json('password')));
$user->setAttribute('force_change_password', 0);
$user->setAttribute('password_changed_at', Carbon::now()->toDateTimeString());

// Remove login error message related to password expired if exists
session()->forget('login-error');

try {
$user = $user->save();
Expand Down
9 changes: 9 additions & 0 deletions ProcessMaker/Http/Controllers/Api/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ProcessMaker\Http\Controllers\Api;

use Carbon\Carbon;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand Down Expand Up @@ -167,6 +168,10 @@ public function store(Request $request)

if (isset($fields['password'])) {
$fields['password'] = Hash::make($fields['password']);
$fields['password_changed_at'] = Carbon::now()->toDateTimeString();

// Remove login error message related to password expired if exists
session()->forget('login-error');
}

$user->fill($fields);
Expand Down Expand Up @@ -301,6 +306,10 @@ public function update(User $user, Request $request)
$fields = $request->json()->all();
if (isset($fields['password'])) {
$fields['password'] = Hash::make($fields['password']);
$fields['password_changed_at'] = Carbon::now()->toDateTimeString();

// Remove login error message related to password expired if exists
session()->forget('login-error');
}
$original = $user->getOriginal();
$user->fill($fields);
Expand Down
3 changes: 3 additions & 0 deletions ProcessMaker/Http/Controllers/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ class LoginController extends Controller
*/
protected $redirectTo = '/';

protected $maxAttempts;

/**
* Create a new controller instance.
*
Expand All @@ -46,6 +48,7 @@ class LoginController extends Controller
public function __construct()
{
$this->middleware('guest')->except(['logout', 'beforeLogout', 'keepAlive']);
$this->maxAttempts = (int) config('password-policies.login_attempts');
}

/**
Expand Down
19 changes: 19 additions & 0 deletions ProcessMaker/Http/Middleware/VerifyChangePasswordNeeded.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace ProcessMaker\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Auth;

Expand All @@ -20,11 +21,29 @@ public function handle($request, Closure $next)
return redirect()->route('password.change');
}

if ($this->checkPasswordExpiration()) {
// Set the error message
session()->put('login-error', _('Your password has expired.'));

// Redirect to change password screen
return redirect()->route('password.change');
}

return $next($request);
}

public function checkForForceChangePassword()
{
return Auth::user() && Auth::user()->force_change_password;
}

public function checkPasswordExpiration()
{
$validationRequired = config('password-policies.expiration_days') &&
Auth::user() && Auth::user()->password_changed_at;

return $validationRequired &&
(Carbon::now()->diffInDays(Auth::user()->password_changed_at) >=
config('password-policies.expiration_days'));
}
}
28 changes: 22 additions & 6 deletions ProcessMaker/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Laravel\Passport\HasApiTokens;
use ProcessMaker\Models\EmptyModel;
use ProcessMaker\Notifications\ResetPassword as ResetPasswordNotification;
use ProcessMaker\Query\Traits\PMQL;
use ProcessMaker\Rules\StringHasAtLeastOneUpperCaseCharacter;
use ProcessMaker\Rules\StringHasNumberOrSpecialCharacter;
use ProcessMaker\Traits\Exportable;
use ProcessMaker\Traits\HasAuthorization;
use ProcessMaker\Traits\HideSystemResources;
Expand Down Expand Up @@ -122,6 +122,7 @@ class User extends Authenticatable implements HasMedia
'manager_id',
'schedule',
'force_change_password',
'password_changed_at',
];

protected $appends = [
Expand Down Expand Up @@ -183,13 +184,28 @@ public static function rules(self $existing = null)
*/
public static function passwordRules(self $existing = null)
{
return array_filter([
// Mandatory policies
$passwordPolicies = [
'required',
$existing ? 'sometimes' : '',
'min:8',
new StringHasNumberOrSpecialCharacter(),
new StringHasAtLeastOneUpperCaseCharacter(),
]);
];
// Configurable policies
$passwordRules = Password::min(config('password-policies.minimum_length'));
if (config('password-policies.maximum_length')) {
$passwordPolicies[] = 'max:' . config('password-policies.maximum_length');
}
if (config('password-policies.numbers')) {
$passwordRules->numbers();
}
if (config('password-policies.uppercase')) {
$passwordPolicies[] = new StringHasAtLeastOneUpperCaseCharacter();
}
if (config('password-policies.special')) {
$passwordRules->symbols();
}
$passwordPolicies[] = $passwordRules;

return $passwordPolicies;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions config/password-policies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

return [
'minimum_length' => env('PASSWORD_POLICY_MINIMUM_LENGTH', 8),
'maximum_length' => env('PASSWORD_POLICY_MAXIMUM_LENGTH', null),
'numbers' => env('PASSWORD_POLICY_NUMBERS', true),
'uppercase' => env('PASSWORD_POLICY_UPPERCASE', true),
'special' => env('PASSWORD_POLICY_SPECIAL', true),
'expiration_days' => env('PASSWORD_POLICY_EXPIRATION_DAYS', null),
'login_attempts' => env('PASSWORD_POLICY_LOGIN_ATTEMPTS', 5),
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('password_changed_at')->nullable();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('password_changed_at');
});
}
};
3 changes: 2 additions & 1 deletion resources/lang/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -1801,5 +1801,6 @@
"This environment already contains an older version of the {{ item }} named '{{ name }}.'": "Diese Umgebung enthält bereits eine ältere Version des {{ item }} namens '{{ name }}'.",
"This environment already contains the same version of the {{ item }} named '{{ name }}.'": "Diese Umgebung enthält bereits die gleiche Version des {{ item }} namens '{{ name }}'.",
"Visit our Gallery for more Templates": "Besuchen Sie unsere Galerie für mehr Vorlagen",
"Start a new process from a blank canvas, a text description, or a preset template.": "Starten Sie einen neuen Prozess von einer leeren Leinwand, einer Textbeschreibung oder einer voreingestellten Vorlage."
"Start a new process from a blank canvas, a text description, or a preset template.": "Starten Sie einen neuen Prozess von einer leeren Leinwand, einer Textbeschreibung oder einer voreingestellten Vorlage.",
"Your password has expired.": "Your password has expired."
}
1 change: 1 addition & 0 deletions resources/lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1870,6 +1870,7 @@
"Your account has been timed out for security.": "Your account has been timed out for security.",
"Your password has been reset!": "Your password has been reset!",
"Your password has been updated.": "Your password has been updated.",
"Your password has expired.": "Your password has expired.",
"Your PMQL contains invalid syntax.": "Your PMQL contains invalid syntax.",
"Your PMQL search could not be completed.": "Your PMQL search could not be completed.",
"Your profile was saved.": "Your profile was saved.",
Expand Down
3 changes: 2 additions & 1 deletion resources/lang/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1802,5 +1802,6 @@
"This environment already contains an older version of the {{ item }} named '{{ name }}.'": "Este entorno ya contiene una versión más antigua del {{ item }} llamado '{{ name }}'.",
"This environment already contains the same version of the {{ item }} named '{{ name }}.'": "Este entorno ya contiene la misma versión del {{ item }} llamado '{{ name }}'.",
"Visit our Gallery for more Templates": "Visita nuestra Galería para más Plantillas",
"Start a new process from a blank canvas, a text description, or a preset template.": "Inicie un nuevo proceso desde un lienzo en blanco, una descripción de texto o una plantilla preestablecida."
"Start a new process from a blank canvas, a text description, or a preset template.": "Inicie un nuevo proceso desde un lienzo en blanco, una descripción de texto o una plantilla preestablecida.",
"Your password has expired.": "Tu contraseña ha expirado."
}
3 changes: 2 additions & 1 deletion resources/lang/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -1801,5 +1801,6 @@
"This environment already contains an older version of the {{ item }} named '{{ name }}.'": "Cet environnement contient déjà une version plus ancienne de {{ item }} nommé '{{ name }}'.",
"This environment already contains the same version of the {{ item }} named '{{ name }}.'": "Cet environnement contient déjà la même version de l'{{ item }} nommé '{{ name }}'.",
"Visit our Gallery for more Templates": "Visitez notre Galerie pour plus de Modèles",
"Start a new process from a blank canvas, a text description, or a preset template.": "Démarrez un nouveau processus à partir d'une toile vierge, d'une description textuelle ou d'un modèle prédéfini."
"Start a new process from a blank canvas, a text description, or a preset template.": "Démarrez un nouveau processus à partir d'une toile vierge, d'une description textuelle ou d'un modèle prédéfini.",
"Your password has expired.": "Your password has expired."
}
6 changes: 0 additions & 6 deletions resources/views/admin/users/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,6 @@
delete this.formData.password;
return true
}
if (this.formData.password.trim().length > 0 && this.formData.password.trim().length < 8) {
this.errors.password = ['Password must be at least 8 characters']
this.password = ''
this.submitted = false
return false
}
if (this.formData.password !== this.formData.confPassword) {
this.errors.password = ['Passwords must match']
this.password = ''
Expand Down
13 changes: 1 addition & 12 deletions resources/views/auth/passwords/change.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
'v-bind:class' => '{\'form-control\':true, \'is-invalid\':errors.password}']) !!}
</div>
</vue-password>
<small v-if="errors && errors.password && errors.password.length" class="text-danger">@{{ errors.password[0] }}</small>
<small v-for="(error, index) in errors.password" class="text-danger">@{{ error }}</small>
</div>
<div class="form-group">
{!!Form::label('confpassword', __('Confirm Password'))!!}<small class="ml-1">*</small>
Expand Down Expand Up @@ -94,11 +94,6 @@
});
},
validatePassword() {
if (this.$refs.passwordStrength.strength.score < 2) {
this.errors.password = ['Password is too weak']
return false
}

if (!this.formData.password && !this.formData.confpassword) {
return false;
}
Expand All @@ -107,12 +102,6 @@
return false
}

if (this.formData.password.trim().length > 0 && this.formData.password.trim().length < 8) {
this.errors.password = ['Password must be at least 8 characters']
this.formData.password = ''
return false
}

if (this.formData.password !== this.formData.confpassword) {
this.errors.password = ['Passwords must match']
return false
Expand Down
6 changes: 0 additions & 6 deletions resources/views/profile/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,6 @@
delete this.formData.password;
return true
}
if (this.formData.password.trim().length > 0 && this.formData.password.trim().length < 8) {
this.errors.password = ['Password must be at least 8 characters']
this.password = ''
this.submitted = false
return false
}
if (this.formData.password !== this.formData.confPassword) {
this.errors.password = ['Passwords must match']
this.password = ''
Expand Down
7 changes: 4 additions & 3 deletions resources/views/shared/users/sidebar.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
</div>
</div>
<div class="card card-body mt-3">
<fieldset :disabled="{{ \Auth::user()->hasPermission('edit-user-and-password') || \Auth::user()->is_administrator ? 'false' : 'true' }}">
<legend>
<fieldset :disabled="{{ \Auth::user()->hasPermission('edit-user-and-password') || \Auth::user()->is_administrator ? 'false' : 'true' }}">
<legend>
<h5 class="mb-3 font-weight-bold">{{__('Login Information')}}</h5>
</legend>
<div class="form-group">
Expand Down Expand Up @@ -54,7 +54,8 @@
{!! Form::label('confPassword', __('Confirm Password')) !!}
{!! Form::password('confPassword', ['id' => 'confPassword', 'rows' => 4, 'class'=> 'form-control', 'v-model'
=> 'formData.confPassword', 'autocomplete' => 'new-password', 'v-bind:class' => '{\'form-control\':true, \'is-invalid\':errors.password}']) !!}
<div class="invalid-feedback" :style="{display: (errors.password) ? 'block' : 'none' }" role="alert" v-if="errors.password">@{{errors.password[0]}}</div>
<div class="invalid-feedback" :style="{display: (errors.password) ? 'block' : 'none' }" role="alert"
v-for="(error, index) in errors.password">@{{error}}</div>
</div>
@cannot('edit-user-and-password')
<div class="form-group">
Expand Down
9 changes: 5 additions & 4 deletions tests/Feature/Api/ChangePasswordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ public function testUserPasswordChangeWithInvalidPassword()
'confpassword' => 'ProcessMaker',
]);

$response->assertStatus(422)
->assertSeeText('The password must contain either a number or a special character');
$response->assertStatus(422);
$json = $response->json();
$this->assertTrue(in_array('The Password field must contain at least one symbol.', $json['errors']['password']));

// Validate updated user password changed
$updatedUser = User::where('id', $user->id)->first();
Expand All @@ -72,8 +73,8 @@ public function testUserChangePasswordMustSetFlagToFalse()

// Post data with new password
$response = $this->apiCall('PUT', self::API_TEST_URL, [
'password' => 'ProcessMaker1',
'confpassword' => 'ProcessMaker1',
'password' => 'ProcessMaker1_',
'confpassword' => 'ProcessMaker1_',
]);

// Validate the header status code
Expand Down
14 changes: 7 additions & 7 deletions tests/Feature/Api/UsersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function getUpdatedData()
'timezone' => $faker->timezone(),
'status' => $faker->randomElement(['ACTIVE', 'INACTIVE']),
'birthdate' => $faker->dateTimeThisCentury()->format('Y-m-d'),
'password' => $faker->sentence(10),
'password' => $faker->sentence(8) . 'A_' . '1',
];
}

Expand Down Expand Up @@ -100,7 +100,7 @@ public function testCreateUser()
'lastname' => 'name',
'email' => $faker->email(),
'status' => $faker->randomElement(['ACTIVE', 'INACTIVE']),
'password' => $faker->sentence(10),
'password' => $faker->password(8) . 'A_' . '1',
]);

// Validate the header status code
Expand Down Expand Up @@ -602,9 +602,9 @@ public function testCreateWithoutPassword()
$response = $this->apiCall('POST', self::API_TEST_URL, $payload);
$response->assertStatus(422);
$json = $response->json();
$this->assertEquals('The Password field must be at least 8 characters.', $json['errors']['password'][0]);
$this->assertTrue(in_array('The Password field must be at least 8 characters.', $json['errors']['password']));

$payload['password'] = 'Abc12345';
$payload['password'] = 'Abc12345_';
$response = $this->apiCall('POST', self::API_TEST_URL, $payload);
$response->assertStatus(201);
$json = $response->json();
Expand All @@ -616,9 +616,9 @@ public function testCreateWithoutPassword()
$response = $this->apiCall('PUT', route('api.users.update', $userId), $payload);
$response->assertStatus(422);
$json = $response->json();
$this->assertEquals('The Password field must be at least 8 characters.', $json['errors']['password'][0]);
$this->assertTrue(in_array('The Password field must be at least 8 characters.', $json['errors']['password']));

$payload['password'] = 'Abc12345';
$payload['password'] = 'Abc12345_';
$response = $this->apiCall('PUT', route('api.users.update', $userId), $payload);
$response->assertStatus(204);

Expand Down Expand Up @@ -673,7 +673,7 @@ public function testCreateUserValidateUsername()
'lastname' => $faker->lastName(),
'email' => $faker->email(),
'status' => $faker->randomElement(['ACTIVE', 'INACTIVE']),
'password' => $faker->sentence(10),
'password' => $faker->sentence(8) . 'A_' . '1',
]);
// Validate the header status code
$response->assertStatus(201);
Expand Down