PHP code example of cms-orbit / password-security

1. Go to this page and download the library: Download cms-orbit/password-security library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cms-orbit / password-security example snippets




namespace App\Models;

use CmsOrbit\PasswordSecurity\Traits\HasPasswordSecurity;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasPasswordSecurity;
    
    // 패스워드 필드명 (기본값: 'password')
    protected $passwordSecurityField = 'password';
    
    // 개인정보 필드 (패스워드에 포함 방지)
    protected $passwordSecurityPersonalFields = [
        'name',
        'email',
        'username',
    ];
}

'models' => [
    \App\Models\User::class,
    // 다른 모델 추가...
],

protected $middlewareGroups = [
    'web' => [
        // ...
        \CmsOrbit\PasswordSecurity\Middleware\CheckPasswordExpiration::class,
        \CmsOrbit\PasswordSecurity\Middleware\CheckAccountActive::class,
    ],
];

Route::middleware(['auth', 'password.expiration', 'account.active'])->group(function () {
    // 보호된 라우트들...
});

use CmsOrbit\PasswordSecurity\Rules\PasswordSecurityRule;

$request->validate([
    'password' => ['

use CmsOrbit\PasswordSecurity\Rules\PasswordSecurityRule;
use Laravel\Nova\Fields\Password;

Password::make('Password', 'password')
    ->rules('

use CmsOrbit\PasswordSecurity\Validators\PasswordValidator;

$validator = new PasswordValidator();

try {
    $validator->validate($password, $user, true);
    // 검증 성공
} catch (\CmsOrbit\PasswordSecurity\Exceptions\WeakPasswordException $e) {
    // 검증 실패
    $errors = $e->getErrors();
    $message = $e->getMessage();
}

$validator = new PasswordValidator();

// 복잡도만 검증
if (!$validator->validateComplexity($password)) {
    // 복잡도 검증 실패
}

// 일반 패턴만 검증
if (!$validator->validateCommonPattern($password)) {
    // 일반 패턴 검증 실패
}

// 개인정보만 검증
if (!$validator->validatePersonalInfo($password, $user)) {
    // 개인정보 검증 실패
}

// 히스토리만 검증
if (!$validator->validateHistory($password, $user)) {
    // 히스토리 검증 실패
}

// 패스워드 만료 확인
if ($user->isPasswordExpired()) {
    // 만료됨
}

// 만료까지 남은 일수
$daysRemaining = $user->getDaysUntilPasswordExpiration();

// 계정 활성화 상태 확인
if ($user->isAccountActive()) {
    // 활성화됨
}

// 계정 비활성화
$user->deactivateAccount('inactivity');

// 계정 활성화
$user->activateAccount();

// 패스워드 히스토리 확인
if ($user->isPasswordInHistory($newPassword)) {
    // 최근 사용한 패스워드
}

// 마지막 로그인 업데이트
$user->updateLastLogin();

// 휴면 계정 관리 (HasFreezePolicy trait 사용 시)
// 계정이 휴면 상태인지 확인
if ($user->isFrozen()) {
    // 휴면 상태
}

// 계정을 휴면 상태로 설정
$user->freeze();

// 계정을 활성 상태로 복구
$user->unfreeze();

// 활성화 상태 기준일 가져오기
$baseDate = $user->getDaysUntilFreeze();

// 휴면 기준일 가져오기
$inactiveDays = $user->getFreezeInactiveDays();

// 비활성화 전 알림 일자들 가져오기
$notifyBeforeDays = $user->getFreezeNotifyBeforeDays();

// 제외 여부 확인
if ($user->isExclusion()) {
    // 휴면 대상에서 제외됨
}

'complexity' => [
    'enabled' => true,
    'min_length_2_types' => 10,         // 2가지 조합 시 최소 길이
    'min_length_3_types' => 8,          // 3가지 조합 시 최소 길이
    'min_length_4_types' => 8,          // 4가지 조합 시 최소 길이
    '

'common_patterns' => [
    'enabled' => true,
    'block_sequential_numbers' => true,      // 연속 숫자 차단
    'block_sequential_letters' => true,      // 연속 문자 차단
    'block_repeated_characters' => true,     // 반복 문자 차단
    'repeated_char_threshold' => 3,          // 반복 허용 횟수
    'block_keyboard_patterns' => true,       // 키보드 패턴 차단
    'block_common_words' => true,            // 일반 단어 차단
    'block_birthday_patterns' => true,       // 생일 패턴 차단
    'block_phone_patterns' => true,          // 전화번호 패턴 차단
    'sequential_threshold' => 3,             // 연속 허용 개수
    'common_words_list' => [...],            // 차단할 단어 목록
    'keyboard_patterns' => [...],            // 키보드 패턴 목록
],

'personal_info' => [
    'enabled' => true,
    'block_name' => true,                    // 이름 포함 차단
    'block_email' => true,                   // 이메일 포함 차단
    'block_username' => true,                // 사용자명 포함 차단
    'additional_fields' => [],               // 추가 차단 필드
    'min_substring_length' => 3,             // 최소 부분 문자열 길이
    'case_insensitive' => true,              // 대소문자 구분 없음
],

'history' => [
    'enabled' => true,
    'check_last_n_passwords' => 3,          // 최근 N개 체크
    'keep_history_for_days' => 365,         // 보관 기간
    'auto_cleanup' => true,                 // 자동 정리
],

'expiration' => [
    'enabled' => true,
    'expires_in_days' => 90,                 // 만료 기간 (분기)
    'notify_before_days' => [7, 3, 1],       // 만료 전 알림
    'grace_period_days' => 0,                // 유예 기간
    'force_change_on_first_login' => false,  // 첫 로그인 강제 변경
    'redirect_after_change' => '/',          // 변경 후 리다이렉트
    'excluded_routes' => [...],              // 제외 라우트
    'excluded_urls' => [...],                // 제외 URL 패턴
],

'inactive_accounts' => [
    'enabled' => true,
    'target_models' => [
        \AppCentral\Models\User::class,
    ],
    'target_tenant_models' => [
        \AppTenants\Models\Promoter::class,
    ],
],

use CmsOrbit\PasswordSecurity\Traits\HasFreezePolicy;

class User extends Authenticatable
{
    use HasFreezePolicy;
    
    // 휴면 기준일 (기본값: 90일)
    protected $freezeInactiveDays = 90;
    // 또는 메서드로
    public function getFreezeInactiveDays(): int
    {
        return 90;
    }
    
    // 비활성화 전 알림 일자들 (기본값: [14, 7, 3])
    protected $freezeNotifyBeforeDays = [14, 7, 3];
    
    // 비활성화 후 삭제기간 (기본값: 7일, null이면 삭제 안 함)
    protected $freezeDeleteAfterDays = 7;
    
    // 강제삭제 기간 (SoftDeletes 모델용, 기본값: 5일)
    protected $freezeForceDeleteAfterDays = 5;
    
    // 계정활성화 상태 필드명 (기본값: 'is_freeze')
    protected $freezeStatusField = 'is_freeze';
    
    // 휴면대상에서 제외할 모델인지 판별
    public function isExclusion(): bool
    {
        // 특정 조건에 따라 제외
        return $this->hasRole('admin');
    }
    
    // 활성화 상태 기준일 반환 (마지막 로그인일 또는 생성일)
    public function getDaysUntilFreeze(): \Carbon\Carbon
    {
        $lastLoginAt = $this->lastLoginAt();
        return $lastLoginAt ? \Carbon\Carbon::parse($lastLoginAt) : $this->created_at;
    }
}

'notifications' => [
    'enabled' => true,
    'channels' => ['mail'],                  // 알림 채널
    'expiration' => [
        'enabled' => true,
        'mail_subject' => 'Password Expiration Notice',
    ],
    'inactive_account' => [
        'enabled' => true,
        'mail_subject' => 'Account Inactivity Notice',
    ],
],

'views' => [
    'password_change' => 'password-security::password-change',
    'account_inactive' => 'password-security::account-inactive',
],

'exceptions' => [
    'throw_exceptions' => true,              // Exception 발생 여부
    'log_violations' => true,                // 위반 사항 로그 기록
    'log_channel' => null,                   // 로그 채널
],
bash
php artisan vendor:publish --tag=password-security-config
php artisan vendor:publish --tag=password-security-migrations
php artisan vendor:publish --tag=password-security-views
php artisan vendor:publish --tag=password-security-lang
bash
php artisan migrate
bash
# 일반 실행
php artisan password-security:freeze

# Dry-run (실제 처리 없이 확인)
php artisan password-security:freeze --dry-run

# 비활성화 전 알림 발송
php artisan password-security:freeze --notify
bash
php artisan vendor:publish --tag=password-security-views
bash
php artisan vendor:publish --tag=password-security-lang