Files
CodingSandbox/winforms_security_sandbox.md
T
2026-05-31 15:54:46 +03:00

19 KiB
Raw Blame History

📄 .NET 4.8.1 WinForms Authentication & Security Sandbox Manual

Welcome to the technical documentation of the C# WinForms Authentication & Security Sandbox. This manual is organized into two complete sections: Section 1 in English and Bölüm 2 in Turkish.


SECTION 1: English (Technical Manual)

A premium, modern desktop authentication and user management sandbox designed for C# WinForms targeting .NET Framework 4.8.1.

🏗 Architecture & Design

The application utilizes a clean Separation of Concerns (SoC) model with shared service layers and event-driven updates.

graph TD
    classDef main fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,color:#fff;
    classDef service fill:#0F172A,stroke:#6366F1,stroke-width:2px,color:#fff;
    classDef model fill:#1E293B,stroke:#10B981,stroke-width:2px,color:#fff;

    MainForm[MainForm<br/>Dashboard]:::main
    LoginDialog[LoginDialog<br/>Sign In]:::main
    UserSettings[UserSettings<br/>Directory Manager]:::main
    
    SessionManager[SessionManager<br/>State & Events]:::service
    User[User Model]:::model

    MainForm -->|Subscribes to Events| SessionManager
    MainForm -->|Opens dialog| LoginDialog
    MainForm -->|Opens dialog| UserSettings

    LoginDialog -->|Authenticates| SessionManager
    UserSettings -->|Modifies directories| SessionManager
    
    SessionManager -->|Manages| User

📂 Project Directory Structure

Here are the key files created for this project in UserPermissionTest_CS_WinForms:

  • 📄 UserPermissionTest_CS_WinForms.csproj: SDK-style project file configured for net481 with Windows Forms enabled and Newtonsoft.Json package installed.
  • 📄 Program.cs: Main execution entry point.
  • 📄 User.cs: Object model for users holding Username, Full Name, Password (hashed), and Permissions list (ID-based, List).
  • 📄 Permission.cs: Object model for system permissions holding Id (int) and Name (string).
  • 📄 SessionManager.cs: Dynamic state and session service utilizing cross-form event notifications (SessionStateChanged, UsersUpdated).
  • 📄 PasswordHasher.cs: Cryptographic utility providing one-way SHA-256 password hashing and validation.
  • 🖥 MainForm:
  • 🖥 LoginDialog:
  • 🖥 UserSettings:
    • UserSettings.cs: Directory editor, user details modifier, and dynamic system permissions register. Supports secure password placeholders and toggles.
    • UserSettings.Designer.cs: Side-by-side catalog and profile fields.

🗄️ Repository Pattern & PostgreSQL Database Integration

To address enterprise-level data persistence, the data layer has been decoupled using the Repository Pattern and is fully integrated with PostgreSQL using the Npgsql database driver:

graph LR
    SessionManager -->|Uses| IUserRepository
    IUserRepository <|.. JsonUserRepository
    IUserRepository <|.. PostgreSqlUserRepository
    
    style IUserRepository fill:#1E293B,stroke:#F59E0B,stroke-width:2px,color:#fff
    style JsonUserRepository fill:#1E293B,stroke:#10B981,stroke-width:2px,stroke-dasharray: 5 5
    style PostgreSqlUserRepository fill:#1E293B,stroke:#0EA5E9,stroke-width:2px

Decoupled Implementations:

  • IUserRepository.cs: Contract layer. Declares LoadUsers, SaveUsers, LoadPermissions, and SavePermissions.
  • PostgreSqlUserRepository.cs: Active Production Provider. Connects to a local PostgreSQL instance, handles automatic schema initialization (tables users, user_permissions, available_permissions), and uses robust atomic transactions for synchronization.
  • JsonUserRepository.cs: Alternative file-based (JSON) storage provider using Newtonsoft.Json. Writes/reads database parameters to local files users.json / permissions.json inside output build directories.

🐘 Active PostgreSQL Configuration:

The database connection is managed directly via Dependency Injection in SessionManager.cs:

private static readonly IUserRepository UserRepository = new PostgreSqlUserRepository("Host=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=postgres");
  • Seamless Interchangeability: Switching back to JSON file storage is as simple as commenting out the PostgreSQL line and uncommenting the JSON class. None of the Windows Forms (MainForm, LoginDialog, UserSettings) require any code edits.

