Files
PIbd-32_BuslaevRoman_KOP/WinFormsComponentOrientedHost/Auth/LoginForm.cs
2025-09-23 14:47:56 +04:00

83 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsComponentOrientedHost.Data.Entities;
namespace WinFormsComponentOrientedHost.Auth;
public sealed class LoginForm : Form
{
private readonly IAuthService _auth;
private readonly TextBox _tbLogin = new() { Dock = DockStyle.Fill };
private readonly TextBox _tbPass = new() { Dock = DockStyle.Fill, UseSystemPasswordChar = true };
private readonly Button _btnLogin = new() { Text = "Войти", AutoSize = true };
private readonly Button _btnReg = new() { Text = "Регистрация", AutoSize = true };
private readonly Button _btnCancel = new() { Text = "Отмена", AutoSize = true, DialogResult = DialogResult.Cancel };
public User? AuthenticatedUser { get; private set; }
public LoginForm(IAuthService auth)
{
_auth = auth;
Text = "Вход";
StartPosition = FormStartPosition.CenterScreen;
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = MinimizeBox = false;
Width = 400; Height = 200;
var table = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 3, Padding = new Padding(10) };
table.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
table.Controls.Add(new Label { Text = "Логин:", AutoSize = true }, 0, 0);
table.Controls.Add(_tbLogin, 1, 0);
table.Controls.Add(new Label { Text = "Пароль:", AutoSize = true }, 0, 1);
table.Controls.Add(_tbPass, 1, 1);
var buttons = new FlowLayoutPanel { FlowDirection = FlowDirection.RightToLeft, Dock = DockStyle.Fill, AutoSize = true };
buttons.Controls.Add(_btnLogin);
buttons.Controls.Add(_btnReg);
buttons.Controls.Add(_btnCancel);
table.Controls.Add(buttons, 0, 2);
table.SetColumnSpan(buttons, 2);
Controls.Add(table);
AcceptButton = _btnLogin;
CancelButton = _btnCancel;
_btnLogin.Click += async (_, __) =>
{
try
{
var user = await _auth.AuthenticateAsync(_tbLogin.Text.Trim(), _tbPass.Text);
if (user == null)
{
MessageBox.Show(this, "Неверный логин или пароль.", "Вход", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
AuthenticatedUser = user;
DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageBox.Show(this, "Ошибка входа: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
};
_btnReg.Click += async (_, __) =>
{
using var reg = new RegistrationForm(_auth);
if (reg.ShowDialog(this) == DialogResult.OK && !string.IsNullOrWhiteSpace(reg.RegisteredLogin))
{
_tbLogin.Text = reg.RegisteredLogin;
_tbPass.Focus();
}
};
}
}