| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- using Npgsql;
- using System;
- using System.Configuration;
- using System.Security.Cryptography;
- using System.Text;
- using System.Windows.Forms;
- namespace WindowsFormsApp4
- {
- public partial class Register : Form
- {
- private readonly string connStr = ConfigurationManager.ConnectionStrings["PostgreSQL"].ConnectionString;
- public Register()
- {
- InitializeComponent();
- }
- private void Register_Load(object sender, EventArgs e)
- {
- LoadLibraries();
- }
- private void LoadLibraries()
- {
- using (var conn = new NpgsqlConnection(connStr))
- {
- conn.Open();
- string query = "SELECT id, name FROM libraries ORDER BY name";
- using (var cmd = new NpgsqlCommand(query, conn))
- using (var reader = cmd.ExecuteReader())
- {
- comboBox1.Items.Clear();
- while (reader.Read())
- {
- string item = $"{reader["id"]} - {reader["name"]}";
- comboBox1.Items.Add(item);
- }
- }
- }
- }
- private bool IsValidEmail(string email)
- {
- if (string.IsNullOrWhiteSpace(email)) return false;
- try
- {
- var addr = new System.Net.Mail.MailAddress(email);
- return addr.Address == email;
- }
- catch
- {
- return false;
- }
- }
- private void button2_Click_1(object sender, EventArgs e)
- {
- if (!CheckFields())
- return;
- if (!IsValidEmail(textBox9.Text))
- {
- MessageBox.Show("Неверный формат Email", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return;
- }
- RegisterUser();
- }
- private bool CheckFields()
- {
- if (textBox5.Text != textBox6.Text)
- {
- MessageBox.Show("Пароли не совпадают", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return false;
- }
- if (string.IsNullOrWhiteSpace(textBox1.Text) ||
- string.IsNullOrWhiteSpace(textBox2.Text) ||
- string.IsNullOrWhiteSpace(textBox7.Text) ||
- string.IsNullOrWhiteSpace(maskedTextBox1.Text) ||
- string.IsNullOrWhiteSpace(textBox5.Text) ||
- string.IsNullOrWhiteSpace(textBox9.Text))
- {
- MessageBox.Show("Заполните все обязательные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return false;
- }
- if (comboBox1.SelectedItem == null)
- {
- MessageBox.Show("Выберите библиотеку", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- return false;
- }
- return true;
- }
- private void RegisterUser()
- {
- try
- {
- string selected = comboBox1.SelectedItem.ToString();
- int libraryId = int.Parse(selected.Split('-')[0].Trim());
- string login = textBox1.Text.Trim();
- string rawPassword = textBox5.Text;
- string name = textBox2.Text.Trim();
- string lastname = textBox7.Text.Trim();
- string phone = maskedTextBox1.Text.Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "");
- string email = textBox9.Text.Trim();
- string address = textBox4.Text.Trim();
- string salt = GenerateSalt();
- string hashedPassword = HashPassword(rawPassword, salt);
- int userId = CallRegisterFunction(libraryId, name, lastname, phone, email, address, login, hashedPassword, salt);
- if (userId > 0)
- {
- MessageBox.Show("Регистрация успешна! Теперь вы можете войти.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
- this.Close();
- }
- else
- {
- MessageBox.Show("Не удалось зарегистрировать пользователя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- catch (PostgresException ex)
- {
- MessageBox.Show($"Ошибка базы данных: {ex.MessageText}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- catch (Exception ex)
- {
- MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private string GenerateSalt()
- {
- byte[] saltBytes = new byte[16];
- using (var rng = new RNGCryptoServiceProvider())
- {
- rng.GetBytes(saltBytes);
- }
- return Convert.ToBase64String(saltBytes);
- }
- private string HashPassword(string password, string salt)
- {
- byte[] combined = Encoding.UTF8.GetBytes(password + salt);
- using (SHA256 sha256 = SHA256.Create())
- {
- byte[] hashBytes = sha256.ComputeHash(combined);
- return Convert.ToBase64String(hashBytes);
- }
- }
- private int CallRegisterFunction(int libraryId, string name, string lastname, string phone, string email, string address, string login, string hashedPassword, string salt)
- {
- using (var conn = new NpgsqlConnection(connStr))
- {
- conn.Open();
- string sql = "SELECT register_reader(@libId, @name, @lastname, @phone, @email, @address, @login, @password_hash, @salt)";
- using (var cmd = new NpgsqlCommand(sql, conn))
- {
- cmd.Parameters.AddWithValue("libId", libraryId);
- cmd.Parameters.AddWithValue("name", name);
- cmd.Parameters.AddWithValue("lastname", lastname);
- cmd.Parameters.AddWithValue("phone", phone);
- cmd.Parameters.AddWithValue("email", email);
- cmd.Parameters.AddWithValue("address", address ?? (object)DBNull.Value);
- cmd.Parameters.AddWithValue("login", login);
- cmd.Parameters.AddWithValue("password_hash", hashedPassword);
- cmd.Parameters.AddWithValue("salt", salt);
- object result = cmd.ExecuteScalar();
- return result != null ? Convert.ToInt32(result) : 0;
- }
- }
- }
- }
- }
|