change the protection to authorize view tags

change the protection to authorize view tags
pull/2/head
paulcortez 12 months ago
parent ae687b1cf4
commit 2ab9eb1160

@ -1,4 +1,42 @@
<Router AppAssembly="@typeof(App).Assembly">
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<!-- Content to display when the user is not authorized
<MudText Typo="Typo.body1">You are not authorized to access this page. <MudLink Typo="Typo.body1" Href="/userlogin">Go to Login</MudLink></MudText>
-->
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
@*<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>*@
@*<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
@ -8,4 +46,4 @@
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</Router>*@

@ -0,0 +1,8 @@
namespace KWWebInvApp.Data
{
public class LoginData
{
public string username { get; set; }
public string password { get; set; }
}
}

@ -1,13 +0,0 @@
namespace KWWebInvApp.Data
{
public class UserServices
{
public UserInfoServices.userinfo? CurrentUser { get; set; } = null;
public bool IsAuthenticated()
{
if (CurrentUser == null) return false;
else return true;
}
}
}

@ -1,8 +1,12 @@
@page "/brmaintenance/invtycorrection"
@attribute [Authorize]
@using KWWebInvApp.Data;
@using KWWebInvApp.Services;
@inject IDialogService DialogService;
@inject UserServices userService;
@inject IAuthenticationService AuthenticationStateService;
<PageTitle>Branch Inventory Correction</PageTitle>
<MudText Typo="Typo.h4" GutterBottom="true">Branch Inventory Correction</MudText>
@ -138,8 +142,10 @@ else
disableStatusGetRecord = true;
disableStatusSave = true;
var currentUser = await AuthenticationStateService.GetAuthenticatedUserAsync();
branchItemLedger = await branchItemLedgerServiceClient.GetRemoteDataByBrCodeModelnoAsync(selectedBranch, modelNo);
newRemarks = $"Manually edit by {userService?.CurrentUser?.fullName}. {DateTime.Now:MM/dd/yyyy hh:mm:sstt}";
newRemarks = $"Manually edit by {currentUser?.fullName}. {DateTime.Now:MM/dd/yyyy hh:mm:sstt}";
disableStatusGetRecord = false;
disableStatusSave = false;
@ -153,7 +159,9 @@ else
disableStatusGetRecord = true;
disableStatusSave = true;
branchItemLedger.remarks = $"|Manually edit by {userService?.CurrentUser?.fullName}. {DateTime.Now:MM/dd/yyyy hh:mm:sstt} [{branchItemLedger.beginningqty} {branchItemLedger.inqty} {branchItemLedger.outqty} {branchItemLedger.sales} {branchItemLedger.adjustment} {branchItemLedger.endingqty}]";
var currentUser = await AuthenticationStateService.GetAuthenticatedUserAsync();
branchItemLedger.remarks = $"|Manually edit by {currentUser?.fullName}. {DateTime.Now:MM/dd/yyyy hh:mm:sstt} [{branchItemLedger.beginningqty} {branchItemLedger.inqty} {branchItemLedger.outqty} {branchItemLedger.sales} {branchItemLedger.adjustment} {branchItemLedger.endingqty}]";
int result = await branchItemLedgerServiceClient.UpdateRemoteBranchItemLedgerAsync(branchItemLedger);
if(result > 0)

@ -1,8 +1,6 @@
@page "/"
@using KWWebInvApp.Data
@inject UserServices userServices
@inject NavigationManager navigationManager
@attribute [Authorize]
<PageTitle>Index</PageTitle>

