AuthService.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Npgsql;
  2. using TravelAgencyWinForms.Data;
  3. using TravelAgencyWinForms.Models;
  4. using TravelAgencyWinForms.Utils;
  5. namespace TravelAgencyWinForms.Services;
  6. public static class AuthService
  7. {
  8. public static bool Login(string login, string password, out string error)
  9. {
  10. error = string.Empty;
  11. try
  12. {
  13. var table = Db.Query(
  14. "SELECT * FROM fn_authenticate_user(@login, @password);",
  15. new NpgsqlParameter("login", login.Trim()),
  16. new NpgsqlParameter("password", password));
  17. if (table.Rows.Count == 0)
  18. {
  19. error = "Неверный логин или пароль, либо учётная запись отключена.";
  20. return false;
  21. }
  22. var row = table.Rows[0];
  23. CurrentUser.UserId = Convert.ToInt32(row["user_id"]);
  24. CurrentUser.Login = Convert.ToString(row["login"]) ?? string.Empty;
  25. CurrentUser.Role = Convert.ToString(row["role"]) ?? string.Empty;
  26. if (table.Columns.Contains("client_id"))
  27. CurrentUser.ClientId = row["client_id"] == DBNull.Value ? null : Convert.ToInt32(row["client_id"]);
  28. else if (table.Columns.Contains("employee_id"))
  29. CurrentUser.ClientId = row["employee_id"] == DBNull.Value ? null : Convert.ToInt32(row["employee_id"]);
  30. else
  31. CurrentUser.ClientId = null;
  32. if (table.Columns.Contains("client_name"))
  33. {
  34. CurrentUser.ClientName = Convert.ToString(row["client_name"]) ?? string.Empty;
  35. }
  36. else if (CurrentUser.ClientId != null)
  37. {
  38. var clientTable = Db.Query(
  39. "SELECT concat_ws(' ', last_name, first_name, middle_name) AS client_name FROM clients WHERE client_id = @client_id;",
  40. new NpgsqlParameter("client_id", CurrentUser.ClientId.Value));
  41. CurrentUser.ClientName = clientTable.Rows.Count > 0
  42. ? Convert.ToString(clientTable.Rows[0]["client_name"]) ?? string.Empty
  43. : string.Empty;
  44. }
  45. else
  46. {
  47. CurrentUser.ClientName = string.Empty;
  48. }
  49. Db.SetAppContext(CurrentUser.Login);
  50. return true;
  51. }
  52. catch (Exception ex)
  53. {
  54. error = "Ошибка авторизации: " + ErrorHelper.ToUserMessage(ex);
  55. return false;
  56. }
  57. }
  58. }