🔒 Role-Based Access Control (RBAC)

The application enforces fine-grained authorization constraints on dashboard actions based on active session permissions:

  • Locked State (Not Logged In):
    • The Manage Users button is completely disabled and marked as 🔒 Manage Users.
  • Unauthorized State (Logged In without privilege):
    • If a user logs in (e.g., user) but does not have the Manage Users or Full Control permission:
      • The directory button is locked and updated to 🔒 Manage Users (Locked).
      • Client-side defensive checks verify permissions upon any attempt to click the control, displaying a security alert if breached.
  • Authorized State (Logged In with privilege):
    • If a user logs in (e.g., admin) and has the Manage Users or Full Control permission:
      • The directory button becomes fully active and updates to 👥 Manage Users.

🔐 Cryptographic Security & Password UX

The application implements enterprise-level password security and high-fidelity visibility controls:

  • SHA-256 One-Way Hashing:
    • Passwords are never stored or processed in plain text. PasswordHasher.cs computes a secure SHA-256 hash using System.Security.Cryptography for database-compatible security.
  • On-the-Fly Hashing Migration:
    • The file parser in JsonUserRepository dynamically intercepts old plain-text database profiles on startup. If a legacy plain-text password is encountered, it hashes it instantly and saves the migrated database back to disk transparently.
  • Secure Administrator Directory Workflows:
    • When loading user profiles in UserSettings, the password is never sent to the UI. Instead, a protective bullet mask ●●●●●●●● is shown.
    • If the administrator edits other details but leaves the password field containing the mask ●●●●●●●●, the system detects this and keeps the current hashed password completely intact.
    • If the administrator writes a new string, it hashes and overrides it.
  • Interactive Password Toggles (Show/Hide):
    • An elegant, borderless eye button (btnTogglePassword with 👁/🙈 states) is added adjacent to password boxes in LoginDialog and UserSettings to dynamically toggle characters between masked bullets '•' and plain text.