@ -1,5 +1,7 @@
@page "/items/itemdetails"
@attribute [Authorize]
<h3>Item Details</h3>
@code {

@ -1,5 +1,7 @@
@page "/items/tracesearch"
@attribute [Authorize]
<h3>ItemSearch</h3>
@code {

@ -1,5 +1,7 @@
@page "/items/tracehistory"
@attribute [Authorize]
<h3>TraceHistory</h3>
@code {

@ -0,0 +1,85 @@
@page "/userlogin"
@using KWWebInvApp.Data;
@using KWWebInvApp.Services;
@using Microsoft.AspNetCore.WebUtilities;
@inject IAuthenticationService AuthenticationStateService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
<PageTitle>User Login</PageTitle>
<MudText Typo="Typo.h3" GutterBottom="true">Enter your credential for verification</MudText>
<EditForm Model="@loginData" OnValidSubmit="SubmitLogin">
<MudGrid>
<MudItem sm="12">
<MudCard>
<MudCardContent>
<MudText Typo="Typo.h4">Login</MudText>
<MudText Typo="Typo.subtitle1">Welcome to Merchandise and SAC System</MudText>
@if (error != null)
{
<MudAlert Severity="Severity.Error">@error</MudAlert>
}
<MudTextField T="string" Label="Username" Required="true" RequiredError="Username is required"
@bind-Value="loginData.username" />
<MudTextField T="string" Label="Password" Required="true" RequiredError="Password is required"
InputType="InputType.Password"
@bind-Value="loginData.password" />
<MudCardActions Class="mt-5">
<MudButton Variant="Variant.Filled" Color="Color.Primary" ButtonType="ButtonType.Submit" Disabled="submitButtonDisabled">@submitButtonText</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Secondary" Class="mx-2" ButtonType="ButtonType.Reset" Disabled="submitButtonDisabled">Reset</MudButton>
</MudCardActions>
</MudCardContent>
</MudCard>
</MudItem>
</MudGrid>
</EditForm>
@code {
bool submitButtonDisabled = false;
string? error, submitButtonText = "Login";
LoginData loginData = new();
protected override async Task OnInitializedAsync()
{
}
async Task SubmitLogin()
{
error = null;
waitingButton(true);
var webAuthenticationStateProvider = (WebAuthenticationStateProvider)AuthenticationStateProvider;
var loginSuccess = await webAuthenticationStateProvider.LoginAsync(loginData);
if (loginSuccess)
{
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("returnUrl", out var returnURL))
NavigationManager.NavigateTo($"/{returnURL}");
else
NavigationManager.NavigateTo("/");
}
else
error = "Invalid username or password. Please try again.";
waitingButton(false);
}
void waitingButton(bool waiting = false)
{
if(waiting)
{
submitButtonDisabled = true;
submitButtonText = "Please Wait...";
}
else
{
submitButtonDisabled = false;
submitButtonText = "Login";
}
}
}

@ -1,5 +1,8 @@
using KWWebInvApp.Data;
using KWWebInvApp.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Hosting.StaticWebAssets;
using MudBlazor.Services;
@ -8,13 +11,21 @@ var builder = WebApplication.CreateBuilder(args);
StaticWebAssetsLoader.UseStaticWebAssets(builder.Environment, builder.Configuration);
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1); // Set the session timeout as needed
});
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<UserServices>();
builder.Services.AddMudServices();
builder.Services.AddScoped<ProtectedSessionStorage>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<AuthenticationStateProvider, WebAuthenticationStateProvider>();
var app = builder.Build();
// Configure the HTTP request pipeline.
@ -25,12 +36,15 @@ if (!app.Environment.IsDevelopment())
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

@ -0,0 +1,47 @@
using KWWebInvApp.Data;
using UserInfoServices;
namespace KWWebInvApp.Services
{
public class AuthenticationService : IAuthenticationService
{
private UserInfoServices.userinfo? CurrentUser;
public async Task<userinfo> GetAuthenticatedUserAsync()
{
return CurrentUser;
}
public async Task SetAuthenticatedUserAsync(UserInfoServices.userinfo currentUser)
{
CurrentUser = currentUser;
}
public async Task<bool> LoginAsync(LoginData loginData)
{
if (!string.IsNullOrWhiteSpace(loginData.username) && !string.IsNullOrWhiteSpace(loginData.password))
{
UserInfoServices.UserInfoServiceClient userInfoServiceClient = new();
UserInfoServices.userinfo userAttemptingToLogin = new UserInfoServices.userinfo()
{
username = loginData.username,
pass = await userInfoServiceClient.md5EncodingAsync(loginData.password)
};
CurrentUser = await userInfoServiceClient.AuthenticateUserAsync(userAttemptingToLogin);
if (CurrentUser == null)
return false;
else
return true;
}
return false;
}
public async Task LogoutAsync()
{
CurrentUser = null;
}
}
}

@ -0,0 +1,12 @@
using KWWebInvApp.Data;
namespace KWWebInvApp.Services
{
public interface IAuthenticationService
{
Task<UserInfoServices.userinfo> GetAuthenticatedUserAsync();
Task SetAuthenticatedUserAsync(UserInfoServices.userinfo userInfo);
Task<bool> LoginAsync(LoginData loginData);
Task LogoutAsync();
}
}

