RegestViewModel.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using ApplicationAvalonia.Models;
  2. using ApplicationAvalonia.Utilities;
  3. using CommunityToolkit.Mvvm.ComponentModel;
  4. using CommunityToolkit.Mvvm.Input;
  5. using Microsoft.EntityFrameworkCore;
  6. using MsBox.Avalonia;
  7. using MsBox.Avalonia.Enums;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel.DataAnnotations;
  11. using System.Linq;
  12. using System.Security.Cryptography;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. namespace ApplicationAvalonia.ViewModels
  16. {
  17. internal partial class RegestViewModel : ViewModelBase
  18. {
  19. PageSwitcher pgSwitch;
  20. #region Properties
  21. [ObservableProperty]
  22. private string _login = string.Empty;
  23. [ObservableProperty]
  24. private string _password = string.Empty;
  25. [ObservableProperty]
  26. private string _name = string.Empty;
  27. [ObservableProperty]
  28. private string _surname = string.Empty;
  29. [ObservableProperty]
  30. private string _message = string.Empty;
  31. #endregion
  32. public RegestViewModel(ref PageSwitcher pageSwitcher)
  33. {
  34. this.pgSwitch = pageSwitcher;
  35. }
  36. [RelayCommand]
  37. private async void RegistrationBtn()
  38. {
  39. Message = "";
  40. // AES encrypted
  41. if (Login.Trim() != "" && Password.Trim() != "" && Name.Trim() != "" && Surname.Trim() != "")
  42. {
  43. byte[] key = new byte[16];
  44. byte[] iv = new byte[16];
  45. using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
  46. {
  47. rng.GetBytes(key);
  48. rng.GetBytes(iv);
  49. }
  50. byte[] encryptedPassword = EncryptionClass.Encrypt(Password, key, iv);
  51. LoginTable newUser = new LoginTable() { Login = Login.Trim(), Password = encryptedPassword, Iv = iv, Key = key };
  52. dbContext.LoginTables.Add(newUser);
  53. dbContext.SaveChanges();
  54. var userInDB = dbContext.LoginTables.SingleOrDefault(x => encryptedPassword == x.Password);
  55. if (userInDB != null)
  56. {
  57. UserTable userTable = new UserTable() { IdLoginNavigation = userInDB, IdLogin = userInDB.Id, UserName = Name.Trim(),
  58. UserSurname = Surname.Trim(), IdRole = 2 };
  59. dbContext.UserTables.Add(userTable);
  60. dbContext.SaveChanges();
  61. var mbox = MessageBoxManager.GetMessageBoxStandard("Уведомление", "Регистрация прошла успешно перенаправляем вас на другую страницу",
  62. ButtonEnum.Ok, Icon.Success);
  63. var waiter = await mbox.ShowWindowAsync();
  64. pgSwitch.View = new AuthViewModel(ref pgSwitch);
  65. return;
  66. }
  67. Message = "Что-то пошло не так";
  68. }
  69. else
  70. {
  71. Message = "Поля или поле не заполнены";
  72. }
  73. }
  74. }
  75. }