LoginForm.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Npgsql;
  2. using System;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using System.Windows.Forms;
  6. namespace DeanOfficeApp
  7. {
  8. public partial class LoginForm : Form
  9. {
  10. private readonly string _connString = "Host=245e1-rw.db.pub.dbaas.postgrespro.ru;Port=5432;Database=dbpractice;Username=mardasov_mv;Password=A4%2x$$2Ynr";
  11. public string UserRole { get; private set; }
  12. public string Username { get; private set; }
  13. public string FullName { get; private set; }
  14. public LoginForm()
  15. {
  16. InitializeComponent();
  17. txtPassword.PasswordChar = '*';
  18. }
  19. private async void btnLogin_Click(object sender, EventArgs e)
  20. {
  21. string username = txtUsername.Text.Trim();
  22. string password = txtPassword.Text;
  23. if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
  24. {
  25. MessageBox.Show("Введите логин и пароль!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  26. return;
  27. }
  28. string hash = ComputeMd5(password);
  29. try
  30. {
  31. using (var conn = new NpgsqlConnection(_connString))
  32. {
  33. await conn.OpenAsync();
  34. string sql = "SELECT role, full_name FROM appuser WHERE username = @user AND password_hash = @hash";
  35. using (var cmd = new NpgsqlCommand(sql, conn))
  36. {
  37. cmd.Parameters.AddWithValue("@user", username);
  38. cmd.Parameters.AddWithValue("@hash", hash);
  39. using (var reader = await cmd.ExecuteReaderAsync())
  40. {
  41. if (await reader.ReadAsync())
  42. {
  43. UserRole = reader.GetString(0);
  44. FullName = reader.GetString(1);
  45. Username = username;
  46. DialogResult = DialogResult.OK;
  47. Close();
  48. }
  49. else
  50. {
  51. MessageBox.Show("Неверный логин или пароль!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  52. }
  53. }
  54. }
  55. }
  56. }
  57. catch (Exception ex)
  58. {
  59. MessageBox.Show($"Ошибка подключения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  60. }
  61. }
  62. private string ComputeMd5(string input)
  63. {
  64. using (MD5 md5 = MD5.Create())
  65. {
  66. byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
  67. StringBuilder sb = new StringBuilder();
  68. foreach (byte b in hash) sb.Append(b.ToString("x2"));
  69. return sb.ToString();
  70. }
  71. }
  72. private void btnExit_Click(object sender, EventArgs e) => Application.Exit();
  73. private void chkShowPassword_CheckedChanged(object sender, EventArgs e) => txtPassword.PasswordChar = chkShowPassword.Checked ? '\0' : '*';
  74. private void panelLogin_Paint(object sender, PaintEventArgs e)
  75. {
  76. }
  77. }
  78. }