@ -0,0 +1,145 @@
using KWWebInvApp.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System.Security.Claims;
namespace KWWebInvApp.Services
{
public class WebAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IAuthenticationService _authService;
private readonly ProtectedSessionStorage _sessionStorage;
public WebAuthenticationStateProvider(IAuthenticationService authService, ProtectedSessionStorage sessionStorage)
{
_authService = authService;
_sessionStorage = sessionStorage;
}
/*
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var user = await _authService.GetAuthenticatedUserAsync();
if (user == null)
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.username),
new Claim(ClaimTypes.Role, user.userlvl.ToString())
// Add any other claims based on your application's requirements
};
var identity = new ClaimsIdentity(claims, "CustomAuth");
var principal = new ClaimsPrincipal(identity);
return new AuthenticationState(principal);
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var principal = new ClaimsPrincipal(new ClaimsIdentity());
UserInfoServices.userinfo? user = null;
try
{
var userSessionResult = await _sessionStorage.GetAsync<UserInfoServices.userinfo>("UserInfoSession");
user = (userSessionResult.Success) ? userSessionResult.Value : null;
if (user == null)
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.username),
new Claim(ClaimTypes.Role, user.userlvl.ToString())
// Add any other claims based on your application's requirements
};
var identity = new ClaimsIdentity(claims, "KWWebInvAppAuth");
principal = new ClaimsPrincipal(identity);
}
catch { return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); }
var authState = new AuthenticationState(principal);
return authState;
}
*/
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var principal = new ClaimsPrincipal(new ClaimsIdentity());
UserInfoServices.userinfo? user = null;
try
{
user = await _authService.GetAuthenticatedUserAsync();
if (user == null)
{
var userSessionResult = await _sessionStorage.GetAsync<UserInfoServices.userinfo>("UserInfoSession");
user = (userSessionResult.Success) ? userSessionResult.Value : null;
if (user == null)
return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
else
await _authService.SetAuthenticatedUserAsync(user);
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.username),
new Claim(ClaimTypes.Role, user.userlvl.ToString())
// Add any other claims based on your application's requirements
};
var identity = new ClaimsIdentity(claims, "KWWebInvAppAuth");
principal = new ClaimsPrincipal(identity);
}
catch { return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); }
return new AuthenticationState(principal);
}
public async Task<bool> LoginAsync(LoginData loginData)
{
bool loginSuccess = await _authService.LoginAsync(loginData);
if(loginSuccess)
{
UserInfoServices.userinfo user = await _authService.GetAuthenticatedUserAsync();
// Supply sessionStorage with user data first before using SetAuthenticationState.
// authState will rely on the value of UserInfoSession stored here
await _sessionStorage.SetAsync("UserInfoSession", user);
AuthenticationState authState = await GetAuthenticationStateAsync();
SetAuthenticationState(authState);
}
return loginSuccess;
}
public async Task LogoutAsync()
{
await _authService.LogoutAsync();
await _sessionStorage.DeleteAsync("UserInfoSession");
SetAuthenticationState(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
}
public void SetAuthenticationState(AuthenticationState authState)
{
NotifyAuthenticationStateChanged(Task.FromResult(authState));
}
}
}

@ -1,81 +0,0 @@
@using KWWebInvApp.Data
@inject UserServices userService
@inject IDialogService DialogService
@inject NavigationManager navigationManager
<EditForm Model="@userAttemtingToLogin" OnValidSubmit="SubmitLogin">
<MudGrid>
<MudItem sm="12">
<MudCard>
<MudCardContent>
<MudText Typo="Typo.h4">Login</MudText>
<MudText Typo="Typo.subtitle1">Welcome to Merchandise and SAC System</MudText>
@if (error != null)
{
<MudAlert Severity="Severity.Error">@error</MudAlert>
}
<MudTextField T="string" Label="Username"
@bind-Value="userAttemtingToLogin.username" />
<MudTextField T="string" Label="Password"
InputType="InputType.Password"
@bind-Value="pass" />
<MudCardActions Class="mt-5">
<MudButton Variant="Variant.Filled" Color="Color.Primary" ButtonType="ButtonType.Submit" Disabled="submitButtonDisabled">@submitButtonText</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Secondary" Class="mx-2" ButtonType="ButtonType.Reset" Disabled="submitButtonDisabled">Reset</MudButton>
</MudCardActions>
</MudCardContent>
</MudCard>
</MudItem>
</MudGrid>
</EditForm>
@code {
bool submitButtonDisabled = false;
string? pass, error, submitButtonText = "Login";
UserInfoServices.userinfo userAttemtingToLogin = new();
//protected override async Task OnInitializedAsync()
//{
//}
async Task SubmitLogin()
{
error = null;
if (String.IsNullOrEmpty(userAttemtingToLogin.username) || String.IsNullOrEmpty(pass))
{
error = "Username and Password is required";
return;
}
UserInfoServices.UserInfoServiceClient userInfoServiceClient = new();
waitingButton(true);
userAttemtingToLogin.pass = await userInfoServiceClient.md5EncodingAsync(pass);
userService.CurrentUser = await userInfoServiceClient.AuthenticateUserAsync(userAttemtingToLogin);
waitingButton();
if (userService.CurrentUser == null)
error = "Invalid Username or Password";
else
navigationManager.NavigateTo("/");
}
void waitingButton(bool waiting = false)
{
if(waiting)
{
submitButtonDisabled = true;
submitButtonText = "Please Wait...";
}
else
{
submitButtonDisabled = false;
submitButtonText = "Login";
}
}
}

