Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Surefire\Components\Account\Shared\RedirectToLogin.razor
- ```razor
- @inject NavigationManager NavigationManager
- @code {
- protected override void OnInitialized()
- {
- Console.WriteLine($"Redr RENDERMODE: {RendererInfo.IsInteractive}");
- NavigationManager.NavigateTo($"Account/Login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}", forceLoad: true);
- }
- }
- ```
- ### Surefire\Components\Account\Pages\Login.razor
- ```razor
- @namespace Surefire.Components.Account.Pages
- @page "/Account/Login"
- @using System.ComponentModel.DataAnnotations
- @using Microsoft.AspNetCore.Authentication
- @using Microsoft.AspNetCore.Identity
- @using Surefire.Data
- @inject SignInManager<ApplicationUser> SignInManager
- @inject ILogger<Login> Logger
- @inject NavigationManager NavigationManager
- @inject IdentityRedirectManager RedirectManager
- <PageTitle>Surefire success from relentless focus.</PageTitle>
- <div class="page-content">
- <div class="staticlogin">
- <section>
- <div class="txt-alert-main">Login</div>
- <div class="txt-alert-sub"><StatusMessage Message="@errorMessage" /></div>
- <EditForm Model="Input" method="post" OnValidSubmit="LoginUser" FormName="login">
- <DataAnnotationsValidator />
- <ValidationSummary class="text-danger" role="alert" />
- <span class="sf-thead">Email</span>
- <div class="e-input-group e-control-container e-control-wrapper e-float-input" style="padding-top:0px !important;">
- <InputText @bind-Value="Input.Email" id="Input.Email" class="e-control e-textbox e-lib" autocomplete="username" aria-required="true" placeholder="[email protected]" />
- <ValidationMessage For="() => Input.Email" class="text-danger" />
- </div>
- <div style="height:20px;"></div>
- <span class="sf-thead">Password</span>
- <div class="e-input-group e-control-container e-control-wrapper e-float-input" style="padding-top:0px !important;">
- <InputText type="password" @bind-Value="Input.Password" id="Input.Password" class="e-control e-textbox e-lib" autocomplete="current-password" aria-required="true" placeholder="password" />
- <ValidationMessage For="() => Input.Password" class="text-danger" />
- </div>
- <div style="height:10px;"></div>
- <div class="checkbox mb-3" style="font-size:12px;">
- <label class="form-label">
- <InputCheckbox @bind-Value="Input.RememberMe" class="darker-border-checkbox form-check-input" />
- Remember me
- </label>
- </div>
- <div>
- <button type="submit" class="submitbtn">Log in</button>
- </div>
- </EditForm>
- </section>
- </div>
- </div>
- <style>
- :root .e-float-input {
- padding-top: 0px !important;
- margin-top: 0px !important;
- }
- </style>
- @code {
- private string? errorMessage = "Let's get you logged back in...";
- [CascadingParameter]
- private HttpContext HttpContext { get; set; } = default!;
- [SupplyParameterFromForm]
- private InputModel Input { get; set; } = new();
- [SupplyParameterFromQuery]
- private string? ReturnUrl { get; set; }
- protected override async Task OnInitializedAsync()
- {
- Console.WriteLine($"LOGN RENDERMODE: {RendererInfo.IsInteractive}");
- if (HttpMethods.IsGet(HttpContext.Request.Method))
- {
- await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
- }
- }
- public async Task LoginUser()
- {
- Console.WriteLine($"LOG1 RENDERMODE: {RendererInfo.IsInteractive}");
- var result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
- if (result.Succeeded)
- {
- Console.WriteLine($"LOG2 RENDERMODE: {RendererInfo.IsInteractive}");
- Logger.LogInformation("User logged in.");
- RedirectManager.RedirectTo("loading");
- }
- else if (result.RequiresTwoFactor)
- {
- RedirectManager.RedirectTo(
- "Account/LoginWith2fa",
- new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe });
- }
- else if (result.IsLockedOut)
- {
- Logger.LogWarning("User account locked out.");
- RedirectManager.RedirectTo("Account/Lockout");
- }
- else
- {
- errorMessage = "Error: Invalid login attempt.";
- }
- }
- private sealed class InputModel
- {
- [Required]
- [EmailAddress]
- public string Email { get; set; } = "";
- [Required]
- [DataType(DataType.Password)]
- public string Password { get; set; } = "";
- [Display(Name = "Remember me?")]
- public bool RememberMe { get; set; }
- }
- }
- ```
- ### Surefire\Components\App.razor
- ```razor
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <base href="/" />
- <link rel="stylesheet" href="app.css" />
- <link rel="stylesheet" href="Surefire.styles.css" />
- <ImportMap />
- <link rel="icon" type="image/png" href="favicon.png" />
- <HeadOutlet @rendermode="PageRenderMode" />
- <link rel="stylesheet" href="_content/Syncfusion.Blazor.Themes/fluent2.css" />
- <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
- <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js" type="text/javascript"></script>
- <script src="_content/Syncfusion.Blazor.SfPdfViewer/scripts/syncfusion-blazor-sfpdfviewer.min.js" type="text/javascript"></script>
- <script src="/scripts/forms.js" type="text/javascript"></script>
- </head>
- <body>
- <Routes @rendermode="PageRenderMode" />
- <script src="_framework/blazor.web.js"></script>
- </body>
- </html>
- @code {
- [CascadingParameter]
- private HttpContext HttpContext { get; set; } = default!;
- private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
- protected override void OnInitialized()
- {
- Console.WriteLine($"Init RENDERMODE: {RendererInfo.IsInteractive}");
- }
- }
- ```
- ### Surefire\Components\Routes.razor
- ```razor
- @using Surefire.Components.Account.Shared
- <Router AppAssembly="typeof(Program).Assembly">
- <Found Context="routeData">
- <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
- <NotAuthorized>
- <RedirectToLogin />
- </NotAuthorized>
- </AuthorizeRouteView>
- <FocusOnNavigate RouteData="routeData" Selector="h1" />
- </Found>
- </Router>
- @code {
- protected override void OnInitialized()
- {
- Console.WriteLine($"Rout RENDERMODE: {RendererInfo.IsInteractive}");
- }
- }
- ```
- ### Surefire\Program.cs
- ```csharp
- using Surefire.Components.Account;
- using Surefire.Components;
- using Surefire.Data;
- using Surefire.Domain.Attachments.Services;
- using Surefire.Domain.Carriers.Services;
- using Surefire.Domain.Policies.Services;
- using Surefire.Domain.Clients.Services;
- using Surefire.Domain.Renewals.Services;
- using Surefire.Domain.Forms.Services;
- using Surefire.Domain.Contacts.Services;
- using Surefire.Domain.Shared.Services;
- using Surefire.Domain.Users.Services;
- using Surefire.Domain.Ember;
- using Surefire.Domain.Logs;
- using Surefire.Domain.OpenAI;
- using Surefire.Domain.Plugins;
- using Microsoft.AspNetCore.Components.Authorization;
- using Microsoft.AspNetCore.Identity;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.FluentUI.AspNetCore.Components;
- using Microsoft.FluentUI.AspNetCore.Components.Components.Tooltip;
- using Syncfusion.Blazor;
- using DotNetEnv;
- using Microsoft.Extensions.DependencyInjection;
- // INITIAL VARIABLES -- -- -- - - -
- var builder = WebApplication.CreateBuilder(args);
- builder.Services.AddHttpClient();
- builder.Services.AddRazorComponents().AddInteractiveServerComponents();
- //builder.Services.AddControllers();
- builder.Services.AddMemoryCache();
- Env.Load();
- bool detailedErrorsEnabled = builder.Configuration.GetValue<bool>("DetailedErrors:Enabled");
- // SYNCFUSION -- -- -- - - -
- builder.Services.AddSyncfusionBlazor();
- builder.Services.AddFluentUIComponents();
- builder.Services.AddDataGridEntityFrameworkAdapter();
- Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("");
- // IDEN AND AUTH -- -- -- - - -
- builder.Services.AddCascadingAuthenticationState();
- builder.Services.AddScoped<IdentityUserAccessor>();
- builder.Services.AddScoped<IdentityRedirectManager>();
- builder.Services.AddAuthorization();
- builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
- builder.Services.AddAuthentication(options =>
- {
- options.DefaultScheme = IdentityConstants.ApplicationScheme;
- options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
- }).AddIdentityCookies();
- builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>().AddSignInManager().AddDefaultTokenProviders();
- // DATABASE -- -- -- - - -
- string connectionString = Environment.GetEnvironmentVariable("DEFAULTCONNECTION");
- if (string.IsNullOrEmpty(connectionString)) { connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); }
- builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
- options.UseSqlServer(connectionString, sqlOptions =>
- sqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));
- // PLUGINS -- -- -- - - -
- builder.Services.AddScoped<PluginManager>();
- var pluginsPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\Plugins");
- var serviceProvider = builder.Services.BuildServiceProvider();
- PluginLoader.LoadPlugins(builder.Services, pluginsPath, serviceProvider);
- // DEPENDENCIES -- -- -- - - -
- builder.Services.AddScoped<AttachmentService>();
- builder.Services.AddScoped<CarrierService>();
- builder.Services.AddScoped<ClientService>();
- builder.Services.AddScoped<ContactService>();
- builder.Services.AddScoped<EmberService>();
- builder.Services.AddScoped<FormService>();
- builder.Services.AddScoped<HomeService>();
- builder.Services.AddScoped<PolicyService>();
- builder.Services.AddScoped<RenewalService>();
- builder.Services.AddScoped<SearchService>();
- builder.Services.AddScoped<SharedService>();
- builder.Services.AddScoped<TaskService>();
- builder.Services.AddScoped<UserService>();
- builder.Services.AddSingleton<StateService>();
- builder.Services.AddScoped<ILoggingService, LoggingService>();
- builder.Services.AddScoped<ITooltipService, TooltipService>();
- builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
- builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
- builder.Services.AddSignalR();
- builder.Services.AddHttpContextAccessor();
- builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true).AddEnvironmentVariables();
- // ---------------------------------------------------//
- // App Configuration Protocols ---------------------- //
- // ---------------------------------------------------//
- var app = builder.Build();
- app.UseDeveloperExceptionPage();
- app.UseMigrationsEndPoint();
- if (!app.Environment.IsDevelopment())
- {
- app.UseHsts();
- }
- app.UseHttpsRedirection();
- app.MapStaticAssets();
- app.UseStaticFiles();
- app.UseAntiforgery();
- app.UseAuthentication();
- app.UseAuthorization();
- app.MapHub<NotificationHub>("/notificationHub");
- app.MapHub<EmberHub>("/emberHub");
- app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
- //app.MapControllers();
- app.MapAdditionalIdentityEndpoints();
- app.Run();
- ```
- ### Surefire\Components\Account\IdentityRedirectManager.cs
- ```csharp
- using System.Diagnostics.CodeAnalysis;
- using Microsoft.AspNetCore.Components;
- using Microsoft.AspNetCore.Components.Authorization;
- namespace Surefire.Components.Account
- {
- internal sealed class IdentityRedirectManager(NavigationManager navigationManager)
- {
- public const string StatusCookieName = "Identity.StatusMessage";
- private static readonly CookieBuilder StatusCookieBuilder = new()
- {
- SameSite = SameSiteMode.Strict,
- HttpOnly = true,
- IsEssential = true,
- MaxAge = TimeSpan.FromSeconds(5),
- };
- [DoesNotReturn]
- public void RedirectTo(string? uri)
- {
- Console.WriteLine("test");
- uri ??= "";
- // Prevent open redirects.
- if (!Uri.IsWellFormedUriString(uri, UriKind.Relative))
- {
- uri = navigationManager.ToBaseRelativePath(uri);
- }
- // During static rendering, NavigateTo throws a NavigationException which is handled by the framework as a redirect.
- // So as long as this is called from a statically rendered Identity component, the InvalidOperationException is never thrown.
- //THIS MO FO RIGHT HERE
- navigationManager.NavigateTo(uri);
- throw new InvalidOperationException($"{nameof(IdentityRedirectManager)} can only be used during static rendering.");
- }
- [DoesNotReturn]
- public void RedirectTo(string uri, Dictionary<string, object?> queryParameters)
- {
- Console.WriteLine("test2");
- var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path);
- var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters);
- RedirectTo(newUri);
- }
- [DoesNotReturn]
- public void RedirectToWithStatus(string uri, string message, HttpContext context)
- {
- Console.WriteLine("test4");
- context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context));
- RedirectTo(uri);
- }
- private string CurrentPath => navigationManager.ToAbsoluteUri(navigationManager.Uri).GetLeftPart(UriPartial.Path);
- [DoesNotReturn]
- public void RedirectToCurrentPage() => RedirectTo(CurrentPath);
- [DoesNotReturn]
- public void RedirectToCurrentPageWithStatus(string message, HttpContext context)
- => RedirectToWithStatus(CurrentPath, message, context);
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment