question

EduardoGomez-1870 avatar image
0 Votes"
EduardoGomez-1870 asked EduardoGomez-1870 edited

maintain the user LogIn into the app

Hello

My note app is finished, but I still have something that annoys me.

Every time I use the app, I have to log in, what I want to do is to store the IdTokent of the user somewhere

I already tried several ways, but it breaks en the Login Method and it says that confirm password is null

Here is my Auth to firebase

       public static string FirebaseKey = "AIzaSyA-ZJyEl0cQJlu0LUKBgOv3Q-1Vjr2-qaY";
      public static async Task<bool> RegisterUser(User user) {

         using HttpClient client = new();
         var body = new {

             email = user.email,
             password = user.Password,
             returnSecureToken = true
         };

         var bodyJson = JsonConvert.SerializeObject(body);
         var data = new StringContent(bodyJson, Encoding.UTF8, "application/json");
         var response = await client.PostAsync
             ($"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={FirebaseKey}", data);

         if (response.IsSuccessStatusCode) {
             string resutJson = await response.Content.ReadAsStringAsync();
             var res = JsonConvert.DeserializeObject<AuthResult>(resutJson);
             App.UserId = res.localId;

             return true;

         } else {
             string errorJson = await response.Content.ReadAsStringAsync();
             var res = JsonConvert.DeserializeObject<AuthError>(errorJson);
             MessageBox.Show(res.error.message);

             return false;
         }


     }
     public static async Task<bool> LoginUser(User user) {

         using HttpClient client = new();
         var body = new {

             email = user.email,
             password = user.Password,
             returnSecureToken = true
         };

         var bodyJson = JsonConvert.SerializeObject(body);
         var data = new StringContent(bodyJson, Encoding.UTF8, "application/json");
         var response = await client.PostAsync
             ($"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={FirebaseKey}", data);
         if (response.IsSuccessStatusCode) {
             string resutJson = await response.Content.ReadAsStringAsync();
             var res = JsonConvert.DeserializeObject<AuthResult>(resutJson);
             App.UserId = res.localId;
             return true;

         } else {
             string errorJson = await response.Content.ReadAsStringAsync();
             var res = JsonConvert.DeserializeObject<AuthError>(errorJson);
             MessageBox.Show(res.error.message);

             return false;
         }
     }
 }

}

And my login VM

public User User { get; set; }


     private string _Email;
     public string Email {
         get { return _Email; }
         set {
             if (_Email != value) {
                 _Email = value;
                 User.email = Email;
                 RaisePropertyChanged();
             }
         }
     }

     private string _Password;
     public string Password {
         get { return _Password; }
         set {
             if (_Password != value) {
                 _Password = value;
                 User.Password = _Password;
                 RaisePropertyChanged();
                 RaisePropertyChanged("User");

             }
         }
     }

     private string _ConfirmPassword;
     public string ConfirmPassword {
         get { return _ConfirmPassword; }
         set {
             if (_ConfirmPassword != value) {
                 _ConfirmPassword = value;
                 User.ConfirmPassword = ConfirmPassword;
                 RaisePropertyChanged();
                 RaisePropertyChanged("User");
             }
         }
     }

     private Visibility _LoginVis;
     public Visibility LoginVis {
         get { return _LoginVis; }
         set {
             if (_LoginVis != value) {
                 _LoginVis = value;
                 RaisePropertyChanged();
             }
         }
     }


     private Visibility _RegisterVis;
     public Visibility RegisterVis {
         get { return _RegisterVis; }
         set {
             if (_RegisterVis != value) {
                 _RegisterVis = value;
                 RaisePropertyChanged();
             }
         }
     }

     public event EventHandler Authenticacated;

     public LoginVM() {
         User = new User();
         LoginVis = Visibility.Visible;
         RegisterVis = Visibility.Collapsed;
         SwitchViewsCommand = new Command(() => SwitchViews());
         LoginCommand = new HelperCommand {
             ExecuteDelegate = x => LoginAsync(),
             CanExecuteDelegate = x => CanLogin()
         };
         CreateAccountCommand = new HelperCommand {
             ExecuteDelegate = x => CreateAccount(),
             CanExecuteDelegate = x => CanCreateAccount()
         };
     }

     private async void CreateAccount() {
         bool isSuccessful = await FirebaseAuth.RegisterUser(User);
         if (isSuccessful) {
             Authenticacated?.Invoke(this, new EventArgs());
         }
     }

     private bool CanCreateAccount() {
         if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password)
          && !string.IsNullOrEmpty(ConfirmPassword)
          && Password == ConfirmPassword) {
             return true;
         }
         return false;
     }

     private async void LoginAsync() {
         bool isSuccessful = await FirebaseAuth.LoginUser(User);
         if (isSuccessful) {
             Authenticacated?.Invoke(this, new EventArgs());
         }

     }

     private bool CanLogin() {

         if (!string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(Password)) {
             return true;
         }
         return false;
     }

     private void SwitchViews() {

         isShowingRegister = !isShowingRegister;
         if (isShowingRegister) {
             RegisterVis = Visibility.Visible;
             LoginVis = Visibility.Collapsed;
         } else {
             RegisterVis = Visibility.Collapsed;
             LoginVis = Visibility.Visible;
         }
     }
 }

