Browse Source

Добавлено хеширование, мелкие правки

Oleg Kireev 3 năm trước cách đây
mục cha
commit
31acfdc89c

+ 10 - 7
Hotel_Course_Project/AdminPage.xaml.cs

@@ -10,8 +10,6 @@ namespace Hotel_Course_Project
     /// </summary>
     public partial class AdminPage : Page
     {
-        public List<Staff> staffSearchedlist;
-        public List<Client> clientSearchedList;
         public AdminPage(Staff admin)
         {
             InitializeComponent();
@@ -131,7 +129,7 @@ namespace Hotel_Course_Project
         {
             string searchText = StaffSeacrhTB.Text;
             //var seacrhed = DataBase.db.Staff.Where(item => (item.LName + " " + item.FName + " " + item.MName + " " + item.Login + " " + item.Password).Contains(StaffSeacrhTB.Text)).ToList();
-            var searched = SearchStaff(DataBase.db.Staff.ToList(), searchText, staffSearchedlist);
+            var searched = SearchStaff(DataBase.db.Staff.ToList(), searchText);
             if (SortStaffCB.SelectedItem == activeS)
             {
                 StaffList.ItemsSource = searched.Where(item => item.Id_PersStatus == 1).ToList();
@@ -142,8 +140,9 @@ namespace Hotel_Course_Project
             }
         }
 
-        public List<Staff> SearchStaff(List<Staff> listStaff, string searchText, List<Staff> staffSearchedList)
+        public List<Staff> SearchStaff(List<Staff> listStaff, string searchText)
         {
+            List<Staff> staffSearchedList = new List<Staff>();
             staffSearchedList = listStaff.Where(item => (item.LName + " " + item.FName + " " + item.MName + " " + item.Login + " " + item.Password).Contains(searchText)).ToList();
             return staffSearchedList;
         }
@@ -152,7 +151,7 @@ namespace Hotel_Course_Project
         {
             string searchText = ClientSeacrhTB.Text;
             //var seacrhed = DataBase.db.Client.Where(item => (item.LName + " " + item.FName + " " + item.MName).Contains(ClientSeacrhTB.Text)).ToList();
-            var searched = SearchClient(DataBase.db.Client.ToList(), searchText, clientSearchedList);
+            var searched = SearchClient(DataBase.db.Client.ToList(), searchText);
             if (SortClientCB.SelectedItem == activeC)
             {
                 ClientList.ItemsSource = searched.Where(item => item.Id_PersStatus == 1).ToList();
@@ -162,8 +161,9 @@ namespace Hotel_Course_Project
                 ClientList.ItemsSource = searched.Where(item => item.Id_PersStatus == 2).ToList();
             }
         }
-        public List<Client> SearchClient(List<Client> listClient, string searchText, List<Client> clientSearchedList)
+        public List<Client> SearchClient(List<Client> listClient, string searchText)
         {
+            List<Client> clientSearchedList = new List<Client>();
             clientSearchedList = listClient.Where(item => (item.LName + " " + item.FName + " " + item.MName).Contains(searchText)).ToList();
             return clientSearchedList;
         }
@@ -186,7 +186,10 @@ namespace Hotel_Course_Project
 
         private void ClientSeacrhTB_TextChanged(object sender, TextChangedEventArgs e)
         {
-
+            if (ClientSeacrhTB.Text == "") 
+            {
+                Page_Loaded(sender, e);
+            }
         }
 
         private void PaySeacrhTB_TextChanged(object sender, TextChangedEventArgs e)

+ 0 - 3
Hotel_Course_Project/App.xaml

@@ -3,7 +3,4 @@
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:local="clr-namespace:Hotel_Course_Project"
              StartupUri="AuthorizationWindow.xaml">
-    <Application.Resources>
-        <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
-    </Application.Resources>
 </Application>

+ 0 - 1
Hotel_Course_Project/AuthorizationWindow.xaml

@@ -3,7 +3,6 @@
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-        xmlns:materialDesign="https://materialdesigninxaml.net/winfx/xaml/themes"
         xmlns:local="clr-namespace:Hotel_Course_Project"
         mc:Ignorable="d"
         Title="Авторизация" Height="300" Width="400" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" Loaded="Window_Loaded">

+ 5 - 2
Hotel_Course_Project/AuthorizationWindow.xaml.cs

@@ -23,7 +23,8 @@ namespace Hotel_Course_Project
             }
             else
             {
-                var user = DataBase.db.Staff.SingleOrDefault(x => x.Login == Login.Text && x.Password == Password.Password);
+                string Pass = SomeMethods.Hash(Password.Password);
+                var user = DataBase.db.Staff.SingleOrDefault(x => x.Login == Login.Text && x.Password == Pass);
                 if (user != null && user.Id_PersStatus == 2)
                 {
                     MessageBox.Show("Данный пользователь удалён из базы данных");
@@ -39,7 +40,8 @@ namespace Hotel_Course_Project
 
         public bool Auth(string login, string password)
         {
-            var user = DataBase.db.Staff.SingleOrDefault(x => x.Login == login && x.Password == password);
+            string pass = SomeMethods.Hash(password);
+            var user = DataBase.db.Staff.SingleOrDefault(x => x.Login == login && x.Password == pass);
             if (user != null && user.Id_PersStatus == 2)
             {
                 return true;
@@ -54,6 +56,7 @@ namespace Hotel_Course_Project
             }
         }
 
+
         private void Window_Loaded(object sender, RoutedEventArgs e)
         {
             Login.Focus();

+ 0 - 13
Hotel_Course_Project/Hotel_Course_Project.csproj

@@ -43,12 +43,6 @@
     <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
       <HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
     </Reference>
-    <Reference Include="MaterialDesignColors, Version=2.0.4.3, Culture=neutral, PublicKeyToken=df2a72020bd7962a, processorArchitecture=MSIL">
-      <HintPath>..\packages\MaterialDesignColors.2.0.4\lib\net452\MaterialDesignColors.dll</HintPath>
-    </Reference>
-    <Reference Include="MaterialDesignThemes.Wpf, Version=4.3.0.3, Culture=neutral, PublicKeyToken=df2a72020bd7962a, processorArchitecture=MSIL">
-      <HintPath>..\packages\MaterialDesignThemes.4.3.0\lib\net452\MaterialDesignThemes.Wpf.dll</HintPath>
-    </Reference>
     <Reference Include="System" />
     <Reference Include="System.ComponentModel.DataAnnotations" />
     <Reference Include="System.Data" />
@@ -283,11 +277,4 @@
     <WCFMetadata Include="Connected Services\" />
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <Import Project="..\packages\MaterialDesignThemes.4.3.0\build\MaterialDesignThemes.targets" Condition="Exists('..\packages\MaterialDesignThemes.4.3.0\build\MaterialDesignThemes.targets')" />
-  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
-    <PropertyGroup>
-      <ErrorText>Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их.  Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}.</ErrorText>
-    </PropertyGroup>
-    <Error Condition="!Exists('..\packages\MaterialDesignThemes.4.3.0\build\MaterialDesignThemes.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MaterialDesignThemes.4.3.0\build\MaterialDesignThemes.targets'))" />
-  </Target>
 </Project>

+ 2 - 2
Hotel_Course_Project/MainWindow.xaml

@@ -2,8 +2,7 @@
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
-        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
-        xmlns:materialDesign="https://materialdesigninxaml.net/winfx/xaml/themes"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"       
         xmlns:local="clr-namespace:Hotel_Course_Project"
         mc:Ignorable="d"
         Title="{Binding ElementName=MainFrame,Path=Content.Title}" Height="450" Width="800" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
@@ -14,6 +13,7 @@
         </Grid.RowDefinitions>
 
         <Button HorizontalAlignment="Left" Name="BackBtn" Click="BackBtn_Click">Назад</Button>
+        <Button HorizontalAlignment="Left" Name="ExitBtn" Click="ExitBtn_Click">Выйти</Button>
         <Frame Name="MainFrame" Grid.Row="1" NavigationUIVisibility="Hidden" ContentRendered="MainFrame_ContentRendered"></Frame>
     </Grid>
 </Window>

+ 8 - 0
Hotel_Course_Project/MainWindow.xaml.cs

@@ -25,6 +25,7 @@ namespace Hotel_Course_Project
 
         private void MainFrame_ContentRendered(object sender, EventArgs e)
         {
+            var visibleExitBtn = PChanger.MainFrame.CanGoBack ? ExitBtn.Visibility = Visibility.Collapsed : ExitBtn.Visibility = Visibility.Visible;
             if (Title == "Добавление заказа")
             {
                 var visibleBackBtnOnOrder = BackBtn.Visibility == Visibility.Collapsed;
@@ -39,5 +40,12 @@ namespace Hotel_Course_Project
         {
             PChanger.MainFrame.GoBack();
         }
+
+        private void ExitBtn_Click(object sender, RoutedEventArgs e)
+        {
+            AuthorizationWindow authorization = new AuthorizationWindow();
+            authorization.Show();
+            this.Close();
+        }
     }
 }

+ 5 - 5
Hotel_Course_Project/ModelDB.edmx

@@ -83,11 +83,11 @@
           <Property Name="Id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
           <Property Name="LName" Type="nvarchar" MaxLength="50" Nullable="false" />
           <Property Name="FName" Type="nvarchar" MaxLength="50" Nullable="false" />
-          <Property Name="MName" Type="nchar" MaxLength="10" />
+          <Property Name="MName" Type="nvarchar" MaxLength="50" />
           <Property Name="Id_StaffRole" Type="int" />
           <Property Name="PhotoContract" Type="image" />
           <Property Name="Login" Type="nvarchar" MaxLength="50" Nullable="false" />
-          <Property Name="Password" Type="nvarchar" MaxLength="50" Nullable="false" />
+          <Property Name="Password" Type="nvarchar(max)" Nullable="false" />
           <Property Name="Id_PersStatus" Type="int" Nullable="false" />
         </EntityType>
         <EntityType Name="StaffRole">
@@ -306,7 +306,7 @@
           <Property Name="Id_Client" Type="Int32" />
           <Property Name="Id_Room" Type="Int32" />
           <Property Name="DateStart" Type="DateTime" Precision="0" />
-          <Property Name="DateEnd" Type="DateTime" />
+          <Property Name="DateEnd" Type="DateTime" Precision="0" />
           <NavigationProperty Name="Client" Relationship="Self.FK_Order_Client" FromRole="Order" ToRole="Client" />
           <NavigationProperty Name="Room" Relationship="Self.FK_Order_Room" FromRole="Order" ToRole="Room" />
           <NavigationProperty Name="Staff" Relationship="Self.FK_Order_Staff" FromRole="Order" ToRole="Staff" />
@@ -342,11 +342,11 @@
           <Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
           <Property Name="LName" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
           <Property Name="FName" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
-          <Property Name="MName" Type="String" MaxLength="10" FixedLength="true" Unicode="true" />
+          <Property Name="MName" Type="String" MaxLength="50" FixedLength="false" Unicode="true" />
           <Property Name="Id_StaffRole" Type="Int32" />
           <Property Name="PhotoContract" Type="Binary" MaxLength="Max" FixedLength="false" />
           <Property Name="Login" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
-          <Property Name="Password" Type="String" MaxLength="50" FixedLength="false" Unicode="true" Nullable="false" />
+          <Property Name="Password" Type="String" MaxLength="Max" FixedLength="false" Unicode="true" Nullable="false" />
           <NavigationProperty Name="Order" Relationship="Self.FK_Order_Staff" FromRole="Staff" ToRole="Order" />
           <NavigationProperty Name="StaffRole" Relationship="Self.FK_Staff_StaffRole" FromRole="Staff" ToRole="StaffRole" />
           <Property Name="Id_PersStatus" Type="Int32" Nullable="false" />

+ 25 - 0
Hotel_Course_Project/SomeMethods.cs

@@ -1,4 +1,6 @@
 using System.IO;
+using System.Security.Cryptography;
+using System.Text;
 using System.Windows.Media.Imaging;
 
 namespace Hotel_Course_Project
@@ -60,5 +62,28 @@ namespace Hotel_Course_Project
         }
         #endregion
 
+        #region Хеширование
+        public static string Hash(string password)
+        {
+            //переводим строку в байт-массим  
+            byte[] bytes = Encoding.Unicode.GetBytes(password);
+
+            //создаем объект для получения средст шифрования  
+            MD5CryptoServiceProvider CSP = new MD5CryptoServiceProvider();
+
+            //вычисляем хеш-представление в байтах  
+            byte[] byteHash = CSP.ComputeHash(bytes);
+
+            //создаем пустую строку
+            string hash = string.Empty;
+
+            //формируем одну цельную строку из массива  
+            foreach (byte b in byteHash)
+            {
+                hash += string.Format("{0:x2}", b);
+            }
+            return hash;
+        }
+        #endregion
     }
 }

