AuthService.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using Npgsql;
  5. namespace ComputerShopWpf.Services
  6. {
  7. public class AuthService
  8. {
  9. public bool Login(string login, string password, out string errorMessage)
  10. {
  11. errorMessage = string.Empty;
  12. if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
  13. {
  14. errorMessage = "Введите логин и пароль.";
  15. return false;
  16. }
  17. try
  18. {
  19. DatabaseService database = new DatabaseService(ConnectionSettings.MainConnection);
  20. DataTable table = database.ExecuteSelect(
  21. "SELECT user_id, login, password_hash, role_name FROM app_users WHERE login = @login;",
  22. new Dictionary<string, object> { { "@login", login.Trim() } });
  23. if (table.Rows.Count == 0)
  24. {
  25. errorMessage = "Пользователь не найден.";
  26. return false;
  27. }
  28. DataRow row = table.Rows[0];
  29. string storedHash = Convert.ToString(row["password_hash"]);
  30. string enteredHash = PasswordHasher.ComputeSha256Hash(password);
  31. if (!string.Equals(storedHash, enteredHash, StringComparison.OrdinalIgnoreCase))
  32. {
  33. errorMessage = "Неверный пароль.";
  34. return false;
  35. }
  36. UserSession.UserId = Convert.ToInt32(row["user_id"]);
  37. UserSession.Login = Convert.ToString(row["login"]);
  38. UserSession.RoleName = Convert.ToString(row["role_name"]);
  39. return true;
  40. }
  41. catch (PostgresException ex)
  42. {
  43. errorMessage = "Ошибка PostgreSQL: " + ex.MessageText;
  44. return false;
  45. }
  46. catch (NpgsqlException ex)
  47. {
  48. errorMessage = "Ошибка подключения к базе данных: " + BuildExceptionMessage(ex);
  49. return false;
  50. }
  51. catch (Exception ex)
  52. {
  53. errorMessage = "Ошибка авторизации: " + BuildExceptionMessage(ex);
  54. return false;
  55. }
  56. }
  57. private static string BuildExceptionMessage(Exception exception)
  58. {
  59. string message = exception.Message;
  60. Exception current = exception.InnerException;
  61. while (current != null)
  62. {
  63. message += Environment.NewLine + current.GetType().Name + ": " + current.Message;
  64. current = current.InnerException;
  65. }
  66. return message;
  67. }
  68. }
  69. }