diff --git a/IMaoTai.Core/CommonX.cs b/IMaoTai.Core/CommonX.cs index fad135a..49f4210 100644 --- a/IMaoTai.Core/CommonX.cs +++ b/IMaoTai.Core/CommonX.cs @@ -25,6 +25,9 @@ public class CommonX //登录用户账号缓存 public static string LoginUserListFile = Path.Combine(CacheDir, "loginUserList.json"); + //登录账户session缓存(wpf) + public static string LoginCacheUserListFile = Path.Combine(CacheDir, "loginCacheUserList.json"); + /// /// 订单数据库表名 /// diff --git a/IMaoTai.Core/IMaoTai.Core.csproj b/IMaoTai.Core/IMaoTai.Core.csproj index 4e86ab9..4b4e10b 100644 --- a/IMaoTai.Core/IMaoTai.Core.csproj +++ b/IMaoTai.Core/IMaoTai.Core.csproj @@ -12,6 +12,7 @@ + diff --git a/IMaoTai.MasaBlazor/Components/App.razor b/IMaoTai.MasaBlazor/Components/App.razor index 0eca61a..d2b1518 100644 --- a/IMaoTai.MasaBlazor/Components/App.razor +++ b/IMaoTai.MasaBlazor/Components/App.razor @@ -10,13 +10,14 @@ - + - + + \ No newline at end of file diff --git a/IMaoTai.MasaBlazor/Helpers/IocHelper.cs b/IMaoTai.MasaBlazor/Helpers/IocHelper.cs index 67d488b..5cd201b 100644 --- a/IMaoTai.MasaBlazor/Helpers/IocHelper.cs +++ b/IMaoTai.MasaBlazor/Helpers/IocHelper.cs @@ -11,6 +11,7 @@ using Yitter.IdGenerator; using IMaoTai.MasaUI.Core; using Microsoft.AspNetCore.Components.Authorization; +using Blazored.LocalStorage; namespace IMaoTai.MasaBlazor.Web.Helpers; @@ -19,9 +20,11 @@ public static class IocHelper public static IServiceCollection RegisterService(IServiceCollection _services) { _services.AddAuthorizationCore(); + _services.AddCascadingAuthenticationState(); _services.AddScoped(); - _services.AddScoped(s => s.GetRequiredService()); - + _services.AddScoped(); + _services.AddBlazoredLocalStorage(config => + config.JsonSerializerOptions.WriteIndented = true); _services.TryAddSingleton(); _services.TryAddSingleton(); _services.TryAddSingleton(); diff --git a/IMaoTai.MasaBlazor/Program.cs b/IMaoTai.MasaBlazor/Program.cs index bd6b3e1..8e0de0f 100644 --- a/IMaoTai.MasaBlazor/Program.cs +++ b/IMaoTai.MasaBlazor/Program.cs @@ -15,7 +15,17 @@ builder.Services.AddMasaBlazor(); await IocHelper.InitBusiness(); -builder.Services.AddAdminCaviar(new Type[] { typeof(Program), typeof(IMaoTai.MasaUI._Imports) }); +builder.Services.AddIMaoTaiAdmin(new Type[] { typeof(Program), typeof(IMaoTai.MasaUI._Imports) }); + +//API +builder.Services.AddCors(options => options.AddPolicy("Any", + builder => + { + builder.AllowAnyMethod() + .AllowAnyHeader() + .SetIsOriginAllowed(_ => true) + .AllowCredentials(); + })); var app = builder.Build(); @@ -24,7 +34,7 @@ { app.UseExceptionHandler("/Error", createScopeForErrors: true); } - +app.UseCors("Any"); app.UseStaticFiles(); app.UseAntiforgery(); diff --git a/IMaoTai.MasaBlazor/Properties/launchSettings.json b/IMaoTai.MasaBlazor/Properties/launchSettings.json index ef240d2..2222596 100644 --- a/IMaoTai.MasaBlazor/Properties/launchSettings.json +++ b/IMaoTai.MasaBlazor/Properties/launchSettings.json @@ -1,29 +1,12 @@ { - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:56107", - "sslPort": 0 - } - }, - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "applicationUrl": "http://localhost:5004", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "profiles": { + "IMaoTai.MasaBlazor": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } + "applicationUrl": "http://localhost:5004;https://localhost:5005" } } +} diff --git a/IMaoTai.MasaUI/Config.cs b/IMaoTai.MasaUI/Config.cs index cec81b3..ff4d0a1 100644 --- a/IMaoTai.MasaUI/Config.cs +++ b/IMaoTai.MasaUI/Config.cs @@ -33,18 +33,8 @@ public static bool IsServer /// public static List AdditionalAssemblies; - public static WebAssemblyHostBuilder AddCavWasm(this WebAssemblyHostBuilder builder) - { - //IsServer = false; - //builder.Services.AddScoped(); - builder.Services.AddOptions(); - //builder.Services.AddAuthorizationCore(); - //builder.Services.AddSingleton(); - //builder.Services.AddSingleton(); - return builder; - } - public static IServiceCollection AddAdminCaviar(this IServiceCollection services, Type[] assemblies) + public static IServiceCollection AddIMaoTaiAdmin(this IServiceCollection services, Type[] assemblies) { if (assemblies != null) { diff --git a/IMaoTai.MasaUI/Core/HostAuthenticationStateProvider.cs b/IMaoTai.MasaUI/Core/HostAuthenticationStateProvider.cs index 180e365..90a9e59 100644 --- a/IMaoTai.MasaUI/Core/HostAuthenticationStateProvider.cs +++ b/IMaoTai.MasaUI/Core/HostAuthenticationStateProvider.cs @@ -1,69 +1,55 @@ -// Copyright (c) BeiYinZhiNian (1031622947@qq.com). All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// Website: http://www.caviar.wang/ or https://gitee.com/Cherryblossoms/caviar. - -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Security.Claims; -using System.Threading.Tasks; +using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; using IMaoTai.Core.Domain; using IMaoTai.Core.Service; +using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage; namespace IMaoTai.MasaUI.Core { public class HostAuthenticationStateProvider : AuthenticationStateProvider { private readonly ILoginUserService _loginUserService; + private ProtectedSessionStorage _protectedSessionStore; - //private CurrentUser _currentUser; private ClaimsIdentity identity = new ClaimsIdentity(); - public HostAuthenticationStateProvider(ILoginUserService loginUserService) + public HostAuthenticationStateProvider( + ILoginUserService loginUserService, + ProtectedSessionStorage protectedSessionStore) { _loginUserService = loginUserService; + _protectedSessionStore = protectedSessionStore; } public override async Task GetAuthenticationStateAsync() { + var userSessionStorageResult = await _protectedSessionStore.GetAsync("UserSession"); + var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null; + if (userSession != null) + { + var claims = new[] { + new Claim(ClaimTypes.Name, userSession.UserName)}; + identity = new ClaimsIdentity(claims,"IMaoTai"); + } var user = new ClaimsPrincipal(identity); - return new AuthenticationState(new ClaimsPrincipal(identity)); - //var identity = new ClaimsIdentity(); - //try - //{ - // var userInfo = await GetCurrentUser(); - // if (userInfo.IsAuthenticated) - // { - // var claims = new[] { new Claim(ClaimTypes.Name, _currentUser.UserName) }; + return await Task.FromResult( new AuthenticationState(user)); - // identity = new ClaimsIdentity(claims, nameof(HostAuthenticationStateProvider)); - // } - //} - //catch (HttpRequestException ex) - //{ - // Console.WriteLine("Request failed:" + ex.ToString()); - //} + + //var user = new ClaimsPrincipal(identity); //return new AuthenticationState(new ClaimsPrincipal(identity)); + } - //public async Task GetCurrentUser() - //{ - // if (_currentUser != null && _currentUser.IsAuthenticated) return _currentUser; - // _currentUser = await _loginUserService.CurrentUserInfo(); - // //_currentUser = new CurrentUser() - // //{ - // // UserName = "admin", - // // IsAuthenticated = true, - // //}; - // return _currentUser; - //} + + public ClaimsPrincipal GetCurrentUser() + { + var user = new ClaimsPrincipal(identity); + return user; + } public async Task Logout() { var result = await _loginUserService.Logout(); - // _currentUser = null; identity = new ClaimsIdentity(); if (!Config.IsServer) { @@ -79,6 +65,7 @@ public async Task Login(UserLogin loginParameters, string returnUrl) { var claims = new[] { new Claim(ClaimTypes.Name, loginParameters.UserName) }; identity = new ClaimsIdentity(claims, "IMaoTai"); + await _protectedSessionStore.SetAsync("UserSession", loginParameters); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } return result; diff --git a/IMaoTai.MasaUI/Core/WHostAuthenticationStateProvider.cs b/IMaoTai.MasaUI/Core/WHostAuthenticationStateProvider.cs new file mode 100644 index 0000000..ebf968a --- /dev/null +++ b/IMaoTai.MasaUI/Core/WHostAuthenticationStateProvider.cs @@ -0,0 +1,95 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Authorization; +using IMaoTai.Core.Domain; +using IMaoTai.Core.Service; +using JsonFlatFileDataStore; +using IMaoTai.Core; + +namespace IMaoTai.MasaUI.Core +{ + public class WHostAuthenticationStateProvider : AuthenticationStateProvider + { + private readonly ILoginUserService _loginUserService; + + private ClaimsIdentity identity = new ClaimsIdentity(); + + public WHostAuthenticationStateProvider( + ILoginUserService loginUserService) + { + _loginUserService = loginUserService; + } + + public override async Task GetAuthenticationStateAsync() + { + // Open database (create new if file doesn't exist) + var store = new DataStore(CommonX.LoginCacheUserListFile); + // Get employee collection + var collection = store.GetCollection(); + + // Find item with name + var userSession = collection + .AsQueryable() + .FirstOrDefault(); + + if (userSession != null) + { + var claims = new[] { + new Claim(ClaimTypes.Name, userSession.UserName)}; + identity = new ClaimsIdentity(claims, "IMaoTai"); + } + var user = new ClaimsPrincipal(identity); + return await Task.FromResult( new AuthenticationState(user)); + + } + + + public ClaimsPrincipal GetCurrentUser() + { + var user = new ClaimsPrincipal(identity); + return user; + } + + public async Task Logout() + { + var result = await _loginUserService.Logout(); + identity = new ClaimsIdentity(); + if (!Config.IsServer) + { + NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); + } + return result; + } + + public async Task Login(UserLogin loginParameters, string returnUrl) + { + var result = await _loginUserService.Login(loginParameters, returnUrl); + if (result) + { + var claims = new[] { new Claim(ClaimTypes.Name, loginParameters.UserName) }; + identity = new ClaimsIdentity(claims, "IMaoTai"); + + // Open database (create new if file doesn't exist) + var store = new DataStore(CommonX.LoginCacheUserListFile); + // Get employee collection + var collection = store.GetCollection(); + + // Find item with name + var userDynamic = collection + .AsQueryable() + .FirstOrDefault(p => p.UserName == loginParameters.UserName); + if (userDynamic == null) + { + await collection.InsertOneAsync(loginParameters); + } + else + { + await collection.UpdateOneAsync(p => p.UserName == loginParameters.UserName, loginParameters); + } + + + NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); + } + return result; + } + } +} \ No newline at end of file diff --git a/IMaoTai.MasaUI/IMaoTai.MasaUI.csproj b/IMaoTai.MasaUI/IMaoTai.MasaUI.csproj index 4316dca..0b23e21 100644 --- a/IMaoTai.MasaUI/IMaoTai.MasaUI.csproj +++ b/IMaoTai.MasaUI/IMaoTai.MasaUI.csproj @@ -12,6 +12,7 @@ + diff --git a/IMaoTai.MasaUI/NoAuthorizeRoutes.razor b/IMaoTai.MasaUI/NoAuthorizeRoutes.razor index 5c4e4cb..9071b6b 100644 --- a/IMaoTai.MasaUI/NoAuthorizeRoutes.razor +++ b/IMaoTai.MasaUI/NoAuthorizeRoutes.razor @@ -2,7 +2,6 @@ AdditionalAssemblies="Config.AdditionalAssemblies"> - diff --git a/IMaoTai.MasaUI/Pages/Index.razor b/IMaoTai.MasaUI/Pages/Index.razor index 4c31fb7..5d39423 100644 --- a/IMaoTai.MasaUI/Pages/Index.razor +++ b/IMaoTai.MasaUI/Pages/Index.razor @@ -2,9 +2,6 @@ @using Masa.Blazor @using IMaoTai.MasaUI.Core @inherits AuthComponentBase - - - diff --git a/IMaoTai.MasaUI/Pages/InstructionsData.razor b/IMaoTai.MasaUI/Pages/InstructionsData.razor index 838f3f8..38d96e9 100644 --- a/IMaoTai.MasaUI/Pages/InstructionsData.razor +++ b/IMaoTai.MasaUI/Pages/InstructionsData.razor @@ -21,7 +21,6 @@ @code { - } diff --git a/IMaoTai.MasaUI/Pages/LogData.razor b/IMaoTai.MasaUI/Pages/LogData.razor index a94c02e..abfe9f0 100644 --- a/IMaoTai.MasaUI/Pages/LogData.razor +++ b/IMaoTai.MasaUI/Pages/LogData.razor @@ -117,11 +117,6 @@ else await GetListDataFromApi(); } - protected override async Task OnInitializedAsync() - { - await GetListDataFromApi(); - } - protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) diff --git a/IMaoTai.MasaUI/Pages/LoginData.razor b/IMaoTai.MasaUI/Pages/LoginData.razor index d098faa..32bbfcb 100644 --- a/IMaoTai.MasaUI/Pages/LoginData.razor +++ b/IMaoTai.MasaUI/Pages/LoginData.razor @@ -5,9 +5,10 @@ @using System @using System.Web @using Microsoft.AspNetCore.Components -@using Microsoft.JSInterop +@using AlertTypes = Masa.Blazor.AlertTypes @using IMaoTai.MasaUI.Core @layout EmptyLayout +@inject NavigationManager NavigationManager @@ -16,10 +17,7 @@
-

