Register.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using Npgsql;
  2. using System;
  3. using System.Configuration;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Windows.Forms;
  7. namespace WindowsFormsApp4
  8. {
  9. public partial class Register : Form
  10. {
  11. private readonly string connStr = ConfigurationManager.ConnectionStrings["PostgreSQL"].ConnectionString;
  12. public Register()
  13. {
  14. InitializeComponent();
  15. }
  16. private void Register_Load(object sender, EventArgs e)
  17. {
  18. LoadLibraries();
  19. }
  20. private void LoadLibraries()
  21. {
  22. using (var conn = new NpgsqlConnection(connStr))
  23. {
  24. conn.Open();
  25. string query = "SELECT id, name FROM libraries ORDER BY name";
  26. using (var cmd = new NpgsqlCommand(query, conn))
  27. using (var reader = cmd.ExecuteReader())
  28. {
  29. comboBox1.Items.Clear();
  30. while (reader.Read())
  31. {
  32. string item = $"{reader["id"]} - {reader["name"]}";
  33. comboBox1.Items.Add(item);
  34. }
  35. }
  36. }
  37. }
  38. private bool IsValidEmail(string email)
  39. {
  40. if (string.IsNullOrWhiteSpace(email)) return false;
  41. try
  42. {
  43. var addr = new System.Net.Mail.MailAddress(email);
  44. return addr.Address == email;
  45. }
  46. catch
  47. {
  48. return false;
  49. }
  50. }
  51. private void button2_Click_1(object sender, EventArgs e)
  52. {
  53. if (!CheckFields())
  54. return;
  55. if (!IsValidEmail(textBox9.Text))
  56. {
  57. MessageBox.Show("Неверный формат Email", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  58. return;
  59. }
  60. RegisterUser();
  61. }
  62. private bool CheckFields()
  63. {
  64. if (textBox5.Text != textBox6.Text)
  65. {
  66. MessageBox.Show("Пароли не совпадают", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  67. return false;
  68. }
  69. if (string.IsNullOrWhiteSpace(textBox1.Text) ||
  70. string.IsNullOrWhiteSpace(textBox2.Text) ||
  71. string.IsNullOrWhiteSpace(textBox7.Text) ||
  72. string.IsNullOrWhiteSpace(maskedTextBox1.Text) ||
  73. string.IsNullOrWhiteSpace(textBox5.Text) ||
  74. string.IsNullOrWhiteSpace(textBox9.Text))
  75. {
  76. MessageBox.Show("Заполните все обязательные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  77. return false;
  78. }
  79. if (comboBox1.SelectedItem == null)
  80. {
  81. MessageBox.Show("Выберите библиотеку", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  82. return false;
  83. }
  84. return true;
  85. }
  86. private void RegisterUser()
  87. {
  88. try
  89. {
  90. string selected = comboBox1.SelectedItem.ToString();
  91. int libraryId = int.Parse(selected.Split('-')[0].Trim());
  92. string login = textBox1.Text.Trim();
  93. string rawPassword = textBox5.Text;
  94. string name = textBox2.Text.Trim();
  95. string lastname = textBox7.Text.Trim();
  96. string phone = maskedTextBox1.Text.Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
  97. string email = textBox9.Text.Trim();
  98. string address = textBox4.Text.Trim();
  99. string salt = GenerateSalt();
  100. string hashedPassword = HashPassword(rawPassword, salt);
  101. int userId = CallRegisterFunction(libraryId, name, lastname, phone, email, address, login, hashedPassword, salt);
  102. if (userId > 0)
  103. {
  104. MessageBox.Show("Регистрация успешна! Теперь вы можете войти.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
  105. this.Close();
  106. }
  107. else
  108. {
  109. MessageBox.Show("Не удалось зарегистрировать пользователя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  110. }
  111. }
  112. catch (PostgresException ex)
  113. {
  114. MessageBox.Show($"Ошибка базы данных: {ex.MessageText}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  115. }
  116. catch (Exception ex)
  117. {
  118. MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  119. }
  120. }
  121. private string GenerateSalt()
  122. {
  123. byte[] saltBytes = new byte[16];
  124. using (var rng = new RNGCryptoServiceProvider())
  125. {
  126. rng.GetBytes(saltBytes);
  127. }
  128. return Convert.ToBase64String(saltBytes);
  129. }
  130. private string HashPassword(string password, string salt)
  131. {
  132. byte[] combined = Encoding.UTF8.GetBytes(password + salt);
  133. using (SHA256 sha256 = SHA256.Create())
  134. {
  135. byte[] hashBytes = sha256.ComputeHash(combined);
  136. return Convert.ToBase64String(hashBytes);
  137. }
  138. }
  139. private int CallRegisterFunction(int libraryId, string name, string lastname, string phone, string email, string address, string login, string hashedPassword, string salt)
  140. {
  141. using (var conn = new NpgsqlConnection(connStr))
  142. {
  143. conn.Open();
  144. string sql = "SELECT register_reader(@libId, @name, @lastname, @phone, @email, @address, @login, @password_hash, @salt)";
  145. using (var cmd = new NpgsqlCommand(sql, conn))
  146. {
  147. cmd.Parameters.AddWithValue("libId", libraryId);
  148. cmd.Parameters.AddWithValue("name", name);
  149. cmd.Parameters.AddWithValue("lastname", lastname);
  150. cmd.Parameters.AddWithValue("phone", phone);
  151. cmd.Parameters.AddWithValue("email", email);
  152. cmd.Parameters.AddWithValue("address", address ?? (object)DBNull.Value);
  153. cmd.Parameters.AddWithValue("login", login);
  154. cmd.Parameters.AddWithValue("password_hash", hashedPassword);
  155. cmd.Parameters.AddWithValue("salt", salt);
  156. object result = cmd.ExecuteScalar();
  157. return result != null ? Convert.ToInt32(result) : 0;
  158. }
  159. }
  160. }
  161. }
  162. }