Skip to content
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ AGENTS.md
tests/Browser/Screenshots/
tests/Browser/screenshots/
tests/Browser/.session_state.json
graphify-out
16 changes: 1 addition & 15 deletions app/Http/Controllers/Auth/ResetPasswordController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@

use App\Http\Controllers\Controller;
use App\Http\Requests\ResetPasswordRequest;
use App\Models\PasswordHistory;
use App\Providers\AppServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Password;

class ResetPasswordController extends Controller
{
Expand Down Expand Up @@ -75,26 +73,14 @@ protected function resetPassword($user, $password)
{
$expiryDays = config('password.expiry_days');

// Save old password to history
if ($user->password) {
PasswordHistory::create([
'user_id' => $user->id,
'password' => $user->password,
'reason' => 'password_reset',
]);
}

// Set new password
$user->passwordHistoryReason = 'password_reset';
$user->password = $password;

// Set expiry if configured
if ($expiryDays) {
$user->password_expires_at = now()->addDays($expiryDays);
}

// Reset force_password_reset flag
$user->force_password_reset = false;

$user->save();
}
}
12 changes: 1 addition & 11 deletions app/Http/Controllers/ForcePasswordResetController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace App\Http\Controllers;

use App\Http\Requests\ForcePasswordResetRequest;
use App\Models\PasswordHistory;
use App\Providers\AppServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
Expand Down Expand Up @@ -39,22 +38,13 @@ public function reset(ForcePasswordResetRequest $request)

$expiryDays = config('password.expiry_days');

// Save old password to history
PasswordHistory::create([
'user_id' => $user->id,
'password' => $user->password,
'reason' => 'forced_reset_completed',
]);

// Set new password
$user->passwordHistoryReason = 'forced_reset_completed';
$user->password = $request->password;

// Set expiry if configured
if ($expiryDays) {
$user->password_expires_at = now()->addDays($expiryDays);
}

// Reset force_password_reset flag
$user->force_password_reset = false;
$user->save();

Expand Down
11 changes: 11 additions & 0 deletions app/Http/Requests/ChangePasswordRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Rules\MatchOldPassword;
use App\Rules\StrongPassword;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class ChangePasswordRequest extends FormRequest
Expand All @@ -16,6 +17,16 @@ public function authorize(): bool
return auth()->check();
}

/**
* Handle a failed validation attempt.
*/
protected function failedValidation(Validator $validator): void
{
session()->flash('error', $validator->errors()->first());

parent::failedValidation($validator);
}

/**
* Get the validation rules that apply to the request.
*
Expand Down
18 changes: 17 additions & 1 deletion app/Http/Requests/ResetPasswordRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Http\Requests;

use App\Rules\StrongPassword;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class ResetPasswordRequest extends FormRequest
Expand All @@ -15,17 +16,32 @@ public function authorize(): bool
return true;
}

/**
* Handle a failed validation attempt.
*/
protected function failedValidation(Validator $validator): void
{
session()->flash('error', $validator->errors()->first());

parent::failedValidation($validator);
}

/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
$user = null;
if ($this->has('email')) {
$user = \App\Models\User::where('email', $this->input('email'))->first();
}

return [
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'string', 'confirmed', new StrongPassword()],
'password' => ['required', 'string', 'confirmed', new StrongPassword(user: $user)],
];
}

Expand Down
17 changes: 6 additions & 11 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ public function delete()
return parent::delete();
}

public ?string $passwordHistoryReason = null;
public ?string $oldPasswordHash = null;

