LoginForm.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Windows.Forms;
  3. using Npgsql;
  4. namespace PhotoStudioApp
  5. {
  6. public partial class LoginForm : Form
  7. {
  8. private string connectionString = "Host=245e1-rw.db.pub.dbaas.postgrespro.ru;Port=5432;Database=dbproject;Username=smirnova_ul;Password=Q#Rto%g$$$5;SSL Mode=Require;Trust Server Certificate=true;";
  9. public LoginForm()
  10. {
  11. InitializeComponent();
  12. }
  13. private void btnLogin_Click(object sender, EventArgs e)
  14. {
  15. string login = txtLogin.Text;
  16. string password = txtPassword.Text;
  17. string hash = GetSHA256Hash(password);
  18. using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
  19. {
  20. conn.Open();
  21. string sql = "select u.user_id, r.role_name from users u join roles r on u.role_id = r.role_id where u.login = @login and u.password_hash = @hash";
  22. NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
  23. cmd.Parameters.AddWithValue("@login", login);
  24. cmd.Parameters.AddWithValue("@hash", hash);
  25. using (NpgsqlDataReader reader = cmd.ExecuteReader())
  26. {
  27. if (reader.Read())
  28. {
  29. int userId = reader.GetInt32(0);
  30. string role = reader.GetString(1);
  31. MessageBox.Show($"Добро пожаловать, {login}! Роль: {role}");
  32. MainForm mainForm = new MainForm(userId, role, login, connectionString);
  33. mainForm.Show();
  34. this.Hide();
  35. }
  36. else
  37. {
  38. MessageBox.Show("Неверный логин или пароль");
  39. }
  40. }
  41. }
  42. }
  43. private string GetSHA256Hash(string input)
  44. {
  45. using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create())
  46. {
  47. byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
  48. byte[] hashBytes = sha256.ComputeHash(inputBytes);
  49. return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
  50. }
  51. }
  52. protected override void OnFormClosing(FormClosingEventArgs e)
  53. {
  54. if (this.Owner == null)
  55. {
  56. Application.Exit();
  57. }
  58. base.OnFormClosing(e);
  59. }
  60. }
  61. }