Added Login system

This commit is contained in:
BOT Alex 2023-05-20 05:03:32 +02:00
parent 80fe9246cc
commit 2b8cc84053
3 changed files with 138 additions and 43 deletions

View File

@ -3,10 +3,12 @@
@using System.ComponentModel.DataAnnotations @using System.ComponentModel.DataAnnotations
@inject HttpClient httpClient @inject HttpClient httpClient
@inject Blazored.LocalStorage.ILocalStorageService localStorage @inject Blazored.LocalStorage.ILocalStorageService localStorage
@inject NavigationManager NavManager
@inject ISnackbar Snackbar
<MudLayout Class="overflow-hidden"> <MudLayout Class="overflow-hidden">
<MudAppBar Elevation="1"> <MudAppBar Elevation="1">
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="ClearAllCookies">Clear cookies</MudButton> <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="RegisterAccount">Clear cookies</MudButton>
<MudSpacer /> <MudSpacer />
@if (!isLoggedIn) @if (!isLoggedIn)
{ {
@ -14,8 +16,12 @@
<MudText Style="font-size: 15px;">Log-in or sign-up here</MudText> <MudText Style="font-size: 15px;">Log-in or sign-up here</MudText>
<MudIcon Class="mr-n1" Icon="@Icons.Material.Filled.ArrowRightAlt" /> <MudIcon Class="mr-n1" Icon="@Icons.Material.Filled.ArrowRightAlt" />
</MudPaper> </MudPaper>
}
<MudAvatar @onclick="ToggleDrawer" Style="cursor:pointer;" Variant="Variant.Outlined" Color="Color.Surface" Class="mr-n2">?</MudAvatar> <MudAvatar @onclick="ToggleDrawer" Style="cursor:pointer;" Variant="Variant.Outlined" Color="Color.Surface" Class="mr-n2">?</MudAvatar>
}
else
{
<MudAvatar @onclick="ToggleDrawer" Style="cursor:pointer;" Variant="Variant.Outlined" Color="Color.Success" Class="mr-n2">@(char.ToUpper(Program.LoggedInName[0]))</MudAvatar>
}
</MudAppBar> </MudAppBar>
<MudDrawer @bind-Open="@openContentDrawer" ClipMode="DrawerClipMode.Always" Breakpoint="Breakpoint.Lg" PreserveOpenState="false" Elevation="1" Variant="@DrawerVariant.Mini" OpenMiniOnHover="true"> <MudDrawer @bind-Open="@openContentDrawer" ClipMode="DrawerClipMode.Always" Breakpoint="Breakpoint.Lg" PreserveOpenState="false" Elevation="1" Variant="@DrawerVariant.Mini" OpenMiniOnHover="true">
@ -29,17 +35,17 @@
<MudDrawer Anchor="Anchor.End" @bind-Open="@openProfileDrawer" ClipMode="DrawerClipMode.Always" Breakpoint="Breakpoint.Lg" PreserveOpenState="true" Elevation="1" Variant="@DrawerVariant.Temporary"> <MudDrawer Anchor="Anchor.End" @bind-Open="@openProfileDrawer" ClipMode="DrawerClipMode.Always" Breakpoint="Breakpoint.Lg" PreserveOpenState="true" Elevation="1" Variant="@DrawerVariant.Temporary">
@if (isLoggedIn) @if (isLoggedIn)
{ {
<MudNavMenu> <MudPaper Class="ma-2">
<MudNavLink Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Store">Store</MudNavLink> <MudStack Spacing="0" Class="justify-center">
<MudNavLink Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Chat">Library</MudNavLink> <MudButton Class="ma-4" Variant="Variant.Outlined" Color="Color.Error" OnClick="Logout">Logout</MudButton>
<MudNavLink Match="NavLinkMatch.All" Icon="@Icons.Material.Filled.Group">Community</MudNavLink> </MudStack>
</MudNavMenu> </MudPaper>
} }
else else
{ {
<MudPaper Class="ma-2"> <MudPaper Class="ma-2">
<MudStack Spacing="0" Class="justify-center"> <MudStack Spacing="0" Class="justify-center">
<MudButton Class="ma-4" Variant="Variant.Outlined" Color="Color.Primary" OnClick="ShowLogIn">Log-in</MudButton> <MudButton Class="ma-4" Variant="Variant.Outlined" Color="Color.Primary" OnClick="ShowLogIn">Sign-in</MudButton>
<MudButton Class="ma-4" Variant="Variant.Outlined" Color="Color.Success" OnClick="ShowSignUp">Sign-up</MudButton> <MudButton Class="ma-4" Variant="Variant.Outlined" Color="Color.Success" OnClick="ShowSignUp">Sign-up</MudButton>
</MudStack> </MudStack>
</MudPaper> </MudPaper>
@ -58,16 +64,16 @@
<MudText Typo="Typo.h3">Sign-up</MudText> <MudText Typo="Typo.h3">Sign-up</MudText>
<MudForm @ref="form" @bind-IsValid="@isValid" @bind-Errors="@errors"> <MudForm @ref="form" @bind-IsValid="@isValid" @bind-Errors="@errors">
<MudTextField T="string" Label="Username" Required="true" RequiredError="User name is required!" <MudTextField T="string" Label="Username" Required="true" RequiredError="Username is required!" HelperText="This is case sensitive!"
@bind-Text=tempUser.Username /> @bind-Text=tempUser.Username />
<MudTextField T="string" Label="Email" Required="true" RequiredError="Email is required!" <MudTextField T="string" Label="Email" Required="true" RequiredError="Email is required!"
Validation="@(new EmailAddressAttribute() {ErrorMessage = "The email address is invalid"})" Validation="@(new EmailAddressAttribute() {ErrorMessage = "The email address is invalid"})"
@bind-Text=tempUser.Email/> @bind-Text=tempUser.Email />
<MudTextField T="string" Label="Password" HelperText="(This will not be encrypted)" @ref="pwField1" <MudTextField T="string" Label="Password" HelperText="(This will not be encrypted)" @ref="pwField1"
InputType="InputType.Password" InputType="InputType.Password"
Validation="@(new Func<string, IEnumerable<string>>(PasswordStrength))" Required="true" Validation="@(new Func<string, IEnumerable<string>>(PasswordStrength))" Required="true"
RequiredError="Password is required!" RequiredError="Password is required!"
@bind-Text=tempUser.Password/> @bind-Text=tempUser.Password />
<MudTextField T="string" <MudTextField T="string"
Label="Password" HelperText="Repeat the password" InputType="InputType.Password" Label="Password" HelperText="Repeat the password" InputType="InputType.Password"
Validation="@(new Func<string, string>(PasswordMatch))" /> Validation="@(new Func<string, string>(PasswordMatch))" />
@ -75,16 +81,31 @@
<MudStack> <MudStack>
<MudCheckBox Class="ml-n2" T="bool" Required="true" RequiredError="You must agree"><MudText Style="font-size:10px;">I agree with <MudLink Href="/TOS" OnClick="HideOverlays" Style="font-size:10px;">Terms Of Service</MudLink></MudText></MudCheckBox> <MudCheckBox Class="ml-n2" T="bool" Required="true" RequiredError="You must agree"><MudText Style="font-size:10px;">I agree with <MudLink Href="/TOS" OnClick="HideOverlays" Style="font-size:10px;">Terms Of Service</MudLink></MudText></MudCheckBox>
</MudStack> </MudStack>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Disabled="@(!isValid)" Class="ml-auto" OnClick="AddUser">Register</MudButton> <MudButton Variant="Variant.Filled" Color="Color.Primary" Disabled="@(!isValid)" Class="ml-auto" OnClick="RegisterAccount">Register</MudButton>
</MudStack> </MudStack>
</MudForm> </MudForm>
</MudPaper> </MudPaper>
</MudOverlay> </MudOverlay>
@*Log-in overlay*@ @*Log-in overlay*@
<MudOverlay @bind-Visible="isLoggingIn" DarkBackground="true" AutoClose=true Style="backdrop-filter:blur(5px)"> <MudOverlay ZIndex="1400" @bind-Visible="isLoggingIn" DarkBackground="true" Style="backdrop-filter:blur(5px)">
<MudPaper @onclick:stopPropagation=true> <MudPaper Class="pa-4 rounded-lg" @onclick:stopPropagation=true>
<MudText>Login</MudText> <MudIconButton Style="position: absolute; right: 0; top: 0;" Icon="@Icons.Material.Filled.Close" OnClick="HideOverlays" />
<MudText Typo="Typo.h3">Sign-in</MudText>
<MudText>Welcome back!</MudText>
<MudForm @ref="form" @bind-IsValid="@isValid" @bind-Errors="@errors">
<MudTextField T="string" Label="Username" Variant="Variant.Filled" Required="true" RequiredError="Username is empty?" HelperText="This is case sensitive!"
@bind-Text=tempUser.Username />
<MudTextField T="string" Label="Password" Variant="Variant.Filled" HelperText="(This will not be encrypted)" @ref="pwField1"
InputType="InputType.Password"
Required="true"
RequiredError="Password is empty?"
@bind-Text=tempUser.Password />
<MudStack Row=true Class="d-flex align-center mt-6">
<MudButton Variant="Variant.Filled" Color="Color.Primary" Disabled="@(!isValid)" Class="ml-auto" OnClick="StartLoggingIn">Login!</MudButton>
</MudStack>
</MudForm>
</MudPaper> </MudPaper>
</MudOverlay> </MudOverlay>
@ -96,6 +117,7 @@
bool isSigningUp = false; bool isSigningUp = false;
bool isLoggingIn = false; bool isLoggingIn = false;
bool isValid = false; bool isValid = false;
User[]? allUsers;
User tempUser = new User(); User tempUser = new User();
@ -118,14 +140,76 @@
} }
void HideOverlays() => isSigningUp = isLoggingIn = false; void HideOverlays() => isSigningUp = isLoggingIn = false;
#endregion #endregion
async void AddUser() async void RegisterAccount()
{ {
//await httpClient.PostAsJsonAsync("https://globalchat-4a89f-default-rtdb.europe-west1.firebasedatabase.app/Database/Users.json", new User()); if (await GetUserFromName(tempUser) == null)
Console.WriteLine(tempUser.Username); {
Console.WriteLine(tempUser.Email); Console.WriteLine("Creating username");
Console.WriteLine(tempUser.Password); await httpClient.PostAsJsonAsync("https://globalchat-4a89f-default-rtdb.europe-west1.firebasedatabase.app/Database/Users.json", tempUser);
LoginAs(tempUser);
}
else
{
Console.WriteLine("Username already exists!");
Snackbar.Add("Username already exists!", Severity.Warning);
}
}
async void StartLoggingIn()
{
User? serverSideUser = await GetUserFromName(tempUser);
if (serverSideUser == null)
{
Console.WriteLine("User not found");
Snackbar.Add("User not found", Severity.Warning);
return;
}
if (serverSideUser.Password != tempUser.Password)
{
Console.WriteLine("Wrong password!");
Snackbar.Add("Wrong password! Hackerman!", Severity.Error);
return;
}
Console.WriteLine("Login success!");
LoginAs(tempUser);
}
async Task<User?> GetUserFromName(User user)
{
allUsers = await GetAllUsers();
if (allUsers == null) return null;
User? selectedUser = allUsers.FirstOrDefault(x => x.Username == user.Username);
if (selectedUser == null) return null;
return selectedUser;
}
async void LoginAs(User user)
{
await localStorage.SetItemAsStringAsync("User", user.Username);
RefreshPage();
}
async void Logout()
{
await localStorage.RemoveItemAsync("User");
RefreshPage();
}
async Task<User[]?> GetAllUsers()
{
var allUsers = await httpClient.GetFromJsonAsync<Dictionary<string, User>>("https://globalchat-4a89f-default-rtdb.europe-west1.firebasedatabase.app/Database/Users.json");
if (allUsers == null)
return null;
User[] users = allUsers.Values.ToArray();
return users;
} }
#region Signup #region Signup
@ -161,17 +245,19 @@
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
// Reads "cookie" CheckLoggedin();
var cookieContent = await localStorage.GetItemAsync<User>("cookieName"); }
if (cookieContent == null) async void CheckLoggedin()
{ {
Console.WriteLine("Cookie is blank"); string? name = await localStorage.GetItemAsStringAsync("User");
} if (name == null) return;
else
{ Snackbar.Add("Successfully logged in!", Severity.Success);
Console.WriteLine("We have a cookie with contents: " + cookieContent);
} Program.LoggedInName = name;
isLoggedIn = true;
StateHasChanged();
} }
async void ClearAllCookies() async void ClearAllCookies()
@ -179,6 +265,11 @@
await localStorage.ClearAsync(); await localStorage.ClearAsync();
} }
private void RefreshPage()
{
NavManager.NavigateTo(NavManager.Uri, forceLoad: true);
}
public class User public class User
{ {
public string? Username { get; set; } public string? Username { get; set; }

View File

@ -6,9 +6,12 @@ using Otakians;
using System; using System;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using MudBlazor;
internal class Program internal class Program
{ {
public static string? LoggedInName;
private static async Task Main(string[] args) private static async Task Main(string[] args)
{ {
var builder = WebAssemblyHostBuilder.CreateDefault(args); var builder = WebAssemblyHostBuilder.CreateDefault(args);
@ -16,8 +19,8 @@ internal class Program
builder.RootComponents.Add<HeadOutlet>("head::after"); builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddMudServices(); builder.Services.AddMudServices(config =>
builder.Services.AddBlazoredLocalStorage(); // local storage config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.TopCenter);
builder.Services.AddBlazoredLocalStorage(config => builder.Services.AddBlazoredLocalStorage(config =>
config.JsonSerializerOptions.WriteIndented = true); // local storage config.JsonSerializerOptions.WriteIndented = true); // local storage

View File

@ -7,3 +7,4 @@
@using Microsoft.JSInterop @using Microsoft.JSInterop
@using Otakians @using Otakians
@using MudBlazor @using MudBlazor
@using System.Text.Json;