public function team()
{
return $this->belongsToMany(
Expand Down Expand Up @@ -265,27 +268,19 @@ public function requiresPasswordReset(): bool
}

/**
* Set password dengan expiry dan history
* Set password dengan expiry.
* Riwayat password lama otomatis disimpan oleh UserObserver.
*/
public function setPasswordWithHistory(string $password, string $reason = 'password_change', ?int $expiryDays = null): void
{
// Simpan password lama ke history
if ($this->exists && $this->password) {
$this->passwordHistory()->create([
'password' => $this->password,
'reason' => $reason,
]);
}
$this->passwordHistoryReason = $reason;

// Set password baru
$this->password = $password;

// Set expiry jika ditentukan
if ($expiryDays !== null) {
$this->password_expires_at = now()->addDays($expiryDays);
}

// Reset flag force_password_reset
$this->force_password_reset = false;

$this->save();
Expand Down
46 changes: 46 additions & 0 deletions app/Observers/UserObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Observers;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserObserver
{
public function saving(User $user): void
{
if ($user->exists && $user->isDirty('password')) {
$user->oldPasswordHash = $user->getOriginal('password');
}
}

public function saved(User $user): void
{
if (!isset($user->oldPasswordHash)) {
return;
}

DB::transaction(function () use ($user) {
$reason = $user->passwordHistoryReason ?? 'password_change';

$user->passwordHistory()->create([
'password' => $user->oldPasswordHash,
'reason' => $reason,
]);

$historyCount = config('password.history_count', 10);
if ($historyCount > 0) {
$recentIds = $user->passwordHistory()
->orderBy('created_at', 'desc')
->limit($historyCount)
->pluck('id');

$user->passwordHistory()
->whereNotIn('id', $recentIds)
->delete();
}
});

$user->oldPasswordHash = null;
}
}
3 changes: 3 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use App\Models\User;
use App\Observers\UserObserver;
use App\Observers\VisitorObserver;
use Exception;
use Illuminate\Support\Facades\Log;
Expand Down Expand Up @@ -104,6 +106,7 @@ private function shareViewIdentitas(): void

protected function configureObservers(): void
{
User::observe(UserObserver::class);
Visit::observe(VisitorObserver::class);
}

Expand Down
52 changes: 36 additions & 16 deletions app/Rules/StrongPassword.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Rules;

use App\Models\PasswordHistory;
use App\Models\User;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
Expand Down Expand Up @@ -30,24 +31,36 @@ class StrongPassword implements Rule
*/
protected array $weakPatterns;

/**
* Specific user to check history against (for unauthenticated contexts).
*/
protected ?User $user = null;

/**
* Common passwords list.
*/
protected array $commonPasswords;

/**
* The validation rule that failed.
*/
protected ?string $failedRule = null;

/**
* Create a new rule instance.
*/
public function __construct(
?int $minLength = null,
?bool $checkHibp = null,
?int $historySize = null
?int $historySize = null,
?User $user = null
) {
$this->minLength = $minLength ?? config('password.min_length', 12);
$this->checkHibp = $checkHibp ?? config('password.check_hibp', true);
$this->historySize = $historySize ?? config('password.history_count', 5);
$this->historySize = $historySize ?? config('password.history_count', 10);
$this->weakPatterns = config('password.weak_patterns', []);
$this->commonPasswords = config('password.common_passwords', []);
$this->user = $user;
}

/**
Expand All @@ -60,48 +73,48 @@ public function __construct(
*/
public function passes($attribute, $value)
{
// Check minimum length
if (strlen($value) < $this->minLength) {
$this->failedRule = 'length';
return false;
}

// Check for at least one uppercase letter
if (!preg_match('/[A-Z]/', $value)) {
$this->failedRule = 'complexity';
return false;
}

// Check for at least one lowercase letter
if (!preg_match('/[a-z]/', $value)) {
$this->failedRule = 'complexity';
return false;
}

// Check for at least one number
if (!preg_match('/[0-9]/', $value)) {
$this->failedRule = 'complexity';
return false;
}

// Check for at least one special character
if (!preg_match('/[!@#$%^&*(),.?":{}|<>_\-+=\[\]\\;\'\/`~]/', $value)) {
$this->failedRule = 'complexity';
return false;
}

// Check for weak patterns
if ($this->matchesWeakPattern($value)) {
$this->failedRule = 'weak_pattern';
return false;
}

// Check for common passwords
if ($this->isCommonPassword($value)) {
$this->failedRule = 'common';
return false;
}

// Check HIBP database
if ($this->checkHibp && !$this->isNotPwned($value)) {
$this->failedRule = 'hibp';
return false;
}

// Check password history
if (!$this->isNotInHistory($value)) {
$this->failedRule = 'history';
return false;
}

Expand Down Expand Up @@ -168,11 +181,12 @@ protected function isNotPwned(string $password): bool
*/
protected function isNotInHistory(string $password): bool
{
if (!auth()->check()) {
return true; // No logged in user to check history for
$user = $this->user ?? (auth()->check() ? auth()->user() : null);

if (!$user) {
return true;
}

$user = auth()->user();
$passwordHistory = PasswordHistory::where('user_id', $user->id)
->orderBy('created_at', 'desc')
->limit($this->historySize)
Expand All @@ -194,14 +208,20 @@ protected function isNotInHistory(string $password): bool
*/
public function message()
{
return [
'length' => 'Password harus memiliki minimal :min karakter.',
$messages = [
'length' => 'Password harus memiliki minimal '.$this->minLength.' karakter.',
'complexity' => 'Password harus mengandung huruf kapital, huruf kecil, angka, dan karakter spesial (!@#$%^&*...).',
'hibp' => 'Password ini telah bocor di database password yang pernah diretas. Silakan gunakan password lain yang lebih unik.',
'history' => 'Password ini telah digunakan sebelumnya. Silakan gunakan password baru.',
'weak_pattern' => 'Password terlalu lemah atau mudah ditebak. Hindari pola berulang atau berurutan.',
'common' => 'Password ini terlalu umum dan mudah ditebak. Silakan gunakan password yang lebih unik.',
];

if ($this->failedRule && isset($messages[$this->failedRule])) {
return $messages[$this->failedRule];
}

return 'Password tidak memenuhi persyaratan keamanan.';
}

/**
Expand Down
Loading
Loading