@ -1,6 +1,10 @@
@inherits LayoutComponentBase
@using KWWebInvApp.Data
@inject UserServices userServices
@using KWWebInvApp.Services;
@inject IAuthenticationService AuthenticationStateService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager navigationManager
<MudThemeProvider />
@ -8,52 +12,58 @@
<MudSnackbarProvider />
<MudLayout>
<MudAppBar Elevation="0">
@if (userServices.IsAuthenticated())
{
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
<MudSpacer />
<MudIconButton Icon="@Icons.Custom.Brands.MudBlazor" Color="Color.Inherit" Link="https://mudblazor.com/" Target="_blank" />
<MudIconButton Icon="@Icons.Custom.Brands.GitHub" Color="Color.Inherit" Link="https://github.com/MudBlazor/MudBlazor/" Target="_blank" />
<MudIconButton Icon="@Icons.Material.Filled.Logout" Color="Color.Inherit" OnClick="Logout" />
}
</MudAppBar>
@if (userServices.IsAuthenticated())
{
<MudDrawer @bind-Open="_drawerOpen" Elevation="1">
<MudDrawerHeader>
<MudText Typo="Typo.h6">KW Web App</MudText>
</MudDrawerHeader>
<NavMenu />
</MudDrawer>
<MudMainContent>
<MudContainer MaxWidth="MaxWidth.Large" Class="my-16 pt-16">
@Body
</MudContainer>
</MudMainContent>
}
else
{
<MudMainContent>
<MudContainer MaxWidth="MaxWidth.Large" Class="my-16 pt-16">
<Login />
</MudContainer>
</MudMainContent>
}
<AuthorizeView>
<Authorized>
<MudAppBar Elevation="0">
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
<MudSpacer />
<MudIconButton Icon="@Icons.Custom.Brands.MudBlazor" Color="Color.Inherit" Link="https://mudblazor.com/" Target="_blank" />
<MudIconButton Icon="@Icons.Custom.Brands.GitHub" Color="Color.Inherit" Link="https://github.com/MudBlazor/MudBlazor/" Target="_blank" />
<MudIconButton Icon="@Icons.Material.Filled.Logout" Color="Color.Inherit" OnClick="Logout" />
</MudAppBar>
</Authorized>
</AuthorizeView>
<AuthorizeView>
<Authorized>
<MudDrawer @bind-Open="_drawerOpen" Elevation="1">
<MudDrawerHeader>
<MudText Typo="Typo.h6">KW Web Inventory</MudText>
</MudDrawerHeader>
<NavMenu />
</MudDrawer>
</Authorized>
</AuthorizeView>
<MudMainContent>
<MudContainer MaxWidth="MaxWidth.Large" Class="my-16 pt-16">
@Body
</MudContainer>
</MudMainContent>
</MudLayout>
@code {
bool _drawerOpen = true;
private UserInfoServices.userinfo? user;
protected override async void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
user = await AuthenticationStateService.GetAuthenticatedUserAsync();
}
void DrawerToggle()
{
_drawerOpen = !_drawerOpen;
}
void Logout()
async void Logout()
{
userServices.CurrentUser = null;
var webAuthenticationStateProvider = (WebAuthenticationStateProvider)AuthenticationStateProvider;
await webAuthenticationStateProvider.LogoutAsync();
navigationManager.NavigateTo("/");
}
}

@ -0,0 +1,34 @@
@using KWWebInvApp.Data
@using KWWebInvApp.Services;
@inject NavigationManager navigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
protected override async Task OnInitializedAsync()
{
//var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);
//if (string.IsNullOrWhiteSpace(returnUrl))
// Navigation.NavigateTo("/userlogin", true);
//else
//{
// if (returnUrl == "userlogin")
// Navigation.NavigateTo("/userlogin", true);
// else
// Navigation.NavigateTo($"/userlogin?returnUrl={returnUrl}", true);
//}
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
var returnUrl = navigationManager.ToBaseRelativePath(navigationManager.Uri);
if (string.IsNullOrWhiteSpace(returnUrl))
navigationManager.NavigateTo("/userlogin", true);
else
navigationManager.NavigateTo($"/userlogin?returnUrl={returnUrl}", true);
}
}
Loading…
Cancel
Save