C# MVVM架构下SQLite登录校验实现方案咨询(附现有代码)
Implementing Login Logic with MVVM & SQLite
Hey there! Let's fix up your login flow to properly validate users against your SQLite database. I'll break this down step by step based on the code you've shared, making sure it fits your existing MVVM setup.
Step 1: Complete the AuthorizationService.Login Method
This is where the core validation logic lives. We need to query the database, check if the user exists, and verify their password matches the stored encrypted value. Here's the updated code:
public class AuthorizationService { private readonly ApplicationDbContext _db; // For now, we'll stick with your current DbContext initialization public AuthorizationService() { _db = new ApplicationDbContext(); } // Note: Later, consider using dependency injection to inject DbContext instead of new-ing it every time // public AuthorizationService(ApplicationDbContext db) => _db = db; public ServiceResult Login(string login, string password) { // Find the user by their login (ensure your User model has a Login property) var user = _db.Users.FirstOrDefault(u => u.Login == login); // Case 1: No user found with this login if (user == null) { return new ServiceResult("User with this login does not exist"); } // Case 2: User exists, check password match // Reuse the same Hashing class you used in registration var hashing = new Hashing(); var encryptedInputPassword = hashing.Encrypt(password); if (user.Password != encryptedInputPassword) { return new ServiceResult("Incorrect password"); } // Case 3: All checks passed return new ServiceResult(); } }
Step 2: Update the LoginViewModel to Use the Authorization Service
Next, we'll wire up the login command to call the service, handle results, and trigger navigation or feedback. I've renamed the command for clarity and added error handling:
public class LoginViewModel : BaseViewModel { private readonly AuthorizationService _authService; private readonly IViewFactory _viewFactory; private readonly ICore _core; private string _login; public string Login { get => _login; set { _login = value; RaisePropertyChanged(nameof(Login)); } } private string _password; public string Password { get => _password; set { _password = value; RaisePropertyChanged(nameof(Password)); } } // Optional: Property to display error messages in the UI private string _errorMessage; public string ErrorMessage { get => _errorMessage; set { _errorMessage = value; RaisePropertyChanged(nameof(ErrorMessage)); } } // Renamed AddCommand to LoginCommand for clarity private RelayCommand _loginCommand; public RelayCommand LoginCommand { get => _loginCommand ?? (_loginCommand = new RelayCommand(ExecuteLogin)); } public LoginViewModel(IViewFactory viewFactory, ICore core) : base(viewFactory) { _authService = new AuthorizationService(); _viewFactory = viewFactory; _core = core; } private void ExecuteLogin() { // Clear previous errors ErrorMessage = string.Empty; // Basic input validation (optional but user-friendly) if (string.IsNullOrWhiteSpace(Login)) { ErrorMessage = "Please enter your login"; return; } if (string.IsNullOrWhiteSpace(Password)) { ErrorMessage = "Please enter your password"; return; } // Call the authorization service var result = _authService.Login(Login, Password); if (!result.IsSucceed) { ErrorMessage = result.Error; return; } // On successful login: navigate to your main window (adjust based on your navigation setup) _core.NavigateTo<MainWindowViewModel>(); // Alternative if using view factory: _viewFactory.CreateView<MainWindowViewModel>().Show(); } }
Key Tips for Improvement
- Password Security: Ensure your
Hashing.Encryptmethod uses a secure one-way hashing algorithm like bcrypt or PBKDF2 instead of reversible encryption. This is critical for protecting user passwords. - DbContext Lifecycle: Creating a new
ApplicationDbContextevery time can cause resource leaks. Consider using dependency injection to manage scoped instances. - UI Binding: Bind the
ErrorMessageproperty to a TextBlock or similar element in your Login View to show validation feedback to users.
内容的提问来源于stack exchange,提问作者Deniz Hiumiustekin
相关产品推荐
相关产品推荐