+ 1 - 0
Hotel_Course_Project/StaffChangeOrAddPage.xaml.cs

@@ -69,6 +69,7 @@ namespace Hotel_Course_Project
                         DataBase.db.Staff.SingleOrDefault(item => item.Id == lastId).PhotoContract = contractImage;
                         DataBase.db.SaveChanges();
                         MessageBox.Show("Сотрудник добавлен в базу.");
+                        PChanger.MainFrame.GoBack();
                     }
                     else
                     {

+ 0 - 2
Hotel_Course_Project/packages.config

@@ -2,6 +2,4 @@
 <packages>
   <package id="EntityFramework" version="6.2.0" targetFramework="net472" />
   <package id="EntityFramework.ru" version="6.2.0" targetFramework="net472" />
-  <package id="MaterialDesignColors" version="2.0.4" targetFramework="net472" />
-  <package id="MaterialDesignThemes" version="4.3.0" targetFramework="net472" />
 </packages>

+ 4 - 7
UnitTestCourseProject/UnitTest.cs

@@ -14,7 +14,6 @@ namespace UnitTestCourseProject
             AuthorizationWindow authorization = new AuthorizationWindow();
             //Корректные пары логина и пароля
             Assert.IsTrue(authorization.Auth("123", "123"));
-            Assert.IsTrue(authorization.Auth("456", "456"));
             //Некорректные пары логина и пароля
             Assert.IsFalse(authorization.Auth("123456", "123546"));
             Assert.IsFalse(authorization.Auth("12334", "541231"));
@@ -151,12 +150,11 @@ namespace UnitTestCourseProject
             searchedStaffList.Add(staff3);
             searchedStaffList.Add(staff4);
             searchText = "45";
-            List<Staff> scrh = new List<Staff>();
-            CollectionAssert.AreEqual(adminPage.SearchStaff(staffList, searchText, scrh), searchedStaffList);
+            CollectionAssert.AreEqual(adminPage.SearchStaff(staffList, searchText), searchedStaffList);
             searchedStaffList = new List<Staff>();
             searchedStaffList.Add(staff4);
             searchText = "Давид";
-            CollectionAssert.AreEqual(adminPage.SearchStaff(staffList, searchText, scrh), searchedStaffList);
+            CollectionAssert.AreEqual(adminPage.SearchStaff(staffList, searchText), searchedStaffList);
         }
         [TestMethod]
         public void TestSearchClient()
@@ -202,12 +200,11 @@ namespace UnitTestCourseProject
 
             //заполняем итоговый лист с тем, что должно найтись после поиска
             searchText = "1231234124";
-            List<Client> scrh = new List<Client>();
-            CollectionAssert.AreEqual(adminPage.SearchClient(clientList, searchText, scrh), searchedClientList);
+            CollectionAssert.AreEqual(adminPage.SearchClient(clientList, searchText), searchedClientList);
             searchedClientList = new List<Client>();
             searchedClientList.Add(Client3);
             searchText = "Фёдор";
-            CollectionAssert.AreEqual(adminPage.SearchClient(clientList, searchText, scrh), searchedClientList);
+            CollectionAssert.AreEqual(adminPage.SearchClient(clientList, searchText), searchedClientList);
 
         }
     }