让预约更简单

-
- i茅台预约。 -
+

让i茅台预约更简单

@@ -33,7 +31,9 @@
欢迎来到i茅台预约! 👋
- + + @Msg + - Login - @Msg
@@ -56,31 +54,39 @@ @code{ [Inject] - public NavigationManager Navigation { get; set; } = default!; - - [Inject] - HostAuthenticationStateProvider AuthStateProvider { get; set; } + AuthenticationStateProvider AuthStateProvider { get; set; } - [Inject] - IJSRuntime JSRuntime { get; set; } public async Task Login(MouseEventArgs args) { - var returnUrl = HttpUtility.ParseQueryString(new Uri(Navigation.Uri).Query)["returnUrl"]; + var returnUrl = HttpUtility.ParseQueryString(new Uri(NavigationManager.Uri).Query)["returnUrl"]; if (returnUrl == null) returnUrl = "/"; - var result = await AuthStateProvider.Login(ApplicationUser, returnUrl); - if (result) + bool result; + if (AuthStateProvider is HostAuthenticationStateProvider) + { + result = await (AuthStateProvider as HostAuthenticationStateProvider).Login(ApplicationUser, returnUrl); + }else + { + result = await (AuthStateProvider as WHostAuthenticationStateProvider).Login(ApplicationUser, returnUrl); + } + + _alertShow = true; + if (!result) + { + _alertTypes = AlertTypes.Error; + Msg = "账号或者密码错误"; + } + else { - Msg = ""; - Navigation.NavigateTo(returnUrl, false, false); - return; + Msg = "登录成功"; + NavigationManager.NavigateTo(returnUrl, true, true); } - Msg = "账号或者密码错误"; return; - // Navigation.NavigateTo(Navigation.BaseUri); } - public string Msg; + private string Msg; + private AlertTypes _alertTypes = AlertTypes.Success; + private bool _alertShow = false; @@ -107,50 +113,3 @@ } } - -@* - - - -
-
- - - - -
欢迎来到i茅台预约! 👋
- - - - - - - 登录 - -
-
-
-
-
- - -@code { - [Inject] - public NavigationManager Navigation { get; set; } = default!; - - public void Login(MouseEventArgs args) - { - Navigation.NavigateTo(Navigation.BaseUri); - } - - private bool _show; - - [Parameter] - public bool HideLogo { get; set; } - - [Parameter] - public double Width { get; set; } = 410; -} - *@ diff --git a/IMaoTai.MasaUI/Pages/ProductData.razor b/IMaoTai.MasaUI/Pages/ProductData.razor index 8a0a523..153caa6 100644 --- a/IMaoTai.MasaUI/Pages/ProductData.razor +++ b/IMaoTai.MasaUI/Pages/ProductData.razor @@ -57,10 +57,13 @@ else new() { Text = "ʱ", Value = nameof(ProductEntity.Created)} }; - protected override async Task OnInitializedAsync() + protected override async Task OnAfterRenderAsync(bool firstRender) { - _productList = AppointProjectViewModel.ProductList; - await Task.CompletedTask; + if (firstRender) + { + await GetProductListDataFromApi(); + StateHasChanged(); + } } private async Task GetProductListDataFromApi() diff --git a/IMaoTai.MasaUI/Pages/ShopData.razor b/IMaoTai.MasaUI/Pages/ShopData.razor index ff1b6b2..27335d1 100644 --- a/IMaoTai.MasaUI/Pages/ShopData.razor +++ b/IMaoTai.MasaUI/Pages/ShopData.razor @@ -130,11 +130,6 @@ else await GetShopListDataFromApi(); } - protected override async Task OnInitializedAsync() - { - await GetShopListDataFromApi(); - } - protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) diff --git a/IMaoTai.MasaUI/Pages/UserData.razor b/IMaoTai.MasaUI/Pages/UserData.razor index 91de9df..e438a2d 100644 --- a/IMaoTai.MasaUI/Pages/UserData.razor +++ b/IMaoTai.MasaUI/Pages/UserData.razor @@ -654,11 +654,6 @@ else } - protected override async Task OnInitializedAsync() - { - await GetUserListDataFromApi(); - } - protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) diff --git a/IMaoTai.MasaUI/Routes.razor b/IMaoTai.MasaUI/Routes.razor index 0ff8072..fd9b30e 100644 --- a/IMaoTai.MasaUI/Routes.razor +++ b/IMaoTai.MasaUI/Routes.razor @@ -1,48 +1,38 @@ -@using Microsoft.AspNetCore.Components.Routing; +@inject NavigationManager NavigationManager +@using Microsoft.AspNetCore.Components.Authorization @using IMaoTai.Core - - - - - + + + + + + 您没有权限访问此页面 + + - - - - - - - - - - - - - - + + + + + + + + -@code{ - private Microsoft.AspNetCore.Components.Routing.Router router; - - protected override void OnInitialized() - { - // 获取当前页面的 Router - // router = (Microsoft.AspNetCore.Components.Routing.Router)NavigationManager.GetType().GetField("_router", BindingFlags.NonPublic).GetValue(NavigationManager); - } - - protected override async Task OnAfterRenderAsync(bool firstRender) - { - - } - - [Inject] - public NavigationManager Navigation { get; set; } = default!; - - public void ReturnToLoginPage() +@code { + private RenderFragment RedirectToLogin => builder => { - Navigation.NavigateTo("/login"); - } + var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); + if (string.IsNullOrWhiteSpace(returnUrl)) + { + NavigationManager.NavigateTo("/login"); + } + else + { + NavigationManager.NavigateTo($"/login?returnUrl={Uri.EscapeDataString(returnUrl)}", true); + } + }; } diff --git a/IMaoTai.sln b/IMaoTai.sln index c97b4b3..266dda7 100644 --- a/IMaoTai.sln +++ b/IMaoTai.sln @@ -17,6 +17,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IMaoTai.Masa.Wpf", "IMaoTai EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "IMaoTai.Masa.BlazorWeb", "IMaoTai.Masa.BlazorWeb", "{38D48092-AC81-4B71-9852-831C2F7C8BFF}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docker", "Docker", "{F7901042-F1D1-4135-A445-12A394D715FE}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Aspire", "Aspire", "{10FFE24D-CF0C-4466-B806-BDE64C924306}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/IMaoTai/Helpers/IocHelper.cs b/IMaoTai/Helpers/IocHelper.cs index 49f5e51..e69f558 100644 --- a/IMaoTai/Helpers/IocHelper.cs +++ b/IMaoTai/Helpers/IocHelper.cs @@ -37,16 +37,16 @@ public static ServiceCollection GetIoc() _services.AddBlazorWebViewDeveloperTools(); _services.AddAuthorizationCore(); - _services.AddScoped(); - _services.AddScoped(s => s.GetRequiredService()); - + _services.AddCascadingAuthenticationState(); + _services.AddScoped(); + _services.AddScoped(); _services.TryAddSingleton(); _services.TryAddSingleton(); _services.TryAddSingleton(); _services.TryAddSingleton(); _services.TryAddSingleton(); - _services.AddAdminCaviar(new Type[] { typeof(IocHelper), typeof(IMaoTai.MasaUI._Imports) }); + _services.AddIMaoTaiAdmin(new Type[] { typeof(IocHelper), typeof(IMaoTai.MasaUI._Imports) }); return _services!; } diff --git a/IMaoTai/IMaoTai.csproj b/IMaoTai/IMaoTai.csproj index 843f364..ac3738a 100644 --- a/IMaoTai/IMaoTai.csproj +++ b/IMaoTai/IMaoTai.csproj @@ -1,7 +1,7 @@  WinExe - net7.0-windows + net8.0-windows7.0 enable enable true @@ -18,9 +18,10 @@ + - + diff --git a/IMaoTai/wwwroot/index.html b/IMaoTai/wwwroot/index.html index 6265eaf..4d9365f 100644 --- a/IMaoTai/wwwroot/index.html +++ b/IMaoTai/wwwroot/index.html @@ -27,7 +27,7 @@ - + \ No newline at end of file