this is my noteWindows, what I want to do is to go to this windows automatically, if I have an ID

  public NotesWindow() {
         InitializeComponent();

         vM = Resources["vm"] as NotesWindowVM;
         vM.SelectedNoteChanged += VM_SelectedNoteChanged;

         var speechRecognizer = SpeechConfig.FromSubscription(App.azureSpeeshKey, App.region);
         var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
         recog = new SpeechRecognizer(speechRecognizer, audioConfig);

         recog.Recognized += SpeechRecognizer_Recognized;
     }

     private async void VM_SelectedNoteChanged(object sender, EventArgs e) {
         NoteContent.Document.Blocks.Clear();
         if (vM.SelectedNote != null) {
             string downloadPath = $"{vM.SelectedNote.Id}.rtf";
             if (vM.SelectedNote.FileLocation != null) {
                 await new BlobClient(new Uri(vM.SelectedNote.FileLocation)).DownloadToAsync(downloadPath);
             }
             if (!string.IsNullOrEmpty(vM.SelectedNote.FileLocation)) {
                 using (FileStream fs = new(downloadPath, FileMode.Open)) {
                     var contents = new TextRange(NoteContent.Document.ContentStart,
                     NoteContent.Document.ContentEnd);
                     contents.Load(fs, DataFormats.Rtf);
                 }
             }
         }
     }

     private async void SpeechRecognizer_Recognized(object sender, SpeechRecognitionEventArgs e) {
         if (e.Result.Reason == ResultReason.RecognizedSpeech) {
             await Dispatcher.InvokeAsync(() => NoteContent.AppendText($"{e.Result.Text}"));

         }
     }

     protected override void OnActivated(EventArgs e) {
         base.OnActivated(e);

         if (string.IsNullOrEmpty(App.UserId)) {
             LoginWindow loginWindow = new();
             loginWindow.ShowDialog();
             vM.GetNoteBooksAsync();
         }
     }
     private void NoteContent_TextChanged(object sender, TextChangedEventArgs e) {
         FlowDocument doc = NoteContent.Document;
         int count = new TextRange(doc.ContentStart, doc.ContentEnd).Text.Length;
         NumOfCharacters.Text = $"Characters: {count}";
     }
     private async void SpeechBton_Click(object sender, RoutedEventArgs e) {

         var toggle = sender as System.Windows.Controls.Primitives.ToggleButton;
         switch (toggle.Tag) {
             case "0":
                 if (!isRecognizing) {
                     await recog.StartContinuousRecognitionAsync();

                     isRecognizing = true;
                     SpeechBton.IsChecked = true;
                 } else {
                     await recog.StopContinuousRecognitionAsync();

                     isRecognizing = false;
                     SpeechBton.IsChecked = false;
                 }
                 break;
             case "1":
                 bool isChecked = toggle.IsChecked ?? false;
                 if (isChecked) {
                     NoteContent.Selection.ApplyPropertyValue(FontWeightProperty, FontWeights.Bold);
                 } else {
                     NoteContent.Selection.ApplyPropertyValue(FontWeightProperty, FontWeights.Normal);
                 }
                 break;
             case "2":
                 bool isEnable = toggle.IsChecked ?? false;
                 if (isEnable) {
                     NoteContent.Selection.ApplyPropertyValue(FontStyleProperty, FontStyles.Italic);
                 } else {
                     NoteContent.Selection.ApplyPropertyValue(FontStyleProperty, FontStyles.Normal);
                 }
                 break;
             case "3":
                 bool isPressed = toggle.IsChecked ?? false;
                 if (isPressed) {
                     NoteContent.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
                 } else {

                     (NoteContent.Selection.GetPropertyValue(Inline.TextDecorationsProperty) as TextDecorationCollection)
                         .TryRemove(TextDecorations.Underline, out TextDecorationCollection decorations);
                     NoteContent.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty, decorations);
                 }
                 break;
         }
     }
     private void NoteContent_SelectionChanged(object sender, RoutedEventArgs e) {

         var selectionFontWeight = NoteContent.Selection.GetPropertyValue(TextElement.FontWeightProperty);
         boldBton.IsChecked = (selectionFontWeight != DependencyProperty.UnsetValue)
             && selectionFontWeight.Equals(FontWeights.Bold);

         var selectionFontStyle = NoteContent.Selection.GetPropertyValue(TextElement.FontStyleProperty);
         italicBton.IsChecked = (selectionFontStyle != DependencyProperty.UnsetValue)
             && selectionFontStyle.Equals(FontStyles.Italic);

         var selectionFontDecoration = NoteContent.Selection.GetPropertyValue(Inline.TextDecorationsProperty);
         UndelineBton.IsChecked = (selectionFontDecoration != DependencyProperty.UnsetValue)
             && selectionFontDecoration.Equals(TextDecorations.Underline);

         FontsComboBox.SelectedItem = NoteContent.Selection.GetPropertyValue(FontFamilyProperty);
         SizeConboBox.Text = (NoteContent.Selection.GetPropertyValue(FontSizeProperty)).ToString();
     }

     private void FontsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
         if (FontsComboBox.SelectedItem != null) {
             NoteContent.Selection.ApplyPropertyValue(FontFamilyProperty, FontsComboBox.SelectedItem);
         }
     }

     private void SizeConboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
         NoteContent.Selection.ApplyPropertyValue(FontSizeProperty, SizeConboBox.Text);
     }
     private async void SaveBton_Click(object sender, RoutedEventArgs e) {

         var fileName = $"{vM.SelectedNote.Id}";
         var rtfFile = Path.Combine(Environment.CurrentDirectory, fileName);
         vM.SelectedNote.FileLocation = rtfFile;

         using (FileStream fs = new(rtfFile, FileMode.Create)) {
             var contents = new TextRange(NoteContent.Document.ContentStart,
             NoteContent.Document.ContentEnd);
             contents.Save(fs, DataFormats.Rtf);
         }

         vM.SelectedNote.FileLocation = await UpdateFileAsync(rtfFile, fileName);
         await Database.UpdateAsync(vM.SelectedNote);
     }

     private async Task<string> UpdateFileAsync(string rtfFile, string fileName) {

         var connectionString = App.azureStorageKey;
         var containerName = "notes";

         var containerClient = new BlobContainerClient(connectionString, containerName);

         var blob = containerClient.GetBlobClient(fileName);
         await blob.UploadAsync(rtfFile, overwrite: true);

         return $"https://safestoragewpf.blob.core.windows.net/notes/{fileName}";
     }
 }

}

what I was thinking of is using Azure Key Vault, but how?

windows-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

0 Answers