Files
winui3-learning/winui-learning/winui-learning-2/Views/LoginPage.xaml.cs
T

92 lines
2.2 KiB
C#

using System;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using winui_learning_2.Services;
namespace winui_learning_2.Views;
public sealed partial class LoginPage : Page
{
private readonly NodplayAuthService _authService = new();
public LoginPage()
{
InitializeComponent();
}
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
await TryLoginAsync();
}
private async void InputBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
await TryLoginAsync();
}
}
private async Task TryLoginAsync()
{
ErrorText.Visibility = Visibility.Collapsed;
ErrorText.Text = string.Empty;
var username = UsernameBox.Text.Trim();
var password = PasswordBox.Password;
if (string.IsNullOrWhiteSpace(username))
{
ShowError("Username is required.");
return;
}
if (string.IsNullOrEmpty(password))
{
ShowError("Password is required.");
return;
}
SetLoading(true);
try
{
var result = await _authService.LoginAsync(username, password);
if (!result.IsSuccess)
{
ShowError(result.ErrorMessage ?? "Login failed.");
return;
}
AuthSession.SignIn(result.Username ?? username, result.Token);
Frame?.Navigate(typeof(HomePage));
}
catch (Exception)
{
ShowError("Could not reach the Nodplay API. Check your connection and try again.");
}
finally
{
SetLoading(false);
}
}
private void ShowError(string message)
{
ErrorText.Text = message;
ErrorText.Visibility = Visibility.Visible;
}
private void SetLoading(bool isLoading)
{
LoginButton.IsEnabled = !isLoading;
UsernameBox.IsEnabled = !isLoading;
PasswordBox.IsEnabled = !isLoading;
LoadingRing.IsActive = isLoading;
LoadingRing.Visibility = isLoading ? Visibility.Visible : Visibility.Collapsed;
}
}