🎨 Visual Design Choices

  • Harmonious Palettes:
    • Header Panels: Slate Navy (#1E293B)
    • Buttons: Indigo Purple (#6366F1) and Emerald Green (#10B981)
    • Backgrounds: White (#FFFFFF) with contrasting light slate fills (#F8FAFC, #F1F5F9)
  • Typography: Clean Segoe UI fonts utilizing structured bold/semi-bold weight hierarchy for high legibility.
  • Badges & Lists: Green/Red status badge for signed-in sessions and bulleted checklists displaying privileges.

🧪 Pre-Configured Test Credentials

For quick testing, the sandbox initializes with the following default users:

  1. Administrator User

    • Username: admin
    • Password: admin
    • Permissions: View Dashboard, Edit Settings, Manage Users, Full Control
  2. Standard User

    • Username: user
    • Password: user
    • Permissions: View Dashboard


BÖLÜM 2: Türkçe (Teknik Kılavuz)

C# WinForms ortamında geliştirilen ve .NET Framework 4.8.1 sürümünü hedefleyen modern, yüksek güvenlikli kullanıcı oturum ve yetki yönetim laboratuvarı belgesidir.

🏗 Mimari Tasarım ve Akış

Uygulama, veri katmanını kullanıcı arayüzünden tamamen ayıran temiz bir Sorumlulukların Ayrılması (SoC) mimarisi ve olay güdümlü (event-driven) güncelleme akışları kullanır.

graph TD
    classDef main fill:#1E293B,stroke:#0EA5E9,stroke-width:2px,color:#fff;
    classDef service fill:#0F172A,stroke:#6366F1,stroke-width:2px,color:#fff;
    classDef model fill:#1E293B,stroke:#10B981,stroke-width:2px,color:#fff;

    MainForm[MainForm<br/>Dashboard / Panel]:::main
    LoginDialog[LoginDialog<br/>Giriş Ekranı]:::main
    UserSettings[UserSettings<br/>Dizin ve Ayarlar]:::main
    
    SessionManager[SessionManager<br/>Durum ve Olaylar]:::service
    User[User Modeli]:::model

    MainForm -->|Olaylara Abone Olur| SessionManager
    MainForm -->|Açılır Dialog| LoginDialog
    MainForm -->|Açılır Dialog| UserSettings

    LoginDialog -->|Kimlik Doğrular| SessionManager
    UserSettings -->|Dizini Düzenler| SessionManager
    
    SessionManager -->|Yönetir| User

📂 Proje Dizin Yapısı

UserPermissionTest_CS_WinForms dizininde oluşturulan temel bileşenler şunlardır:

  • 📄 UserPermissionTest_CS_WinForms.csproj: net481 hedefleyen, Windows Forms etkinleştirilmiş ve Newtonsoft.Json bağımlılığı yüklenmiş SDK stili modern proje dosyası.
  • 📄 Program.cs: Uygulamanın ana giriş noktası.
  • 📄 User.cs: Kullanıcı adı, Ad Soyad, Parola (Hash formatında) ve İzin listesini (ID tabanlı, List) barındıran veri sınıfı.
  • 📄 Permission.cs: Sistemdeki yetkilerin benzersiz kimliğini (Id) ve metnini (Name) barındıran veri sınıfı.
  • 📄 SessionManager.cs: Formlar arasında gerçek zamanlı olay bildirimleri (SessionStateChanged, UsersUpdated) sunan merkezi statik oturum yöneticisi.
  • 📄 PasswordHasher.cs: SHA-256 tek yönlü parola kriptolama ve doğrulama yardımcı sınıfı.
  • 🖥 MainForm:
    • MainForm.cs: Aktif oturum ve yetki durumu değişikliklerini dinleyen ana panel kodları.
    • MainForm.Designer.cs: Tasarım arayüzü ve yerleşim bileşenleri.
  • 🖥 LoginDialog:
  • 🖥 UserSettings:
    • UserSettings.cs: Kullanıcı listeleme, ekleme, silme ve dinamik izin tanımlama kodları. Maskelenmiş yönetici şifre düzenleme korumasını barındırır.
    • UserSettings.Designer.cs: Yan yana katalog ve profil giriş alanları.

🗄️ Depo Tasarım Deseni (Repository Pattern) & Aktif PostgreSQL Entegrasyonu

Veri erişim katmanı tamamen Repository Deseni ile soyutlaştırılmış ve Npgsql veritabanı sürücüsü kullanılarak aktif olarak PostgreSQL veritabanına bağlanmıştır:

graph LR
    SessionManager -->|Kullanır| IUserRepository
    IUserRepository <|.. JsonUserRepository
    IUserRepository <|.. PostgreSqlUserRepository
    
    style IUserRepository fill:#1E293B,stroke:#F59E0B,stroke-width:2px,color:#fff
    style JsonUserRepository fill:#1E293B,stroke:#10B981,stroke-width:2px,stroke-dasharray: 5 5
    style PostgreSqlUserRepository fill:#1E293B,stroke:#0EA5E9,stroke-width:2px

Depo Gerçekleştirmeleri:

  • IUserRepository.cs: Tanım arayüzüdür. LoadUsers, SaveUsers, LoadPermissions ve SavePermissions imzalarını içerir.
  • PostgreSqlUserRepository.cs: Aktif Veritabanı Sağlayıcısı. PostgreSQL servisine bağlanır, sistem tablolarını (users, user_permissions, available_permissions) başlangıçta otomatik olarak oluşturur ve güvenli veritabanı işlemleri için Transaction tabanlı veri senkronizasyonu yapar.
  • JsonUserRepository.cs: Alternatif dosya tabanlı (JSON) veri saklayıcıdır. Çıktı dizinindeki users.json ve permissions.json dosyalarını okur/yazar.

🐘 Aktif PostgreSQL Yapılandırması:

Veritabanı bağlantısı SessionManager.cs dosyasında tek bir satır üzerinden Dependency Injection ile yönetilir:

private static readonly IUserRepository UserRepository = new PostgreSqlUserRepository("Host=127.0.0.1;Port=5432;Database=postgres;Username=postgres;Password=postgres");
  • Kusursuz Değiştirilebilirlik: JSON tabanlı dosya saklama modülüne geri geçmek isterseniz, PostgreSQL satırını yorum satırı yapıp JSON satırını açmanız yeterlidir. Arayüz kodlarında (MainForm, LoginDialog veya UserSettings) tek bir satır dahi değişmez.

🔒 Rol Tabanlı Yetki Kontrolü (RBAC)

Uygulama, giriş yapan kullanıcının aktif izinlerine göre arayüzdeki işlemleri dinamik olarak kısıtlar:

  • Oturum Yokken (Kilitli Durum):
    • Kullanıcı yönetim butonu devre dışı kalır ve 🔒 Manage Users metniyle gösterilir.
  • Oturum Var Ancak İzin Yetersizken (Yetkisiz Durum):
    • Giriş yapan kullanıcının yetkileri arasında Manage Users veya Full Control yoksa:
      • Buton pasif kalır ve durum bilgisini belli etmek için 🔒 Manage Users (Locked) olarak güncellenir.
      • Tıklama olayında arka planda yetki kontrolü tekrarlanır ve yetkisiz erişim teşebbüslerinde güvenlik uyarısı verilir.
  • Oturum Var ve Yetki Yeterliyken (Yetkili Durum):
    • Kullanıcı yetkili ise buton anında aktifleşir, simgesi ve metni 👥 Manage Users olarak güncellenir ve tıklanabilir hale gelir.

🔐 Kriptografik Güvenlik & Parola Deneyimi (UX)

Uygulama üst düzey parola güvenliği standartları ve gelişmiş gizleme/gösterme yetenekleriyle donatılmıştır:

  • SHA-256 Tek Yönlü Kriptolama:
    • Şifreler diskte asla düz metin olarak saklanmaz. PasswordHasher.cs sınıfı, System.Security.Cryptography kütüphanesini kullanarak parolaları SHA-256 formatında şifreler.
  • Arka Planda Dinamik Otomatik Göç (Auto Hashing Migration):
    • JsonUserRepository dosya okuma aşamasında eski/açık metin parola kayıtları algılarsa, bunları arka planda otomatik olarak SHA-256 hash formatına dönüştürür ve diske güvenli şekilde geri yazar.
  • Güvenli Yönetim Ekranı Parola İşlemleri:
    • Kullanıcı detayları yüklendiğinde gerçek şifre hash'i arayüze gönderilmez; yerine ●●●●●●●● şeklinde güvenli bir maske gösterilir.
    • Şifre alanını ●●●●●●●● olarak bıraktığınızda sistem şifrenin değiştirilmediğini algılar ve mevcut hash'i aynen korur. Yeni bir şifre yazıldığında ise bunu şifreleyerek kaydeder.
  • Şifre Göster/Gizle Butonları (Eye Toggles):
    • LoginDialog ve UserSettings şifre kutularının sağına eklenen modern kenarlıksız göz butonu (btnTogglePassword ile 👁/🙈 durumları) şifrenin maskelenmesi '•' ve düz metin gösterilmesi arasında dinamik geçiş sağlar.

🎨 Görsel Tasarım Tercihleri

  • Özel Uyumlu Renk Paleti:
    • Üst Bilgi Panelleri: Modern Koyu Lacivert/Siyah (#1E293B)
    • Etkin Butonlar: İndigo Moru (#6366F1) ve Zümrüt Yeşili (#10B981)
    • Form Zeminleri: Beyaz (#FFFFFF) ve kontrast açık gri/slate dolgular (#F8FAFC, #F1F5F9)
  • Tipografi: Browser varsayılanları yerine temiz, okunaklılığı yüksek yarı kalın/kalın yapılandırılmış Segoe UI yazı tipleri kullanılmıştır.
  • Durum Bildirimleri: Oturum durumunu gösteren Yeşil/Kırmızı dinamik rozetler ve izin listesinde zengin onay sembolleri ().

🧪 Hazır Test Kullanıcı Bilgileri

Hızlı test işlemleri için sistem başlangıçta şu hesapları barındırır:

  1. Yönetici Kullanıcı (Tüm Yetkilere Sahip)

    • Kullanıcı Adı: admin
    • Parola: admin
    • Yetkileri: View Dashboard, Edit Settings, Manage Users, Full Control
  2. Standart Kullanıcı

    • Kullanıcı Adı: user
    • Parola: user
    • Yetkileri: View Dashboard