Guest User

Untitled

a guest
Nov 23rd, 2024
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.00 KB | None | 0 0
  1. ### Surefire\Components\Account\Shared\RedirectToLogin.razor
  2.  
  3. ```razor
  4. @inject NavigationManager NavigationManager
  5. @code {
  6. protected override void OnInitialized()
  7. {
  8. Console.WriteLine($"Redr RENDERMODE: {RendererInfo.IsInteractive}");
  9. NavigationManager.NavigateTo($"Account/Login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}", forceLoad: true);
  10. }
  11. }
  12. ```
  13.  
  14. ### Surefire\Components\Account\Pages\Login.razor
  15.  
  16. ```razor
  17. @namespace Surefire.Components.Account.Pages
  18. @page "/Account/Login"
  19.  
  20. @using System.ComponentModel.DataAnnotations
  21. @using Microsoft.AspNetCore.Authentication
  22. @using Microsoft.AspNetCore.Identity
  23. @using Surefire.Data
  24.  
  25. @inject SignInManager<ApplicationUser> SignInManager
  26. @inject ILogger<Login> Logger
  27. @inject NavigationManager NavigationManager
  28. @inject IdentityRedirectManager RedirectManager
  29.  
  30. <PageTitle>Surefire success from relentless focus.</PageTitle>
  31.  
  32. <div class="page-content">
  33. <div class="staticlogin">
  34. <section>
  35. <div class="txt-alert-main">Login</div>
  36. <div class="txt-alert-sub"><StatusMessage Message="@errorMessage" /></div>
  37. <EditForm Model="Input" method="post" OnValidSubmit="LoginUser" FormName="login">
  38. <DataAnnotationsValidator />
  39.  
  40. <ValidationSummary class="text-danger" role="alert" />
  41. <span class="sf-thead">Email</span>
  42. <div class="e-input-group e-control-container e-control-wrapper e-float-input" style="padding-top:0px !important;">
  43. <InputText @bind-Value="Input.Email" id="Input.Email" class="e-control e-textbox e-lib" autocomplete="username" aria-required="true" placeholder="[email protected]" />
  44. <ValidationMessage For="() => Input.Email" class="text-danger" />
  45. </div>
  46. <div style="height:20px;"></div>
  47. <span class="sf-thead">Password</span>
  48. <div class="e-input-group e-control-container e-control-wrapper e-float-input" style="padding-top:0px !important;">
  49. <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" />
  50. <ValidationMessage For="() => Input.Password" class="text-danger" />
  51. </div>
  52. <div style="height:10px;"></div>
  53. <div class="checkbox mb-3" style="font-size:12px;">
  54. <label class="form-label">
  55. <InputCheckbox @bind-Value="Input.RememberMe" class="darker-border-checkbox form-check-input" />
  56. Remember me
  57. </label>
  58. </div>
  59.  
  60. <div>
  61. <button type="submit" class="submitbtn">Log in</button>
  62. </div>
  63. </EditForm>
  64. </section>
  65. </div>
  66. </div>
  67.  
  68. <style>
  69. :root .e-float-input {
  70. padding-top: 0px !important;
  71. margin-top: 0px !important;
  72. }
  73. </style>
  74. @code {
  75. private string? errorMessage = "Let's get you logged back in...";
  76.  
  77. [CascadingParameter]
  78. private HttpContext HttpContext { get; set; } = default!;
  79.  
  80. [SupplyParameterFromForm]
  81. private InputModel Input { get; set; } = new();
  82.  
  83. [SupplyParameterFromQuery]
  84. private string? ReturnUrl { get; set; }
  85.  
  86. protected override async Task OnInitializedAsync()
  87. {
  88. Console.WriteLine($"LOGN RENDERMODE: {RendererInfo.IsInteractive}");
  89. if (HttpMethods.IsGet(HttpContext.Request.Method))
  90. {
  91. await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
  92. }
  93. }
  94.  
  95. public async Task LoginUser()
  96. {
  97. Console.WriteLine($"LOG1 RENDERMODE: {RendererInfo.IsInteractive}");
  98. var result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
  99. if (result.Succeeded)
  100. {
  101. Console.WriteLine($"LOG2 RENDERMODE: {RendererInfo.IsInteractive}");
  102. Logger.LogInformation("User logged in.");
  103. RedirectManager.RedirectTo("loading");
  104. }
  105. else if (result.RequiresTwoFactor)
  106. {
  107. RedirectManager.RedirectTo(
  108. "Account/LoginWith2fa",
  109. new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe });
  110. }
  111. else if (result.IsLockedOut)
  112. {
  113. Logger.LogWarning("User account locked out.");
  114. RedirectManager.RedirectTo("Account/Lockout");
  115. }
  116. else
  117. {
  118. errorMessage = "Error: Invalid login attempt.";
  119. }
  120. }
  121.  
  122. private sealed class InputModel
  123. {
  124. [Required]
  125. [EmailAddress]
  126. public string Email { get; set; } = "";
  127.  
  128. [Required]
  129. [DataType(DataType.Password)]
  130. public string Password { get; set; } = "";
  131.  
  132. [Display(Name = "Remember me?")]
  133. public bool RememberMe { get; set; }
  134. }
  135. }
  136.  
  137. ```
  138.  
  139. ### Surefire\Components\App.razor
  140.  
  141. ```razor
  142. <!DOCTYPE html>
  143. <html lang="en">
  144.  
  145. <head>
  146. <meta charset="utf-8" />
  147. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  148. <base href="/" />
  149. <link rel="stylesheet" href="app.css" />
  150. <link rel="stylesheet" href="Surefire.styles.css" />
  151. <ImportMap />
  152. <link rel="icon" type="image/png" href="favicon.png" />
  153. <HeadOutlet @rendermode="PageRenderMode" />
  154. <link rel="stylesheet" href="_content/Syncfusion.Blazor.Themes/fluent2.css" />
  155. <script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
  156. <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js" type="text/javascript"></script>
  157. <script src="_content/Syncfusion.Blazor.SfPdfViewer/scripts/syncfusion-blazor-sfpdfviewer.min.js" type="text/javascript"></script>
  158. <script src="/scripts/forms.js" type="text/javascript"></script>
  159. </head>
  160.  
  161. <body>
  162. <Routes @rendermode="PageRenderMode" />
  163. <script src="_framework/blazor.web.js"></script>
  164. </body>
  165. </html>
  166. @code {
  167. [CascadingParameter]
  168. private HttpContext HttpContext { get; set; } = default!;
  169.  
  170. private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
  171.  
  172. protected override void OnInitialized()
  173. {
  174. Console.WriteLine($"Init RENDERMODE: {RendererInfo.IsInteractive}");
  175. }
  176. }
  177.  
  178. ```
  179.  
  180. ### Surefire\Components\Routes.razor
  181.  
  182. ```razor
  183. @using Surefire.Components.Account.Shared
  184. <Router AppAssembly="typeof(Program).Assembly">
  185. <Found Context="routeData">
  186. <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
  187. <NotAuthorized>
  188. <RedirectToLogin />
  189. </NotAuthorized>
  190. </AuthorizeRouteView>
  191. <FocusOnNavigate RouteData="routeData" Selector="h1" />
  192. </Found>
  193. </Router>
  194. @code {
  195. protected override void OnInitialized()
  196. {
  197. Console.WriteLine($"Rout RENDERMODE: {RendererInfo.IsInteractive}");
  198. }
  199. }
  200. ```
  201.  
  202. ### Surefire\Program.cs
  203.  
  204. ```csharp
  205. using Surefire.Components.Account;
  206. using Surefire.Components;
  207. using Surefire.Data;
  208. using Surefire.Domain.Attachments.Services;
  209. using Surefire.Domain.Carriers.Services;
  210. using Surefire.Domain.Policies.Services;
  211. using Surefire.Domain.Clients.Services;
  212. using Surefire.Domain.Renewals.Services;
  213. using Surefire.Domain.Forms.Services;
  214. using Surefire.Domain.Contacts.Services;
  215. using Surefire.Domain.Shared.Services;
  216. using Surefire.Domain.Users.Services;
  217. using Surefire.Domain.Ember;
  218. using Surefire.Domain.Logs;
  219. using Surefire.Domain.OpenAI;
  220. using Surefire.Domain.Plugins;
  221. using Microsoft.AspNetCore.Components.Authorization;
  222. using Microsoft.AspNetCore.Identity;
  223. using Microsoft.EntityFrameworkCore;
  224. using Microsoft.FluentUI.AspNetCore.Components;
  225. using Microsoft.FluentUI.AspNetCore.Components.Components.Tooltip;
  226. using Syncfusion.Blazor;
  227. using DotNetEnv;
  228. using Microsoft.Extensions.DependencyInjection;
  229.  
  230.  
  231. // INITIAL VARIABLES -- -- -- - - -
  232. var builder = WebApplication.CreateBuilder(args);
  233. builder.Services.AddHttpClient();
  234. builder.Services.AddRazorComponents().AddInteractiveServerComponents();
  235. //builder.Services.AddControllers();
  236. builder.Services.AddMemoryCache();
  237. Env.Load();
  238. bool detailedErrorsEnabled = builder.Configuration.GetValue<bool>("DetailedErrors:Enabled");
  239.  
  240.  
  241. // SYNCFUSION -- -- -- - - -
  242. builder.Services.AddSyncfusionBlazor();
  243. builder.Services.AddFluentUIComponents();
  244. builder.Services.AddDataGridEntityFrameworkAdapter();
  245. Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("");
  246.  
  247.  
  248. // IDEN AND AUTH -- -- -- - - -
  249. builder.Services.AddCascadingAuthenticationState();
  250. builder.Services.AddScoped<IdentityUserAccessor>();
  251. builder.Services.AddScoped<IdentityRedirectManager>();
  252. builder.Services.AddAuthorization();
  253. builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
  254.  
  255. builder.Services.AddAuthentication(options =>
  256. {
  257. options.DefaultScheme = IdentityConstants.ApplicationScheme;
  258. options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
  259. }).AddIdentityCookies();
  260. builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>().AddSignInManager().AddDefaultTokenProviders();
  261.  
  262. // DATABASE -- -- -- - - -
  263. string connectionString = Environment.GetEnvironmentVariable("DEFAULTCONNECTION");
  264. if (string.IsNullOrEmpty(connectionString)) { connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); }
  265. builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
  266. options.UseSqlServer(connectionString, sqlOptions =>
  267. sqlOptions.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));
  268.  
  269.  
  270.  
  271. // PLUGINS -- -- -- - - -
  272. builder.Services.AddScoped<PluginManager>();
  273. var pluginsPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\Plugins");
  274. var serviceProvider = builder.Services.BuildServiceProvider();
  275. PluginLoader.LoadPlugins(builder.Services, pluginsPath, serviceProvider);
  276.  
  277.  
  278. // DEPENDENCIES -- -- -- - - -
  279. builder.Services.AddScoped<AttachmentService>();
  280. builder.Services.AddScoped<CarrierService>();
  281. builder.Services.AddScoped<ClientService>();
  282. builder.Services.AddScoped<ContactService>();
  283. builder.Services.AddScoped<EmberService>();
  284. builder.Services.AddScoped<FormService>();
  285. builder.Services.AddScoped<HomeService>();
  286. builder.Services.AddScoped<PolicyService>();
  287. builder.Services.AddScoped<RenewalService>();
  288. builder.Services.AddScoped<SearchService>();
  289. builder.Services.AddScoped<SharedService>();
  290. builder.Services.AddScoped<TaskService>();
  291. builder.Services.AddScoped<UserService>();
  292. builder.Services.AddSingleton<StateService>();
  293. builder.Services.AddScoped<ILoggingService, LoggingService>();
  294. builder.Services.AddScoped<ITooltipService, TooltipService>();
  295. builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
  296. builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
  297. builder.Services.AddSignalR();
  298. builder.Services.AddHttpContextAccessor();
  299. builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true).AddEnvironmentVariables();
  300.  
  301.  
  302. // ---------------------------------------------------//
  303. // App Configuration Protocols ---------------------- //
  304. // ---------------------------------------------------//
  305. var app = builder.Build();
  306. app.UseDeveloperExceptionPage();
  307. app.UseMigrationsEndPoint();
  308. if (!app.Environment.IsDevelopment())
  309. {
  310. app.UseHsts();
  311. }
  312. app.UseHttpsRedirection();
  313. app.MapStaticAssets();
  314. app.UseStaticFiles();
  315. app.UseAntiforgery();
  316. app.UseAuthentication();
  317. app.UseAuthorization();
  318. app.MapHub<NotificationHub>("/notificationHub");
  319. app.MapHub<EmberHub>("/emberHub");
  320. app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
  321. //app.MapControllers();
  322. app.MapAdditionalIdentityEndpoints();
  323. app.Run();
  324.  
  325. ```
  326. ### Surefire\Components\Account\IdentityRedirectManager.cs
  327.  
  328. ```csharp
  329. using System.Diagnostics.CodeAnalysis;
  330. using Microsoft.AspNetCore.Components;
  331. using Microsoft.AspNetCore.Components.Authorization;
  332.  
  333. namespace Surefire.Components.Account
  334. {
  335. internal sealed class IdentityRedirectManager(NavigationManager navigationManager)
  336. {
  337. public const string StatusCookieName = "Identity.StatusMessage";
  338.  
  339. private static readonly CookieBuilder StatusCookieBuilder = new()
  340. {
  341. SameSite = SameSiteMode.Strict,
  342. HttpOnly = true,
  343. IsEssential = true,
  344. MaxAge = TimeSpan.FromSeconds(5),
  345. };
  346.  
  347. [DoesNotReturn]
  348. public void RedirectTo(string? uri)
  349. {
  350. Console.WriteLine("test");
  351. uri ??= "";
  352.  
  353. // Prevent open redirects.
  354. if (!Uri.IsWellFormedUriString(uri, UriKind.Relative))
  355. {
  356. uri = navigationManager.ToBaseRelativePath(uri);
  357. }
  358. // During static rendering, NavigateTo throws a NavigationException which is handled by the framework as a redirect.
  359. // So as long as this is called from a statically rendered Identity component, the InvalidOperationException is never thrown.
  360. //THIS MO FO RIGHT HERE
  361. navigationManager.NavigateTo(uri);
  362. throw new InvalidOperationException($"{nameof(IdentityRedirectManager)} can only be used during static rendering.");
  363. }
  364.  
  365. [DoesNotReturn]
  366. public void RedirectTo(string uri, Dictionary<string, object?> queryParameters)
  367. {
  368. Console.WriteLine("test2");
  369. var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path);
  370. var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters);
  371. RedirectTo(newUri);
  372. }
  373.  
  374. [DoesNotReturn]
  375. public void RedirectToWithStatus(string uri, string message, HttpContext context)
  376. {
  377. Console.WriteLine("test4");
  378. context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context));
  379. RedirectTo(uri);
  380. }
  381.  
  382. private string CurrentPath => navigationManager.ToAbsoluteUri(navigationManager.Uri).GetLeftPart(UriPartial.Path);
  383.  
  384. [DoesNotReturn]
  385. public void RedirectToCurrentPage() => RedirectTo(CurrentPath);
  386.  
  387. [DoesNotReturn]
  388. public void RedirectToCurrentPageWithStatus(string message, HttpContext context)
  389. => RedirectToWithStatus(CurrentPath, message, context);
  390. }
  391. }
  392.  
  393. ```
  394.  
  395.  
  396.  
Advertisement
Add Comment
Please, Sign In to add comment